repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
apache/flink
flink-core/src/main/java/org/apache/flink/types/Record.java
Record.getField
@SuppressWarnings("unchecked") public <T extends Value> T getField(final int fieldNum, final Class<T> type) { """ Gets the field at the given position from the record. This method checks internally, if this instance of the record has previously returned a value for this field. If so, it reuses the object, if not, it creates one from the supplied class. @param <T> The type of the field. @param fieldNum The logical position of the field. @param type The type of the field as a class. This class is used to instantiate a value object, if none had previously been instantiated. @return The field at the given position, or null, if the field was null. @throws IndexOutOfBoundsException Thrown, if the field number is negative or larger or equal to the number of fields in this record. """ // range check if (fieldNum < 0 || fieldNum >= this.numFields) { throw new IndexOutOfBoundsException(fieldNum + " for range [0.." + (this.numFields - 1) + "]"); } // get offset and check for null final int offset = this.offsets[fieldNum]; if (offset == NULL_INDICATOR_OFFSET) { return null; } else if (offset == MODIFIED_INDICATOR_OFFSET) { // value that has been set is new or modified return (T) this.writeFields[fieldNum]; } final int limit = offset + this.lengths[fieldNum]; // get an instance, either from the instance cache or create a new one final Value oldField = this.readFields[fieldNum]; final T field; if (oldField != null && oldField.getClass() == type) { field = (T) oldField; } else { field = InstantiationUtil.instantiate(type, Value.class); this.readFields[fieldNum] = field; } // deserialize deserialize(field, offset, limit, fieldNum); return field; }
java
@SuppressWarnings("unchecked") public <T extends Value> T getField(final int fieldNum, final Class<T> type) { // range check if (fieldNum < 0 || fieldNum >= this.numFields) { throw new IndexOutOfBoundsException(fieldNum + " for range [0.." + (this.numFields - 1) + "]"); } // get offset and check for null final int offset = this.offsets[fieldNum]; if (offset == NULL_INDICATOR_OFFSET) { return null; } else if (offset == MODIFIED_INDICATOR_OFFSET) { // value that has been set is new or modified return (T) this.writeFields[fieldNum]; } final int limit = offset + this.lengths[fieldNum]; // get an instance, either from the instance cache or create a new one final Value oldField = this.readFields[fieldNum]; final T field; if (oldField != null && oldField.getClass() == type) { field = (T) oldField; } else { field = InstantiationUtil.instantiate(type, Value.class); this.readFields[fieldNum] = field; } // deserialize deserialize(field, offset, limit, fieldNum); return field; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "Value", ">", "T", "getField", "(", "final", "int", "fieldNum", ",", "final", "Class", "<", "T", ">", "type", ")", "{", "// range check", "if", "(", "fieldNum", "<", "0", "||", "fieldNum", ">=", "this", ".", "numFields", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "fieldNum", "+", "\" for range [0..\"", "+", "(", "this", ".", "numFields", "-", "1", ")", "+", "\"]\"", ")", ";", "}", "// get offset and check for null", "final", "int", "offset", "=", "this", ".", "offsets", "[", "fieldNum", "]", ";", "if", "(", "offset", "==", "NULL_INDICATOR_OFFSET", ")", "{", "return", "null", ";", "}", "else", "if", "(", "offset", "==", "MODIFIED_INDICATOR_OFFSET", ")", "{", "// value that has been set is new or modified", "return", "(", "T", ")", "this", ".", "writeFields", "[", "fieldNum", "]", ";", "}", "final", "int", "limit", "=", "offset", "+", "this", ".", "lengths", "[", "fieldNum", "]", ";", "// get an instance, either from the instance cache or create a new one", "final", "Value", "oldField", "=", "this", ".", "readFields", "[", "fieldNum", "]", ";", "final", "T", "field", ";", "if", "(", "oldField", "!=", "null", "&&", "oldField", ".", "getClass", "(", ")", "==", "type", ")", "{", "field", "=", "(", "T", ")", "oldField", ";", "}", "else", "{", "field", "=", "InstantiationUtil", ".", "instantiate", "(", "type", ",", "Value", ".", "class", ")", ";", "this", ".", "readFields", "[", "fieldNum", "]", "=", "field", ";", "}", "// deserialize", "deserialize", "(", "field", ",", "offset", ",", "limit", ",", "fieldNum", ")", ";", "return", "field", ";", "}" ]
Gets the field at the given position from the record. This method checks internally, if this instance of the record has previously returned a value for this field. If so, it reuses the object, if not, it creates one from the supplied class. @param <T> The type of the field. @param fieldNum The logical position of the field. @param type The type of the field as a class. This class is used to instantiate a value object, if none had previously been instantiated. @return The field at the given position, or null, if the field was null. @throws IndexOutOfBoundsException Thrown, if the field number is negative or larger or equal to the number of fields in this record.
[ "Gets", "the", "field", "at", "the", "given", "position", "from", "the", "record", ".", "This", "method", "checks", "internally", "if", "this", "instance", "of", "the", "record", "has", "previously", "returned", "a", "value", "for", "this", "field", ".", "If", "so", "it", "reuses", "the", "object", "if", "not", "it", "creates", "one", "from", "the", "supplied", "class", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/types/Record.java#L222-L255
azkaban/azkaban
azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java
ProjectServlet.handleFetchUserProjects
private void handleFetchUserProjects(final HttpServletRequest req, final Session session, final ProjectManager manager, final HashMap<String, Object> ret) throws ServletException { """ We know the intention of API call is to return project ownership based on given user. <br> If user provides an user name, the method honors it <br> If user provides an empty user name, the user defaults to the session user<br> If user does not provide the user param, the user also defaults to the session user<br> """ User user = null; // if key "user" is specified, follow this logic if (hasParam(req, "user")) { final String userParam = getParam(req, "user"); if (userParam.isEmpty()) { user = session.getUser(); } else { user = new User(userParam); } } else { // if key "user" is not specified, default to the session user user = session.getUser(); } final List<Project> projects = manager.getUserProjects(user); final List<SimplifiedProject> simplifiedProjects = toSimplifiedProjects(projects); ret.put("projects", simplifiedProjects); }
java
private void handleFetchUserProjects(final HttpServletRequest req, final Session session, final ProjectManager manager, final HashMap<String, Object> ret) throws ServletException { User user = null; // if key "user" is specified, follow this logic if (hasParam(req, "user")) { final String userParam = getParam(req, "user"); if (userParam.isEmpty()) { user = session.getUser(); } else { user = new User(userParam); } } else { // if key "user" is not specified, default to the session user user = session.getUser(); } final List<Project> projects = manager.getUserProjects(user); final List<SimplifiedProject> simplifiedProjects = toSimplifiedProjects(projects); ret.put("projects", simplifiedProjects); }
[ "private", "void", "handleFetchUserProjects", "(", "final", "HttpServletRequest", "req", ",", "final", "Session", "session", ",", "final", "ProjectManager", "manager", ",", "final", "HashMap", "<", "String", ",", "Object", ">", "ret", ")", "throws", "ServletException", "{", "User", "user", "=", "null", ";", "// if key \"user\" is specified, follow this logic", "if", "(", "hasParam", "(", "req", ",", "\"user\"", ")", ")", "{", "final", "String", "userParam", "=", "getParam", "(", "req", ",", "\"user\"", ")", ";", "if", "(", "userParam", ".", "isEmpty", "(", ")", ")", "{", "user", "=", "session", ".", "getUser", "(", ")", ";", "}", "else", "{", "user", "=", "new", "User", "(", "userParam", ")", ";", "}", "}", "else", "{", "// if key \"user\" is not specified, default to the session user", "user", "=", "session", ".", "getUser", "(", ")", ";", "}", "final", "List", "<", "Project", ">", "projects", "=", "manager", ".", "getUserProjects", "(", "user", ")", ";", "final", "List", "<", "SimplifiedProject", ">", "simplifiedProjects", "=", "toSimplifiedProjects", "(", "projects", ")", ";", "ret", ".", "put", "(", "\"projects\"", ",", "simplifiedProjects", ")", ";", "}" ]
We know the intention of API call is to return project ownership based on given user. <br> If user provides an user name, the method honors it <br> If user provides an empty user name, the user defaults to the session user<br> If user does not provide the user param, the user also defaults to the session user<br>
[ "We", "know", "the", "intention", "of", "API", "call", "is", "to", "return", "project", "ownership", "based", "on", "given", "user", ".", "<br", ">", "If", "user", "provides", "an", "user", "name", "the", "method", "honors", "it", "<br", ">", "If", "user", "provides", "an", "empty", "user", "name", "the", "user", "defaults", "to", "the", "session", "user<br", ">", "If", "user", "does", "not", "provide", "the", "user", "param", "the", "user", "also", "defaults", "to", "the", "session", "user<br", ">" ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectServlet.java#L113-L134
entrusc/Pi-RC-Switch
src/main/java/de/pi3g/pi/rcswitch/RCSwitch.java
RCSwitch.switchOn
public void switchOn(BitSet switchGroupAddress, int switchCode) { """ Switch a remote switch on (Type A with 10 pole DIP switches) @param switchGroupAddress Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") @param switchCode Number of the switch itself (1..4) """ if (switchGroupAddress.length() > 5) { throw new IllegalArgumentException("switch group address has more than 5 bits!"); } this.sendTriState(this.getCodeWordA(switchGroupAddress, switchCode, true)); }
java
public void switchOn(BitSet switchGroupAddress, int switchCode) { if (switchGroupAddress.length() > 5) { throw new IllegalArgumentException("switch group address has more than 5 bits!"); } this.sendTriState(this.getCodeWordA(switchGroupAddress, switchCode, true)); }
[ "public", "void", "switchOn", "(", "BitSet", "switchGroupAddress", ",", "int", "switchCode", ")", "{", "if", "(", "switchGroupAddress", ".", "length", "(", ")", ">", "5", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"switch group address has more than 5 bits!\"", ")", ";", "}", "this", ".", "sendTriState", "(", "this", ".", "getCodeWordA", "(", "switchGroupAddress", ",", "switchCode", ",", "true", ")", ")", ";", "}" ]
Switch a remote switch on (Type A with 10 pole DIP switches) @param switchGroupAddress Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") @param switchCode Number of the switch itself (1..4)
[ "Switch", "a", "remote", "switch", "on", "(", "Type", "A", "with", "10", "pole", "DIP", "switches", ")" ]
train
https://github.com/entrusc/Pi-RC-Switch/blob/3a7433074a3382154cfc31c086eee75e928aced7/src/main/java/de/pi3g/pi/rcswitch/RCSwitch.java#L89-L94
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringParser.java
StringParser.parseFloat
public static float parseFloat (@Nullable final Object aObject, final float fDefault) { """ Parse the given {@link Object} as float. Note: both the locale independent form of a float 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 fDefault The default value to be returned if the passed object could not be converted to a valid value. @return The default value if the object does not represent a valid value. """ if (aObject == null) return fDefault; if (aObject instanceof Number) return ((Number) aObject).floatValue (); return parseFloat (aObject.toString (), fDefault); }
java
public static float parseFloat (@Nullable final Object aObject, final float fDefault) { if (aObject == null) return fDefault; if (aObject instanceof Number) return ((Number) aObject).floatValue (); return parseFloat (aObject.toString (), fDefault); }
[ "public", "static", "float", "parseFloat", "(", "@", "Nullable", "final", "Object", "aObject", ",", "final", "float", "fDefault", ")", "{", "if", "(", "aObject", "==", "null", ")", "return", "fDefault", ";", "if", "(", "aObject", "instanceof", "Number", ")", "return", "(", "(", "Number", ")", "aObject", ")", ".", "floatValue", "(", ")", ";", "return", "parseFloat", "(", "aObject", ".", "toString", "(", ")", ",", "fDefault", ")", ";", "}" ]
Parse the given {@link Object} as float. Note: both the locale independent form of a float 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 fDefault The default value to be returned if the passed object could not be converted to a valid value. @return The default value if the object does not represent a valid value.
[ "Parse", "the", "given", "{", "@link", "Object", "}", "as", "float", ".", "Note", ":", "both", "the", "locale", "independent", "form", "of", "a", "float", "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#L588-L595
Azure/azure-sdk-for-java
iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java
IotHubResourcesInner.listJobsAsync
public Observable<Page<JobResponseInner>> listJobsAsync(final String resourceGroupName, final String resourceName) { """ Get a list of all the jobs in an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. Get a list of all the jobs in an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. @param resourceGroupName The name of the resource group that contains the IoT hub. @param resourceName The name of the IoT hub. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobResponseInner&gt; object """ return listJobsWithServiceResponseAsync(resourceGroupName, resourceName) .map(new Func1<ServiceResponse<Page<JobResponseInner>>, Page<JobResponseInner>>() { @Override public Page<JobResponseInner> call(ServiceResponse<Page<JobResponseInner>> response) { return response.body(); } }); }
java
public Observable<Page<JobResponseInner>> listJobsAsync(final String resourceGroupName, final String resourceName) { return listJobsWithServiceResponseAsync(resourceGroupName, resourceName) .map(new Func1<ServiceResponse<Page<JobResponseInner>>, Page<JobResponseInner>>() { @Override public Page<JobResponseInner> call(ServiceResponse<Page<JobResponseInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "JobResponseInner", ">", ">", "listJobsAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "resourceName", ")", "{", "return", "listJobsWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "JobResponseInner", ">", ">", ",", "Page", "<", "JobResponseInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "JobResponseInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "JobResponseInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get a list of all the jobs in an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. Get a list of all the jobs in an IoT hub. For more information, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. @param resourceGroupName The name of the resource group that contains the IoT hub. @param resourceName The name of the IoT hub. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobResponseInner&gt; object
[ "Get", "a", "list", "of", "all", "the", "jobs", "in", "an", "IoT", "hub", ".", "For", "more", "information", "see", ":", "https", ":", "//", "docs", ".", "microsoft", ".", "com", "/", "azure", "/", "iot", "-", "hub", "/", "iot", "-", "hub", "-", "devguide", "-", "identity", "-", "registry", ".", "Get", "a", "list", "of", "all", "the", "jobs", "in", "an", "IoT", "hub", ".", "For", "more", "information", "see", ":", "https", ":", "//", "docs", ".", "microsoft", ".", "com", "/", "azure", "/", "iot", "-", "hub", "/", "iot", "-", "hub", "-", "devguide", "-", "identity", "-", "registry", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L2120-L2128
google/j2objc
jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/datatype/XMLGregorianCalendar.java
XMLGregorianCalendar.setTime
public void setTime(int hour, int minute, int second, int millisecond) { """ <p>Set time as one unit, including optional milliseconds.</p> @param hour value constraints are summarized in <a href="#datetimefield-hour">hour field of date/time field mapping table</a>. @param minute value constraints are summarized in <a href="#datetimefield-minute">minute field of date/time field mapping table</a>. @param second value constraints are summarized in <a href="#datetimefield-second">second field of date/time field mapping table</a>. @param millisecond value of {@link DatatypeConstants#FIELD_UNDEFINED} indicates this optional field is not set. @throws IllegalArgumentException if any parameter is outside value constraints for the field as specified in <a href="#datetimefieldmapping">date/time field mapping table</a>. """ setHour(hour); setMinute(minute); setSecond(second); setMillisecond(millisecond); }
java
public void setTime(int hour, int minute, int second, int millisecond) { setHour(hour); setMinute(minute); setSecond(second); setMillisecond(millisecond); }
[ "public", "void", "setTime", "(", "int", "hour", ",", "int", "minute", ",", "int", "second", ",", "int", "millisecond", ")", "{", "setHour", "(", "hour", ")", ";", "setMinute", "(", "minute", ")", ";", "setSecond", "(", "second", ")", ";", "setMillisecond", "(", "millisecond", ")", ";", "}" ]
<p>Set time as one unit, including optional milliseconds.</p> @param hour value constraints are summarized in <a href="#datetimefield-hour">hour field of date/time field mapping table</a>. @param minute value constraints are summarized in <a href="#datetimefield-minute">minute field of date/time field mapping table</a>. @param second value constraints are summarized in <a href="#datetimefield-second">second field of date/time field mapping table</a>. @param millisecond value of {@link DatatypeConstants#FIELD_UNDEFINED} indicates this optional field is not set. @throws IllegalArgumentException if any parameter is outside value constraints for the field as specified in <a href="#datetimefieldmapping">date/time field mapping table</a>.
[ "<p", ">", "Set", "time", "as", "one", "unit", "including", "optional", "milliseconds", ".", "<", "/", "p", ">" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/javax/xml/datatype/XMLGregorianCalendar.java#L444-L450
alibaba/transmittable-thread-local
src/main/java/com/alibaba/ttl/TtlCallable.java
TtlCallable.get
public static <T> TtlCallable<T> get(Callable<T> callable) { """ Factory method, wrap input {@link Callable} to {@link TtlCallable}. <p> This method is idempotent. @param callable input {@link Callable} @return Wrapped {@link Callable} """ return get(callable, false); }
java
public static <T> TtlCallable<T> get(Callable<T> callable) { return get(callable, false); }
[ "public", "static", "<", "T", ">", "TtlCallable", "<", "T", ">", "get", "(", "Callable", "<", "T", ">", "callable", ")", "{", "return", "get", "(", "callable", ",", "false", ")", ";", "}" ]
Factory method, wrap input {@link Callable} to {@link TtlCallable}. <p> This method is idempotent. @param callable input {@link Callable} @return Wrapped {@link Callable}
[ "Factory", "method", "wrap", "input", "{", "@link", "Callable", "}", "to", "{", "@link", "TtlCallable", "}", ".", "<p", ">", "This", "method", "is", "idempotent", "." ]
train
https://github.com/alibaba/transmittable-thread-local/blob/30b4d99cdb7064b4c1797d2e40bfa07adce8e7f9/src/main/java/com/alibaba/ttl/TtlCallable.java#L93-L95
aws/aws-sdk-java
aws-java-sdk-sts/src/main/java/com/amazonaws/auth/RefreshableTask.java
RefreshableTask.asyncRefresh
private void asyncRefresh() { """ Used to asynchronously refresh the value. Caller is never blocked. """ // Immediately return if refresh already in progress if (asyncRefreshing.compareAndSet(false, true)) { try { executor.submit(new Runnable() { @Override public void run() { try { refreshValue(); } finally { asyncRefreshing.set(false); } } }); } catch (RuntimeException ex) { asyncRefreshing.set(false); throw ex; } } }
java
private void asyncRefresh() { // Immediately return if refresh already in progress if (asyncRefreshing.compareAndSet(false, true)) { try { executor.submit(new Runnable() { @Override public void run() { try { refreshValue(); } finally { asyncRefreshing.set(false); } } }); } catch (RuntimeException ex) { asyncRefreshing.set(false); throw ex; } } }
[ "private", "void", "asyncRefresh", "(", ")", "{", "// Immediately return if refresh already in progress", "if", "(", "asyncRefreshing", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "try", "{", "executor", ".", "submit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "refreshValue", "(", ")", ";", "}", "finally", "{", "asyncRefreshing", ".", "set", "(", "false", ")", ";", "}", "}", "}", ")", ";", "}", "catch", "(", "RuntimeException", "ex", ")", "{", "asyncRefreshing", ".", "set", "(", "false", ")", ";", "throw", "ex", ";", "}", "}", "}" ]
Used to asynchronously refresh the value. Caller is never blocked.
[ "Used", "to", "asynchronously", "refresh", "the", "value", ".", "Caller", "is", "never", "blocked", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sts/src/main/java/com/amazonaws/auth/RefreshableTask.java#L230-L249
apache/incubator-heron
heron/api/src/java/org/apache/heron/streamlet/impl/utils/StreamletUtils.java
StreamletUtils.checkNotBlank
public static String checkNotBlank(String text, String errorMessage) { """ Verifies not blank text as the utility function. @param text The text to verify @param errorMessage The error message @throws IllegalArgumentException if the requirement fails """ if (StringUtils.isBlank(text)) { throw new IllegalArgumentException(errorMessage); } else { return text; } }
java
public static String checkNotBlank(String text, String errorMessage) { if (StringUtils.isBlank(text)) { throw new IllegalArgumentException(errorMessage); } else { return text; } }
[ "public", "static", "String", "checkNotBlank", "(", "String", "text", ",", "String", "errorMessage", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "text", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "errorMessage", ")", ";", "}", "else", "{", "return", "text", ";", "}", "}" ]
Verifies not blank text as the utility function. @param text The text to verify @param errorMessage The error message @throws IllegalArgumentException if the requirement fails
[ "Verifies", "not", "blank", "text", "as", "the", "utility", "function", "." ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/utils/StreamletUtils.java#L47-L53
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemTemplateElement.java
ElemTemplateElement.shouldStripWhiteSpace
public boolean shouldStripWhiteSpace( org.apache.xpath.XPathContext support, org.w3c.dom.Element targetElement) throws TransformerException { """ Get information about whether or not an element should strip whitespace. @see <a href="http://www.w3.org/TR/xslt#strip">strip in XSLT Specification</a> @param support The XPath runtime state. @param targetElement Element to check @return true if the whitespace should be stripped. @throws TransformerException """ StylesheetRoot sroot = this.getStylesheetRoot(); return (null != sroot) ? sroot.shouldStripWhiteSpace(support, targetElement) :false; }
java
public boolean shouldStripWhiteSpace( org.apache.xpath.XPathContext support, org.w3c.dom.Element targetElement) throws TransformerException { StylesheetRoot sroot = this.getStylesheetRoot(); return (null != sroot) ? sroot.shouldStripWhiteSpace(support, targetElement) :false; }
[ "public", "boolean", "shouldStripWhiteSpace", "(", "org", ".", "apache", ".", "xpath", ".", "XPathContext", "support", ",", "org", ".", "w3c", ".", "dom", ".", "Element", "targetElement", ")", "throws", "TransformerException", "{", "StylesheetRoot", "sroot", "=", "this", ".", "getStylesheetRoot", "(", ")", ";", "return", "(", "null", "!=", "sroot", ")", "?", "sroot", ".", "shouldStripWhiteSpace", "(", "support", ",", "targetElement", ")", ":", "false", ";", "}" ]
Get information about whether or not an element should strip whitespace. @see <a href="http://www.w3.org/TR/xslt#strip">strip in XSLT Specification</a> @param support The XPath runtime state. @param targetElement Element to check @return true if the whitespace should be stripped. @throws TransformerException
[ "Get", "information", "about", "whether", "or", "not", "an", "element", "should", "strip", "whitespace", ".", "@see", "<a", "href", "=", "http", ":", "//", "www", ".", "w3", ".", "org", "/", "TR", "/", "xslt#strip", ">", "strip", "in", "XSLT", "Specification<", "/", "a", ">" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemTemplateElement.java#L1533-L1539
b3dgs/lionengine
lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java
NetworkMessageEntity.addAction
public void addAction(M element, char value) { """ Add an action. @param element The action type. @param value The action value. """ actions.put(element, Character.valueOf(value)); }
java
public void addAction(M element, char value) { actions.put(element, Character.valueOf(value)); }
[ "public", "void", "addAction", "(", "M", "element", ",", "char", "value", ")", "{", "actions", ".", "put", "(", "element", ",", "Character", ".", "valueOf", "(", "value", ")", ")", ";", "}" ]
Add an action. @param element The action type. @param value The action value.
[ "Add", "an", "action", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java#L122-L125
apptik/JustJson
json-core/src/main/java/io/apptik/json/JsonObject.java
JsonObject.getLong
public Long getLong(String name, boolean strict) throws JsonException { """ Returns the value mapped by {@code name} if it exists and is a long or can be coerced to a long, or throws otherwise. Note that Util represents numbers as doubles, so this is <a href="#lossy">lossy</a>; use strings to transfer numbers via Util. @throws JsonException if the mapping doesn't exist or cannot be coerced to a long. """ JsonElement el = get(name); Long res = null; if (strict && !el.isNumber()) { throw Util.typeMismatch(name, el, "long", true); } if (el.isNumber()) { res = el.asLong(); } if (el.isString()) { res = Util.toLong(el.asString()); } if (res == null) throw Util.typeMismatch(name, el, "long", strict); return res; }
java
public Long getLong(String name, boolean strict) throws JsonException { JsonElement el = get(name); Long res = null; if (strict && !el.isNumber()) { throw Util.typeMismatch(name, el, "long", true); } if (el.isNumber()) { res = el.asLong(); } if (el.isString()) { res = Util.toLong(el.asString()); } if (res == null) throw Util.typeMismatch(name, el, "long", strict); return res; }
[ "public", "Long", "getLong", "(", "String", "name", ",", "boolean", "strict", ")", "throws", "JsonException", "{", "JsonElement", "el", "=", "get", "(", "name", ")", ";", "Long", "res", "=", "null", ";", "if", "(", "strict", "&&", "!", "el", ".", "isNumber", "(", ")", ")", "{", "throw", "Util", ".", "typeMismatch", "(", "name", ",", "el", ",", "\"long\"", ",", "true", ")", ";", "}", "if", "(", "el", ".", "isNumber", "(", ")", ")", "{", "res", "=", "el", ".", "asLong", "(", ")", ";", "}", "if", "(", "el", ".", "isString", "(", ")", ")", "{", "res", "=", "Util", ".", "toLong", "(", "el", ".", "asString", "(", ")", ")", ";", "}", "if", "(", "res", "==", "null", ")", "throw", "Util", ".", "typeMismatch", "(", "name", ",", "el", ",", "\"long\"", ",", "strict", ")", ";", "return", "res", ";", "}" ]
Returns the value mapped by {@code name} if it exists and is a long or can be coerced to a long, or throws otherwise. Note that Util represents numbers as doubles, so this is <a href="#lossy">lossy</a>; use strings to transfer numbers via Util. @throws JsonException if the mapping doesn't exist or cannot be coerced to a long.
[ "Returns", "the", "value", "mapped", "by", "{", "@code", "name", "}", "if", "it", "exists", "and", "is", "a", "long", "or", "can", "be", "coerced", "to", "a", "long", "or", "throws", "otherwise", ".", "Note", "that", "Util", "represents", "numbers", "as", "doubles", "so", "this", "is", "<a", "href", "=", "#lossy", ">", "lossy<", "/", "a", ">", ";", "use", "strings", "to", "transfer", "numbers", "via", "Util", "." ]
train
https://github.com/apptik/JustJson/blob/c90f0dd7f84df26da4749be8cd9b026fff499a79/json-core/src/main/java/io/apptik/json/JsonObject.java#L520-L535
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.hosting_privateDatabase_serviceName_ram_duration_GET
public OvhOrder hosting_privateDatabase_serviceName_ram_duration_GET(String serviceName, String duration, OvhAvailableRamSizeEnum ram) throws IOException { """ Get prices and contracts information REST: GET /order/hosting/privateDatabase/{serviceName}/ram/{duration} @param ram [required] Private database ram size @param serviceName [required] The internal name of your private database @param duration [required] Duration """ String qPath = "/order/hosting/privateDatabase/{serviceName}/ram/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); query(sb, "ram", ram); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder hosting_privateDatabase_serviceName_ram_duration_GET(String serviceName, String duration, OvhAvailableRamSizeEnum ram) throws IOException { String qPath = "/order/hosting/privateDatabase/{serviceName}/ram/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); query(sb, "ram", ram); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "hosting_privateDatabase_serviceName_ram_duration_GET", "(", "String", "serviceName", ",", "String", "duration", ",", "OvhAvailableRamSizeEnum", "ram", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/hosting/privateDatabase/{serviceName}/ram/{duration}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "duration", ")", ";", "query", "(", "sb", ",", "\"ram\"", ",", "ram", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOrder", ".", "class", ")", ";", "}" ]
Get prices and contracts information REST: GET /order/hosting/privateDatabase/{serviceName}/ram/{duration} @param ram [required] Private database ram size @param serviceName [required] The internal name of your private database @param duration [required] Duration
[ "Get", "prices", "and", "contracts", "information" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5168-L5174
JOML-CI/JOML
src/org/joml/Matrix4x3f.java
Matrix4x3f.setOrthoSymmetric
public Matrix4x3f setOrthoSymmetric(float width, float height, float zNear, float zFar) { """ Set this matrix to be a symmetric orthographic projection transformation for a right-handed coordinate system using OpenGL's NDC z range of <code>[-1..+1]</code>. <p> This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. <p> In order to apply the symmetric orthographic projection to an already existing transformation, use {@link #orthoSymmetric(float, float, float, float) orthoSymmetric()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #orthoSymmetric(float, float, float, float) @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 @return this """ return setOrthoSymmetric(width, height, zNear, zFar, false); }
java
public Matrix4x3f setOrthoSymmetric(float width, float height, float zNear, float zFar) { return setOrthoSymmetric(width, height, zNear, zFar, false); }
[ "public", "Matrix4x3f", "setOrthoSymmetric", "(", "float", "width", ",", "float", "height", ",", "float", "zNear", ",", "float", "zFar", ")", "{", "return", "setOrthoSymmetric", "(", "width", ",", "height", ",", "zNear", ",", "zFar", ",", "false", ")", ";", "}" ]
Set this matrix to be a symmetric orthographic projection transformation for a right-handed coordinate system using OpenGL's NDC z range of <code>[-1..+1]</code>. <p> This method is equivalent to calling {@link #setOrtho(float, float, float, float, float, float) setOrtho()} with <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. <p> In order to apply the symmetric orthographic projection to an already existing transformation, use {@link #orthoSymmetric(float, float, float, float) orthoSymmetric()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #orthoSymmetric(float, float, float, float) @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 @return this
[ "Set", "this", "matrix", "to", "be", "a", "symmetric", "orthographic", "projection", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "using", "OpenGL", "s", "NDC", "z", "range", "of", "<code", ">", "[", "-", "1", "..", "+", "1", "]", "<", "/", "code", ">", ".", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", "{", "@link", "#setOrtho", "(", "float", "float", "float", "float", "float", "float", ")", "setOrtho", "()", "}", "with", "<code", ">", "left", "=", "-", "width", "/", "2<", "/", "code", ">", "<code", ">", "right", "=", "+", "width", "/", "2<", "/", "code", ">", "<code", ">", "bottom", "=", "-", "height", "/", "2<", "/", "code", ">", "and", "<code", ">", "top", "=", "+", "height", "/", "2<", "/", "code", ">", ".", "<p", ">", "In", "order", "to", "apply", "the", "symmetric", "orthographic", "projection", "to", "an", "already", "existing", "transformation", "use", "{", "@link", "#orthoSymmetric", "(", "float", "float", "float", "float", ")", "orthoSymmetric", "()", "}", ".", "<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/Matrix4x3f.java#L5584-L5586
deephacks/confit
provider-jpa20/src/main/java/org/deephacks/confit/internal/jpa/JpaBeanQueryAssembler.java
JpaBeanQueryAssembler.addRefs
public void addRefs(Multimap<BeanId, JpaRef> queryRefs) { """ Add references found from a partial query of bean references. """ refs.putAll(queryRefs); for (BeanId id : refs.keySet()) { putIfAbsent(id); for (JpaRef ref : refs.get(id)) { putIfAbsent(ref.getTarget()); } } }
java
public void addRefs(Multimap<BeanId, JpaRef> queryRefs) { refs.putAll(queryRefs); for (BeanId id : refs.keySet()) { putIfAbsent(id); for (JpaRef ref : refs.get(id)) { putIfAbsent(ref.getTarget()); } } }
[ "public", "void", "addRefs", "(", "Multimap", "<", "BeanId", ",", "JpaRef", ">", "queryRefs", ")", "{", "refs", ".", "putAll", "(", "queryRefs", ")", ";", "for", "(", "BeanId", "id", ":", "refs", ".", "keySet", "(", ")", ")", "{", "putIfAbsent", "(", "id", ")", ";", "for", "(", "JpaRef", "ref", ":", "refs", ".", "get", "(", "id", ")", ")", "{", "putIfAbsent", "(", "ref", ".", "getTarget", "(", ")", ")", ";", "}", "}", "}" ]
Add references found from a partial query of bean references.
[ "Add", "references", "found", "from", "a", "partial", "query", "of", "bean", "references", "." ]
train
https://github.com/deephacks/confit/blob/4e6d4ee5fed32cbc5104433e61de1bcf1b360832/provider-jpa20/src/main/java/org/deephacks/confit/internal/jpa/JpaBeanQueryAssembler.java#L80-L88
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/FileUtils.java
FileUtils.toFile
public static File toFile(final URL aURL) throws MalformedURLException { """ Returns a Java <code>File</code> for the supplied file-based URL. @param aURL A URL that has a file protocol @return A Java <code>File</code> for the supplied URL @throws MalformedURLException If the supplied URL doesn't have a file protocol """ if (aURL.getProtocol().equals(FILE_TYPE)) { return new File(aURL.toString().replace("file:", "")); } throw new MalformedURLException(LOGGER.getI18n(MessageCodes.UTIL_036, aURL)); }
java
public static File toFile(final URL aURL) throws MalformedURLException { if (aURL.getProtocol().equals(FILE_TYPE)) { return new File(aURL.toString().replace("file:", "")); } throw new MalformedURLException(LOGGER.getI18n(MessageCodes.UTIL_036, aURL)); }
[ "public", "static", "File", "toFile", "(", "final", "URL", "aURL", ")", "throws", "MalformedURLException", "{", "if", "(", "aURL", ".", "getProtocol", "(", ")", ".", "equals", "(", "FILE_TYPE", ")", ")", "{", "return", "new", "File", "(", "aURL", ".", "toString", "(", ")", ".", "replace", "(", "\"file:\"", ",", "\"\"", ")", ")", ";", "}", "throw", "new", "MalformedURLException", "(", "LOGGER", ".", "getI18n", "(", "MessageCodes", ".", "UTIL_036", ",", "aURL", ")", ")", ";", "}" ]
Returns a Java <code>File</code> for the supplied file-based URL. @param aURL A URL that has a file protocol @return A Java <code>File</code> for the supplied URL @throws MalformedURLException If the supplied URL doesn't have a file protocol
[ "Returns", "a", "Java", "<code", ">", "File<", "/", "code", ">", "for", "the", "supplied", "file", "-", "based", "URL", "." ]
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L326-L332
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/jboss/logging/Logger.java
Logger.debugf
public void debugf(Throwable t, String format, Object... params) { """ Issue a formatted log message with a level of DEBUG. @param t the throwable @param format the format string, as per {@link String#format(String, Object...)} @param params the parameters """ doLogf(Level.DEBUG, FQCN, format, params, t); }
java
public void debugf(Throwable t, String format, Object... params) { doLogf(Level.DEBUG, FQCN, format, params, t); }
[ "public", "void", "debugf", "(", "Throwable", "t", ",", "String", "format", ",", "Object", "...", "params", ")", "{", "doLogf", "(", "Level", ".", "DEBUG", ",", "FQCN", ",", "format", ",", "params", ",", "t", ")", ";", "}" ]
Issue a formatted log message with a level of DEBUG. @param t the throwable @param format the format string, as per {@link String#format(String, Object...)} @param params the parameters
[ "Issue", "a", "formatted", "log", "message", "with", "a", "level", "of", "DEBUG", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L750-L752
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/HintedHandOffManager.java
HintedHandOffManager.hintFor
public Mutation hintFor(Mutation mutation, long now, int ttl, UUID targetId) { """ Returns a mutation representing a Hint to be sent to <code>targetId</code> as soon as it becomes available again. """ assert ttl > 0; InetAddress endpoint = StorageService.instance.getTokenMetadata().getEndpointForHostId(targetId); // during tests we may not have a matching endpoint, but this would be unexpected in real clusters if (endpoint != null) metrics.incrCreatedHints(endpoint); else logger.warn("Unable to find matching endpoint for target {} when storing a hint", targetId); UUID hintId = UUIDGen.getTimeUUID(); // serialize the hint with id and version as a composite column name CellName name = CFMetaData.HintsCf.comparator.makeCellName(hintId, MessagingService.current_version); ByteBuffer value = ByteBuffer.wrap(FBUtilities.serialize(mutation, Mutation.serializer, MessagingService.current_version)); ColumnFamily cf = ArrayBackedSortedColumns.factory.create(Schema.instance.getCFMetaData(Keyspace.SYSTEM_KS, SystemKeyspace.HINTS_CF)); cf.addColumn(name, value, now, ttl); return new Mutation(Keyspace.SYSTEM_KS, UUIDType.instance.decompose(targetId), cf); }
java
public Mutation hintFor(Mutation mutation, long now, int ttl, UUID targetId) { assert ttl > 0; InetAddress endpoint = StorageService.instance.getTokenMetadata().getEndpointForHostId(targetId); // during tests we may not have a matching endpoint, but this would be unexpected in real clusters if (endpoint != null) metrics.incrCreatedHints(endpoint); else logger.warn("Unable to find matching endpoint for target {} when storing a hint", targetId); UUID hintId = UUIDGen.getTimeUUID(); // serialize the hint with id and version as a composite column name CellName name = CFMetaData.HintsCf.comparator.makeCellName(hintId, MessagingService.current_version); ByteBuffer value = ByteBuffer.wrap(FBUtilities.serialize(mutation, Mutation.serializer, MessagingService.current_version)); ColumnFamily cf = ArrayBackedSortedColumns.factory.create(Schema.instance.getCFMetaData(Keyspace.SYSTEM_KS, SystemKeyspace.HINTS_CF)); cf.addColumn(name, value, now, ttl); return new Mutation(Keyspace.SYSTEM_KS, UUIDType.instance.decompose(targetId), cf); }
[ "public", "Mutation", "hintFor", "(", "Mutation", "mutation", ",", "long", "now", ",", "int", "ttl", ",", "UUID", "targetId", ")", "{", "assert", "ttl", ">", "0", ";", "InetAddress", "endpoint", "=", "StorageService", ".", "instance", ".", "getTokenMetadata", "(", ")", ".", "getEndpointForHostId", "(", "targetId", ")", ";", "// during tests we may not have a matching endpoint, but this would be unexpected in real clusters", "if", "(", "endpoint", "!=", "null", ")", "metrics", ".", "incrCreatedHints", "(", "endpoint", ")", ";", "else", "logger", ".", "warn", "(", "\"Unable to find matching endpoint for target {} when storing a hint\"", ",", "targetId", ")", ";", "UUID", "hintId", "=", "UUIDGen", ".", "getTimeUUID", "(", ")", ";", "// serialize the hint with id and version as a composite column name", "CellName", "name", "=", "CFMetaData", ".", "HintsCf", ".", "comparator", ".", "makeCellName", "(", "hintId", ",", "MessagingService", ".", "current_version", ")", ";", "ByteBuffer", "value", "=", "ByteBuffer", ".", "wrap", "(", "FBUtilities", ".", "serialize", "(", "mutation", ",", "Mutation", ".", "serializer", ",", "MessagingService", ".", "current_version", ")", ")", ";", "ColumnFamily", "cf", "=", "ArrayBackedSortedColumns", ".", "factory", ".", "create", "(", "Schema", ".", "instance", ".", "getCFMetaData", "(", "Keyspace", ".", "SYSTEM_KS", ",", "SystemKeyspace", ".", "HINTS_CF", ")", ")", ";", "cf", ".", "addColumn", "(", "name", ",", "value", ",", "now", ",", "ttl", ")", ";", "return", "new", "Mutation", "(", "Keyspace", ".", "SYSTEM_KS", ",", "UUIDType", ".", "instance", ".", "decompose", "(", "targetId", ")", ",", "cf", ")", ";", "}" ]
Returns a mutation representing a Hint to be sent to <code>targetId</code> as soon as it becomes available again.
[ "Returns", "a", "mutation", "representing", "a", "Hint", "to", "be", "sent", "to", "<code", ">", "targetId<", "/", "code", ">", "as", "soon", "as", "it", "becomes", "available", "again", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/HintedHandOffManager.java#L117-L135
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataXceiver.java
DataXceiver.copyBlock
private void copyBlock(DataInputStream in, VersionAndOpcode versionAndOpcode) throws IOException { """ Read a block from the disk and then sends it to a destination. @param in The stream to read from @throws IOException """ // Read in the header CopyBlockHeader copyBlockHeader = new CopyBlockHeader(versionAndOpcode); copyBlockHeader.readFields(in); long startTime = System.currentTimeMillis(); int namespaceId = copyBlockHeader.getNamespaceId(); long blockId = copyBlockHeader.getBlockId(); long genStamp = copyBlockHeader.getGenStamp(); Block block = new Block(blockId, 0, genStamp); if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to start LOG.info("Not able to copy block " + blockId + " to " + s.getRemoteSocketAddress() + " because threads quota is exceeded."); return; } BlockSender blockSender = null; DataOutputStream reply = null; boolean isOpSuccess = true; updateCurrentThreadName("Copying block " + block); try { // check if the block exists or not blockSender = new BlockSender(namespaceId, block, 0, -1, false, false, false, false, versionAndOpcode.getDataTransferVersion() >= DataTransferProtocol.PACKET_INCLUDE_VERSION_VERSION, true, datanode, null); // set up response stream OutputStream baseStream = NetUtils.getOutputStream( s, datanode.socketWriteTimeout); reply = new DataOutputStream(new BufferedOutputStream( baseStream, SMALL_BUFFER_SIZE)); // send block content to the target long read = blockSender.sendBlock(reply, baseStream, dataXceiverServer.balanceThrottler); long readDuration = System.currentTimeMillis() - startTime; datanode.myMetrics.bytesReadLatency.inc(readDuration); datanode.myMetrics.bytesRead.inc((int) read); if (read > KB_RIGHT_SHIFT_MIN) { datanode.myMetrics.bytesReadRate.inc((int) (read >> KB_RIGHT_SHIFT_BITS), readDuration); } datanode.myMetrics.blocksRead.inc(); LOG.info("Copied block " + block + " to " + s.getRemoteSocketAddress()); } catch (IOException ioe) { isOpSuccess = false; throw ioe; } finally { dataXceiverServer.balanceThrottler.release(); if (isOpSuccess) { try { // send one last byte to indicate that the resource is cleaned. reply.writeChar('d'); } catch (IOException ignored) { } } IOUtils.closeStream(reply); IOUtils.closeStream(blockSender); } }
java
private void copyBlock(DataInputStream in, VersionAndOpcode versionAndOpcode) throws IOException { // Read in the header CopyBlockHeader copyBlockHeader = new CopyBlockHeader(versionAndOpcode); copyBlockHeader.readFields(in); long startTime = System.currentTimeMillis(); int namespaceId = copyBlockHeader.getNamespaceId(); long blockId = copyBlockHeader.getBlockId(); long genStamp = copyBlockHeader.getGenStamp(); Block block = new Block(blockId, 0, genStamp); if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to start LOG.info("Not able to copy block " + blockId + " to " + s.getRemoteSocketAddress() + " because threads quota is exceeded."); return; } BlockSender blockSender = null; DataOutputStream reply = null; boolean isOpSuccess = true; updateCurrentThreadName("Copying block " + block); try { // check if the block exists or not blockSender = new BlockSender(namespaceId, block, 0, -1, false, false, false, false, versionAndOpcode.getDataTransferVersion() >= DataTransferProtocol.PACKET_INCLUDE_VERSION_VERSION, true, datanode, null); // set up response stream OutputStream baseStream = NetUtils.getOutputStream( s, datanode.socketWriteTimeout); reply = new DataOutputStream(new BufferedOutputStream( baseStream, SMALL_BUFFER_SIZE)); // send block content to the target long read = blockSender.sendBlock(reply, baseStream, dataXceiverServer.balanceThrottler); long readDuration = System.currentTimeMillis() - startTime; datanode.myMetrics.bytesReadLatency.inc(readDuration); datanode.myMetrics.bytesRead.inc((int) read); if (read > KB_RIGHT_SHIFT_MIN) { datanode.myMetrics.bytesReadRate.inc((int) (read >> KB_RIGHT_SHIFT_BITS), readDuration); } datanode.myMetrics.blocksRead.inc(); LOG.info("Copied block " + block + " to " + s.getRemoteSocketAddress()); } catch (IOException ioe) { isOpSuccess = false; throw ioe; } finally { dataXceiverServer.balanceThrottler.release(); if (isOpSuccess) { try { // send one last byte to indicate that the resource is cleaned. reply.writeChar('d'); } catch (IOException ignored) { } } IOUtils.closeStream(reply); IOUtils.closeStream(blockSender); } }
[ "private", "void", "copyBlock", "(", "DataInputStream", "in", ",", "VersionAndOpcode", "versionAndOpcode", ")", "throws", "IOException", "{", "// Read in the header", "CopyBlockHeader", "copyBlockHeader", "=", "new", "CopyBlockHeader", "(", "versionAndOpcode", ")", ";", "copyBlockHeader", ".", "readFields", "(", "in", ")", ";", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "int", "namespaceId", "=", "copyBlockHeader", ".", "getNamespaceId", "(", ")", ";", "long", "blockId", "=", "copyBlockHeader", ".", "getBlockId", "(", ")", ";", "long", "genStamp", "=", "copyBlockHeader", ".", "getGenStamp", "(", ")", ";", "Block", "block", "=", "new", "Block", "(", "blockId", ",", "0", ",", "genStamp", ")", ";", "if", "(", "!", "dataXceiverServer", ".", "balanceThrottler", ".", "acquire", "(", ")", ")", "{", "// not able to start", "LOG", ".", "info", "(", "\"Not able to copy block \"", "+", "blockId", "+", "\" to \"", "+", "s", ".", "getRemoteSocketAddress", "(", ")", "+", "\" because threads quota is exceeded.\"", ")", ";", "return", ";", "}", "BlockSender", "blockSender", "=", "null", ";", "DataOutputStream", "reply", "=", "null", ";", "boolean", "isOpSuccess", "=", "true", ";", "updateCurrentThreadName", "(", "\"Copying block \"", "+", "block", ")", ";", "try", "{", "// check if the block exists or not", "blockSender", "=", "new", "BlockSender", "(", "namespaceId", ",", "block", ",", "0", ",", "-", "1", ",", "false", ",", "false", ",", "false", ",", "false", ",", "versionAndOpcode", ".", "getDataTransferVersion", "(", ")", ">=", "DataTransferProtocol", ".", "PACKET_INCLUDE_VERSION_VERSION", ",", "true", ",", "datanode", ",", "null", ")", ";", "// set up response stream", "OutputStream", "baseStream", "=", "NetUtils", ".", "getOutputStream", "(", "s", ",", "datanode", ".", "socketWriteTimeout", ")", ";", "reply", "=", "new", "DataOutputStream", "(", "new", "BufferedOutputStream", "(", "baseStream", ",", "SMALL_BUFFER_SIZE", ")", ")", ";", "// send block content to the target", "long", "read", "=", "blockSender", ".", "sendBlock", "(", "reply", ",", "baseStream", ",", "dataXceiverServer", ".", "balanceThrottler", ")", ";", "long", "readDuration", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "startTime", ";", "datanode", ".", "myMetrics", ".", "bytesReadLatency", ".", "inc", "(", "readDuration", ")", ";", "datanode", ".", "myMetrics", ".", "bytesRead", ".", "inc", "(", "(", "int", ")", "read", ")", ";", "if", "(", "read", ">", "KB_RIGHT_SHIFT_MIN", ")", "{", "datanode", ".", "myMetrics", ".", "bytesReadRate", ".", "inc", "(", "(", "int", ")", "(", "read", ">>", "KB_RIGHT_SHIFT_BITS", ")", ",", "readDuration", ")", ";", "}", "datanode", ".", "myMetrics", ".", "blocksRead", ".", "inc", "(", ")", ";", "LOG", ".", "info", "(", "\"Copied block \"", "+", "block", "+", "\" to \"", "+", "s", ".", "getRemoteSocketAddress", "(", ")", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "isOpSuccess", "=", "false", ";", "throw", "ioe", ";", "}", "finally", "{", "dataXceiverServer", ".", "balanceThrottler", ".", "release", "(", ")", ";", "if", "(", "isOpSuccess", ")", "{", "try", "{", "// send one last byte to indicate that the resource is cleaned.", "reply", ".", "writeChar", "(", "'", "'", ")", ";", "}", "catch", "(", "IOException", "ignored", ")", "{", "}", "}", "IOUtils", ".", "closeStream", "(", "reply", ")", ";", "IOUtils", ".", "closeStream", "(", "blockSender", ")", ";", "}", "}" ]
Read a block from the disk and then sends it to a destination. @param in The stream to read from @throws IOException
[ "Read", "a", "block", "from", "the", "disk", "and", "then", "sends", "it", "to", "a", "destination", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataXceiver.java#L1107-L1172
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addConstraintsMod10CheckMessage
public FessMessages addConstraintsMod10CheckMessage(String property, String value) { """ Add the created action message for the key 'constraints.Mod10Check.message' with parameters. <pre> message: The check digit for ${value} is invalid, Modulo 10 checksum failed. </pre> @param property The property name for the message. (NotNull) @param value The parameter value for message. (NotNull) @return this. (NotNull) """ assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Mod10Check_MESSAGE, value)); return this; }
java
public FessMessages addConstraintsMod10CheckMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Mod10Check_MESSAGE, value)); return this; }
[ "public", "FessMessages", "addConstraintsMod10CheckMessage", "(", "String", "property", ",", "String", "value", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "CONSTRAINTS_Mod10Check_MESSAGE", ",", "value", ")", ")", ";", "return", "this", ";", "}" ]
Add the created action message for the key 'constraints.Mod10Check.message' with parameters. <pre> message: The check digit for ${value} is invalid, Modulo 10 checksum failed. </pre> @param property The property name for the message. (NotNull) @param value The parameter value for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "constraints", ".", "Mod10Check", ".", "message", "with", "parameters", ".", "<pre", ">", "message", ":", "The", "check", "digit", "for", "$", "{", "value", "}", "is", "invalid", "Modulo", "10", "checksum", "failed", ".", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L874-L878
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/traceinfo/ejbcontainer/TEBeanMetaDataInfo.java
TEBeanMetaDataInfo.writeMethodInfo
private static void writeMethodInfo(StringBuffer sbuf, EJBMethodInfoImpl methodInfos[]) { """ Writes all the method info data representd by <i>methodInfos</i> to <i>sbuf</i> """ if (methodInfos == null) { sbuf.append("" + -1).append(DataDelimiter); } else { int size = methodInfos.length; sbuf.append("" + size).append(DataDelimiter); for (int i = 0; i < size; ++i) { EJBMethodInfoImpl info = methodInfos[i]; sbuf .append(i).append(DataDelimiter) .append(info.getMethodName()).append(DataDelimiter) .append(info.getJDIMethodSignature()).append(DataDelimiter) .append(info.getTransactionAttribute().getValue()).append(DataDelimiter) .append(info.getActivitySessionAttribute().getValue()).append(DataDelimiter) .append(info.getIsolationLevel()).append(DataDelimiter) .append(info.getReadOnlyAttribute() ? "true" : "false").append(DataDelimiter); } } }
java
private static void writeMethodInfo(StringBuffer sbuf, EJBMethodInfoImpl methodInfos[]) { if (methodInfos == null) { sbuf.append("" + -1).append(DataDelimiter); } else { int size = methodInfos.length; sbuf.append("" + size).append(DataDelimiter); for (int i = 0; i < size; ++i) { EJBMethodInfoImpl info = methodInfos[i]; sbuf .append(i).append(DataDelimiter) .append(info.getMethodName()).append(DataDelimiter) .append(info.getJDIMethodSignature()).append(DataDelimiter) .append(info.getTransactionAttribute().getValue()).append(DataDelimiter) .append(info.getActivitySessionAttribute().getValue()).append(DataDelimiter) .append(info.getIsolationLevel()).append(DataDelimiter) .append(info.getReadOnlyAttribute() ? "true" : "false").append(DataDelimiter); } } }
[ "private", "static", "void", "writeMethodInfo", "(", "StringBuffer", "sbuf", ",", "EJBMethodInfoImpl", "methodInfos", "[", "]", ")", "{", "if", "(", "methodInfos", "==", "null", ")", "{", "sbuf", ".", "append", "(", "\"\"", "+", "-", "1", ")", ".", "append", "(", "DataDelimiter", ")", ";", "}", "else", "{", "int", "size", "=", "methodInfos", ".", "length", ";", "sbuf", ".", "append", "(", "\"\"", "+", "size", ")", ".", "append", "(", "DataDelimiter", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "++", "i", ")", "{", "EJBMethodInfoImpl", "info", "=", "methodInfos", "[", "i", "]", ";", "sbuf", ".", "append", "(", "i", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getMethodName", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getJDIMethodSignature", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getTransactionAttribute", "(", ")", ".", "getValue", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getActivitySessionAttribute", "(", ")", ".", "getValue", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getIsolationLevel", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getReadOnlyAttribute", "(", ")", "?", "\"true\"", ":", "\"false\"", ")", ".", "append", "(", "DataDelimiter", ")", ";", "}", "}", "}" ]
Writes all the method info data representd by <i>methodInfos</i> to <i>sbuf</i>
[ "Writes", "all", "the", "method", "info", "data", "representd", "by", "<i", ">", "methodInfos<", "/", "i", ">", "to", "<i", ">", "sbuf<", "/", "i", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/traceinfo/ejbcontainer/TEBeanMetaDataInfo.java#L51-L73
bmwcarit/joynr
java/core/libjoynr/src/main/java/io/joynr/proxy/ProxyInvocationHandlerImpl.java
ProxyInvocationHandlerImpl.executeSyncMethod
@CheckForNull private Object executeSyncMethod(Method method, Object[] args) throws ApplicationException { """ executeSyncMethod is called whenever a method of the synchronous interface which is provided by the proxy is called. The ProxyInvocationHandler will check the arbitration status before the call is delegated to the connector. If the arbitration is still in progress the synchronous call will block until the arbitration was successful or the timeout elapsed. @throws ApplicationException @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) """ if (preparingForShutdown.get()) { throw new JoynrIllegalStateException("Preparing for shutdown. Only stateless methods can be called."); } return executeMethodWithCaller(method, args, new ConnectorCaller() { @Override public Object call(Method method, Object[] args) throws ApplicationException { return connector.executeSyncMethod(method, args); } }); }
java
@CheckForNull private Object executeSyncMethod(Method method, Object[] args) throws ApplicationException { if (preparingForShutdown.get()) { throw new JoynrIllegalStateException("Preparing for shutdown. Only stateless methods can be called."); } return executeMethodWithCaller(method, args, new ConnectorCaller() { @Override public Object call(Method method, Object[] args) throws ApplicationException { return connector.executeSyncMethod(method, args); } }); }
[ "@", "CheckForNull", "private", "Object", "executeSyncMethod", "(", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "ApplicationException", "{", "if", "(", "preparingForShutdown", ".", "get", "(", ")", ")", "{", "throw", "new", "JoynrIllegalStateException", "(", "\"Preparing for shutdown. Only stateless methods can be called.\"", ")", ";", "}", "return", "executeMethodWithCaller", "(", "method", ",", "args", ",", "new", "ConnectorCaller", "(", ")", "{", "@", "Override", "public", "Object", "call", "(", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "ApplicationException", "{", "return", "connector", ".", "executeSyncMethod", "(", "method", ",", "args", ")", ";", "}", "}", ")", ";", "}" ]
executeSyncMethod is called whenever a method of the synchronous interface which is provided by the proxy is called. The ProxyInvocationHandler will check the arbitration status before the call is delegated to the connector. If the arbitration is still in progress the synchronous call will block until the arbitration was successful or the timeout elapsed. @throws ApplicationException @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
[ "executeSyncMethod", "is", "called", "whenever", "a", "method", "of", "the", "synchronous", "interface", "which", "is", "provided", "by", "the", "proxy", "is", "called", ".", "The", "ProxyInvocationHandler", "will", "check", "the", "arbitration", "status", "before", "the", "call", "is", "delegated", "to", "the", "connector", ".", "If", "the", "arbitration", "is", "still", "in", "progress", "the", "synchronous", "call", "will", "block", "until", "the", "arbitration", "was", "successful", "or", "the", "timeout", "elapsed", "." ]
train
https://github.com/bmwcarit/joynr/blob/b7a92bad1cf2f093de080facd2c803560f4c6c26/java/core/libjoynr/src/main/java/io/joynr/proxy/ProxyInvocationHandlerImpl.java#L143-L154
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/services/Services.java
Services.startServices
public static void startServices(IServiceManager manager) { """ Start the services associated to the given service manager. <p>This starting function supports the {@link DependentService prioritized services}. @param manager the manager of the services to start. """ final List<Service> otherServices = new ArrayList<>(); final List<Service> infraServices = new ArrayList<>(); final LinkedList<DependencyNode> serviceQueue = new LinkedList<>(); final Accessors accessors = new StartingPhaseAccessors(); // Build the dependency graph buildDependencyGraph(manager, serviceQueue, infraServices, otherServices, accessors); // Launch the services runDependencyGraph(serviceQueue, infraServices, otherServices, accessors); manager.awaitHealthy(); }
java
public static void startServices(IServiceManager manager) { final List<Service> otherServices = new ArrayList<>(); final List<Service> infraServices = new ArrayList<>(); final LinkedList<DependencyNode> serviceQueue = new LinkedList<>(); final Accessors accessors = new StartingPhaseAccessors(); // Build the dependency graph buildDependencyGraph(manager, serviceQueue, infraServices, otherServices, accessors); // Launch the services runDependencyGraph(serviceQueue, infraServices, otherServices, accessors); manager.awaitHealthy(); }
[ "public", "static", "void", "startServices", "(", "IServiceManager", "manager", ")", "{", "final", "List", "<", "Service", ">", "otherServices", "=", "new", "ArrayList", "<>", "(", ")", ";", "final", "List", "<", "Service", ">", "infraServices", "=", "new", "ArrayList", "<>", "(", ")", ";", "final", "LinkedList", "<", "DependencyNode", ">", "serviceQueue", "=", "new", "LinkedList", "<>", "(", ")", ";", "final", "Accessors", "accessors", "=", "new", "StartingPhaseAccessors", "(", ")", ";", "// Build the dependency graph", "buildDependencyGraph", "(", "manager", ",", "serviceQueue", ",", "infraServices", ",", "otherServices", ",", "accessors", ")", ";", "// Launch the services", "runDependencyGraph", "(", "serviceQueue", ",", "infraServices", ",", "otherServices", ",", "accessors", ")", ";", "manager", ".", "awaitHealthy", "(", ")", ";", "}" ]
Start the services associated to the given service manager. <p>This starting function supports the {@link DependentService prioritized services}. @param manager the manager of the services to start.
[ "Start", "the", "services", "associated", "to", "the", "given", "service", "manager", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/services/Services.java#L75-L88
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.doubleToLongFunction
public static DoubleToLongFunction doubleToLongFunction(CheckedDoubleToLongFunction function, Consumer<Throwable> handler) { """ Wrap a {@link CheckedDoubleToLongFunction} in a {@link DoubleToLongFunction} with a custom handler for checked exceptions. <p> Example: <code><pre> DoubleStream.of(1.0, 2.0, 3.0).mapToLong(Unchecked.doubleToLongFunction( d -> { if (d &lt; 0.0) throw new Exception("Only positive numbers allowed"); return (long) d; }, e -> { throw new IllegalStateException(e); } )); </pre></code> """ return t -> { try { return function.applyAsLong(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
java
public static DoubleToLongFunction doubleToLongFunction(CheckedDoubleToLongFunction function, Consumer<Throwable> handler) { return t -> { try { return function.applyAsLong(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
[ "public", "static", "DoubleToLongFunction", "doubleToLongFunction", "(", "CheckedDoubleToLongFunction", "function", ",", "Consumer", "<", "Throwable", ">", "handler", ")", "{", "return", "t", "->", "{", "try", "{", "return", "function", ".", "applyAsLong", "(", "t", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "handler", ".", "accept", "(", "e", ")", ";", "throw", "new", "IllegalStateException", "(", "\"Exception handler must throw a RuntimeException\"", ",", "e", ")", ";", "}", "}", ";", "}" ]
Wrap a {@link CheckedDoubleToLongFunction} in a {@link DoubleToLongFunction} with a custom handler for checked exceptions. <p> Example: <code><pre> DoubleStream.of(1.0, 2.0, 3.0).mapToLong(Unchecked.doubleToLongFunction( d -> { if (d &lt; 0.0) throw new Exception("Only positive numbers allowed"); return (long) d; }, e -> { throw new IllegalStateException(e); } )); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedDoubleToLongFunction", "}", "in", "a", "{", "@link", "DoubleToLongFunction", "}", "with", "a", "custom", "handler", "for", "checked", "exceptions", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "DoubleStream", ".", "of", "(", "1", ".", "0", "2", ".", "0", "3", ".", "0", ")", ".", "mapToLong", "(", "Unchecked", ".", "doubleToLongFunction", "(", "d", "-", ">", "{", "if", "(", "d", "&lt", ";", "0", ".", "0", ")", "throw", "new", "Exception", "(", "Only", "positive", "numbers", "allowed", ")", ";" ]
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1451-L1462
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java
XmlStringBuilder.attribute
public XmlStringBuilder attribute(String name, String value) { """ Does nothing if value is null. @param name @param value @return the XmlStringBuilder """ assert value != null; sb.append(' ').append(name).append("='"); escapeAttributeValue(value); sb.append('\''); return this; }
java
public XmlStringBuilder attribute(String name, String value) { assert value != null; sb.append(' ').append(name).append("='"); escapeAttributeValue(value); sb.append('\''); return this; }
[ "public", "XmlStringBuilder", "attribute", "(", "String", "name", ",", "String", "value", ")", "{", "assert", "value", "!=", "null", ";", "sb", ".", "append", "(", "'", "'", ")", ".", "append", "(", "name", ")", ".", "append", "(", "\"='\"", ")", ";", "escapeAttributeValue", "(", "value", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "return", "this", ";", "}" ]
Does nothing if value is null. @param name @param value @return the XmlStringBuilder
[ "Does", "nothing", "if", "value", "is", "null", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/XmlStringBuilder.java#L241-L247
ironjacamar/ironjacamar
common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java
AbstractParser.attributeAsInt
protected Integer attributeAsInt(XMLStreamReader reader, String attributeName, Map<String, String> expressions) throws XMLStreamException { """ convert an xml element in String value @param reader the StAX reader @param attributeName the name of the attribute @param expressions The expressions @return the string representing element @throws XMLStreamException StAX exception """ String attributeString = rawAttributeText(reader, attributeName); if (attributeName != null && expressions != null && attributeString != null && attributeString.indexOf("${") != -1) expressions.put(attributeName, attributeString); return attributeString != null ? Integer.valueOf(getSubstitutionValue(attributeString)) : null; }
java
protected Integer attributeAsInt(XMLStreamReader reader, String attributeName, Map<String, String> expressions) throws XMLStreamException { String attributeString = rawAttributeText(reader, attributeName); if (attributeName != null && expressions != null && attributeString != null && attributeString.indexOf("${") != -1) expressions.put(attributeName, attributeString); return attributeString != null ? Integer.valueOf(getSubstitutionValue(attributeString)) : null; }
[ "protected", "Integer", "attributeAsInt", "(", "XMLStreamReader", "reader", ",", "String", "attributeName", ",", "Map", "<", "String", ",", "String", ">", "expressions", ")", "throws", "XMLStreamException", "{", "String", "attributeString", "=", "rawAttributeText", "(", "reader", ",", "attributeName", ")", ";", "if", "(", "attributeName", "!=", "null", "&&", "expressions", "!=", "null", "&&", "attributeString", "!=", "null", "&&", "attributeString", ".", "indexOf", "(", "\"${\"", ")", "!=", "-", "1", ")", "expressions", ".", "put", "(", "attributeName", ",", "attributeString", ")", ";", "return", "attributeString", "!=", "null", "?", "Integer", ".", "valueOf", "(", "getSubstitutionValue", "(", "attributeString", ")", ")", ":", "null", ";", "}" ]
convert an xml element in String value @param reader the StAX reader @param attributeName the name of the attribute @param expressions The expressions @return the string representing element @throws XMLStreamException StAX exception
[ "convert", "an", "xml", "element", "in", "String", "value" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/common/AbstractParser.java#L217-L227
sarl/sarl
main/externalmaven/io.sarl.maven.docs.generator/src/main/java/io/sarl/maven/docs/markdown/MarkdownParser.java
MarkdownParser.transformMardownLinks
protected String transformMardownLinks(String content, ReferenceContext references) { """ Apply link transformation on the Markdown links. @param content the original content. @param references the references into the document. @return the result of the transformation. """ if (!isMarkdownToHtmlReferenceTransformation()) { return content; } // Prepare replacement data structures final Map<BasedSequence, String> replacements = new TreeMap<>((cmp1, cmp2) -> { final int cmp = Integer.compare(cmp2.getStartOffset(), cmp1.getStartOffset()); if (cmp != 0) { return cmp; } return Integer.compare(cmp2.getEndOffset(), cmp1.getEndOffset()); }); // Visit the links and record the transformations final MutableDataSet options = new MutableDataSet(); final Parser parser = Parser.builder(options).build(); final Node document = parser.parse(content); final NodeVisitor visitor = new NodeVisitor( new VisitHandler<>(Link.class, it -> { URL url = FileSystem.convertStringToURL(it.getUrl().toString(), true); url = transformURL(url, references); if (url != null) { replacements.put(it.getUrl(), convertURLToString(url)); } })); visitor.visitChildren(document); // Apply the replacements if (!replacements.isEmpty()) { final StringBuilder buffer = new StringBuilder(content); for (final Entry<BasedSequence, String> entry : replacements.entrySet()) { final BasedSequence seq = entry.getKey(); buffer.replace(seq.getStartOffset(), seq.getEndOffset(), entry.getValue()); } return buffer.toString(); } return content; }
java
protected String transformMardownLinks(String content, ReferenceContext references) { if (!isMarkdownToHtmlReferenceTransformation()) { return content; } // Prepare replacement data structures final Map<BasedSequence, String> replacements = new TreeMap<>((cmp1, cmp2) -> { final int cmp = Integer.compare(cmp2.getStartOffset(), cmp1.getStartOffset()); if (cmp != 0) { return cmp; } return Integer.compare(cmp2.getEndOffset(), cmp1.getEndOffset()); }); // Visit the links and record the transformations final MutableDataSet options = new MutableDataSet(); final Parser parser = Parser.builder(options).build(); final Node document = parser.parse(content); final NodeVisitor visitor = new NodeVisitor( new VisitHandler<>(Link.class, it -> { URL url = FileSystem.convertStringToURL(it.getUrl().toString(), true); url = transformURL(url, references); if (url != null) { replacements.put(it.getUrl(), convertURLToString(url)); } })); visitor.visitChildren(document); // Apply the replacements if (!replacements.isEmpty()) { final StringBuilder buffer = new StringBuilder(content); for (final Entry<BasedSequence, String> entry : replacements.entrySet()) { final BasedSequence seq = entry.getKey(); buffer.replace(seq.getStartOffset(), seq.getEndOffset(), entry.getValue()); } return buffer.toString(); } return content; }
[ "protected", "String", "transformMardownLinks", "(", "String", "content", ",", "ReferenceContext", "references", ")", "{", "if", "(", "!", "isMarkdownToHtmlReferenceTransformation", "(", ")", ")", "{", "return", "content", ";", "}", "// Prepare replacement data structures", "final", "Map", "<", "BasedSequence", ",", "String", ">", "replacements", "=", "new", "TreeMap", "<>", "(", "(", "cmp1", ",", "cmp2", ")", "->", "{", "final", "int", "cmp", "=", "Integer", ".", "compare", "(", "cmp2", ".", "getStartOffset", "(", ")", ",", "cmp1", ".", "getStartOffset", "(", ")", ")", ";", "if", "(", "cmp", "!=", "0", ")", "{", "return", "cmp", ";", "}", "return", "Integer", ".", "compare", "(", "cmp2", ".", "getEndOffset", "(", ")", ",", "cmp1", ".", "getEndOffset", "(", ")", ")", ";", "}", ")", ";", "// Visit the links and record the transformations", "final", "MutableDataSet", "options", "=", "new", "MutableDataSet", "(", ")", ";", "final", "Parser", "parser", "=", "Parser", ".", "builder", "(", "options", ")", ".", "build", "(", ")", ";", "final", "Node", "document", "=", "parser", ".", "parse", "(", "content", ")", ";", "final", "NodeVisitor", "visitor", "=", "new", "NodeVisitor", "(", "new", "VisitHandler", "<>", "(", "Link", ".", "class", ",", "it", "->", "{", "URL", "url", "=", "FileSystem", ".", "convertStringToURL", "(", "it", ".", "getUrl", "(", ")", ".", "toString", "(", ")", ",", "true", ")", ";", "url", "=", "transformURL", "(", "url", ",", "references", ")", ";", "if", "(", "url", "!=", "null", ")", "{", "replacements", ".", "put", "(", "it", ".", "getUrl", "(", ")", ",", "convertURLToString", "(", "url", ")", ")", ";", "}", "}", ")", ")", ";", "visitor", ".", "visitChildren", "(", "document", ")", ";", "// Apply the replacements", "if", "(", "!", "replacements", ".", "isEmpty", "(", ")", ")", "{", "final", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", "content", ")", ";", "for", "(", "final", "Entry", "<", "BasedSequence", ",", "String", ">", "entry", ":", "replacements", ".", "entrySet", "(", ")", ")", "{", "final", "BasedSequence", "seq", "=", "entry", ".", "getKey", "(", ")", ";", "buffer", ".", "replace", "(", "seq", ".", "getStartOffset", "(", ")", ",", "seq", ".", "getEndOffset", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "return", "buffer", ".", "toString", "(", ")", ";", "}", "return", "content", ";", "}" ]
Apply link transformation on the Markdown links. @param content the original content. @param references the references into the document. @return the result of the transformation.
[ "Apply", "link", "transformation", "on", "the", "Markdown", "links", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/externalmaven/io.sarl.maven.docs.generator/src/main/java/io/sarl/maven/docs/markdown/MarkdownParser.java#L608-L646
groupon/odo
proxylib/src/main/java/com/groupon/odo/proxylib/Utils.java
Utils.arrayFromStringOfIntegers
public static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException { """ Split string of comma-delimited ints into an a int array @param str @return @throws IllegalArgumentException """ StringTokenizer tokenizer = new StringTokenizer(str, ","); int n = tokenizer.countTokens(); int[] list = new int[n]; for (int i = 0; i < n; i++) { String token = tokenizer.nextToken(); list[i] = Integer.parseInt(token); } return list; }
java
public static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException { StringTokenizer tokenizer = new StringTokenizer(str, ","); int n = tokenizer.countTokens(); int[] list = new int[n]; for (int i = 0; i < n; i++) { String token = tokenizer.nextToken(); list[i] = Integer.parseInt(token); } return list; }
[ "public", "static", "int", "[", "]", "arrayFromStringOfIntegers", "(", "String", "str", ")", "throws", "IllegalArgumentException", "{", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "str", ",", "\",\"", ")", ";", "int", "n", "=", "tokenizer", ".", "countTokens", "(", ")", ";", "int", "[", "]", "list", "=", "new", "int", "[", "n", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "String", "token", "=", "tokenizer", ".", "nextToken", "(", ")", ";", "list", "[", "i", "]", "=", "Integer", ".", "parseInt", "(", "token", ")", ";", "}", "return", "list", ";", "}" ]
Split string of comma-delimited ints into an a int array @param str @return @throws IllegalArgumentException
[ "Split", "string", "of", "comma", "-", "delimited", "ints", "into", "an", "a", "int", "array" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/Utils.java#L44-L53
graknlabs/grakn
server/src/server/exception/TransactionException.java
TransactionException.transactionClosed
public static TransactionException transactionClosed(@Nullable TransactionOLTP tx, @Nullable String reason) { """ Thrown when attempting to use the graph when the transaction is closed """ if (reason == null) { Preconditions.checkNotNull(tx); return create(ErrorMessage.TX_CLOSED.getMessage(tx.keyspace())); } else { return create(reason); } }
java
public static TransactionException transactionClosed(@Nullable TransactionOLTP tx, @Nullable String reason) { if (reason == null) { Preconditions.checkNotNull(tx); return create(ErrorMessage.TX_CLOSED.getMessage(tx.keyspace())); } else { return create(reason); } }
[ "public", "static", "TransactionException", "transactionClosed", "(", "@", "Nullable", "TransactionOLTP", "tx", ",", "@", "Nullable", "String", "reason", ")", "{", "if", "(", "reason", "==", "null", ")", "{", "Preconditions", ".", "checkNotNull", "(", "tx", ")", ";", "return", "create", "(", "ErrorMessage", ".", "TX_CLOSED", ".", "getMessage", "(", "tx", ".", "keyspace", "(", ")", ")", ")", ";", "}", "else", "{", "return", "create", "(", "reason", ")", ";", "}", "}" ]
Thrown when attempting to use the graph when the transaction is closed
[ "Thrown", "when", "attempting", "to", "use", "the", "graph", "when", "the", "transaction", "is", "closed" ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/TransactionException.java#L215-L222
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java
AlertResources.deleteAllNotificationsByAlertId
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/ { """ Deletes all notifications for a given alert. @param req The HttpServlet request object. Cannot be null. @param alertId The alert id. Cannot be null and must be a positive non-zero number. @return Updated alert object. @throws WebApplicationException The exception with 404 status will be thrown if an alert does not exist. """alertId}/notifications") @Description("Deletes all notifications for the given alert ID. Associated triggers are not deleted from the alert.") public Response deleteAllNotificationsByAlertId(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId) { if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } Alert alert = alertService.findAlertByPrimaryKey(alertId); if (alert != null) { validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req)); alert.setNotifications(new ArrayList<Notification>(0)); alert.setModifiedBy(getRemoteUser(req)); alertService.updateAlert(alert); return Response.status(Status.OK).build(); } throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); }
java
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{alertId}/notifications") @Description("Deletes all notifications for the given alert ID. Associated triggers are not deleted from the alert.") public Response deleteAllNotificationsByAlertId(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId) { if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } Alert alert = alertService.findAlertByPrimaryKey(alertId); if (alert != null) { validateResourceAuthorization(req, alert.getOwner(), getRemoteUser(req)); alert.setNotifications(new ArrayList<Notification>(0)); alert.setModifiedBy(getRemoteUser(req)); alertService.updateAlert(alert); return Response.status(Status.OK).build(); } throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); }
[ "@", "DELETE", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Path", "(", "\"/{alertId}/notifications\"", ")", "@", "Description", "(", "\"Deletes all notifications for the given alert ID. Associated triggers are not deleted from the alert.\"", ")", "public", "Response", "deleteAllNotificationsByAlertId", "(", "@", "Context", "HttpServletRequest", "req", ",", "@", "PathParam", "(", "\"alertId\"", ")", "BigInteger", "alertId", ")", "{", "if", "(", "alertId", "==", "null", "||", "alertId", ".", "compareTo", "(", "BigInteger", ".", "ZERO", ")", "<", "1", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Alert Id cannot be null and must be a positive non-zero number.\"", ",", "Status", ".", "BAD_REQUEST", ")", ";", "}", "Alert", "alert", "=", "alertService", ".", "findAlertByPrimaryKey", "(", "alertId", ")", ";", "if", "(", "alert", "!=", "null", ")", "{", "validateResourceAuthorization", "(", "req", ",", "alert", ".", "getOwner", "(", ")", ",", "getRemoteUser", "(", "req", ")", ")", ";", "alert", ".", "setNotifications", "(", "new", "ArrayList", "<", "Notification", ">", "(", "0", ")", ")", ";", "alert", ".", "setModifiedBy", "(", "getRemoteUser", "(", "req", ")", ")", ";", "alertService", ".", "updateAlert", "(", "alert", ")", ";", "return", "Response", ".", "status", "(", "Status", ".", "OK", ")", ".", "build", "(", ")", ";", "}", "throw", "new", "WebApplicationException", "(", "Response", ".", "Status", ".", "NOT_FOUND", ".", "getReasonPhrase", "(", ")", ",", "Response", ".", "Status", ".", "NOT_FOUND", ")", ";", "}" ]
Deletes all notifications for a given alert. @param req The HttpServlet request object. Cannot be null. @param alertId The alert id. Cannot be null and must be a positive non-zero number. @return Updated alert object. @throws WebApplicationException The exception with 404 status will be thrown if an alert does not exist.
[ "Deletes", "all", "notifications", "for", "a", "given", "alert", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/AlertResources.java#L1010-L1030
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/template/TemplateGenerator.java
TemplateGenerator.generateTemplate
public static void generateTemplate( Reader readerTemplate, Writer writerOut, ISymbolTable symTable, boolean strict) throws TemplateParseException { """ Generates a template of any format having embedded Gosu. @param readerTemplate The source of the template. @param writerOut Where the output should go. @param symTable The symbol table to use. @param strict whether to allow althernative template @throws TemplateParseException on execution exception """ TemplateGenerator te = new TemplateGenerator( readerTemplate); te.setDisableAlternative(strict); te.execute( writerOut, symTable); }
java
public static void generateTemplate( Reader readerTemplate, Writer writerOut, ISymbolTable symTable, boolean strict) throws TemplateParseException { TemplateGenerator te = new TemplateGenerator( readerTemplate); te.setDisableAlternative(strict); te.execute( writerOut, symTable); }
[ "public", "static", "void", "generateTemplate", "(", "Reader", "readerTemplate", ",", "Writer", "writerOut", ",", "ISymbolTable", "symTable", ",", "boolean", "strict", ")", "throws", "TemplateParseException", "{", "TemplateGenerator", "te", "=", "new", "TemplateGenerator", "(", "readerTemplate", ")", ";", "te", ".", "setDisableAlternative", "(", "strict", ")", ";", "te", ".", "execute", "(", "writerOut", ",", "symTable", ")", ";", "}" ]
Generates a template of any format having embedded Gosu. @param readerTemplate The source of the template. @param writerOut Where the output should go. @param symTable The symbol table to use. @param strict whether to allow althernative template @throws TemplateParseException on execution exception
[ "Generates", "a", "template", "of", "any", "format", "having", "embedded", "Gosu", "." ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/template/TemplateGenerator.java#L178-L183
wisdom-framework/wisdom
framework/resource-controller/src/main/java/org/wisdom/resources/CacheUtils.java
CacheUtils.addCacheControlAndEtagToResult
public static void addCacheControlAndEtagToResult(Result result, String etag, ApplicationConfiguration configuration) { """ Adds cache control and etag to the given result. @param result the result @param etag the etag @param configuration the application configuration """ String maxAge = configuration.getWithDefault(HTTP_CACHE_CONTROL_MAX_AGE, HTTP_CACHE_CONTROL_DEFAULT); if ("0".equals(maxAge)) { result.with(HeaderNames.CACHE_CONTROL, "no-cache"); } else { result.with(HeaderNames.CACHE_CONTROL, "max-age=" + maxAge); } // Use etag on demand: boolean useEtag = configuration.getBooleanWithDefault(HTTP_USE_ETAG, HTTP_USE_ETAG_DEFAULT); if (useEtag) { result.with(HeaderNames.ETAG, etag); } }
java
public static void addCacheControlAndEtagToResult(Result result, String etag, ApplicationConfiguration configuration) { String maxAge = configuration.getWithDefault(HTTP_CACHE_CONTROL_MAX_AGE, HTTP_CACHE_CONTROL_DEFAULT); if ("0".equals(maxAge)) { result.with(HeaderNames.CACHE_CONTROL, "no-cache"); } else { result.with(HeaderNames.CACHE_CONTROL, "max-age=" + maxAge); } // Use etag on demand: boolean useEtag = configuration.getBooleanWithDefault(HTTP_USE_ETAG, HTTP_USE_ETAG_DEFAULT); if (useEtag) { result.with(HeaderNames.ETAG, etag); } }
[ "public", "static", "void", "addCacheControlAndEtagToResult", "(", "Result", "result", ",", "String", "etag", ",", "ApplicationConfiguration", "configuration", ")", "{", "String", "maxAge", "=", "configuration", ".", "getWithDefault", "(", "HTTP_CACHE_CONTROL_MAX_AGE", ",", "HTTP_CACHE_CONTROL_DEFAULT", ")", ";", "if", "(", "\"0\"", ".", "equals", "(", "maxAge", ")", ")", "{", "result", ".", "with", "(", "HeaderNames", ".", "CACHE_CONTROL", ",", "\"no-cache\"", ")", ";", "}", "else", "{", "result", ".", "with", "(", "HeaderNames", ".", "CACHE_CONTROL", ",", "\"max-age=\"", "+", "maxAge", ")", ";", "}", "// Use etag on demand:", "boolean", "useEtag", "=", "configuration", ".", "getBooleanWithDefault", "(", "HTTP_USE_ETAG", ",", "HTTP_USE_ETAG_DEFAULT", ")", ";", "if", "(", "useEtag", ")", "{", "result", ".", "with", "(", "HeaderNames", ".", "ETAG", ",", "etag", ")", ";", "}", "}" ]
Adds cache control and etag to the given result. @param result the result @param etag the etag @param configuration the application configuration
[ "Adds", "cache", "control", "and", "etag", "to", "the", "given", "result", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/resource-controller/src/main/java/org/wisdom/resources/CacheUtils.java#L127-L144
protostuff/protostuff
protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java
XmlIOUtil.writeTo
public static <T> void writeTo(OutputStream out, T message, Schema<T> schema) throws IOException { """ Serializes the {@code message} into an {@link OutputStream} using the given {@code schema}. """ writeTo(out, message, schema, DEFAULT_OUTPUT_FACTORY); }
java
public static <T> void writeTo(OutputStream out, T message, Schema<T> schema) throws IOException { writeTo(out, message, schema, DEFAULT_OUTPUT_FACTORY); }
[ "public", "static", "<", "T", ">", "void", "writeTo", "(", "OutputStream", "out", ",", "T", "message", ",", "Schema", "<", "T", ">", "schema", ")", "throws", "IOException", "{", "writeTo", "(", "out", ",", "message", ",", "schema", ",", "DEFAULT_OUTPUT_FACTORY", ")", ";", "}" ]
Serializes the {@code message} into an {@link OutputStream} using the given {@code schema}.
[ "Serializes", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java#L353-L357
plaid/plaid-java
src/main/java/com/plaid/client/internal/Util.java
Util.isPositive
public static void isPositive(Integer value, String name) { """ Checks that i is not null and is a positive number @param value The integer value to check. @param name The name of the variable being checked, included when an error is raised. @throws IllegalArgumentException If i is null or less than 0 """ notNull(value, name); if (value < 0) { throw new IllegalArgumentException(name + "must be a positive number."); } }
java
public static void isPositive(Integer value, String name) { notNull(value, name); if (value < 0) { throw new IllegalArgumentException(name + "must be a positive number."); } }
[ "public", "static", "void", "isPositive", "(", "Integer", "value", ",", "String", "name", ")", "{", "notNull", "(", "value", ",", "name", ")", ";", "if", "(", "value", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "name", "+", "\"must be a positive number.\"", ")", ";", "}", "}" ]
Checks that i is not null and is a positive number @param value The integer value to check. @param name The name of the variable being checked, included when an error is raised. @throws IllegalArgumentException If i is null or less than 0
[ "Checks", "that", "i", "is", "not", "null", "and", "is", "a", "positive", "number" ]
train
https://github.com/plaid/plaid-java/blob/360f1f8a5178fa0c3c2c2e07a58f8ccec5f33117/src/main/java/com/plaid/client/internal/Util.java#L92-L98
apache/spark
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java
ExternalShuffleBlockResolver.createNormalizedInternedPathname
@VisibleForTesting static String createNormalizedInternedPathname(String dir1, String dir2, String fname) { """ This method is needed to avoid the situation when multiple File instances for the same pathname "foo/bar" are created, each with a separate copy of the "foo/bar" String. According to measurements, in some scenarios such duplicate strings may waste a lot of memory (~ 10% of the heap). To avoid that, we intern the pathname, and before that we make sure that it's in a normalized form (contains no "//", "///" etc.) Otherwise, the internal code in java.io.File would normalize it later, creating a new "foo/bar" String copy. Unfortunately, we cannot just reuse the normalization code that java.io.File uses, since it is in the package-private class java.io.FileSystem. """ String pathname = dir1 + File.separator + dir2 + File.separator + fname; Matcher m = MULTIPLE_SEPARATORS.matcher(pathname); pathname = m.replaceAll("/"); // A single trailing slash needs to be taken care of separately if (pathname.length() > 1 && pathname.endsWith("/")) { pathname = pathname.substring(0, pathname.length() - 1); } return pathname.intern(); }
java
@VisibleForTesting static String createNormalizedInternedPathname(String dir1, String dir2, String fname) { String pathname = dir1 + File.separator + dir2 + File.separator + fname; Matcher m = MULTIPLE_SEPARATORS.matcher(pathname); pathname = m.replaceAll("/"); // A single trailing slash needs to be taken care of separately if (pathname.length() > 1 && pathname.endsWith("/")) { pathname = pathname.substring(0, pathname.length() - 1); } return pathname.intern(); }
[ "@", "VisibleForTesting", "static", "String", "createNormalizedInternedPathname", "(", "String", "dir1", ",", "String", "dir2", ",", "String", "fname", ")", "{", "String", "pathname", "=", "dir1", "+", "File", ".", "separator", "+", "dir2", "+", "File", ".", "separator", "+", "fname", ";", "Matcher", "m", "=", "MULTIPLE_SEPARATORS", ".", "matcher", "(", "pathname", ")", ";", "pathname", "=", "m", ".", "replaceAll", "(", "\"/\"", ")", ";", "// A single trailing slash needs to be taken care of separately", "if", "(", "pathname", ".", "length", "(", ")", ">", "1", "&&", "pathname", ".", "endsWith", "(", "\"/\"", ")", ")", "{", "pathname", "=", "pathname", ".", "substring", "(", "0", ",", "pathname", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "pathname", ".", "intern", "(", ")", ";", "}" ]
This method is needed to avoid the situation when multiple File instances for the same pathname "foo/bar" are created, each with a separate copy of the "foo/bar" String. According to measurements, in some scenarios such duplicate strings may waste a lot of memory (~ 10% of the heap). To avoid that, we intern the pathname, and before that we make sure that it's in a normalized form (contains no "//", "///" etc.) Otherwise, the internal code in java.io.File would normalize it later, creating a new "foo/bar" String copy. Unfortunately, we cannot just reuse the normalization code that java.io.File uses, since it is in the package-private class java.io.FileSystem.
[ "This", "method", "is", "needed", "to", "avoid", "the", "situation", "when", "multiple", "File", "instances", "for", "the", "same", "pathname", "foo", "/", "bar", "are", "created", "each", "with", "a", "separate", "copy", "of", "the", "foo", "/", "bar", "String", ".", "According", "to", "measurements", "in", "some", "scenarios", "such", "duplicate", "strings", "may", "waste", "a", "lot", "of", "memory", "(", "~", "10%", "of", "the", "heap", ")", ".", "To", "avoid", "that", "we", "intern", "the", "pathname", "and", "before", "that", "we", "make", "sure", "that", "it", "s", "in", "a", "normalized", "form", "(", "contains", "no", "//", "///", "etc", ".", ")", "Otherwise", "the", "internal", "code", "in", "java", ".", "io", ".", "File", "would", "normalize", "it", "later", "creating", "a", "new", "foo", "/", "bar", "String", "copy", ".", "Unfortunately", "we", "cannot", "just", "reuse", "the", "normalization", "code", "that", "java", ".", "io", ".", "File", "uses", "since", "it", "is", "in", "the", "package", "-", "private", "class", "java", ".", "io", ".", "FileSystem", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java#L334-L344
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/IdentityHashMap.java
IdentityHashMap.put
public V put(K key, V value) { """ Associates the specified value with the specified key in this identity hash map. If the map previously contained a mapping for the key, the old value is replaced. @param key the key with which the specified value is to be associated @param value the value to be associated with the specified key @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) @see Object#equals(Object) @see #get(Object) @see #containsKey(Object) """ final Object k = maskNull(key); retryAfterResize: for (;;) { final Object[] tab = table; final int len = tab.length; int i = hash(k, len); for (Object item; (item = tab[i]) != null; i = nextKeyIndex(i, len)) { if (item == k) { @SuppressWarnings("unchecked") V oldValue = (V) tab[i + 1]; tab[i + 1] = value; return oldValue; } } final int s = size + 1; // Use optimized form of 3 * s. // Next capacity is len, 2 * current capacity. if (s + (s << 1) > len && resize(len)) continue retryAfterResize; modCount++; tab[i] = k; tab[i + 1] = value; size = s; return null; } }
java
public V put(K key, V value) { final Object k = maskNull(key); retryAfterResize: for (;;) { final Object[] tab = table; final int len = tab.length; int i = hash(k, len); for (Object item; (item = tab[i]) != null; i = nextKeyIndex(i, len)) { if (item == k) { @SuppressWarnings("unchecked") V oldValue = (V) tab[i + 1]; tab[i + 1] = value; return oldValue; } } final int s = size + 1; // Use optimized form of 3 * s. // Next capacity is len, 2 * current capacity. if (s + (s << 1) > len && resize(len)) continue retryAfterResize; modCount++; tab[i] = k; tab[i + 1] = value; size = s; return null; } }
[ "public", "V", "put", "(", "K", "key", ",", "V", "value", ")", "{", "final", "Object", "k", "=", "maskNull", "(", "key", ")", ";", "retryAfterResize", ":", "for", "(", ";", ";", ")", "{", "final", "Object", "[", "]", "tab", "=", "table", ";", "final", "int", "len", "=", "tab", ".", "length", ";", "int", "i", "=", "hash", "(", "k", ",", "len", ")", ";", "for", "(", "Object", "item", ";", "(", "item", "=", "tab", "[", "i", "]", ")", "!=", "null", ";", "i", "=", "nextKeyIndex", "(", "i", ",", "len", ")", ")", "{", "if", "(", "item", "==", "k", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "V", "oldValue", "=", "(", "V", ")", "tab", "[", "i", "+", "1", "]", ";", "tab", "[", "i", "+", "1", "]", "=", "value", ";", "return", "oldValue", ";", "}", "}", "final", "int", "s", "=", "size", "+", "1", ";", "// Use optimized form of 3 * s.", "// Next capacity is len, 2 * current capacity.", "if", "(", "s", "+", "(", "s", "<<", "1", ")", ">", "len", "&&", "resize", "(", "len", ")", ")", "continue", "retryAfterResize", ";", "modCount", "++", ";", "tab", "[", "i", "]", "=", "k", ";", "tab", "[", "i", "+", "1", "]", "=", "value", ";", "size", "=", "s", ";", "return", "null", ";", "}", "}" ]
Associates the specified value with the specified key in this identity hash map. If the map previously contained a mapping for the key, the old value is replaced. @param key the key with which the specified value is to be associated @param value the value to be associated with the specified key @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) @see Object#equals(Object) @see #get(Object) @see #containsKey(Object)
[ "Associates", "the", "specified", "value", "with", "the", "specified", "key", "in", "this", "identity", "hash", "map", ".", "If", "the", "map", "previously", "contained", "a", "mapping", "for", "the", "key", "the", "old", "value", "is", "replaced", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/IdentityHashMap.java#L425-L455
bramp/objectgraph
src/main/java/net/bramp/objectgraph/ObjectGraph.java
ObjectGraph.addIfNotVisited
private void addIfNotVisited(Object object, Class<?> clazz) { """ Add this object to be visited if it has not already been visited, or scheduled to be. @param object The object @param clazz The type of the field """ if (object != null && !visited.containsKey(object)) { toVisit.add(object); visited.put(object, clazz); } }
java
private void addIfNotVisited(Object object, Class<?> clazz) { if (object != null && !visited.containsKey(object)) { toVisit.add(object); visited.put(object, clazz); } }
[ "private", "void", "addIfNotVisited", "(", "Object", "object", ",", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "object", "!=", "null", "&&", "!", "visited", ".", "containsKey", "(", "object", ")", ")", "{", "toVisit", ".", "add", "(", "object", ")", ";", "visited", ".", "put", "(", "object", ",", "clazz", ")", ";", "}", "}" ]
Add this object to be visited if it has not already been visited, or scheduled to be. @param object The object @param clazz The type of the field
[ "Add", "this", "object", "to", "be", "visited", "if", "it", "has", "not", "already", "been", "visited", "or", "scheduled", "to", "be", "." ]
train
https://github.com/bramp/objectgraph/blob/99be3a76db934f5fb33c0dccd974592cab5761d1/src/main/java/net/bramp/objectgraph/ObjectGraph.java#L161-L166
alkacon/opencms-core
src/org/opencms/security/CmsDefaultPasswordGenerator.java
CmsDefaultPasswordGenerator.getRandomPassword
public String getRandomPassword(int countTotal, int countCapitals, int countSpecials) { """ Generates a random password.<p> @param countTotal Total password length @param countCapitals Minimal count of capitals @param countSpecials count of special chars @return random password """ String res = ""; String[] Normals = ArrayUtils.addAll(ArrayUtils.addAll(Capitals, Letters), Numbers); Random rand = new Random(); for (int i = 0; i < (countTotal - countCapitals - countSpecials); i++) { res = res + Normals[rand.nextInt(Normals.length)]; } for (int i = 0; i < countSpecials; i++) { int pos = rand.nextInt(res.length()); res = res.substring(0, pos) + Specials[rand.nextInt(Specials.length)] + res.substring(pos); } for (int i = 0; i < countCapitals; i++) { int pos = rand.nextInt(res.length()); res = res.substring(0, pos) + Capitals[rand.nextInt(Capitals.length)] + res.substring(pos); } return res; }
java
public String getRandomPassword(int countTotal, int countCapitals, int countSpecials) { String res = ""; String[] Normals = ArrayUtils.addAll(ArrayUtils.addAll(Capitals, Letters), Numbers); Random rand = new Random(); for (int i = 0; i < (countTotal - countCapitals - countSpecials); i++) { res = res + Normals[rand.nextInt(Normals.length)]; } for (int i = 0; i < countSpecials; i++) { int pos = rand.nextInt(res.length()); res = res.substring(0, pos) + Specials[rand.nextInt(Specials.length)] + res.substring(pos); } for (int i = 0; i < countCapitals; i++) { int pos = rand.nextInt(res.length()); res = res.substring(0, pos) + Capitals[rand.nextInt(Capitals.length)] + res.substring(pos); } return res; }
[ "public", "String", "getRandomPassword", "(", "int", "countTotal", ",", "int", "countCapitals", ",", "int", "countSpecials", ")", "{", "String", "res", "=", "\"\"", ";", "String", "[", "]", "Normals", "=", "ArrayUtils", ".", "addAll", "(", "ArrayUtils", ".", "addAll", "(", "Capitals", ",", "Letters", ")", ",", "Numbers", ")", ";", "Random", "rand", "=", "new", "Random", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "(", "countTotal", "-", "countCapitals", "-", "countSpecials", ")", ";", "i", "++", ")", "{", "res", "=", "res", "+", "Normals", "[", "rand", ".", "nextInt", "(", "Normals", ".", "length", ")", "]", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "countSpecials", ";", "i", "++", ")", "{", "int", "pos", "=", "rand", ".", "nextInt", "(", "res", ".", "length", "(", ")", ")", ";", "res", "=", "res", ".", "substring", "(", "0", ",", "pos", ")", "+", "Specials", "[", "rand", ".", "nextInt", "(", "Specials", ".", "length", ")", "]", "+", "res", ".", "substring", "(", "pos", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "countCapitals", ";", "i", "++", ")", "{", "int", "pos", "=", "rand", ".", "nextInt", "(", "res", ".", "length", "(", ")", ")", ";", "res", "=", "res", ".", "substring", "(", "0", ",", "pos", ")", "+", "Capitals", "[", "rand", ".", "nextInt", "(", "Capitals", ".", "length", ")", "]", "+", "res", ".", "substring", "(", "pos", ")", ";", "}", "return", "res", ";", "}" ]
Generates a random password.<p> @param countTotal Total password length @param countCapitals Minimal count of capitals @param countSpecials count of special chars @return random password
[ "Generates", "a", "random", "password", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsDefaultPasswordGenerator.java#L158-L176
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/ReturnUrl.java
ReturnUrl.deleteOrderItemUrl
public static MozuUrl deleteOrderItemUrl(String returnId, String returnItemId) { """ Get Resource Url for DeleteOrderItem @param returnId Unique identifier of the return whose items you want to get. @param returnItemId Unique identifier of the return item whose details you want to get. @return String Resource Url """ UrlFormatter formatter = new UrlFormatter("/api/commerce/returns/{orderId}/items/{orderItemId}?updatemode={updateMode}&version={version}"); formatter.formatUrl("returnId", returnId); formatter.formatUrl("returnItemId", returnItemId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteOrderItemUrl(String returnId, String returnItemId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/returns/{orderId}/items/{orderItemId}?updatemode={updateMode}&version={version}"); formatter.formatUrl("returnId", returnId); formatter.formatUrl("returnItemId", returnItemId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "deleteOrderItemUrl", "(", "String", "returnId", ",", "String", "returnItemId", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/returns/{orderId}/items/{orderItemId}?updatemode={updateMode}&version={version}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"returnId\"", ",", "returnId", ")", ";", "formatter", ".", "formatUrl", "(", "\"returnItemId\"", ",", "returnItemId", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for DeleteOrderItem @param returnId Unique identifier of the return whose items you want to get. @param returnItemId Unique identifier of the return item whose details you want to get. @return String Resource Url
[ "Get", "Resource", "Url", "for", "DeleteOrderItem" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/ReturnUrl.java#L262-L268
paypal/SeLion
dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ExcelDataProviderImpl.java
ExcelDataProviderImpl.getSingleExcelRow
protected Object getSingleExcelRow(Object userObj, int index, boolean isExternalCall) { """ @param userObj The User defined object into which the data is to be packed into. @param index The row number from the excel sheet that is to be read. For e.g., if you wanted to read the 2nd row (which is where your data exists) in your excel sheet, the value for index would be 1. <b>This method assumes that your excel sheet would have a header which it would EXCLUDE.</b> When specifying index value always remember to ignore the header, since this method will look for a particular row ignoring the header row. @param isExternalCall A boolean that helps distinguish internally if the call is being made internally or by the user. @return An object that represents the data for a given row in the excel sheet. """ int newIndex = index; if (isExternalCall) { newIndex++; } logger.entering(new Object[] { userObj, newIndex }); Object obj; Class<?> cls; try { cls = Class.forName(userObj.getClass().getName()); } catch (ClassNotFoundException e) { throw new DataProviderException("Unable to find class of type + '" + userObj.getClass().getName() + "'", e); } Field[] fields = cls.getDeclaredFields(); List<String> excelHeaderRow = getHeaderRowContents(cls.getSimpleName(), fields.length); List<String> excelRowData = getRowContents(cls.getSimpleName(), newIndex, fields.length); Map<String, String> headerRowDataMap = prepareHeaderRowDataMap(excelHeaderRow, excelRowData); if (excelRowData != null && excelRowData.size() != 0) { try { obj = prepareObject(userObj, fields, excelRowData, headerRowDataMap); } catch (IllegalAccessException e) { throw new DataProviderException("Unable to create instance of type '" + userObj.getClass().getName() + "'", e); } } else { throw new DataProviderException("Row with key '" + newIndex + "' is not found"); } logger.exiting(obj); return obj; }
java
protected Object getSingleExcelRow(Object userObj, int index, boolean isExternalCall) { int newIndex = index; if (isExternalCall) { newIndex++; } logger.entering(new Object[] { userObj, newIndex }); Object obj; Class<?> cls; try { cls = Class.forName(userObj.getClass().getName()); } catch (ClassNotFoundException e) { throw new DataProviderException("Unable to find class of type + '" + userObj.getClass().getName() + "'", e); } Field[] fields = cls.getDeclaredFields(); List<String> excelHeaderRow = getHeaderRowContents(cls.getSimpleName(), fields.length); List<String> excelRowData = getRowContents(cls.getSimpleName(), newIndex, fields.length); Map<String, String> headerRowDataMap = prepareHeaderRowDataMap(excelHeaderRow, excelRowData); if (excelRowData != null && excelRowData.size() != 0) { try { obj = prepareObject(userObj, fields, excelRowData, headerRowDataMap); } catch (IllegalAccessException e) { throw new DataProviderException("Unable to create instance of type '" + userObj.getClass().getName() + "'", e); } } else { throw new DataProviderException("Row with key '" + newIndex + "' is not found"); } logger.exiting(obj); return obj; }
[ "protected", "Object", "getSingleExcelRow", "(", "Object", "userObj", ",", "int", "index", ",", "boolean", "isExternalCall", ")", "{", "int", "newIndex", "=", "index", ";", "if", "(", "isExternalCall", ")", "{", "newIndex", "++", ";", "}", "logger", ".", "entering", "(", "new", "Object", "[", "]", "{", "userObj", ",", "newIndex", "}", ")", ";", "Object", "obj", ";", "Class", "<", "?", ">", "cls", ";", "try", "{", "cls", "=", "Class", ".", "forName", "(", "userObj", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "throw", "new", "DataProviderException", "(", "\"Unable to find class of type + '\"", "+", "userObj", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\"'\"", ",", "e", ")", ";", "}", "Field", "[", "]", "fields", "=", "cls", ".", "getDeclaredFields", "(", ")", ";", "List", "<", "String", ">", "excelHeaderRow", "=", "getHeaderRowContents", "(", "cls", ".", "getSimpleName", "(", ")", ",", "fields", ".", "length", ")", ";", "List", "<", "String", ">", "excelRowData", "=", "getRowContents", "(", "cls", ".", "getSimpleName", "(", ")", ",", "newIndex", ",", "fields", ".", "length", ")", ";", "Map", "<", "String", ",", "String", ">", "headerRowDataMap", "=", "prepareHeaderRowDataMap", "(", "excelHeaderRow", ",", "excelRowData", ")", ";", "if", "(", "excelRowData", "!=", "null", "&&", "excelRowData", ".", "size", "(", ")", "!=", "0", ")", "{", "try", "{", "obj", "=", "prepareObject", "(", "userObj", ",", "fields", ",", "excelRowData", ",", "headerRowDataMap", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "DataProviderException", "(", "\"Unable to create instance of type '\"", "+", "userObj", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\"'\"", ",", "e", ")", ";", "}", "}", "else", "{", "throw", "new", "DataProviderException", "(", "\"Row with key '\"", "+", "newIndex", "+", "\"' is not found\"", ")", ";", "}", "logger", ".", "exiting", "(", "obj", ")", ";", "return", "obj", ";", "}" ]
@param userObj The User defined object into which the data is to be packed into. @param index The row number from the excel sheet that is to be read. For e.g., if you wanted to read the 2nd row (which is where your data exists) in your excel sheet, the value for index would be 1. <b>This method assumes that your excel sheet would have a header which it would EXCLUDE.</b> When specifying index value always remember to ignore the header, since this method will look for a particular row ignoring the header row. @param isExternalCall A boolean that helps distinguish internally if the call is being made internally or by the user. @return An object that represents the data for a given row in the excel sheet.
[ "@param", "userObj", "The", "User", "defined", "object", "into", "which", "the", "data", "is", "to", "be", "packed", "into", ".", "@param", "index", "The", "row", "number", "from", "the", "excel", "sheet", "that", "is", "to", "be", "read", ".", "For", "e", ".", "g", ".", "if", "you", "wanted", "to", "read", "the", "2nd", "row", "(", "which", "is", "where", "your", "data", "exists", ")", "in", "your", "excel", "sheet", "the", "value", "for", "index", "would", "be", "1", ".", "<b", ">", "This", "method", "assumes", "that", "your", "excel", "sheet", "would", "have", "a", "header", "which", "it", "would", "EXCLUDE", ".", "<", "/", "b", ">", "When", "specifying", "index", "value", "always", "remember", "to", "ignore", "the", "header", "since", "this", "method", "will", "look", "for", "a", "particular", "row", "ignoring", "the", "header", "row", ".", "@param", "isExternalCall", "A", "boolean", "that", "helps", "distinguish", "internally", "if", "the", "call", "is", "being", "made", "internally", "or", "by", "the", "user", "." ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ExcelDataProviderImpl.java#L422-L456
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/TSDBEntity.java
TSDBEntity.setTags
public void setTags(Map<String, String> tags) { """ Replaces the tags for a metric. Tags cannot use any of the reserved tag names. @param tags The new tags for the metric. """ TSDBEntity.validateTags(tags); _tags.clear(); if (tags != null) { _tags.putAll(tags); } }
java
public void setTags(Map<String, String> tags) { TSDBEntity.validateTags(tags); _tags.clear(); if (tags != null) { _tags.putAll(tags); } }
[ "public", "void", "setTags", "(", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "TSDBEntity", ".", "validateTags", "(", "tags", ")", ";", "_tags", ".", "clear", "(", ")", ";", "if", "(", "tags", "!=", "null", ")", "{", "_tags", ".", "putAll", "(", "tags", ")", ";", "}", "}" ]
Replaces the tags for a metric. Tags cannot use any of the reserved tag names. @param tags The new tags for the metric.
[ "Replaces", "the", "tags", "for", "a", "metric", ".", "Tags", "cannot", "use", "any", "of", "the", "reserved", "tag", "names", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/TSDBEntity.java#L155-L162
cdk/cdk
tool/charges/src/main/java/org/openscience/cdk/charges/Electronegativity.java
Electronegativity.calculateSigmaElectronegativity
public double calculateSigmaElectronegativity(IAtomContainer ac, IAtom atom) { """ calculate the electronegativity of orbitals sigma. @param ac IAtomContainer @param atom atom for which effective atom electronegativity should be calculated @return piElectronegativity """ return calculateSigmaElectronegativity(ac, atom, maxI, maxRS); }
java
public double calculateSigmaElectronegativity(IAtomContainer ac, IAtom atom) { return calculateSigmaElectronegativity(ac, atom, maxI, maxRS); }
[ "public", "double", "calculateSigmaElectronegativity", "(", "IAtomContainer", "ac", ",", "IAtom", "atom", ")", "{", "return", "calculateSigmaElectronegativity", "(", "ac", ",", "atom", ",", "maxI", ",", "maxRS", ")", ";", "}" ]
calculate the electronegativity of orbitals sigma. @param ac IAtomContainer @param atom atom for which effective atom electronegativity should be calculated @return piElectronegativity
[ "calculate", "the", "electronegativity", "of", "orbitals", "sigma", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/charges/src/main/java/org/openscience/cdk/charges/Electronegativity.java#L78-L81
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram/support/SimpleClickSupport.java
SimpleClickSupport.onClick
public void onClick(View targetView, BaseCell cell, int eventType) { """ Handler click event on item @param targetView the view that trigger the click event, not the view respond the cell! @param cell the corresponding cell @param eventType click event type, defined by developer. """ if (cell instanceof Cell) { onClick(targetView, (Cell) cell, eventType); } else { onClick(targetView, cell, eventType, null); } }
java
public void onClick(View targetView, BaseCell cell, int eventType) { if (cell instanceof Cell) { onClick(targetView, (Cell) cell, eventType); } else { onClick(targetView, cell, eventType, null); } }
[ "public", "void", "onClick", "(", "View", "targetView", ",", "BaseCell", "cell", ",", "int", "eventType", ")", "{", "if", "(", "cell", "instanceof", "Cell", ")", "{", "onClick", "(", "targetView", ",", "(", "Cell", ")", "cell", ",", "eventType", ")", ";", "}", "else", "{", "onClick", "(", "targetView", ",", "cell", ",", "eventType", ",", "null", ")", ";", "}", "}" ]
Handler click event on item @param targetView the view that trigger the click event, not the view respond the cell! @param cell the corresponding cell @param eventType click event type, defined by developer.
[ "Handler", "click", "event", "on", "item" ]
train
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram/support/SimpleClickSupport.java#L124-L130
trellis-ldp/trellis
components/webdav/src/main/java/org/trellisldp/webdav/TrellisWebDAV.java
TrellisWebDAV.updateProperties
@PROPPATCH @Consumes( { """ Update properties on a resource. @param response the async response @param request the request @param uriInfo the URI info @param headers the headers @param security the security context @param propertyUpdate the property update request @throws ParserConfigurationException if the XML parser is not properly configured """APPLICATION_XML}) @Produces({APPLICATION_XML}) @Timed public void updateProperties(@Suspended final AsyncResponse response, @Context final Request request, @Context final UriInfo uriInfo, @Context final HttpHeaders headers, @Context final SecurityContext security, final DavPropertyUpdate propertyUpdate) throws ParserConfigurationException { final Document doc = getDocument(); final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security); final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath()); final String baseUrl = getBaseUrl(req); final String location = fromUri(baseUrl).path(req.getPath()).build().toString(); final Session session = getSession(req.getPrincipalName()); services.getResourceService().get(identifier) .thenApply(this::checkResource) .thenCompose(resourceToMultiStatus(doc, identifier, location, baseUrl, session, propertyUpdate)) .thenApply(multistatus -> status(MULTI_STATUS).entity(multistatus).build()) .exceptionally(this::handleException).thenApply(response::resume); }
java
@PROPPATCH @Consumes({APPLICATION_XML}) @Produces({APPLICATION_XML}) @Timed public void updateProperties(@Suspended final AsyncResponse response, @Context final Request request, @Context final UriInfo uriInfo, @Context final HttpHeaders headers, @Context final SecurityContext security, final DavPropertyUpdate propertyUpdate) throws ParserConfigurationException { final Document doc = getDocument(); final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security); final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath()); final String baseUrl = getBaseUrl(req); final String location = fromUri(baseUrl).path(req.getPath()).build().toString(); final Session session = getSession(req.getPrincipalName()); services.getResourceService().get(identifier) .thenApply(this::checkResource) .thenCompose(resourceToMultiStatus(doc, identifier, location, baseUrl, session, propertyUpdate)) .thenApply(multistatus -> status(MULTI_STATUS).entity(multistatus).build()) .exceptionally(this::handleException).thenApply(response::resume); }
[ "@", "PROPPATCH", "@", "Consumes", "(", "{", "APPLICATION_XML", "}", ")", "@", "Produces", "(", "{", "APPLICATION_XML", "}", ")", "@", "Timed", "public", "void", "updateProperties", "(", "@", "Suspended", "final", "AsyncResponse", "response", ",", "@", "Context", "final", "Request", "request", ",", "@", "Context", "final", "UriInfo", "uriInfo", ",", "@", "Context", "final", "HttpHeaders", "headers", ",", "@", "Context", "final", "SecurityContext", "security", ",", "final", "DavPropertyUpdate", "propertyUpdate", ")", "throws", "ParserConfigurationException", "{", "final", "Document", "doc", "=", "getDocument", "(", ")", ";", "final", "TrellisRequest", "req", "=", "new", "TrellisRequest", "(", "request", ",", "uriInfo", ",", "headers", ",", "security", ")", ";", "final", "IRI", "identifier", "=", "rdf", ".", "createIRI", "(", "TRELLIS_DATA_PREFIX", "+", "req", ".", "getPath", "(", ")", ")", ";", "final", "String", "baseUrl", "=", "getBaseUrl", "(", "req", ")", ";", "final", "String", "location", "=", "fromUri", "(", "baseUrl", ")", ".", "path", "(", "req", ".", "getPath", "(", ")", ")", ".", "build", "(", ")", ".", "toString", "(", ")", ";", "final", "Session", "session", "=", "getSession", "(", "req", ".", "getPrincipalName", "(", ")", ")", ";", "services", ".", "getResourceService", "(", ")", ".", "get", "(", "identifier", ")", ".", "thenApply", "(", "this", "::", "checkResource", ")", ".", "thenCompose", "(", "resourceToMultiStatus", "(", "doc", ",", "identifier", ",", "location", ",", "baseUrl", ",", "session", ",", "propertyUpdate", ")", ")", ".", "thenApply", "(", "multistatus", "->", "status", "(", "MULTI_STATUS", ")", ".", "entity", "(", "multistatus", ")", ".", "build", "(", ")", ")", ".", "exceptionally", "(", "this", "::", "handleException", ")", ".", "thenApply", "(", "response", "::", "resume", ")", ";", "}" ]
Update properties on a resource. @param response the async response @param request the request @param uriInfo the URI info @param headers the headers @param security the security context @param propertyUpdate the property update request @throws ParserConfigurationException if the XML parser is not properly configured
[ "Update", "properties", "on", "a", "resource", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/webdav/src/main/java/org/trellisldp/webdav/TrellisWebDAV.java#L266-L286
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/attribute/map/MapfishMapContext.java
MapfishMapContext.getRotatedBounds
public MapBounds getRotatedBounds(final Rectangle2D.Double paintAreaPrecise, final Rectangle paintArea) { """ Return the map bounds rotated with the set rotation. The bounds are adapted to rounding changes of the size of the paint area. @param paintAreaPrecise The exact size of the paint area. @param paintArea The rounded size of the paint area. @return Rotated bounds. """ final MapBounds rotatedBounds = this.getRotatedBounds(); if (rotatedBounds instanceof CenterScaleMapBounds) { return rotatedBounds; } final ReferencedEnvelope envelope = ((BBoxMapBounds) rotatedBounds).toReferencedEnvelope(null); // the paint area size and the map bounds are rotated independently. because // the paint area size is rounded to integers, the map bounds have to be adjusted // to these rounding changes. final double widthRatio = paintArea.getWidth() / paintAreaPrecise.getWidth(); final double heightRatio = paintArea.getHeight() / paintAreaPrecise.getHeight(); final double adaptedWidth = envelope.getWidth() * widthRatio; final double adaptedHeight = envelope.getHeight() * heightRatio; final double widthDiff = adaptedWidth - envelope.getWidth(); final double heigthDiff = adaptedHeight - envelope.getHeight(); envelope.expandBy(widthDiff / 2.0, heigthDiff / 2.0); return new BBoxMapBounds(envelope); }
java
public MapBounds getRotatedBounds(final Rectangle2D.Double paintAreaPrecise, final Rectangle paintArea) { final MapBounds rotatedBounds = this.getRotatedBounds(); if (rotatedBounds instanceof CenterScaleMapBounds) { return rotatedBounds; } final ReferencedEnvelope envelope = ((BBoxMapBounds) rotatedBounds).toReferencedEnvelope(null); // the paint area size and the map bounds are rotated independently. because // the paint area size is rounded to integers, the map bounds have to be adjusted // to these rounding changes. final double widthRatio = paintArea.getWidth() / paintAreaPrecise.getWidth(); final double heightRatio = paintArea.getHeight() / paintAreaPrecise.getHeight(); final double adaptedWidth = envelope.getWidth() * widthRatio; final double adaptedHeight = envelope.getHeight() * heightRatio; final double widthDiff = adaptedWidth - envelope.getWidth(); final double heigthDiff = adaptedHeight - envelope.getHeight(); envelope.expandBy(widthDiff / 2.0, heigthDiff / 2.0); return new BBoxMapBounds(envelope); }
[ "public", "MapBounds", "getRotatedBounds", "(", "final", "Rectangle2D", ".", "Double", "paintAreaPrecise", ",", "final", "Rectangle", "paintArea", ")", "{", "final", "MapBounds", "rotatedBounds", "=", "this", ".", "getRotatedBounds", "(", ")", ";", "if", "(", "rotatedBounds", "instanceof", "CenterScaleMapBounds", ")", "{", "return", "rotatedBounds", ";", "}", "final", "ReferencedEnvelope", "envelope", "=", "(", "(", "BBoxMapBounds", ")", "rotatedBounds", ")", ".", "toReferencedEnvelope", "(", "null", ")", ";", "// the paint area size and the map bounds are rotated independently. because", "// the paint area size is rounded to integers, the map bounds have to be adjusted", "// to these rounding changes.", "final", "double", "widthRatio", "=", "paintArea", ".", "getWidth", "(", ")", "/", "paintAreaPrecise", ".", "getWidth", "(", ")", ";", "final", "double", "heightRatio", "=", "paintArea", ".", "getHeight", "(", ")", "/", "paintAreaPrecise", ".", "getHeight", "(", ")", ";", "final", "double", "adaptedWidth", "=", "envelope", ".", "getWidth", "(", ")", "*", "widthRatio", ";", "final", "double", "adaptedHeight", "=", "envelope", ".", "getHeight", "(", ")", "*", "heightRatio", ";", "final", "double", "widthDiff", "=", "adaptedWidth", "-", "envelope", ".", "getWidth", "(", ")", ";", "final", "double", "heigthDiff", "=", "adaptedHeight", "-", "envelope", ".", "getHeight", "(", ")", ";", "envelope", ".", "expandBy", "(", "widthDiff", "/", "2.0", ",", "heigthDiff", "/", "2.0", ")", ";", "return", "new", "BBoxMapBounds", "(", "envelope", ")", ";", "}" ]
Return the map bounds rotated with the set rotation. The bounds are adapted to rounding changes of the size of the paint area. @param paintAreaPrecise The exact size of the paint area. @param paintArea The rounded size of the paint area. @return Rotated bounds.
[ "Return", "the", "map", "bounds", "rotated", "with", "the", "set", "rotation", ".", "The", "bounds", "are", "adapted", "to", "rounding", "changes", "of", "the", "size", "of", "the", "paint", "area", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/attribute/map/MapfishMapContext.java#L150-L172
js-lib-com/commons
src/main/java/js/lang/Config.java
Config.getProperty
public <T> T getProperty(String name, Class<T> type) { """ Get configuration object property converter to requested type or null if there is no property with given name. @param name property name. @param type type to convert property value to. @param <T> value type. @return newly created value object or null. @throws IllegalArgumentException if <code>name</code> argument is null or empty. @throws IllegalArgumentException if <code>type</code> argument is null. @throws ConverterException if there is no converter registered for value type or value parse fails. """ return getProperty(name, type, null); }
java
public <T> T getProperty(String name, Class<T> type) { return getProperty(name, type, null); }
[ "public", "<", "T", ">", "T", "getProperty", "(", "String", "name", ",", "Class", "<", "T", ">", "type", ")", "{", "return", "getProperty", "(", "name", ",", "type", ",", "null", ")", ";", "}" ]
Get configuration object property converter to requested type or null if there is no property with given name. @param name property name. @param type type to convert property value to. @param <T> value type. @return newly created value object or null. @throws IllegalArgumentException if <code>name</code> argument is null or empty. @throws IllegalArgumentException if <code>type</code> argument is null. @throws ConverterException if there is no converter registered for value type or value parse fails.
[ "Get", "configuration", "object", "property", "converter", "to", "requested", "type", "or", "null", "if", "there", "is", "no", "property", "with", "given", "name", "." ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/lang/Config.java#L409-L412
basho/riak-java-client
src/main/java/com/basho/riak/client/api/convert/reflection/AnnotationUtil.java
AnnotationUtil.populateLinks
public static <T> T populateLinks(RiakLinks links, T domainObject) { """ Attempts to populate a domain object with riak links by looking for a {@literal @RiakLinks} annotated member. @param <T> the type of the domain object @param links a collection of RiakLink objects @param domainObject the domain object @return the domain object """ return AnnotationHelper.getInstance().setLinks(links, domainObject); }
java
public static <T> T populateLinks(RiakLinks links, T domainObject) { return AnnotationHelper.getInstance().setLinks(links, domainObject); }
[ "public", "static", "<", "T", ">", "T", "populateLinks", "(", "RiakLinks", "links", ",", "T", "domainObject", ")", "{", "return", "AnnotationHelper", ".", "getInstance", "(", ")", ".", "setLinks", "(", "links", ",", "domainObject", ")", ";", "}" ]
Attempts to populate a domain object with riak links by looking for a {@literal @RiakLinks} annotated member. @param <T> the type of the domain object @param links a collection of RiakLink objects @param domainObject the domain object @return the domain object
[ "Attempts", "to", "populate", "a", "domain", "object", "with", "riak", "links", "by", "looking", "for", "a", "{", "@literal", "@RiakLinks", "}", "annotated", "member", "." ]
train
https://github.com/basho/riak-java-client/blob/bed6cd60f360bacf1b873ab92dd74f2526651e71/src/main/java/com/basho/riak/client/api/convert/reflection/AnnotationUtil.java#L251-L254
sebastiangraf/jSCSI
bundles/commons/src/main/java/org/jscsi/parser/AdditionalHeaderSegment.java
AdditionalHeaderSegment.deserialize
final void deserialize (final ByteBuffer pdu, final int offset) throws InternetSCSIException { """ Extract the informations given by the int array to this Additional Header Segment object. @param pdu The Protocol Data Unit to be parsed. @param offset The offset, where to start in the pdu. @throws InternetSCSIException If any violation of the iSCSI-Standard emerge. """ pdu.position(offset); length = pdu.getShort(); type = AdditionalHeaderSegmentType.valueOf(pdu.get()); // allocate the needed memory specificField = ByteBuffer.allocate(length); specificField.put(pdu.get()); // deserialize the type specific fields while (specificField.hasRemaining()) { specificField.putInt(pdu.getInt()); } checkIntegrity(); }
java
final void deserialize (final ByteBuffer pdu, final int offset) throws InternetSCSIException { pdu.position(offset); length = pdu.getShort(); type = AdditionalHeaderSegmentType.valueOf(pdu.get()); // allocate the needed memory specificField = ByteBuffer.allocate(length); specificField.put(pdu.get()); // deserialize the type specific fields while (specificField.hasRemaining()) { specificField.putInt(pdu.getInt()); } checkIntegrity(); }
[ "final", "void", "deserialize", "(", "final", "ByteBuffer", "pdu", ",", "final", "int", "offset", ")", "throws", "InternetSCSIException", "{", "pdu", ".", "position", "(", "offset", ")", ";", "length", "=", "pdu", ".", "getShort", "(", ")", ";", "type", "=", "AdditionalHeaderSegmentType", ".", "valueOf", "(", "pdu", ".", "get", "(", ")", ")", ";", "// allocate the needed memory", "specificField", "=", "ByteBuffer", ".", "allocate", "(", "length", ")", ";", "specificField", ".", "put", "(", "pdu", ".", "get", "(", ")", ")", ";", "// deserialize the type specific fields", "while", "(", "specificField", ".", "hasRemaining", "(", ")", ")", "{", "specificField", ".", "putInt", "(", "pdu", ".", "getInt", "(", ")", ")", ";", "}", "checkIntegrity", "(", ")", ";", "}" ]
Extract the informations given by the int array to this Additional Header Segment object. @param pdu The Protocol Data Unit to be parsed. @param offset The offset, where to start in the pdu. @throws InternetSCSIException If any violation of the iSCSI-Standard emerge.
[ "Extract", "the", "informations", "given", "by", "the", "int", "array", "to", "this", "Additional", "Header", "Segment", "object", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/commons/src/main/java/org/jscsi/parser/AdditionalHeaderSegment.java#L238-L254
cryptomator/cryptofs
src/main/java/org/cryptomator/cryptofs/ConflictResolver.java
ConflictResolver.resolveConflict
private Path resolveConflict(Path conflictingPath, String ciphertextFileName, String dirId) throws IOException { """ Resolves a conflict. @param conflictingPath The path of a file containing a valid base 32 part. @param ciphertextFileName The base32 part inside the filename of the conflicting file. @param dirId The directory id of the file's parent directory. @return The new path of the conflicting file after the conflict has been resolved. @throws IOException """ String conflictingFileName = conflictingPath.getFileName().toString(); Preconditions.checkArgument(conflictingFileName.contains(ciphertextFileName), "%s does not contain %s", conflictingPath, ciphertextFileName); Path parent = conflictingPath.getParent(); String inflatedFileName; Path canonicalPath; if (longFileNameProvider.isDeflated(conflictingFileName)) { String deflatedName = ciphertextFileName + LONG_NAME_FILE_EXT; inflatedFileName = longFileNameProvider.inflate(deflatedName); canonicalPath = parent.resolve(deflatedName); } else { inflatedFileName = ciphertextFileName; canonicalPath = parent.resolve(ciphertextFileName); } CiphertextFileType type = CiphertextFileType.forFileName(inflatedFileName); assert inflatedFileName.startsWith(type.getPrefix()); String ciphertext = inflatedFileName.substring(type.getPrefix().length()); if (CiphertextFileType.DIRECTORY.equals(type) && resolveDirectoryConflictTrivially(canonicalPath, conflictingPath)) { return canonicalPath; } else { return renameConflictingFile(canonicalPath, conflictingPath, ciphertext, dirId, type.getPrefix()); } }
java
private Path resolveConflict(Path conflictingPath, String ciphertextFileName, String dirId) throws IOException { String conflictingFileName = conflictingPath.getFileName().toString(); Preconditions.checkArgument(conflictingFileName.contains(ciphertextFileName), "%s does not contain %s", conflictingPath, ciphertextFileName); Path parent = conflictingPath.getParent(); String inflatedFileName; Path canonicalPath; if (longFileNameProvider.isDeflated(conflictingFileName)) { String deflatedName = ciphertextFileName + LONG_NAME_FILE_EXT; inflatedFileName = longFileNameProvider.inflate(deflatedName); canonicalPath = parent.resolve(deflatedName); } else { inflatedFileName = ciphertextFileName; canonicalPath = parent.resolve(ciphertextFileName); } CiphertextFileType type = CiphertextFileType.forFileName(inflatedFileName); assert inflatedFileName.startsWith(type.getPrefix()); String ciphertext = inflatedFileName.substring(type.getPrefix().length()); if (CiphertextFileType.DIRECTORY.equals(type) && resolveDirectoryConflictTrivially(canonicalPath, conflictingPath)) { return canonicalPath; } else { return renameConflictingFile(canonicalPath, conflictingPath, ciphertext, dirId, type.getPrefix()); } }
[ "private", "Path", "resolveConflict", "(", "Path", "conflictingPath", ",", "String", "ciphertextFileName", ",", "String", "dirId", ")", "throws", "IOException", "{", "String", "conflictingFileName", "=", "conflictingPath", ".", "getFileName", "(", ")", ".", "toString", "(", ")", ";", "Preconditions", ".", "checkArgument", "(", "conflictingFileName", ".", "contains", "(", "ciphertextFileName", ")", ",", "\"%s does not contain %s\"", ",", "conflictingPath", ",", "ciphertextFileName", ")", ";", "Path", "parent", "=", "conflictingPath", ".", "getParent", "(", ")", ";", "String", "inflatedFileName", ";", "Path", "canonicalPath", ";", "if", "(", "longFileNameProvider", ".", "isDeflated", "(", "conflictingFileName", ")", ")", "{", "String", "deflatedName", "=", "ciphertextFileName", "+", "LONG_NAME_FILE_EXT", ";", "inflatedFileName", "=", "longFileNameProvider", ".", "inflate", "(", "deflatedName", ")", ";", "canonicalPath", "=", "parent", ".", "resolve", "(", "deflatedName", ")", ";", "}", "else", "{", "inflatedFileName", "=", "ciphertextFileName", ";", "canonicalPath", "=", "parent", ".", "resolve", "(", "ciphertextFileName", ")", ";", "}", "CiphertextFileType", "type", "=", "CiphertextFileType", ".", "forFileName", "(", "inflatedFileName", ")", ";", "assert", "inflatedFileName", ".", "startsWith", "(", "type", ".", "getPrefix", "(", ")", ")", ";", "String", "ciphertext", "=", "inflatedFileName", ".", "substring", "(", "type", ".", "getPrefix", "(", ")", ".", "length", "(", ")", ")", ";", "if", "(", "CiphertextFileType", ".", "DIRECTORY", ".", "equals", "(", "type", ")", "&&", "resolveDirectoryConflictTrivially", "(", "canonicalPath", ",", "conflictingPath", ")", ")", "{", "return", "canonicalPath", ";", "}", "else", "{", "return", "renameConflictingFile", "(", "canonicalPath", ",", "conflictingPath", ",", "ciphertext", ",", "dirId", ",", "type", ".", "getPrefix", "(", ")", ")", ";", "}", "}" ]
Resolves a conflict. @param conflictingPath The path of a file containing a valid base 32 part. @param ciphertextFileName The base32 part inside the filename of the conflicting file. @param dirId The directory id of the file's parent directory. @return The new path of the conflicting file after the conflict has been resolved. @throws IOException
[ "Resolves", "a", "conflict", "." ]
train
https://github.com/cryptomator/cryptofs/blob/67fc1a4950dd1c150cd2e2c75bcabbeb7c9ac82e/src/main/java/org/cryptomator/cryptofs/ConflictResolver.java#L72-L97
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/sql/SqlGeneratorDefaultImpl.java
SqlGeneratorDefaultImpl.getPreparedSelectStatement
public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld) { """ generate a select-Statement according to query @param query the Query @param cld the ClassDescriptor """ SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger); if (logger.isDebugEnabled()) { logger.debug("SQL:" + sql.getStatement()); } return sql; }
java
public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld) { SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger); if (logger.isDebugEnabled()) { logger.debug("SQL:" + sql.getStatement()); } return sql; }
[ "public", "SelectStatement", "getPreparedSelectStatement", "(", "Query", "query", ",", "ClassDescriptor", "cld", ")", "{", "SelectStatement", "sql", "=", "new", "SqlSelectStatement", "(", "m_platform", ",", "cld", ",", "query", ",", "logger", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"SQL:\"", "+", "sql", ".", "getStatement", "(", ")", ")", ";", "}", "return", "sql", ";", "}" ]
generate a select-Statement according to query @param query the Query @param cld the ClassDescriptor
[ "generate", "a", "select", "-", "Statement", "according", "to", "query" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlGeneratorDefaultImpl.java#L186-L194
landawn/AbacusUtil
src/com/landawn/abacus/util/stream/Collectors.java
Collectors.distinctBy
public static <T> Collector<T, ?, List<T>> distinctBy(final Function<? super T, ?> mapper) { """ It's copied from StreamEx: https://github.com/amaembo/streamex under Apache License v2 and may be modified. <br /> Returns a {@code Collector} which collects into the {@link List} the input elements for which given mapper function returns distinct results. <p> For ordered source the order of collected elements is preserved. If the same result is returned by mapper function for several elements, only the first element is included into the resulting list. <p> There are no guarantees on the type, mutability, serializability, or thread-safety of the {@code List} returned. <p> The operation performed by the returned collector is equivalent to {@code stream.distinct(mapper).toList()}, but may work faster. @param <T> the type of the input elements @param mapper a function which classifies input elements. @return a collector which collects distinct elements to the {@code List}. @since 0.3.8 """ @SuppressWarnings("rawtypes") final Supplier<Map<Object, T>> supplier = (Supplier) Suppliers.<Object, T> ofLinkedHashMap(); final BiConsumer<Map<Object, T>, T> accumulator = new BiConsumer<Map<Object, T>, T>() { @Override public void accept(Map<Object, T> map, T t) { final Object key = mapper.apply(t); if (map.containsKey(key) == false) { map.put(key, t); } } }; final BinaryOperator<Map<Object, T>> combiner = new BinaryOperator<Map<Object, T>>() { @Override public Map<Object, T> apply(Map<Object, T> a, Map<Object, T> b) { for (Map.Entry<Object, T> entry : b.entrySet()) { if (a.containsKey(entry.getKey()) == false) { a.put(entry.getKey(), entry.getValue()); } } return a; } }; final Function<Map<Object, T>, List<T>> finisher = new Function<Map<Object, T>, List<T>>() { @Override public List<T> apply(Map<Object, T> map) { return new ArrayList<>(map.values()); } }; return new CollectorImpl<>(supplier, accumulator, combiner, finisher, CH_UNORDERED_NOID); }
java
public static <T> Collector<T, ?, List<T>> distinctBy(final Function<? super T, ?> mapper) { @SuppressWarnings("rawtypes") final Supplier<Map<Object, T>> supplier = (Supplier) Suppliers.<Object, T> ofLinkedHashMap(); final BiConsumer<Map<Object, T>, T> accumulator = new BiConsumer<Map<Object, T>, T>() { @Override public void accept(Map<Object, T> map, T t) { final Object key = mapper.apply(t); if (map.containsKey(key) == false) { map.put(key, t); } } }; final BinaryOperator<Map<Object, T>> combiner = new BinaryOperator<Map<Object, T>>() { @Override public Map<Object, T> apply(Map<Object, T> a, Map<Object, T> b) { for (Map.Entry<Object, T> entry : b.entrySet()) { if (a.containsKey(entry.getKey()) == false) { a.put(entry.getKey(), entry.getValue()); } } return a; } }; final Function<Map<Object, T>, List<T>> finisher = new Function<Map<Object, T>, List<T>>() { @Override public List<T> apply(Map<Object, T> map) { return new ArrayList<>(map.values()); } }; return new CollectorImpl<>(supplier, accumulator, combiner, finisher, CH_UNORDERED_NOID); }
[ "public", "static", "<", "T", ">", "Collector", "<", "T", ",", "?", ",", "List", "<", "T", ">", ">", "distinctBy", "(", "final", "Function", "<", "?", "super", "T", ",", "?", ">", "mapper", ")", "{", "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "final", "Supplier", "<", "Map", "<", "Object", ",", "T", ">", ">", "supplier", "=", "(", "Supplier", ")", "Suppliers", ".", "<", "Object", ",", "T", ">", "ofLinkedHashMap", "(", ")", ";", "final", "BiConsumer", "<", "Map", "<", "Object", ",", "T", ">", ",", "T", ">", "accumulator", "=", "new", "BiConsumer", "<", "Map", "<", "Object", ",", "T", ">", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "Map", "<", "Object", ",", "T", ">", "map", ",", "T", "t", ")", "{", "final", "Object", "key", "=", "mapper", ".", "apply", "(", "t", ")", ";", "if", "(", "map", ".", "containsKey", "(", "key", ")", "==", "false", ")", "{", "map", ".", "put", "(", "key", ",", "t", ")", ";", "}", "}", "}", ";", "final", "BinaryOperator", "<", "Map", "<", "Object", ",", "T", ">", ">", "combiner", "=", "new", "BinaryOperator", "<", "Map", "<", "Object", ",", "T", ">", ">", "(", ")", "{", "@", "Override", "public", "Map", "<", "Object", ",", "T", ">", "apply", "(", "Map", "<", "Object", ",", "T", ">", "a", ",", "Map", "<", "Object", ",", "T", ">", "b", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "T", ">", "entry", ":", "b", ".", "entrySet", "(", ")", ")", "{", "if", "(", "a", ".", "containsKey", "(", "entry", ".", "getKey", "(", ")", ")", "==", "false", ")", "{", "a", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "return", "a", ";", "}", "}", ";", "final", "Function", "<", "Map", "<", "Object", ",", "T", ">", ",", "List", "<", "T", ">", ">", "finisher", "=", "new", "Function", "<", "Map", "<", "Object", ",", "T", ">", ",", "List", "<", "T", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "T", ">", "apply", "(", "Map", "<", "Object", ",", "T", ">", "map", ")", "{", "return", "new", "ArrayList", "<>", "(", "map", ".", "values", "(", ")", ")", ";", "}", "}", ";", "return", "new", "CollectorImpl", "<>", "(", "supplier", ",", "accumulator", ",", "combiner", ",", "finisher", ",", "CH_UNORDERED_NOID", ")", ";", "}" ]
It's copied from StreamEx: https://github.com/amaembo/streamex under Apache License v2 and may be modified. <br /> Returns a {@code Collector} which collects into the {@link List} the input elements for which given mapper function returns distinct results. <p> For ordered source the order of collected elements is preserved. If the same result is returned by mapper function for several elements, only the first element is included into the resulting list. <p> There are no guarantees on the type, mutability, serializability, or thread-safety of the {@code List} returned. <p> The operation performed by the returned collector is equivalent to {@code stream.distinct(mapper).toList()}, but may work faster. @param <T> the type of the input elements @param mapper a function which classifies input elements. @return a collector which collects distinct elements to the {@code List}. @since 0.3.8
[ "It", "s", "copied", "from", "StreamEx", ":", "https", ":", "//", "github", ".", "com", "/", "amaembo", "/", "streamex", "under", "Apache", "License", "v2", "and", "may", "be", "modified", ".", "<br", "/", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/stream/Collectors.java#L1826-L1862
facebookarchive/hive-dwrf
hive-dwrf/src/main/java/com/facebook/hive/orc/MemoryManager.java
MemoryManager.addWriter
synchronized void addWriter(final Path path, final long requestedAllocation, final Callback callback, final long initialAllocation) throws IOException { """ Add a new writer's memory allocation to the pool. We use the path as a unique key to ensure that we don't get duplicates. @param path the file that is being written @param requestedAllocation the requested buffer size @param initialAllocation the current size of the buffer """ WriterInfo oldVal = writerList.get(path); // this should always be null, but we handle the case where the memory // manager wasn't told that a writer wasn't still in use and the task // starts writing to the same path. if (oldVal == null) { LOG.info("Registering writer for path " + path.toString()); oldVal = new WriterInfo(requestedAllocation, callback); writerList.put(path, oldVal); totalAllocation += requestedAllocation; } else { // handle a new writer that is writing to the same path totalAllocation += requestedAllocation - oldVal.allocation; oldVal.setAllocation(requestedAllocation); oldVal.setCallback(callback); } updateScale(true); // If we're not already in low memory mode, and the initial allocation already exceeds the // allocation, enter low memory mode to try to avoid an OOM if (!lowMemoryMode && requestedAllocation * currentScale <= initialAllocation) { lowMemoryMode = true; LOG.info("ORC: Switching to low memory mode"); for (WriterInfo writer : writerList.values()) { writer.callback.enterLowMemoryMode(); } } }
java
synchronized void addWriter(final Path path, final long requestedAllocation, final Callback callback, final long initialAllocation) throws IOException { WriterInfo oldVal = writerList.get(path); // this should always be null, but we handle the case where the memory // manager wasn't told that a writer wasn't still in use and the task // starts writing to the same path. if (oldVal == null) { LOG.info("Registering writer for path " + path.toString()); oldVal = new WriterInfo(requestedAllocation, callback); writerList.put(path, oldVal); totalAllocation += requestedAllocation; } else { // handle a new writer that is writing to the same path totalAllocation += requestedAllocation - oldVal.allocation; oldVal.setAllocation(requestedAllocation); oldVal.setCallback(callback); } updateScale(true); // If we're not already in low memory mode, and the initial allocation already exceeds the // allocation, enter low memory mode to try to avoid an OOM if (!lowMemoryMode && requestedAllocation * currentScale <= initialAllocation) { lowMemoryMode = true; LOG.info("ORC: Switching to low memory mode"); for (WriterInfo writer : writerList.values()) { writer.callback.enterLowMemoryMode(); } } }
[ "synchronized", "void", "addWriter", "(", "final", "Path", "path", ",", "final", "long", "requestedAllocation", ",", "final", "Callback", "callback", ",", "final", "long", "initialAllocation", ")", "throws", "IOException", "{", "WriterInfo", "oldVal", "=", "writerList", ".", "get", "(", "path", ")", ";", "// this should always be null, but we handle the case where the memory", "// manager wasn't told that a writer wasn't still in use and the task", "// starts writing to the same path.", "if", "(", "oldVal", "==", "null", ")", "{", "LOG", ".", "info", "(", "\"Registering writer for path \"", "+", "path", ".", "toString", "(", ")", ")", ";", "oldVal", "=", "new", "WriterInfo", "(", "requestedAllocation", ",", "callback", ")", ";", "writerList", ".", "put", "(", "path", ",", "oldVal", ")", ";", "totalAllocation", "+=", "requestedAllocation", ";", "}", "else", "{", "// handle a new writer that is writing to the same path", "totalAllocation", "+=", "requestedAllocation", "-", "oldVal", ".", "allocation", ";", "oldVal", ".", "setAllocation", "(", "requestedAllocation", ")", ";", "oldVal", ".", "setCallback", "(", "callback", ")", ";", "}", "updateScale", "(", "true", ")", ";", "// If we're not already in low memory mode, and the initial allocation already exceeds the", "// allocation, enter low memory mode to try to avoid an OOM", "if", "(", "!", "lowMemoryMode", "&&", "requestedAllocation", "*", "currentScale", "<=", "initialAllocation", ")", "{", "lowMemoryMode", "=", "true", ";", "LOG", ".", "info", "(", "\"ORC: Switching to low memory mode\"", ")", ";", "for", "(", "WriterInfo", "writer", ":", "writerList", ".", "values", "(", ")", ")", "{", "writer", ".", "callback", ".", "enterLowMemoryMode", "(", ")", ";", "}", "}", "}" ]
Add a new writer's memory allocation to the pool. We use the path as a unique key to ensure that we don't get duplicates. @param path the file that is being written @param requestedAllocation the requested buffer size @param initialAllocation the current size of the buffer
[ "Add", "a", "new", "writer", "s", "memory", "allocation", "to", "the", "pool", ".", "We", "use", "the", "path", "as", "a", "unique", "key", "to", "ensure", "that", "we", "don", "t", "get", "duplicates", "." ]
train
https://github.com/facebookarchive/hive-dwrf/blob/a7b4fcf28a57e006a2fc041d40cf7e5ad16e6b45/hive-dwrf/src/main/java/com/facebook/hive/orc/MemoryManager.java#L148-L178
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/FileUtils.java
FileUtils.toDocument
public static Document toDocument(final String aFilePath, final String aPattern) throws FileNotFoundException, ParserConfigurationException { """ Returns an XML Document representing the file structure found at the supplied file system path. Files included in the representation will match the supplied regular expression pattern. This method doesn't descend through the directory structure. @param aFilePath The directory from which the structural representation should be built @param aPattern A regular expression pattern which files included in the Element should match @return An XML Document representation of the directory structure @throws FileNotFoundException If the supplied directory isn't found @throws ParserConfigurationException If the default XML parser for the JRE isn't configured correctly """ return toDocument(aFilePath, aPattern, false); }
java
public static Document toDocument(final String aFilePath, final String aPattern) throws FileNotFoundException, ParserConfigurationException { return toDocument(aFilePath, aPattern, false); }
[ "public", "static", "Document", "toDocument", "(", "final", "String", "aFilePath", ",", "final", "String", "aPattern", ")", "throws", "FileNotFoundException", ",", "ParserConfigurationException", "{", "return", "toDocument", "(", "aFilePath", ",", "aPattern", ",", "false", ")", ";", "}" ]
Returns an XML Document representing the file structure found at the supplied file system path. Files included in the representation will match the supplied regular expression pattern. This method doesn't descend through the directory structure. @param aFilePath The directory from which the structural representation should be built @param aPattern A regular expression pattern which files included in the Element should match @return An XML Document representation of the directory structure @throws FileNotFoundException If the supplied directory isn't found @throws ParserConfigurationException If the default XML parser for the JRE isn't configured correctly
[ "Returns", "an", "XML", "Document", "representing", "the", "file", "structure", "found", "at", "the", "supplied", "file", "system", "path", ".", "Files", "included", "in", "the", "representation", "will", "match", "the", "supplied", "regular", "expression", "pattern", ".", "This", "method", "doesn", "t", "descend", "through", "the", "directory", "structure", "." ]
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L293-L296
BioPAX/Paxtools
paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java
QueryExecuter.runPathsFromToMultiSet
public static Set<BioPAXElement> runPathsFromToMultiSet( Set<Set<BioPAXElement>> sourceSets, Set<Set<BioPAXElement>> targetSets, Model model, LimitType limitType, int limit, Filter... filters) { """ Gets paths the graph composed of the paths from a source node, and ends at a target node. @param sourceSets Seeds for start points of paths @param targetSets Seeds for end points of paths @param model BioPAX model @param limitType either NORMAL or SHORTEST_PLUS_K @param limit Length limit fothe paths to be found @param filters for filtering graph elements @return BioPAX elements in the result """ Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Set<Node> source = prepareSingleNodeSetFromSets(sourceSets, graph); Set<Node> target = prepareSingleNodeSetFromSets(targetSets, graph); PathsFromToQuery query = new PathsFromToQuery(source, target, limitType, limit, true); Set<GraphObject> resultWrappers = query.run(); return convertQueryResult(resultWrappers, graph, true); }
java
public static Set<BioPAXElement> runPathsFromToMultiSet( Set<Set<BioPAXElement>> sourceSets, Set<Set<BioPAXElement>> targetSets, Model model, LimitType limitType, int limit, Filter... filters) { Graph graph; if (model.getLevel() == BioPAXLevel.L3) { graph = new GraphL3(model, filters); } else return Collections.emptySet(); Set<Node> source = prepareSingleNodeSetFromSets(sourceSets, graph); Set<Node> target = prepareSingleNodeSetFromSets(targetSets, graph); PathsFromToQuery query = new PathsFromToQuery(source, target, limitType, limit, true); Set<GraphObject> resultWrappers = query.run(); return convertQueryResult(resultWrappers, graph, true); }
[ "public", "static", "Set", "<", "BioPAXElement", ">", "runPathsFromToMultiSet", "(", "Set", "<", "Set", "<", "BioPAXElement", ">", ">", "sourceSets", ",", "Set", "<", "Set", "<", "BioPAXElement", ">", ">", "targetSets", ",", "Model", "model", ",", "LimitType", "limitType", ",", "int", "limit", ",", "Filter", "...", "filters", ")", "{", "Graph", "graph", ";", "if", "(", "model", ".", "getLevel", "(", ")", "==", "BioPAXLevel", ".", "L3", ")", "{", "graph", "=", "new", "GraphL3", "(", "model", ",", "filters", ")", ";", "}", "else", "return", "Collections", ".", "emptySet", "(", ")", ";", "Set", "<", "Node", ">", "source", "=", "prepareSingleNodeSetFromSets", "(", "sourceSets", ",", "graph", ")", ";", "Set", "<", "Node", ">", "target", "=", "prepareSingleNodeSetFromSets", "(", "targetSets", ",", "graph", ")", ";", "PathsFromToQuery", "query", "=", "new", "PathsFromToQuery", "(", "source", ",", "target", ",", "limitType", ",", "limit", ",", "true", ")", ";", "Set", "<", "GraphObject", ">", "resultWrappers", "=", "query", ".", "run", "(", ")", ";", "return", "convertQueryResult", "(", "resultWrappers", ",", "graph", ",", "true", ")", ";", "}" ]
Gets paths the graph composed of the paths from a source node, and ends at a target node. @param sourceSets Seeds for start points of paths @param targetSets Seeds for end points of paths @param model BioPAX model @param limitType either NORMAL or SHORTEST_PLUS_K @param limit Length limit fothe paths to be found @param filters for filtering graph elements @return BioPAX elements in the result
[ "Gets", "paths", "the", "graph", "composed", "of", "the", "paths", "from", "a", "source", "node", "and", "ends", "at", "a", "target", "node", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-query/src/main/java/org/biopax/paxtools/query/QueryExecuter.java#L229-L251
ManfredTremmel/gwt-bean-validators
mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/util/PhoneNumberUtil.java
PhoneNumberUtil.formatUrl
public final String formatUrl(final String pphoneNumber, final String pcountryCode) { """ format phone number in URL format. @param pphoneNumber phone number to format @param pcountryCode iso code of country @return formated phone number as String """ return this.formatUrl(this.parsePhoneNumber(pphoneNumber, pcountryCode)); }
java
public final String formatUrl(final String pphoneNumber, final String pcountryCode) { return this.formatUrl(this.parsePhoneNumber(pphoneNumber, pcountryCode)); }
[ "public", "final", "String", "formatUrl", "(", "final", "String", "pphoneNumber", ",", "final", "String", "pcountryCode", ")", "{", "return", "this", ".", "formatUrl", "(", "this", ".", "parsePhoneNumber", "(", "pphoneNumber", ",", "pcountryCode", ")", ")", ";", "}" ]
format phone number in URL format. @param pphoneNumber phone number to format @param pcountryCode iso code of country @return formated phone number as String
[ "format", "phone", "number", "in", "URL", "format", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/util/PhoneNumberUtil.java#L1285-L1287
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/OrientedBox3d.java
OrientedBox3d.setFirstAxisProperties
public void setFirstAxisProperties(Vector3d vector, DoubleProperty extent, CoordinateSystem3D system) { """ Set the second axis of the box. The third axis is updated to be perpendicular to the two other axis. @param vector @param extent @param system """ this.axis1.setProperties(vector.xProperty,vector.yProperty,vector.zProperty); assert(this.axis1.isUnitVector()); if (system.isLeftHanded()) { this.axis3.set(this.axis1.crossLeftHand(this.axis2)); } else { this.axis3.set(this.axis3.crossRightHand(this.axis2)); } this.extent1Property = extent; }
java
public void setFirstAxisProperties(Vector3d vector, DoubleProperty extent, CoordinateSystem3D system) { this.axis1.setProperties(vector.xProperty,vector.yProperty,vector.zProperty); assert(this.axis1.isUnitVector()); if (system.isLeftHanded()) { this.axis3.set(this.axis1.crossLeftHand(this.axis2)); } else { this.axis3.set(this.axis3.crossRightHand(this.axis2)); } this.extent1Property = extent; }
[ "public", "void", "setFirstAxisProperties", "(", "Vector3d", "vector", ",", "DoubleProperty", "extent", ",", "CoordinateSystem3D", "system", ")", "{", "this", ".", "axis1", ".", "setProperties", "(", "vector", ".", "xProperty", ",", "vector", ".", "yProperty", ",", "vector", ".", "zProperty", ")", ";", "assert", "(", "this", ".", "axis1", ".", "isUnitVector", "(", ")", ")", ";", "if", "(", "system", ".", "isLeftHanded", "(", ")", ")", "{", "this", ".", "axis3", ".", "set", "(", "this", ".", "axis1", ".", "crossLeftHand", "(", "this", ".", "axis2", ")", ")", ";", "}", "else", "{", "this", ".", "axis3", ".", "set", "(", "this", ".", "axis3", ".", "crossRightHand", "(", "this", ".", "axis2", ")", ")", ";", "}", "this", ".", "extent1Property", "=", "extent", ";", "}" ]
Set the second axis of the box. The third axis is updated to be perpendicular to the two other axis. @param vector @param extent @param system
[ "Set", "the", "second", "axis", "of", "the", "box", ".", "The", "third", "axis", "is", "updated", "to", "be", "perpendicular", "to", "the", "two", "other", "axis", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/OrientedBox3d.java#L537-L546
phax/ph-css
ph-css/src/main/java/com/helger/css/utils/CSSColorHelper.java
CSSColorHelper.getRGBColorValue
@Nonnull @Nonempty public static String getRGBColorValue (final int nRed, final int nGreen, final int nBlue) { """ Get the passed values as CSS RGB color value @param nRed Red - is scaled to 0-255 @param nGreen Green - is scaled to 0-255 @param nBlue Blue - is scaled to 0-255 @return The CSS string to use """ return new StringBuilder (16).append (CCSSValue.PREFIX_RGB_OPEN) .append (getRGBValue (nRed)) .append (',') .append (getRGBValue (nGreen)) .append (',') .append (getRGBValue (nBlue)) .append (CCSSValue.SUFFIX_RGB_CLOSE) .toString (); }
java
@Nonnull @Nonempty public static String getRGBColorValue (final int nRed, final int nGreen, final int nBlue) { return new StringBuilder (16).append (CCSSValue.PREFIX_RGB_OPEN) .append (getRGBValue (nRed)) .append (',') .append (getRGBValue (nGreen)) .append (',') .append (getRGBValue (nBlue)) .append (CCSSValue.SUFFIX_RGB_CLOSE) .toString (); }
[ "@", "Nonnull", "@", "Nonempty", "public", "static", "String", "getRGBColorValue", "(", "final", "int", "nRed", ",", "final", "int", "nGreen", ",", "final", "int", "nBlue", ")", "{", "return", "new", "StringBuilder", "(", "16", ")", ".", "append", "(", "CCSSValue", ".", "PREFIX_RGB_OPEN", ")", ".", "append", "(", "getRGBValue", "(", "nRed", ")", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "getRGBValue", "(", "nGreen", ")", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "getRGBValue", "(", "nBlue", ")", ")", ".", "append", "(", "CCSSValue", ".", "SUFFIX_RGB_CLOSE", ")", ".", "toString", "(", ")", ";", "}" ]
Get the passed values as CSS RGB color value @param nRed Red - is scaled to 0-255 @param nGreen Green - is scaled to 0-255 @param nBlue Blue - is scaled to 0-255 @return The CSS string to use
[ "Get", "the", "passed", "values", "as", "CSS", "RGB", "color", "value" ]
train
https://github.com/phax/ph-css/blob/c9da5bb4decc681de6e27ce31712aad4c00adafa/ph-css/src/main/java/com/helger/css/utils/CSSColorHelper.java#L365-L377
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/node/locate/KeyValueLocator.java
KeyValueLocator.calculateNodeId
private static int calculateNodeId(int partitionId, BinaryRequest request, CouchbaseBucketConfig config) { """ Helper method to calculate the node if for the given partition and request type. @param partitionId the partition id. @param request the request used. @param config the current bucket configuration. @return the calculated node id. """ boolean useFastForward = request.retryCount() > 0 && config.hasFastForwardMap(); if (request instanceof ReplicaGetRequest) { return config.nodeIndexForReplica(partitionId, ((ReplicaGetRequest) request).replica() - 1, useFastForward); } else if (request instanceof ObserveRequest && ((ObserveRequest) request).replica() > 0) { return config.nodeIndexForReplica(partitionId, ((ObserveRequest) request).replica() - 1, useFastForward); } else if (request instanceof ObserveSeqnoRequest && ((ObserveSeqnoRequest) request).replica() > 0) { return config.nodeIndexForReplica(partitionId, ((ObserveSeqnoRequest) request).replica() - 1, useFastForward); } else { return config.nodeIndexForMaster(partitionId, useFastForward); } }
java
private static int calculateNodeId(int partitionId, BinaryRequest request, CouchbaseBucketConfig config) { boolean useFastForward = request.retryCount() > 0 && config.hasFastForwardMap(); if (request instanceof ReplicaGetRequest) { return config.nodeIndexForReplica(partitionId, ((ReplicaGetRequest) request).replica() - 1, useFastForward); } else if (request instanceof ObserveRequest && ((ObserveRequest) request).replica() > 0) { return config.nodeIndexForReplica(partitionId, ((ObserveRequest) request).replica() - 1, useFastForward); } else if (request instanceof ObserveSeqnoRequest && ((ObserveSeqnoRequest) request).replica() > 0) { return config.nodeIndexForReplica(partitionId, ((ObserveSeqnoRequest) request).replica() - 1, useFastForward); } else { return config.nodeIndexForMaster(partitionId, useFastForward); } }
[ "private", "static", "int", "calculateNodeId", "(", "int", "partitionId", ",", "BinaryRequest", "request", ",", "CouchbaseBucketConfig", "config", ")", "{", "boolean", "useFastForward", "=", "request", ".", "retryCount", "(", ")", ">", "0", "&&", "config", ".", "hasFastForwardMap", "(", ")", ";", "if", "(", "request", "instanceof", "ReplicaGetRequest", ")", "{", "return", "config", ".", "nodeIndexForReplica", "(", "partitionId", ",", "(", "(", "ReplicaGetRequest", ")", "request", ")", ".", "replica", "(", ")", "-", "1", ",", "useFastForward", ")", ";", "}", "else", "if", "(", "request", "instanceof", "ObserveRequest", "&&", "(", "(", "ObserveRequest", ")", "request", ")", ".", "replica", "(", ")", ">", "0", ")", "{", "return", "config", ".", "nodeIndexForReplica", "(", "partitionId", ",", "(", "(", "ObserveRequest", ")", "request", ")", ".", "replica", "(", ")", "-", "1", ",", "useFastForward", ")", ";", "}", "else", "if", "(", "request", "instanceof", "ObserveSeqnoRequest", "&&", "(", "(", "ObserveSeqnoRequest", ")", "request", ")", ".", "replica", "(", ")", ">", "0", ")", "{", "return", "config", ".", "nodeIndexForReplica", "(", "partitionId", ",", "(", "(", "ObserveSeqnoRequest", ")", "request", ")", ".", "replica", "(", ")", "-", "1", ",", "useFastForward", ")", ";", "}", "else", "{", "return", "config", ".", "nodeIndexForMaster", "(", "partitionId", ",", "useFastForward", ")", ";", "}", "}" ]
Helper method to calculate the node if for the given partition and request type. @param partitionId the partition id. @param request the request used. @param config the current bucket configuration. @return the calculated node id.
[ "Helper", "method", "to", "calculate", "the", "node", "if", "for", "the", "given", "partition", "and", "request", "type", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/node/locate/KeyValueLocator.java#L161-L173
GoSimpleLLC/nbvcxz
src/main/java/me/gosimple/nbvcxz/resources/Generator.java
Generator.generatePassphrase
public static String generatePassphrase(final String delimiter, final int words) { """ Generates a passphrase from the eff_large standard dictionary with the requested word count. @param delimiter delimiter to place between words @param words the count of words you want in your passphrase @return the passphrase """ return generatePassphrase(delimiter, words, new Dictionary("eff_large", DictionaryUtil.loadUnrankedDictionary(DictionaryUtil.eff_large), false)); }
java
public static String generatePassphrase(final String delimiter, final int words) { return generatePassphrase(delimiter, words, new Dictionary("eff_large", DictionaryUtil.loadUnrankedDictionary(DictionaryUtil.eff_large), false)); }
[ "public", "static", "String", "generatePassphrase", "(", "final", "String", "delimiter", ",", "final", "int", "words", ")", "{", "return", "generatePassphrase", "(", "delimiter", ",", "words", ",", "new", "Dictionary", "(", "\"eff_large\"", ",", "DictionaryUtil", ".", "loadUnrankedDictionary", "(", "DictionaryUtil", ".", "eff_large", ")", ",", "false", ")", ")", ";", "}" ]
Generates a passphrase from the eff_large standard dictionary with the requested word count. @param delimiter delimiter to place between words @param words the count of words you want in your passphrase @return the passphrase
[ "Generates", "a", "passphrase", "from", "the", "eff_large", "standard", "dictionary", "with", "the", "requested", "word", "count", "." ]
train
https://github.com/GoSimpleLLC/nbvcxz/blob/a86fb24680e646efdf78d6fda9d68a5410145f56/src/main/java/me/gosimple/nbvcxz/resources/Generator.java#L19-L22
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/compiler/batch/SarlBatchCompiler.java
SarlBatchCompiler.createTempDirectory
@SuppressWarnings("static-method") protected File createTempDirectory() { """ Create the temp directory that should be used by the compiler. @return the temp directory, never {@code null}. """ final File tmpPath = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$ int i = 0; File tmp = new File(tmpPath, "sarlc" + i); //$NON-NLS-1$ while (tmp.exists()) { ++i; tmp = new File(tmpPath, "sarlc" + i); //$NON-NLS-1$ } return tmp; }
java
@SuppressWarnings("static-method") protected File createTempDirectory() { final File tmpPath = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$ int i = 0; File tmp = new File(tmpPath, "sarlc" + i); //$NON-NLS-1$ while (tmp.exists()) { ++i; tmp = new File(tmpPath, "sarlc" + i); //$NON-NLS-1$ } return tmp; }
[ "@", "SuppressWarnings", "(", "\"static-method\"", ")", "protected", "File", "createTempDirectory", "(", ")", "{", "final", "File", "tmpPath", "=", "new", "File", "(", "System", ".", "getProperty", "(", "\"java.io.tmpdir\"", ")", ")", ";", "//$NON-NLS-1$", "int", "i", "=", "0", ";", "File", "tmp", "=", "new", "File", "(", "tmpPath", ",", "\"sarlc\"", "+", "i", ")", ";", "//$NON-NLS-1$", "while", "(", "tmp", ".", "exists", "(", ")", ")", "{", "++", "i", ";", "tmp", "=", "new", "File", "(", "tmpPath", ",", "\"sarlc\"", "+", "i", ")", ";", "//$NON-NLS-1$", "}", "return", "tmp", ";", "}" ]
Create the temp directory that should be used by the compiler. @return the temp directory, never {@code null}.
[ "Create", "the", "temp", "directory", "that", "should", "be", "used", "by", "the", "compiler", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/compiler/batch/SarlBatchCompiler.java#L806-L816
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.splitPreserveAllTokens
public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) { """ <p>Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.</p> <p>The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. Adjacent separators are treated as one separator.</p> <p>A {@code null} input String returns {@code null}. A {@code null} separatorChars splits on whitespace.</p> <p>If more than {@code max} delimited substrings are found, the last returned string includes all characters after the first {@code max - 1} returned strings (including separator characters).</p> <pre> StringUtils.splitPreserveAllTokens(null, *, *) = null StringUtils.splitPreserveAllTokens("", *, *) = [] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"] </pre> @param str the String to parse, may be {@code null} @param separatorChars the characters used as the delimiters, {@code null} splits on whitespace @param max the maximum number of elements to include in the array. A zero or negative value implies no limit @return an array of parsed Strings, {@code null} if null String input @since 2.1 """ return splitWorker(str, separatorChars, max, true); }
java
public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) { return splitWorker(str, separatorChars, max, true); }
[ "public", "static", "String", "[", "]", "splitPreserveAllTokens", "(", "final", "String", "str", ",", "final", "String", "separatorChars", ",", "final", "int", "max", ")", "{", "return", "splitWorker", "(", "str", ",", "separatorChars", ",", "max", ",", "true", ")", ";", "}" ]
<p>Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.</p> <p>The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. Adjacent separators are treated as one separator.</p> <p>A {@code null} input String returns {@code null}. A {@code null} separatorChars splits on whitespace.</p> <p>If more than {@code max} delimited substrings are found, the last returned string includes all characters after the first {@code max - 1} returned strings (including separator characters).</p> <pre> StringUtils.splitPreserveAllTokens(null, *, *) = null StringUtils.splitPreserveAllTokens("", *, *) = [] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"] </pre> @param str the String to parse, may be {@code null} @param separatorChars the characters used as the delimiters, {@code null} splits on whitespace @param max the maximum number of elements to include in the array. A zero or negative value implies no limit @return an array of parsed Strings, {@code null} if null String input @since 2.1
[ "<p", ">", "Splits", "the", "provided", "text", "into", "an", "array", "with", "a", "maximum", "length", "separators", "specified", "preserving", "all", "tokens", "including", "empty", "tokens", "created", "by", "adjacent", "separators", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L3627-L3629
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/filter/ExistsFilter.java
ExistsFilter.build
static <S extends Storable> Filter<S> build(ChainedProperty<S> property, Filter<?> subFilter, boolean not) { """ Returns a canonical instance, creating a new one if there isn't one already in the cache. """ if (property == null) { throw new IllegalArgumentException(); } StorableProperty<?> joinProperty = property.getLastProperty(); if (subFilter == null) { subFilter = Filter.getOpenFilter(joinProperty.getJoinedType()); } else if (joinProperty.getJoinedType() != subFilter.getStorableType()) { throw new IllegalArgumentException ("Filter not compatible with join property type: " + property + " joins to a " + joinProperty.getJoinedType().getName() + ", but filter is for a " + subFilter.getStorableType().getName()); } if (subFilter.isClosed()) { // Exists filter reduces to a closed (or open) filter. Filter<S> f = Filter.getClosedFilter(property.getPrimeProperty().getEnclosingType()); return not ? f.not() : f; } else if (joinProperty.isQuery() || subFilter.isOpen()) { return getCanonical(property, subFilter, not); } else { // Convert to normal join filter. return subFilter.asJoinedFrom(property); } }
java
static <S extends Storable> Filter<S> build(ChainedProperty<S> property, Filter<?> subFilter, boolean not) { if (property == null) { throw new IllegalArgumentException(); } StorableProperty<?> joinProperty = property.getLastProperty(); if (subFilter == null) { subFilter = Filter.getOpenFilter(joinProperty.getJoinedType()); } else if (joinProperty.getJoinedType() != subFilter.getStorableType()) { throw new IllegalArgumentException ("Filter not compatible with join property type: " + property + " joins to a " + joinProperty.getJoinedType().getName() + ", but filter is for a " + subFilter.getStorableType().getName()); } if (subFilter.isClosed()) { // Exists filter reduces to a closed (or open) filter. Filter<S> f = Filter.getClosedFilter(property.getPrimeProperty().getEnclosingType()); return not ? f.not() : f; } else if (joinProperty.isQuery() || subFilter.isOpen()) { return getCanonical(property, subFilter, not); } else { // Convert to normal join filter. return subFilter.asJoinedFrom(property); } }
[ "static", "<", "S", "extends", "Storable", ">", "Filter", "<", "S", ">", "build", "(", "ChainedProperty", "<", "S", ">", "property", ",", "Filter", "<", "?", ">", "subFilter", ",", "boolean", "not", ")", "{", "if", "(", "property", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "StorableProperty", "<", "?", ">", "joinProperty", "=", "property", ".", "getLastProperty", "(", ")", ";", "if", "(", "subFilter", "==", "null", ")", "{", "subFilter", "=", "Filter", ".", "getOpenFilter", "(", "joinProperty", ".", "getJoinedType", "(", ")", ")", ";", "}", "else", "if", "(", "joinProperty", ".", "getJoinedType", "(", ")", "!=", "subFilter", ".", "getStorableType", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Filter not compatible with join property type: \"", "+", "property", "+", "\" joins to a \"", "+", "joinProperty", ".", "getJoinedType", "(", ")", ".", "getName", "(", ")", "+", "\", but filter is for a \"", "+", "subFilter", ".", "getStorableType", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "if", "(", "subFilter", ".", "isClosed", "(", ")", ")", "{", "// Exists filter reduces to a closed (or open) filter.\r", "Filter", "<", "S", ">", "f", "=", "Filter", ".", "getClosedFilter", "(", "property", ".", "getPrimeProperty", "(", ")", ".", "getEnclosingType", "(", ")", ")", ";", "return", "not", "?", "f", ".", "not", "(", ")", ":", "f", ";", "}", "else", "if", "(", "joinProperty", ".", "isQuery", "(", ")", "||", "subFilter", ".", "isOpen", "(", ")", ")", "{", "return", "getCanonical", "(", "property", ",", "subFilter", ",", "not", ")", ";", "}", "else", "{", "// Convert to normal join filter.\r", "return", "subFilter", ".", "asJoinedFrom", "(", "property", ")", ";", "}", "}" ]
Returns a canonical instance, creating a new one if there isn't one already in the cache.
[ "Returns", "a", "canonical", "instance", "creating", "a", "new", "one", "if", "there", "isn", "t", "one", "already", "in", "the", "cache", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/filter/ExistsFilter.java#L42-L71
johnkil/Android-RobotoTextView
robototextview/src/main/java/com/devspark/robototextview/RobotoTypefaces.java
RobotoTypefaces.obtainTypeface
@NonNull public static Typeface obtainTypeface(@NonNull Context context, @RobotoTypeface int typefaceValue) { """ Obtain typeface. @param context The Context the widget is running in, through which it can access the current theme, resources, etc. @param typefaceValue The value of "robotoTypeface" attribute @return specify {@link Typeface} or throws IllegalArgumentException if unknown `robotoTypeface` attribute value. """ Typeface typeface = typefacesCache.get(typefaceValue); if (typeface == null) { typeface = createTypeface(context, typefaceValue); typefacesCache.put(typefaceValue, typeface); } return typeface; }
java
@NonNull public static Typeface obtainTypeface(@NonNull Context context, @RobotoTypeface int typefaceValue) { Typeface typeface = typefacesCache.get(typefaceValue); if (typeface == null) { typeface = createTypeface(context, typefaceValue); typefacesCache.put(typefaceValue, typeface); } return typeface; }
[ "@", "NonNull", "public", "static", "Typeface", "obtainTypeface", "(", "@", "NonNull", "Context", "context", ",", "@", "RobotoTypeface", "int", "typefaceValue", ")", "{", "Typeface", "typeface", "=", "typefacesCache", ".", "get", "(", "typefaceValue", ")", ";", "if", "(", "typeface", "==", "null", ")", "{", "typeface", "=", "createTypeface", "(", "context", ",", "typefaceValue", ")", ";", "typefacesCache", ".", "put", "(", "typefaceValue", ",", "typeface", ")", ";", "}", "return", "typeface", ";", "}" ]
Obtain typeface. @param context The Context the widget is running in, through which it can access the current theme, resources, etc. @param typefaceValue The value of "robotoTypeface" attribute @return specify {@link Typeface} or throws IllegalArgumentException if unknown `robotoTypeface` attribute value.
[ "Obtain", "typeface", "." ]
train
https://github.com/johnkil/Android-RobotoTextView/blob/1341602f16c08057dddd193411e7dab96f963b77/robototextview/src/main/java/com/devspark/robototextview/RobotoTypefaces.java#L168-L176
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.put
public JsonObject put(String name, Number value) { """ Stores a {@link Number} value identified by the field name. @param name the name of the JSON field. @param value the value of the JSON field. @return the {@link JsonObject}. """ content.put(name, value); return this; }
java
public JsonObject put(String name, Number value) { content.put(name, value); return this; }
[ "public", "JsonObject", "put", "(", "String", "name", ",", "Number", "value", ")", "{", "content", ".", "put", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Stores a {@link Number} value identified by the field name. @param name the name of the JSON field. @param value the value of the JSON field. @return the {@link JsonObject}.
[ "Stores", "a", "{", "@link", "Number", "}", "value", "identified", "by", "the", "field", "name", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L811-L814
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/AbstractDsAssignmentStrategy.java
AbstractDsAssignmentStrategy.cancelAssignDistributionSetEvent
void cancelAssignDistributionSetEvent(final Target target, final Long actionId) { """ Sends the {@link CancelTargetAssignmentEvent} for a specific target to the eventPublisher. @param target the Target which has been assigned to a distribution set @param actionId the action id of the assignment """ afterCommit.afterCommit( () -> eventPublisher.publishEvent(new CancelTargetAssignmentEvent(target, actionId, bus.getId()))); }
java
void cancelAssignDistributionSetEvent(final Target target, final Long actionId) { afterCommit.afterCommit( () -> eventPublisher.publishEvent(new CancelTargetAssignmentEvent(target, actionId, bus.getId()))); }
[ "void", "cancelAssignDistributionSetEvent", "(", "final", "Target", "target", ",", "final", "Long", "actionId", ")", "{", "afterCommit", ".", "afterCommit", "(", "(", ")", "->", "eventPublisher", ".", "publishEvent", "(", "new", "CancelTargetAssignmentEvent", "(", "target", ",", "actionId", ",", "bus", ".", "getId", "(", ")", ")", ")", ")", ";", "}" ]
Sends the {@link CancelTargetAssignmentEvent} for a specific target to the eventPublisher. @param target the Target which has been assigned to a distribution set @param actionId the action id of the assignment
[ "Sends", "the", "{", "@link", "CancelTargetAssignmentEvent", "}", "for", "a", "specific", "target", "to", "the", "eventPublisher", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/AbstractDsAssignmentStrategy.java#L216-L219
nostra13/Android-Universal-Image-Loader
library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java
ImageLoader.displayImage
public void displayImage(String uri, ImageView imageView, ImageLoadingListener listener) { """ Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration configuration} will be used.<br /> <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call @param uri Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") @param imageView {@link ImageView} which should display image @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on UI thread if this method is called on UI thread. @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before @throws IllegalArgumentException if passed <b>imageView</b> is null """ displayImage(uri, new ImageViewAware(imageView), null, listener, null); }
java
public void displayImage(String uri, ImageView imageView, ImageLoadingListener listener) { displayImage(uri, new ImageViewAware(imageView), null, listener, null); }
[ "public", "void", "displayImage", "(", "String", "uri", ",", "ImageView", "imageView", ",", "ImageLoadingListener", "listener", ")", "{", "displayImage", "(", "uri", ",", "new", "ImageViewAware", "(", "imageView", ")", ",", "null", ",", "listener", ",", "null", ")", ";", "}" ]
Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration configuration} will be used.<br /> <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call @param uri Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") @param imageView {@link ImageView} which should display image @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on UI thread if this method is called on UI thread. @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before @throws IllegalArgumentException if passed <b>imageView</b> is null
[ "Adds", "display", "image", "task", "to", "execution", "pool", ".", "Image", "will", "be", "set", "to", "ImageView", "when", "it", "s", "turn", ".", "<br", "/", ">", "Default", "{", "@linkplain", "DisplayImageOptions", "display", "image", "options", "}", "from", "{", "@linkplain", "ImageLoaderConfiguration", "configuration", "}", "will", "be", "used", ".", "<br", "/", ">", "<b", ">", "NOTE", ":", "<", "/", "b", ">", "{", "@link", "#init", "(", "ImageLoaderConfiguration", ")", "}", "method", "must", "be", "called", "before", "this", "method", "call" ]
train
https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java#L364-L366
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/Criteria.java
Criteria.addLessOrEqualThan
public void addLessOrEqualThan(Object attribute, Object value) { """ Adds LessOrEqual Than (<=) criteria, customer_id <= 10034 @param attribute The field name to be used @param value An object representing the value of the field """ // PAW // addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getAlias())); addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getUserAlias(attribute))); }
java
public void addLessOrEqualThan(Object attribute, Object value) { // PAW // addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getAlias())); addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getUserAlias(attribute))); }
[ "public", "void", "addLessOrEqualThan", "(", "Object", "attribute", ",", "Object", "value", ")", "{", "// PAW\r", "// addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getAlias()));\r", "addSelectionCriteria", "(", "ValueCriteria", ".", "buildNotGreaterCriteria", "(", "attribute", ",", "value", ",", "getUserAlias", "(", "attribute", ")", ")", ")", ";", "}" ]
Adds LessOrEqual Than (<=) criteria, customer_id <= 10034 @param attribute The field name to be used @param value An object representing the value of the field
[ "Adds", "LessOrEqual", "Than", "(", "<", "=", ")", "criteria", "customer_id", "<", "=", "10034" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L435-L440
mfornos/humanize
humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java
ExtendedMessageFormat.seekNonWs
private void seekNonWs(String pattern, ParsePosition pos) { """ Consume whitespace from the current parse position. @param pattern String to read @param pos current position """ int len = 0; char[] buffer = pattern.toCharArray(); do { len = Arrays.binarySearch(SPLIT_CHARS, buffer[pos.getIndex()]) >= 0 ? 1 : 0; pos.setIndex(pos.getIndex() + len); } while (len > 0 && pos.getIndex() < pattern.length()); }
java
private void seekNonWs(String pattern, ParsePosition pos) { int len = 0; char[] buffer = pattern.toCharArray(); do { len = Arrays.binarySearch(SPLIT_CHARS, buffer[pos.getIndex()]) >= 0 ? 1 : 0; pos.setIndex(pos.getIndex() + len); } while (len > 0 && pos.getIndex() < pattern.length()); }
[ "private", "void", "seekNonWs", "(", "String", "pattern", ",", "ParsePosition", "pos", ")", "{", "int", "len", "=", "0", ";", "char", "[", "]", "buffer", "=", "pattern", ".", "toCharArray", "(", ")", ";", "do", "{", "len", "=", "Arrays", ".", "binarySearch", "(", "SPLIT_CHARS", ",", "buffer", "[", "pos", ".", "getIndex", "(", ")", "]", ")", ">=", "0", "?", "1", ":", "0", ";", "pos", ".", "setIndex", "(", "pos", ".", "getIndex", "(", ")", "+", "len", ")", ";", "}", "while", "(", "len", ">", "0", "&&", "pos", ".", "getIndex", "(", ")", "<", "pattern", ".", "length", "(", ")", ")", ";", "}" ]
Consume whitespace from the current parse position. @param pattern String to read @param pos current position
[ "Consume", "whitespace", "from", "the", "current", "parse", "position", "." ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/text/ExtendedMessageFormat.java#L669-L681
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java
MultipleAlignmentScorer.getRefRMSD
public static double getRefRMSD(MultipleAlignment alignment, int ref) { """ /** Calculates the average RMSD from all structures to a reference s tructure, given a set of superimposed atoms. <p> Complexity: T(n,l) = O(l*n), if n=number of structures and l=alignment length. <p> For ungapped alignments, this is just the sqroot of the average distance from an atom to the aligned atom from the reference. Thus, for R structures aligned over C columns (with structure 0 as the reference), we have: <pre> RefRMSD = \sqrt{ 1/(C*(R-1)) * \sum_{r=1}^{R-1} \sum_{j=0}^{C-1} (atom[1][c]-atom[r][c])^2 } </pre> <p> For gapped alignments, null atoms are omitted from consideration, so that the RMSD is the average over all columns with non-null reference of the average RMSD within the non-null elements of the column. @param alignment MultipleAlignment @param ref reference structure index @return """ List<Atom[]> trans = MultipleAlignmentTools.transformAtoms(alignment); return getRefRMSD(trans, ref); }
java
public static double getRefRMSD(MultipleAlignment alignment, int ref) { List<Atom[]> trans = MultipleAlignmentTools.transformAtoms(alignment); return getRefRMSD(trans, ref); }
[ "public", "static", "double", "getRefRMSD", "(", "MultipleAlignment", "alignment", ",", "int", "ref", ")", "{", "List", "<", "Atom", "[", "]", ">", "trans", "=", "MultipleAlignmentTools", ".", "transformAtoms", "(", "alignment", ")", ";", "return", "getRefRMSD", "(", "trans", ",", "ref", ")", ";", "}" ]
/** Calculates the average RMSD from all structures to a reference s tructure, given a set of superimposed atoms. <p> Complexity: T(n,l) = O(l*n), if n=number of structures and l=alignment length. <p> For ungapped alignments, this is just the sqroot of the average distance from an atom to the aligned atom from the reference. Thus, for R structures aligned over C columns (with structure 0 as the reference), we have: <pre> RefRMSD = \sqrt{ 1/(C*(R-1)) * \sum_{r=1}^{R-1} \sum_{j=0}^{C-1} (atom[1][c]-atom[r][c])^2 } </pre> <p> For gapped alignments, null atoms are omitted from consideration, so that the RMSD is the average over all columns with non-null reference of the average RMSD within the non-null elements of the column. @param alignment MultipleAlignment @param ref reference structure index @return
[ "/", "**", "Calculates", "the", "average", "RMSD", "from", "all", "structures", "to", "a", "reference", "s", "tructure", "given", "a", "set", "of", "superimposed", "atoms", ".", "<p", ">", "Complexity", ":", "T", "(", "n", "l", ")", "=", "O", "(", "l", "*", "n", ")", "if", "n", "=", "number", "of", "structures", "and", "l", "=", "alignment", "length", ".", "<p", ">", "For", "ungapped", "alignments", "this", "is", "just", "the", "sqroot", "of", "the", "average", "distance", "from", "an", "atom", "to", "the", "aligned", "atom", "from", "the", "reference", ".", "Thus", "for", "R", "structures", "aligned", "over", "C", "columns", "(", "with", "structure", "0", "as", "the", "reference", ")", "we", "have", ":" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java#L165-L168
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/ie/AbstractSequenceClassifier.java
AbstractSequenceClassifier.loadClassifier
public void loadClassifier(InputStream in, Properties props) throws IOException, ClassCastException, ClassNotFoundException { """ Load a classifier from the specified InputStream. The classifier is reinitialized from the flags serialized in the classifier. This does not close the InputStream. @param in The InputStream to load the serialized classifier from @param props This Properties object will be used to update the SeqClassifierFlags which are read from the serialized classifier @throws IOException If there are problems accessing the input stream @throws ClassCastException If there are problems interpreting the serialized data @throws ClassNotFoundException If there are problems interpreting the serialized data """ loadClassifier(new ObjectInputStream(in), props); }
java
public void loadClassifier(InputStream in, Properties props) throws IOException, ClassCastException, ClassNotFoundException { loadClassifier(new ObjectInputStream(in), props); }
[ "public", "void", "loadClassifier", "(", "InputStream", "in", ",", "Properties", "props", ")", "throws", "IOException", ",", "ClassCastException", ",", "ClassNotFoundException", "{", "loadClassifier", "(", "new", "ObjectInputStream", "(", "in", ")", ",", "props", ")", ";", "}" ]
Load a classifier from the specified InputStream. The classifier is reinitialized from the flags serialized in the classifier. This does not close the InputStream. @param in The InputStream to load the serialized classifier from @param props This Properties object will be used to update the SeqClassifierFlags which are read from the serialized classifier @throws IOException If there are problems accessing the input stream @throws ClassCastException If there are problems interpreting the serialized data @throws ClassNotFoundException If there are problems interpreting the serialized data
[ "Load", "a", "classifier", "from", "the", "specified", "InputStream", ".", "The", "classifier", "is", "reinitialized", "from", "the", "flags", "serialized", "in", "the", "classifier", ".", "This", "does", "not", "close", "the", "InputStream", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/AbstractSequenceClassifier.java#L1539-L1542
moparisthebest/beehive
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanContext.java
ControlBeanContext.getBeanAnnotationMap
protected PropertyMap getBeanAnnotationMap(ControlBean bean, AnnotatedElement annotElem) { """ The default implementation of getBeanAnnotationMap. This returns a map based purely upon annotation reflection """ PropertyMap map = new AnnotatedElementMap(annotElem); // REVIEW: is this the right place to handle the general control client case? if ( bean != null ) setDelegateMap( map, bean, annotElem ); return map; }
java
protected PropertyMap getBeanAnnotationMap(ControlBean bean, AnnotatedElement annotElem) { PropertyMap map = new AnnotatedElementMap(annotElem); // REVIEW: is this the right place to handle the general control client case? if ( bean != null ) setDelegateMap( map, bean, annotElem ); return map; }
[ "protected", "PropertyMap", "getBeanAnnotationMap", "(", "ControlBean", "bean", ",", "AnnotatedElement", "annotElem", ")", "{", "PropertyMap", "map", "=", "new", "AnnotatedElementMap", "(", "annotElem", ")", ";", "// REVIEW: is this the right place to handle the general control client case?", "if", "(", "bean", "!=", "null", ")", "setDelegateMap", "(", "map", ",", "bean", ",", "annotElem", ")", ";", "return", "map", ";", "}" ]
The default implementation of getBeanAnnotationMap. This returns a map based purely upon annotation reflection
[ "The", "default", "implementation", "of", "getBeanAnnotationMap", ".", "This", "returns", "a", "map", "based", "purely", "upon", "annotation", "reflection" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanContext.java#L391-L400
threerings/nenya
core/src/main/java/com/threerings/media/sprite/SpriteManager.java
SpriteManager.getIntersectingSprites
public void getIntersectingSprites (List<Sprite> list, Shape shape) { """ When an animated view processes its dirty rectangles, it may require an expansion of the dirty region which may in turn require the invalidation of more sprites than were originally invalid. In such cases, the animated view can call back to the sprite manager, asking it to append the sprites that intersect a particular region to the given list. @param list the list to fill with any intersecting sprites. @param shape the shape in which we have interest. """ int size = _sprites.size(); for (int ii = 0; ii < size; ii++) { Sprite sprite = _sprites.get(ii); if (sprite.intersects(shape)) { list.add(sprite); } } }
java
public void getIntersectingSprites (List<Sprite> list, Shape shape) { int size = _sprites.size(); for (int ii = 0; ii < size; ii++) { Sprite sprite = _sprites.get(ii); if (sprite.intersects(shape)) { list.add(sprite); } } }
[ "public", "void", "getIntersectingSprites", "(", "List", "<", "Sprite", ">", "list", ",", "Shape", "shape", ")", "{", "int", "size", "=", "_sprites", ".", "size", "(", ")", ";", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "size", ";", "ii", "++", ")", "{", "Sprite", "sprite", "=", "_sprites", ".", "get", "(", "ii", ")", ";", "if", "(", "sprite", ".", "intersects", "(", "shape", ")", ")", "{", "list", ".", "add", "(", "sprite", ")", ";", "}", "}", "}" ]
When an animated view processes its dirty rectangles, it may require an expansion of the dirty region which may in turn require the invalidation of more sprites than were originally invalid. In such cases, the animated view can call back to the sprite manager, asking it to append the sprites that intersect a particular region to the given list. @param list the list to fill with any intersecting sprites. @param shape the shape in which we have interest.
[ "When", "an", "animated", "view", "processes", "its", "dirty", "rectangles", "it", "may", "require", "an", "expansion", "of", "the", "dirty", "region", "which", "may", "in", "turn", "require", "the", "invalidation", "of", "more", "sprites", "than", "were", "originally", "invalid", ".", "In", "such", "cases", "the", "animated", "view", "can", "call", "back", "to", "the", "sprite", "manager", "asking", "it", "to", "append", "the", "sprites", "that", "intersect", "a", "particular", "region", "to", "the", "given", "list", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/sprite/SpriteManager.java#L50-L59
Netflix/netflix-graph
src/main/java/com/netflix/nfgraph/compressed/NFCompressedGraph.java
NFCompressedGraph.readFrom
public static NFCompressedGraph readFrom(InputStream is, ByteSegmentPool memoryPool) throws IOException { """ When using a {@link ByteSegmentPool}, this method will borrow arrays used to construct the NFCompressedGraph from that pool. <p> Note that because the {@link ByteSegmentPool} is NOT thread-safe, this this call is also NOT thread-safe. It is up to implementations to ensure that only a single update thread is accessing this memory pool at any given time. """ NFCompressedGraphDeserializer deserializer = new NFCompressedGraphDeserializer(); return deserializer.deserialize(is, memoryPool); }
java
public static NFCompressedGraph readFrom(InputStream is, ByteSegmentPool memoryPool) throws IOException { NFCompressedGraphDeserializer deserializer = new NFCompressedGraphDeserializer(); return deserializer.deserialize(is, memoryPool); }
[ "public", "static", "NFCompressedGraph", "readFrom", "(", "InputStream", "is", ",", "ByteSegmentPool", "memoryPool", ")", "throws", "IOException", "{", "NFCompressedGraphDeserializer", "deserializer", "=", "new", "NFCompressedGraphDeserializer", "(", ")", ";", "return", "deserializer", ".", "deserialize", "(", "is", ",", "memoryPool", ")", ";", "}" ]
When using a {@link ByteSegmentPool}, this method will borrow arrays used to construct the NFCompressedGraph from that pool. <p> Note that because the {@link ByteSegmentPool} is NOT thread-safe, this this call is also NOT thread-safe. It is up to implementations to ensure that only a single update thread is accessing this memory pool at any given time.
[ "When", "using", "a", "{" ]
train
https://github.com/Netflix/netflix-graph/blob/ee129252a08a9f51dd296d6fca2f0b28b7be284e/src/main/java/com/netflix/nfgraph/compressed/NFCompressedGraph.java#L251-L254
alkacon/opencms-core
src/org/opencms/xml/CmsXmlUtils.java
CmsXmlUtils.unmarshalHelper
public static Document unmarshalHelper(InputSource source, EntityResolver resolver) throws CmsXmlException { """ Helper to unmarshal (read) xml contents from an input source into a document.<p> Using this method ensures that the OpenCms XML entity resolver is used.<p> Important: The encoding provided will NOT be used during unmarshalling, the XML parser will do this on the base of the information in the source String. The encoding is used for initializing the created instance of the document, which means it will be used when marshalling the document again later.<p> @param source the XML input source to use @param resolver the XML entity resolver to use @return the unmarshalled XML document @throws CmsXmlException if something goes wrong """ return unmarshalHelper(source, resolver, false); }
java
public static Document unmarshalHelper(InputSource source, EntityResolver resolver) throws CmsXmlException { return unmarshalHelper(source, resolver, false); }
[ "public", "static", "Document", "unmarshalHelper", "(", "InputSource", "source", ",", "EntityResolver", "resolver", ")", "throws", "CmsXmlException", "{", "return", "unmarshalHelper", "(", "source", ",", "resolver", ",", "false", ")", ";", "}" ]
Helper to unmarshal (read) xml contents from an input source into a document.<p> Using this method ensures that the OpenCms XML entity resolver is used.<p> Important: The encoding provided will NOT be used during unmarshalling, the XML parser will do this on the base of the information in the source String. The encoding is used for initializing the created instance of the document, which means it will be used when marshalling the document again later.<p> @param source the XML input source to use @param resolver the XML entity resolver to use @return the unmarshalled XML document @throws CmsXmlException if something goes wrong
[ "Helper", "to", "unmarshal", "(", "read", ")", "xml", "contents", "from", "an", "input", "source", "into", "a", "document", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlUtils.java#L745-L748
indeedeng/util
urlparsing/src/main/java/com/indeed/util/urlparsing/ParseUtils.java
ParseUtils.parseSignedLong
public static long parseSignedLong(CharSequence s, final int start, final int end) throws NumberFormatException { """ Parses out a long value from the provided string, equivalent to Long.parseLong(s.substring(start, end)), but has significantly less overhead, no object creation and later garbage collection required @throws {@link NumberFormatException} if it encounters any character that is not [-0-9]. """ if (s.charAt(start) == '-') { // negative! return -parseUnsignedLong(s, start + 1, end); } else { return parseUnsignedLong(s, start, end); } }
java
public static long parseSignedLong(CharSequence s, final int start, final int end) throws NumberFormatException { if (s.charAt(start) == '-') { // negative! return -parseUnsignedLong(s, start + 1, end); } else { return parseUnsignedLong(s, start, end); } }
[ "public", "static", "long", "parseSignedLong", "(", "CharSequence", "s", ",", "final", "int", "start", ",", "final", "int", "end", ")", "throws", "NumberFormatException", "{", "if", "(", "s", ".", "charAt", "(", "start", ")", "==", "'", "'", ")", "{", "// negative!", "return", "-", "parseUnsignedLong", "(", "s", ",", "start", "+", "1", ",", "end", ")", ";", "}", "else", "{", "return", "parseUnsignedLong", "(", "s", ",", "start", ",", "end", ")", ";", "}", "}" ]
Parses out a long value from the provided string, equivalent to Long.parseLong(s.substring(start, end)), but has significantly less overhead, no object creation and later garbage collection required @throws {@link NumberFormatException} if it encounters any character that is not [-0-9].
[ "Parses", "out", "a", "long", "value", "from", "the", "provided", "string", "equivalent", "to", "Long", ".", "parseLong", "(", "s", ".", "substring", "(", "start", "end", "))", "but", "has", "significantly", "less", "overhead", "no", "object", "creation", "and", "later", "garbage", "collection", "required" ]
train
https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/urlparsing/src/main/java/com/indeed/util/urlparsing/ParseUtils.java#L65-L72
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Collectors.java
Collectors.toCollection
@NotNull public static <T, R extends Collection<T>> Collector<T, ?, R> toCollection( @NotNull Supplier<R> collectionSupplier) { """ Returns a {@code Collector} that fills new {@code Collection}, provided by {@code collectionSupplier}, with input elements. @param <T> the type of the input elements @param <R> the type of the resulting collection @param collectionSupplier a supplier function that provides new collection @return a {@code Collector} """ return new CollectorsImpl<T, R, R>( collectionSupplier, new BiConsumer<R, T>() { @Override public void accept(@NotNull R t, T u) { t.add(u); } } ); }
java
@NotNull public static <T, R extends Collection<T>> Collector<T, ?, R> toCollection( @NotNull Supplier<R> collectionSupplier) { return new CollectorsImpl<T, R, R>( collectionSupplier, new BiConsumer<R, T>() { @Override public void accept(@NotNull R t, T u) { t.add(u); } } ); }
[ "@", "NotNull", "public", "static", "<", "T", ",", "R", "extends", "Collection", "<", "T", ">", ">", "Collector", "<", "T", ",", "?", ",", "R", ">", "toCollection", "(", "@", "NotNull", "Supplier", "<", "R", ">", "collectionSupplier", ")", "{", "return", "new", "CollectorsImpl", "<", "T", ",", "R", ",", "R", ">", "(", "collectionSupplier", ",", "new", "BiConsumer", "<", "R", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "@", "NotNull", "R", "t", ",", "T", "u", ")", "{", "t", ".", "add", "(", "u", ")", ";", "}", "}", ")", ";", "}" ]
Returns a {@code Collector} that fills new {@code Collection}, provided by {@code collectionSupplier}, with input elements. @param <T> the type of the input elements @param <R> the type of the resulting collection @param collectionSupplier a supplier function that provides new collection @return a {@code Collector}
[ "Returns", "a", "{", "@code", "Collector", "}", "that", "fills", "new", "{", "@code", "Collection", "}", "provided", "by", "{", "@code", "collectionSupplier", "}", "with", "input", "elements", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L50-L64
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/ReferenceField.java
ReferenceField.moveFieldToThis
public int moveFieldToThis(BaseField field, boolean bDisplayOption, int iMoveMode) { """ Move data to this field from another field. If these isn't a reference record yet, figures out the reference record. @param field The source field. @return The error code (or NORMAL_RETURN). """ // Save the record and datarecord. if (field == null) return DBConstants.NORMAL_RETURN; if (field instanceof CounterField) { if (this.getReferenceRecord(null, false) == null) if (field.getRecord().getListener(ClearFieldReferenceOnCloseHandler.class) == null) // While it is okay to have two fields reference on record, don't default it. this.setReferenceRecord(field.getRecord()); } else if (field instanceof ReferenceField) { //x no this.setReferenceRecord(((ReferenceField)field).getReferenceRecord()); } else this.setReferenceRecord(null); return super.moveFieldToThis(field, bDisplayOption, iMoveMode); }
java
public int moveFieldToThis(BaseField field, boolean bDisplayOption, int iMoveMode) { // Save the record and datarecord. if (field == null) return DBConstants.NORMAL_RETURN; if (field instanceof CounterField) { if (this.getReferenceRecord(null, false) == null) if (field.getRecord().getListener(ClearFieldReferenceOnCloseHandler.class) == null) // While it is okay to have two fields reference on record, don't default it. this.setReferenceRecord(field.getRecord()); } else if (field instanceof ReferenceField) { //x no this.setReferenceRecord(((ReferenceField)field).getReferenceRecord()); } else this.setReferenceRecord(null); return super.moveFieldToThis(field, bDisplayOption, iMoveMode); }
[ "public", "int", "moveFieldToThis", "(", "BaseField", "field", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "// Save the record and datarecord.", "if", "(", "field", "==", "null", ")", "return", "DBConstants", ".", "NORMAL_RETURN", ";", "if", "(", "field", "instanceof", "CounterField", ")", "{", "if", "(", "this", ".", "getReferenceRecord", "(", "null", ",", "false", ")", "==", "null", ")", "if", "(", "field", ".", "getRecord", "(", ")", ".", "getListener", "(", "ClearFieldReferenceOnCloseHandler", ".", "class", ")", "==", "null", ")", "// While it is okay to have two fields reference on record, don't default it.", "this", ".", "setReferenceRecord", "(", "field", ".", "getRecord", "(", ")", ")", ";", "}", "else", "if", "(", "field", "instanceof", "ReferenceField", ")", "{", "//x no this.setReferenceRecord(((ReferenceField)field).getReferenceRecord());", "}", "else", "this", ".", "setReferenceRecord", "(", "null", ")", ";", "return", "super", ".", "moveFieldToThis", "(", "field", ",", "bDisplayOption", ",", "iMoveMode", ")", ";", "}" ]
Move data to this field from another field. If these isn't a reference record yet, figures out the reference record. @param field The source field. @return The error code (or NORMAL_RETURN).
[ "Move", "data", "to", "this", "field", "from", "another", "field", ".", "If", "these", "isn", "t", "a", "reference", "record", "yet", "figures", "out", "the", "reference", "record", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/ReferenceField.java#L83-L100
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.resetVpnClientSharedKeyAsync
public Observable<Void> resetVpnClientSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayName) { """ Resets the VPN client shared key of the virtual network gateway in the specified resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return resetVpnClientSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> resetVpnClientSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayName) { return resetVpnClientSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "resetVpnClientSharedKeyAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ")", "{", "return", "resetVpnClientSharedKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Resets the VPN client shared key of the virtual network gateway in the specified resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Resets", "the", "VPN", "client", "shared", "key", "of", "the", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/VirtualNetworkGatewaysInner.java#L1496-L1503
lucee/Lucee
core/src/main/java/lucee/runtime/type/scope/ScopeFactory.java
ScopeFactory.toStringScope
public static String toStringScope(int scope, String defaultValue) { """ cast a int scope definition to a string definition @param scope @return """ switch (scope) { case Scope.SCOPE_APPLICATION: return "application"; case Scope.SCOPE_ARGUMENTS: return "arguments"; case Scope.SCOPE_CALLER: return "caller"; case Scope.SCOPE_CGI: return "cgi"; case Scope.SCOPE_CLIENT: return "client"; case Scope.SCOPE_COOKIE: return "cookie"; case Scope.SCOPE_FORM: return "form"; case Scope.SCOPE_VAR: case Scope.SCOPE_LOCAL: return "local"; case Scope.SCOPE_REQUEST: return "request"; case Scope.SCOPE_SERVER: return "server"; case Scope.SCOPE_SESSION: return "session"; case Scope.SCOPE_UNDEFINED: return "undefined"; case Scope.SCOPE_URL: return "url"; case Scope.SCOPE_VARIABLES: return "variables"; case Scope.SCOPE_CLUSTER: return "cluster"; } return defaultValue; }
java
public static String toStringScope(int scope, String defaultValue) { switch (scope) { case Scope.SCOPE_APPLICATION: return "application"; case Scope.SCOPE_ARGUMENTS: return "arguments"; case Scope.SCOPE_CALLER: return "caller"; case Scope.SCOPE_CGI: return "cgi"; case Scope.SCOPE_CLIENT: return "client"; case Scope.SCOPE_COOKIE: return "cookie"; case Scope.SCOPE_FORM: return "form"; case Scope.SCOPE_VAR: case Scope.SCOPE_LOCAL: return "local"; case Scope.SCOPE_REQUEST: return "request"; case Scope.SCOPE_SERVER: return "server"; case Scope.SCOPE_SESSION: return "session"; case Scope.SCOPE_UNDEFINED: return "undefined"; case Scope.SCOPE_URL: return "url"; case Scope.SCOPE_VARIABLES: return "variables"; case Scope.SCOPE_CLUSTER: return "cluster"; } return defaultValue; }
[ "public", "static", "String", "toStringScope", "(", "int", "scope", ",", "String", "defaultValue", ")", "{", "switch", "(", "scope", ")", "{", "case", "Scope", ".", "SCOPE_APPLICATION", ":", "return", "\"application\"", ";", "case", "Scope", ".", "SCOPE_ARGUMENTS", ":", "return", "\"arguments\"", ";", "case", "Scope", ".", "SCOPE_CALLER", ":", "return", "\"caller\"", ";", "case", "Scope", ".", "SCOPE_CGI", ":", "return", "\"cgi\"", ";", "case", "Scope", ".", "SCOPE_CLIENT", ":", "return", "\"client\"", ";", "case", "Scope", ".", "SCOPE_COOKIE", ":", "return", "\"cookie\"", ";", "case", "Scope", ".", "SCOPE_FORM", ":", "return", "\"form\"", ";", "case", "Scope", ".", "SCOPE_VAR", ":", "case", "Scope", ".", "SCOPE_LOCAL", ":", "return", "\"local\"", ";", "case", "Scope", ".", "SCOPE_REQUEST", ":", "return", "\"request\"", ";", "case", "Scope", ".", "SCOPE_SERVER", ":", "return", "\"server\"", ";", "case", "Scope", ".", "SCOPE_SESSION", ":", "return", "\"session\"", ";", "case", "Scope", ".", "SCOPE_UNDEFINED", ":", "return", "\"undefined\"", ";", "case", "Scope", ".", "SCOPE_URL", ":", "return", "\"url\"", ";", "case", "Scope", ".", "SCOPE_VARIABLES", ":", "return", "\"variables\"", ";", "case", "Scope", ".", "SCOPE_CLUSTER", ":", "return", "\"cluster\"", ";", "}", "return", "defaultValue", ";", "}" ]
cast a int scope definition to a string definition @param scope @return
[ "cast", "a", "int", "scope", "definition", "to", "a", "string", "definition" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/scope/ScopeFactory.java#L82-L118
baratine/baratine
web/src/main/java/com/caucho/v5/http/protocol/RequestHttpBase.java
RequestHttpBase.addFooter
public void addFooter(String key, String value) { """ Adds a new footer. If an old footer with that name exists, both footers are output. @param key the footer key. @param value the footer value. """ if (headerOutSpecial(key, value)) { return; } _footerKeys.add(key); _footerValues.add(value); }
java
public void addFooter(String key, String value) { if (headerOutSpecial(key, value)) { return; } _footerKeys.add(key); _footerValues.add(value); }
[ "public", "void", "addFooter", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "headerOutSpecial", "(", "key", ",", "value", ")", ")", "{", "return", ";", "}", "_footerKeys", ".", "add", "(", "key", ")", ";", "_footerValues", ".", "add", "(", "value", ")", ";", "}" ]
Adds a new footer. If an old footer with that name exists, both footers are output. @param key the footer key. @param value the footer value.
[ "Adds", "a", "new", "footer", ".", "If", "an", "old", "footer", "with", "that", "name", "exists", "both", "footers", "are", "output", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/web/src/main/java/com/caucho/v5/http/protocol/RequestHttpBase.java#L2250-L2258
jenkinsci/jenkins
core/src/main/java/hudson/search/Search.java
Search.find
public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) { """ Performs a search and returns the match, or null if no match was found or more than one match was found. @since 1.527 """ List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext); if(r.isEmpty()){ return null; } else if(1==r.size()){ return r.get(0); } else { // we have more than one suggested item, so return the item who's url // contains the query as this is probably the job's name return findClosestSuggestedItem(r, query); } }
java
public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) { List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext); if(r.isEmpty()){ return null; } else if(1==r.size()){ return r.get(0); } else { // we have more than one suggested item, so return the item who's url // contains the query as this is probably the job's name return findClosestSuggestedItem(r, query); } }
[ "public", "static", "SuggestedItem", "find", "(", "SearchIndex", "index", ",", "String", "query", ",", "SearchableModelObject", "searchContext", ")", "{", "List", "<", "SuggestedItem", ">", "r", "=", "find", "(", "Mode", ".", "FIND", ",", "index", ",", "query", ",", "searchContext", ")", ";", "if", "(", "r", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "else", "if", "(", "1", "==", "r", ".", "size", "(", ")", ")", "{", "return", "r", ".", "get", "(", "0", ")", ";", "}", "else", "{", "// we have more than one suggested item, so return the item who's url", "// contains the query as this is probably the job's name", "return", "findClosestSuggestedItem", "(", "r", ",", "query", ")", ";", "}", "}" ]
Performs a search and returns the match, or null if no match was found or more than one match was found. @since 1.527
[ "Performs", "a", "search", "and", "returns", "the", "match", "or", "null", "if", "no", "match", "was", "found", "or", "more", "than", "one", "match", "was", "found", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/search/Search.java#L265-L279
box/box-java-sdk
src/main/java/com/box/sdk/BoxFolder.java
BoxFolder.collaborate
public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role) { """ Adds a collaborator to this folder. @param collaborator the collaborator to add. @param role the role of the collaborator. @return info about the new collaboration. """ JsonObject accessibleByField = new JsonObject(); accessibleByField.add("id", collaborator.getID()); if (collaborator instanceof BoxUser) { accessibleByField.add("type", "user"); } else if (collaborator instanceof BoxGroup) { accessibleByField.add("type", "group"); } else { throw new IllegalArgumentException("The given collaborator is of an unknown type."); } return this.collaborate(accessibleByField, role, null, null); }
java
public BoxCollaboration.Info collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role) { JsonObject accessibleByField = new JsonObject(); accessibleByField.add("id", collaborator.getID()); if (collaborator instanceof BoxUser) { accessibleByField.add("type", "user"); } else if (collaborator instanceof BoxGroup) { accessibleByField.add("type", "group"); } else { throw new IllegalArgumentException("The given collaborator is of an unknown type."); } return this.collaborate(accessibleByField, role, null, null); }
[ "public", "BoxCollaboration", ".", "Info", "collaborate", "(", "BoxCollaborator", "collaborator", ",", "BoxCollaboration", ".", "Role", "role", ")", "{", "JsonObject", "accessibleByField", "=", "new", "JsonObject", "(", ")", ";", "accessibleByField", ".", "add", "(", "\"id\"", ",", "collaborator", ".", "getID", "(", ")", ")", ";", "if", "(", "collaborator", "instanceof", "BoxUser", ")", "{", "accessibleByField", ".", "add", "(", "\"type\"", ",", "\"user\"", ")", ";", "}", "else", "if", "(", "collaborator", "instanceof", "BoxGroup", ")", "{", "accessibleByField", ".", "add", "(", "\"type\"", ",", "\"group\"", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"The given collaborator is of an unknown type.\"", ")", ";", "}", "return", "this", ".", "collaborate", "(", "accessibleByField", ",", "role", ",", "null", ",", "null", ")", ";", "}" ]
Adds a collaborator to this folder. @param collaborator the collaborator to add. @param role the role of the collaborator. @return info about the new collaboration.
[ "Adds", "a", "collaborator", "to", "this", "folder", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFolder.java#L137-L150
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/InterpolateTransform.java
InterpolateTransform.putDataPoint
private void putDataPoint(int i, Entry<Long, Double> datapoint) { """ Puts the next data point of an iterator in the next section of internal buffer. @param i The index of the iterator. @param datapoint The last data point returned by that iterator. """ timestamps[i] = datapoint.getKey(); values[i] = datapoint.getValue(); }
java
private void putDataPoint(int i, Entry<Long, Double> datapoint) { timestamps[i] = datapoint.getKey(); values[i] = datapoint.getValue(); }
[ "private", "void", "putDataPoint", "(", "int", "i", ",", "Entry", "<", "Long", ",", "Double", ">", "datapoint", ")", "{", "timestamps", "[", "i", "]", "=", "datapoint", ".", "getKey", "(", ")", ";", "values", "[", "i", "]", "=", "datapoint", ".", "getValue", "(", ")", ";", "}" ]
Puts the next data point of an iterator in the next section of internal buffer. @param i The index of the iterator. @param datapoint The last data point returned by that iterator.
[ "Puts", "the", "next", "data", "point", "of", "an", "iterator", "in", "the", "next", "section", "of", "internal", "buffer", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/InterpolateTransform.java#L226-L229
UrielCh/ovh-java-sdk
ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java
ApiOvhEmaildomain.delegatedAccount_email_filter_name_changeActivity_POST
public OvhTaskFilter delegatedAccount_email_filter_name_changeActivity_POST(String email, String name, Boolean activity) throws IOException { """ Change filter activity REST: POST /email/domain/delegatedAccount/{email}/filter/{name}/changeActivity @param activity [required] New activity @param email [required] Email @param name [required] Filter name """ String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}/changeActivity"; StringBuilder sb = path(qPath, email, name); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "activity", activity); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTaskFilter.class); }
java
public OvhTaskFilter delegatedAccount_email_filter_name_changeActivity_POST(String email, String name, Boolean activity) throws IOException { String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}/changeActivity"; StringBuilder sb = path(qPath, email, name); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "activity", activity); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTaskFilter.class); }
[ "public", "OvhTaskFilter", "delegatedAccount_email_filter_name_changeActivity_POST", "(", "String", "email", ",", "String", "name", ",", "Boolean", "activity", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/domain/delegatedAccount/{email}/filter/{name}/changeActivity\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "email", ",", "name", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"activity\"", ",", "activity", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTaskFilter", ".", "class", ")", ";", "}" ]
Change filter activity REST: POST /email/domain/delegatedAccount/{email}/filter/{name}/changeActivity @param activity [required] New activity @param email [required] Email @param name [required] Filter name
[ "Change", "filter", "activity" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L161-L168
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/variable/VariableUtils.java
VariableUtils.getValueFromScript
public static String getValueFromScript(String scriptEngine, String code) { """ Evaluates script code and returns a variable value as result. @param scriptEngine the name of the scripting engine. @param code the script code. @return the variable value as String. """ try { ScriptEngine engine = new ScriptEngineManager().getEngineByName(scriptEngine); if (engine == null) { throw new CitrusRuntimeException("Unable to find script engine with name '" + scriptEngine + "'"); } return engine.eval(code).toString(); } catch (ScriptException e) { throw new CitrusRuntimeException("Failed to evaluate " + scriptEngine + " script", e); } }
java
public static String getValueFromScript(String scriptEngine, String code) { try { ScriptEngine engine = new ScriptEngineManager().getEngineByName(scriptEngine); if (engine == null) { throw new CitrusRuntimeException("Unable to find script engine with name '" + scriptEngine + "'"); } return engine.eval(code).toString(); } catch (ScriptException e) { throw new CitrusRuntimeException("Failed to evaluate " + scriptEngine + " script", e); } }
[ "public", "static", "String", "getValueFromScript", "(", "String", "scriptEngine", ",", "String", "code", ")", "{", "try", "{", "ScriptEngine", "engine", "=", "new", "ScriptEngineManager", "(", ")", ".", "getEngineByName", "(", "scriptEngine", ")", ";", "if", "(", "engine", "==", "null", ")", "{", "throw", "new", "CitrusRuntimeException", "(", "\"Unable to find script engine with name '\"", "+", "scriptEngine", "+", "\"'\"", ")", ";", "}", "return", "engine", ".", "eval", "(", "code", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "ScriptException", "e", ")", "{", "throw", "new", "CitrusRuntimeException", "(", "\"Failed to evaluate \"", "+", "scriptEngine", "+", "\" script\"", ",", "e", ")", ";", "}", "}" ]
Evaluates script code and returns a variable value as result. @param scriptEngine the name of the scripting engine. @param code the script code. @return the variable value as String.
[ "Evaluates", "script", "code", "and", "returns", "a", "variable", "value", "as", "result", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/variable/VariableUtils.java#L47-L59
TheHortonMachine/hortonmachine
gears/src/main/java/oms3/Controller.java
Controller.mapOut
void mapOut(String out, Object comp, String comp_out) { """ Map two output fields. @param out the output field name of this component @param comp the component @param comp_out the component output name; """ if (comp == ca.getComponent()) { throw new ComponentException("cannot connect 'Out' with itself for " + out); } ComponentAccess ac_dest = lookup(comp); FieldAccess destAccess = (FieldAccess) ac_dest.output(comp_out); FieldAccess srcAccess = (FieldAccess) ca.output(out); checkFA(destAccess, comp, comp_out); checkFA(srcAccess, ca.getComponent(), out); FieldContent data = srcAccess.getData(); data.tagLeaf(); data.tagOut(); destAccess.setData(data); dataSet.add(data); if (log.isLoggable(Level.CONFIG)) { log.log(Level.CONFIG, String.format("@Out(%s) -> @Out(%s)", srcAccess, destAccess)); } // ens.fireMapOut(srcAccess, destAccess); }
java
void mapOut(String out, Object comp, String comp_out) { if (comp == ca.getComponent()) { throw new ComponentException("cannot connect 'Out' with itself for " + out); } ComponentAccess ac_dest = lookup(comp); FieldAccess destAccess = (FieldAccess) ac_dest.output(comp_out); FieldAccess srcAccess = (FieldAccess) ca.output(out); checkFA(destAccess, comp, comp_out); checkFA(srcAccess, ca.getComponent(), out); FieldContent data = srcAccess.getData(); data.tagLeaf(); data.tagOut(); destAccess.setData(data); dataSet.add(data); if (log.isLoggable(Level.CONFIG)) { log.log(Level.CONFIG, String.format("@Out(%s) -> @Out(%s)", srcAccess, destAccess)); } // ens.fireMapOut(srcAccess, destAccess); }
[ "void", "mapOut", "(", "String", "out", ",", "Object", "comp", ",", "String", "comp_out", ")", "{", "if", "(", "comp", "==", "ca", ".", "getComponent", "(", ")", ")", "{", "throw", "new", "ComponentException", "(", "\"cannot connect 'Out' with itself for \"", "+", "out", ")", ";", "}", "ComponentAccess", "ac_dest", "=", "lookup", "(", "comp", ")", ";", "FieldAccess", "destAccess", "=", "(", "FieldAccess", ")", "ac_dest", ".", "output", "(", "comp_out", ")", ";", "FieldAccess", "srcAccess", "=", "(", "FieldAccess", ")", "ca", ".", "output", "(", "out", ")", ";", "checkFA", "(", "destAccess", ",", "comp", ",", "comp_out", ")", ";", "checkFA", "(", "srcAccess", ",", "ca", ".", "getComponent", "(", ")", ",", "out", ")", ";", "FieldContent", "data", "=", "srcAccess", ".", "getData", "(", ")", ";", "data", ".", "tagLeaf", "(", ")", ";", "data", ".", "tagOut", "(", ")", ";", "destAccess", ".", "setData", "(", "data", ")", ";", "dataSet", ".", "add", "(", "data", ")", ";", "if", "(", "log", ".", "isLoggable", "(", "Level", ".", "CONFIG", ")", ")", "{", "log", ".", "log", "(", "Level", ".", "CONFIG", ",", "String", ".", "format", "(", "\"@Out(%s) -> @Out(%s)\"", ",", "srcAccess", ",", "destAccess", ")", ")", ";", "}", "// ens.fireMapOut(srcAccess, destAccess);", "}" ]
Map two output fields. @param out the output field name of this component @param comp the component @param comp_out the component output name;
[ "Map", "two", "output", "fields", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/Controller.java#L85-L106
couchbase/couchbase-lite-java
src/main/java/com/couchbase/lite/Dictionary.java
Dictionary.getValue
@Override public Object getValue(@NonNull String key) { """ Gets a property's value as an object. The object types are Blob, Array, Dictionary, Number, or String based on the underlying data type; or nil if the property value is null or the property doesn't exist. @param key the key. @return the object value or nil. """ if (key == null) { throw new IllegalArgumentException("key cannot be null."); } synchronized (lock) { return getMValue(internalDict, key).asNative(internalDict); } }
java
@Override public Object getValue(@NonNull String key) { if (key == null) { throw new IllegalArgumentException("key cannot be null."); } synchronized (lock) { return getMValue(internalDict, key).asNative(internalDict); } }
[ "@", "Override", "public", "Object", "getValue", "(", "@", "NonNull", "String", "key", ")", "{", "if", "(", "key", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"key cannot be null.\"", ")", ";", "}", "synchronized", "(", "lock", ")", "{", "return", "getMValue", "(", "internalDict", ",", "key", ")", ".", "asNative", "(", "internalDict", ")", ";", "}", "}" ]
Gets a property's value as an object. The object types are Blob, Array, Dictionary, Number, or String based on the underlying data type; or nil if the property value is null or the property doesn't exist. @param key the key. @return the object value or nil.
[ "Gets", "a", "property", "s", "value", "as", "an", "object", ".", "The", "object", "types", "are", "Blob", "Array", "Dictionary", "Number", "or", "String", "based", "on", "the", "underlying", "data", "type", ";", "or", "nil", "if", "the", "property", "value", "is", "null", "or", "the", "property", "doesn", "t", "exist", "." ]
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/Dictionary.java#L114-L121
OpenLiberty/open-liberty
dev/com.ibm.ws.session.db/src/com/ibm/ws/session/store/db/DatabaseHashMap.java
DatabaseHashMap.loadOneValue
protected Object loadOneValue(String attrName, BackedSession sess) { """ /* loadOneValue For multirow db, attempts to get the requested attr from the db Returns null if attr doesn't exist or we're not running multirow After PM90293, we consider populatedAppData as well populatedAppData is true when session is new or when the entire session is read into memory in those cases, we don't want to go to the backend to retrieve the attribute """ Object value = null; if (_smc.isUsingMultirow() && !((DatabaseSession)sess).getPopulatedAppData()) { //PM90293 value = getValue(attrName, sess); } return value; }
java
protected Object loadOneValue(String attrName, BackedSession sess) { Object value = null; if (_smc.isUsingMultirow() && !((DatabaseSession)sess).getPopulatedAppData()) { //PM90293 value = getValue(attrName, sess); } return value; }
[ "protected", "Object", "loadOneValue", "(", "String", "attrName", ",", "BackedSession", "sess", ")", "{", "Object", "value", "=", "null", ";", "if", "(", "_smc", ".", "isUsingMultirow", "(", ")", "&&", "!", "(", "(", "DatabaseSession", ")", "sess", ")", ".", "getPopulatedAppData", "(", ")", ")", "{", "//PM90293", "value", "=", "getValue", "(", "attrName", ",", "sess", ")", ";", "}", "return", "value", ";", "}" ]
/* loadOneValue For multirow db, attempts to get the requested attr from the db Returns null if attr doesn't exist or we're not running multirow After PM90293, we consider populatedAppData as well populatedAppData is true when session is new or when the entire session is read into memory in those cases, we don't want to go to the backend to retrieve the attribute
[ "/", "*", "loadOneValue", "For", "multirow", "db", "attempts", "to", "get", "the", "requested", "attr", "from", "the", "db", "Returns", "null", "if", "attr", "doesn", "t", "exist", "or", "we", "re", "not", "running", "multirow", "After", "PM90293", "we", "consider", "populatedAppData", "as", "well", "populatedAppData", "is", "true", "when", "session", "is", "new", "or", "when", "the", "entire", "session", "is", "read", "into", "memory", "in", "those", "cases", "we", "don", "t", "want", "to", "go", "to", "the", "backend", "to", "retrieve", "the", "attribute" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.session.db/src/com/ibm/ws/session/store/db/DatabaseHashMap.java#L3096-L3102
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/proxy/MapProxySupport.java
MapProxySupport.loadInternal
protected void loadInternal(Set<K> keys, Iterable<Data> dataKeys, boolean replaceExistingValues) { """ Maps keys to corresponding partitions and sends operations to them. """ if (dataKeys == null) { dataKeys = convertToData(keys); } Map<Integer, List<Data>> partitionIdToKeys = getPartitionIdToKeysMap(dataKeys); Iterable<Entry<Integer, List<Data>>> entries = partitionIdToKeys.entrySet(); for (Entry<Integer, List<Data>> entry : entries) { Integer partitionId = entry.getKey(); List<Data> correspondingKeys = entry.getValue(); Operation operation = createLoadAllOperation(correspondingKeys, replaceExistingValues); operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId); } waitUntilLoaded(); }
java
protected void loadInternal(Set<K> keys, Iterable<Data> dataKeys, boolean replaceExistingValues) { if (dataKeys == null) { dataKeys = convertToData(keys); } Map<Integer, List<Data>> partitionIdToKeys = getPartitionIdToKeysMap(dataKeys); Iterable<Entry<Integer, List<Data>>> entries = partitionIdToKeys.entrySet(); for (Entry<Integer, List<Data>> entry : entries) { Integer partitionId = entry.getKey(); List<Data> correspondingKeys = entry.getValue(); Operation operation = createLoadAllOperation(correspondingKeys, replaceExistingValues); operationService.invokeOnPartition(SERVICE_NAME, operation, partitionId); } waitUntilLoaded(); }
[ "protected", "void", "loadInternal", "(", "Set", "<", "K", ">", "keys", ",", "Iterable", "<", "Data", ">", "dataKeys", ",", "boolean", "replaceExistingValues", ")", "{", "if", "(", "dataKeys", "==", "null", ")", "{", "dataKeys", "=", "convertToData", "(", "keys", ")", ";", "}", "Map", "<", "Integer", ",", "List", "<", "Data", ">", ">", "partitionIdToKeys", "=", "getPartitionIdToKeysMap", "(", "dataKeys", ")", ";", "Iterable", "<", "Entry", "<", "Integer", ",", "List", "<", "Data", ">", ">", ">", "entries", "=", "partitionIdToKeys", ".", "entrySet", "(", ")", ";", "for", "(", "Entry", "<", "Integer", ",", "List", "<", "Data", ">", ">", "entry", ":", "entries", ")", "{", "Integer", "partitionId", "=", "entry", ".", "getKey", "(", ")", ";", "List", "<", "Data", ">", "correspondingKeys", "=", "entry", ".", "getValue", "(", ")", ";", "Operation", "operation", "=", "createLoadAllOperation", "(", "correspondingKeys", ",", "replaceExistingValues", ")", ";", "operationService", ".", "invokeOnPartition", "(", "SERVICE_NAME", ",", "operation", ",", "partitionId", ")", ";", "}", "waitUntilLoaded", "(", ")", ";", "}" ]
Maps keys to corresponding partitions and sends operations to them.
[ "Maps", "keys", "to", "corresponding", "partitions", "and", "sends", "operations", "to", "them", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/proxy/MapProxySupport.java#L562-L575
zxing/zxing
core/src/main/java/com/google/zxing/common/BitArray.java
BitArray.isRange
public boolean isRange(int start, int end, boolean value) { """ Efficient method to check if a range of bits is set, or not set. @param start start of range, inclusive. @param end end of range, exclusive @param value if true, checks that bits in range are set, otherwise checks that they are not set @return true iff all bits are set or not set in range, according to value argument @throws IllegalArgumentException if end is less than start or the range is not contained in the array """ if (end < start || start < 0 || end > size) { throw new IllegalArgumentException(); } if (end == start) { return true; // empty range matches } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start / 32; int lastInt = end / 32; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; // Ones from firstBit to lastBit, inclusive int mask = (2 << lastBit) - (1 << firstBit); // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) != (value ? mask : 0)) { return false; } } return true; }
java
public boolean isRange(int start, int end, boolean value) { if (end < start || start < 0 || end > size) { throw new IllegalArgumentException(); } if (end == start) { return true; // empty range matches } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start / 32; int lastInt = end / 32; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; // Ones from firstBit to lastBit, inclusive int mask = (2 << lastBit) - (1 << firstBit); // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) != (value ? mask : 0)) { return false; } } return true; }
[ "public", "boolean", "isRange", "(", "int", "start", ",", "int", "end", ",", "boolean", "value", ")", "{", "if", "(", "end", "<", "start", "||", "start", "<", "0", "||", "end", ">", "size", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "if", "(", "end", "==", "start", ")", "{", "return", "true", ";", "// empty range matches", "}", "end", "--", ";", "// will be easier to treat this as the last actually set bit -- inclusive", "int", "firstInt", "=", "start", "/", "32", ";", "int", "lastInt", "=", "end", "/", "32", ";", "for", "(", "int", "i", "=", "firstInt", ";", "i", "<=", "lastInt", ";", "i", "++", ")", "{", "int", "firstBit", "=", "i", ">", "firstInt", "?", "0", ":", "start", "&", "0x1F", ";", "int", "lastBit", "=", "i", "<", "lastInt", "?", "31", ":", "end", "&", "0x1F", ";", "// Ones from firstBit to lastBit, inclusive", "int", "mask", "=", "(", "2", "<<", "lastBit", ")", "-", "(", "1", "<<", "firstBit", ")", ";", "// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,", "// equals the mask, or we're looking for 0s and the masked portion is not all 0s", "if", "(", "(", "bits", "[", "i", "]", "&", "mask", ")", "!=", "(", "value", "?", "mask", ":", "0", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Efficient method to check if a range of bits is set, or not set. @param start start of range, inclusive. @param end end of range, exclusive @param value if true, checks that bits in range are set, otherwise checks that they are not set @return true iff all bits are set or not set in range, according to value argument @throws IllegalArgumentException if end is less than start or the range is not contained in the array
[ "Efficient", "method", "to", "check", "if", "a", "range", "of", "bits", "is", "set", "or", "not", "set", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/common/BitArray.java#L191-L214
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
CheckArg.isPowerOfTwo
public static void isPowerOfTwo( int argument, String name ) { """ Check that the argument is a power of 2. @param argument The argument @param name The name of the argument @throws IllegalArgumentException If argument is not a power of 2 """ if (Integer.bitCount(argument) != 1) { throw new IllegalArgumentException(CommonI18n.argumentMustBePowerOfTwo.text(name, argument)); } }
java
public static void isPowerOfTwo( int argument, String name ) { if (Integer.bitCount(argument) != 1) { throw new IllegalArgumentException(CommonI18n.argumentMustBePowerOfTwo.text(name, argument)); } }
[ "public", "static", "void", "isPowerOfTwo", "(", "int", "argument", ",", "String", "name", ")", "{", "if", "(", "Integer", ".", "bitCount", "(", "argument", ")", "!=", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "CommonI18n", ".", "argumentMustBePowerOfTwo", ".", "text", "(", "name", ",", "argument", ")", ")", ";", "}", "}" ]
Check that the argument is a power of 2. @param argument The argument @param name The name of the argument @throws IllegalArgumentException If argument is not a power of 2
[ "Check", "that", "the", "argument", "is", "a", "power", "of", "2", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L210-L215
Azure/azure-sdk-for-java
compute/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/compute/v2018_04_01/implementation/SnapshotsInner.java
SnapshotsInner.beginRevokeAccess
public void beginRevokeAccess(String resourceGroupName, String snapshotName) { """ Revokes access to a snapshot. @param resourceGroupName The name of the resource group. @param snapshotName The name of the snapshot that is being created. The name can't be changed after the snapshot is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ beginRevokeAccessWithServiceResponseAsync(resourceGroupName, snapshotName).toBlocking().single().body(); }
java
public void beginRevokeAccess(String resourceGroupName, String snapshotName) { beginRevokeAccessWithServiceResponseAsync(resourceGroupName, snapshotName).toBlocking().single().body(); }
[ "public", "void", "beginRevokeAccess", "(", "String", "resourceGroupName", ",", "String", "snapshotName", ")", "{", "beginRevokeAccessWithServiceResponseAsync", "(", "resourceGroupName", ",", "snapshotName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Revokes access to a snapshot. @param resourceGroupName The name of the resource group. @param snapshotName The name of the snapshot that is being created. The name can't be changed after the snapshot is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The max name length is 80 characters. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Revokes", "access", "to", "a", "snapshot", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/compute/v2018_04_01/implementation/SnapshotsInner.java#L1189-L1191
rzwitserloot/lombok
src/core/lombok/core/handlers/HandlerUtil.java
HandlerUtil.checkName
public static boolean checkName(String nameSpec, String identifier, LombokNode<?, ?, ?> errorNode) { """ Checks if the given name is a valid identifier. If it is, this returns {@code true} and does nothing else. If it isn't, this returns {@code false} and adds an error message to the supplied node. """ if (identifier.isEmpty()) { errorNode.addError(nameSpec + " cannot be the empty string."); return false; } if (!JavaIdentifiers.isValidJavaIdentifier(identifier)) { errorNode.addError(nameSpec + " must be a valid java identifier."); return false; } return true; }
java
public static boolean checkName(String nameSpec, String identifier, LombokNode<?, ?, ?> errorNode) { if (identifier.isEmpty()) { errorNode.addError(nameSpec + " cannot be the empty string."); return false; } if (!JavaIdentifiers.isValidJavaIdentifier(identifier)) { errorNode.addError(nameSpec + " must be a valid java identifier."); return false; } return true; }
[ "public", "static", "boolean", "checkName", "(", "String", "nameSpec", ",", "String", "identifier", ",", "LombokNode", "<", "?", ",", "?", ",", "?", ">", "errorNode", ")", "{", "if", "(", "identifier", ".", "isEmpty", "(", ")", ")", "{", "errorNode", ".", "addError", "(", "nameSpec", "+", "\" cannot be the empty string.\"", ")", ";", "return", "false", ";", "}", "if", "(", "!", "JavaIdentifiers", ".", "isValidJavaIdentifier", "(", "identifier", ")", ")", "{", "errorNode", ".", "addError", "(", "nameSpec", "+", "\" must be a valid java identifier.\"", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if the given name is a valid identifier. If it is, this returns {@code true} and does nothing else. If it isn't, this returns {@code false} and adds an error message to the supplied node.
[ "Checks", "if", "the", "given", "name", "is", "a", "valid", "identifier", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/core/handlers/HandlerUtil.java#L310-L322
mikepenz/Android-Iconics
library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java
IconicsDrawable.iconText
@NonNull public IconicsDrawable iconText(@NonNull String icon, @Nullable Typeface typeface) { """ Loads and draws given text @return The current IconicsDrawable for chaining. """ mPlainIcon = icon; mIcon = null; mIconBrush.getPaint().setTypeface(typeface == null ? Typeface.DEFAULT : typeface); invalidateSelf(); return this; }
java
@NonNull public IconicsDrawable iconText(@NonNull String icon, @Nullable Typeface typeface) { mPlainIcon = icon; mIcon = null; mIconBrush.getPaint().setTypeface(typeface == null ? Typeface.DEFAULT : typeface); invalidateSelf(); return this; }
[ "@", "NonNull", "public", "IconicsDrawable", "iconText", "(", "@", "NonNull", "String", "icon", ",", "@", "Nullable", "Typeface", "typeface", ")", "{", "mPlainIcon", "=", "icon", ";", "mIcon", "=", "null", ";", "mIconBrush", ".", "getPaint", "(", ")", ".", "setTypeface", "(", "typeface", "==", "null", "?", "Typeface", ".", "DEFAULT", ":", "typeface", ")", ";", "invalidateSelf", "(", ")", ";", "return", "this", ";", "}" ]
Loads and draws given text @return The current IconicsDrawable for chaining.
[ "Loads", "and", "draws", "given", "text" ]
train
https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java#L404-L412
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/ImplDisparityScoreSadRectFive_U8.java
ImplDisparityScoreSadRectFive_U8.computeRemainingRows
private void computeRemainingRows(GrayU8 left, GrayU8 right ) { """ Using previously computed results it efficiently finds the disparity in the remaining rows. When a new block is processes the last row/column is subtracted and the new row/column is added. """ for( int row = regionHeight; row < left.height; row++ , activeVerticalScore++) { int oldRow = row%regionHeight; int previous[] = verticalScore[ (activeVerticalScore -1) % regionHeight ]; int active[] = verticalScore[ activeVerticalScore % regionHeight ]; // subtract first row from vertical score int scores[] = horizontalScore[oldRow]; for( int i = 0; i < lengthHorizontal; i++ ) { active[i] = previous[i] - scores[i]; } UtilDisparityScore.computeScoreRow(left, right, row, scores, minDisparity,maxDisparity,regionWidth,elementScore); // add the new score for( int i = 0; i < lengthHorizontal; i++ ) { active[i] += scores[i]; } if( activeVerticalScore >= regionHeight-1 ) { int top[] = verticalScore[ (activeVerticalScore -2*radiusY) % regionHeight ]; int middle[] = verticalScore[ (activeVerticalScore -radiusY) % regionHeight ]; int bottom[] = verticalScore[ activeVerticalScore % regionHeight ]; computeScoreFive(top,middle,bottom,fiveScore,left.width); computeDisparity.process(row - (1 + 4*radiusY) + 2*radiusY+1, fiveScore ); } } }
java
private void computeRemainingRows(GrayU8 left, GrayU8 right ) { for( int row = regionHeight; row < left.height; row++ , activeVerticalScore++) { int oldRow = row%regionHeight; int previous[] = verticalScore[ (activeVerticalScore -1) % regionHeight ]; int active[] = verticalScore[ activeVerticalScore % regionHeight ]; // subtract first row from vertical score int scores[] = horizontalScore[oldRow]; for( int i = 0; i < lengthHorizontal; i++ ) { active[i] = previous[i] - scores[i]; } UtilDisparityScore.computeScoreRow(left, right, row, scores, minDisparity,maxDisparity,regionWidth,elementScore); // add the new score for( int i = 0; i < lengthHorizontal; i++ ) { active[i] += scores[i]; } if( activeVerticalScore >= regionHeight-1 ) { int top[] = verticalScore[ (activeVerticalScore -2*radiusY) % regionHeight ]; int middle[] = verticalScore[ (activeVerticalScore -radiusY) % regionHeight ]; int bottom[] = verticalScore[ activeVerticalScore % regionHeight ]; computeScoreFive(top,middle,bottom,fiveScore,left.width); computeDisparity.process(row - (1 + 4*radiusY) + 2*radiusY+1, fiveScore ); } } }
[ "private", "void", "computeRemainingRows", "(", "GrayU8", "left", ",", "GrayU8", "right", ")", "{", "for", "(", "int", "row", "=", "regionHeight", ";", "row", "<", "left", ".", "height", ";", "row", "++", ",", "activeVerticalScore", "++", ")", "{", "int", "oldRow", "=", "row", "%", "regionHeight", ";", "int", "previous", "[", "]", "=", "verticalScore", "[", "(", "activeVerticalScore", "-", "1", ")", "%", "regionHeight", "]", ";", "int", "active", "[", "]", "=", "verticalScore", "[", "activeVerticalScore", "%", "regionHeight", "]", ";", "// subtract first row from vertical score", "int", "scores", "[", "]", "=", "horizontalScore", "[", "oldRow", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lengthHorizontal", ";", "i", "++", ")", "{", "active", "[", "i", "]", "=", "previous", "[", "i", "]", "-", "scores", "[", "i", "]", ";", "}", "UtilDisparityScore", ".", "computeScoreRow", "(", "left", ",", "right", ",", "row", ",", "scores", ",", "minDisparity", ",", "maxDisparity", ",", "regionWidth", ",", "elementScore", ")", ";", "// add the new score", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lengthHorizontal", ";", "i", "++", ")", "{", "active", "[", "i", "]", "+=", "scores", "[", "i", "]", ";", "}", "if", "(", "activeVerticalScore", ">=", "regionHeight", "-", "1", ")", "{", "int", "top", "[", "]", "=", "verticalScore", "[", "(", "activeVerticalScore", "-", "2", "*", "radiusY", ")", "%", "regionHeight", "]", ";", "int", "middle", "[", "]", "=", "verticalScore", "[", "(", "activeVerticalScore", "-", "radiusY", ")", "%", "regionHeight", "]", ";", "int", "bottom", "[", "]", "=", "verticalScore", "[", "activeVerticalScore", "%", "regionHeight", "]", ";", "computeScoreFive", "(", "top", ",", "middle", ",", "bottom", ",", "fiveScore", ",", "left", ".", "width", ")", ";", "computeDisparity", ".", "process", "(", "row", "-", "(", "1", "+", "4", "*", "radiusY", ")", "+", "2", "*", "radiusY", "+", "1", ",", "fiveScore", ")", ";", "}", "}", "}" ]
Using previously computed results it efficiently finds the disparity in the remaining rows. When a new block is processes the last row/column is subtracted and the new row/column is added.
[ "Using", "previously", "computed", "results", "it", "efficiently", "finds", "the", "disparity", "in", "the", "remaining", "rows", ".", "When", "a", "new", "block", "is", "processes", "the", "last", "row", "/", "column", "is", "subtracted", "and", "the", "new", "row", "/", "column", "is", "added", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/ImplDisparityScoreSadRectFive_U8.java#L113-L143
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java
ViewHelper.setImageUri
public static void setImageUri(EfficientCacheView cacheView, int viewId, @Nullable Uri uri) { """ Equivalent to calling ImageView.setImageUri @param cacheView The cache of views to get the view from @param viewId The id of the view whose image should change @param uri the Uri of an image, or {@code null} to clear the content """ View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof ImageView) { ((ImageView) view).setImageURI(uri); } }
java
public static void setImageUri(EfficientCacheView cacheView, int viewId, @Nullable Uri uri) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof ImageView) { ((ImageView) view).setImageURI(uri); } }
[ "public", "static", "void", "setImageUri", "(", "EfficientCacheView", "cacheView", ",", "int", "viewId", ",", "@", "Nullable", "Uri", "uri", ")", "{", "View", "view", "=", "cacheView", ".", "findViewByIdEfficient", "(", "viewId", ")", ";", "if", "(", "view", "instanceof", "ImageView", ")", "{", "(", "(", "ImageView", ")", "view", ")", ".", "setImageURI", "(", "uri", ")", ";", "}", "}" ]
Equivalent to calling ImageView.setImageUri @param cacheView The cache of views to get the view from @param viewId The id of the view whose image should change @param uri the Uri of an image, or {@code null} to clear the content
[ "Equivalent", "to", "calling", "ImageView", ".", "setImageUri" ]
train
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L217-L222
redkale/redkale
src/org/redkale/net/http/HttpRequest.java
HttpRequest.getFlipper
public org.redkale.source.Flipper getFlipper(boolean needcreate, int maxLimit) { """ 获取翻页对象 同 getFlipper("flipper", needcreate, maxLimit) @param needcreate 无参数时是否创建新Flipper对象 @param maxLimit 最大行数, 小于1则值为Flipper.DEFAULT_LIMIT @return Flipper翻页对象 """ return getFlipper("flipper", needcreate, maxLimit); }
java
public org.redkale.source.Flipper getFlipper(boolean needcreate, int maxLimit) { return getFlipper("flipper", needcreate, maxLimit); }
[ "public", "org", ".", "redkale", ".", "source", ".", "Flipper", "getFlipper", "(", "boolean", "needcreate", ",", "int", "maxLimit", ")", "{", "return", "getFlipper", "(", "\"flipper\"", ",", "needcreate", ",", "maxLimit", ")", ";", "}" ]
获取翻页对象 同 getFlipper("flipper", needcreate, maxLimit) @param needcreate 无参数时是否创建新Flipper对象 @param maxLimit 最大行数, 小于1则值为Flipper.DEFAULT_LIMIT @return Flipper翻页对象
[ "获取翻页对象", "同", "getFlipper", "(", "flipper", "needcreate", "maxLimit", ")" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/HttpRequest.java#L1478-L1480
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/AuditorFactory.java
AuditorFactory.getAuditor
public static IHEAuditor getAuditor(Class<? extends IHEAuditor> clazz, AuditorModuleConfig configToUse, AuditorModuleContext contextToUse) { """ Get an auditor instance for the specified auditor class, auditor configuration, and auditor context. @param clazz Class to instantiate @param configToUse Auditor configuration to use @param contextToUse Auditor context to use @return Instance of an IHE Auditor """ IHEAuditor auditor = AuditorFactory.getAuditorForClass(clazz); if (auditor != null) { auditor.setConfig(configToUse); auditor.setContext(contextToUse); } return auditor; }
java
public static IHEAuditor getAuditor(Class<? extends IHEAuditor> clazz, AuditorModuleConfig configToUse, AuditorModuleContext contextToUse) { IHEAuditor auditor = AuditorFactory.getAuditorForClass(clazz); if (auditor != null) { auditor.setConfig(configToUse); auditor.setContext(contextToUse); } return auditor; }
[ "public", "static", "IHEAuditor", "getAuditor", "(", "Class", "<", "?", "extends", "IHEAuditor", ">", "clazz", ",", "AuditorModuleConfig", "configToUse", ",", "AuditorModuleContext", "contextToUse", ")", "{", "IHEAuditor", "auditor", "=", "AuditorFactory", ".", "getAuditorForClass", "(", "clazz", ")", ";", "if", "(", "auditor", "!=", "null", ")", "{", "auditor", ".", "setConfig", "(", "configToUse", ")", ";", "auditor", ".", "setContext", "(", "contextToUse", ")", ";", "}", "return", "auditor", ";", "}" ]
Get an auditor instance for the specified auditor class, auditor configuration, and auditor context. @param clazz Class to instantiate @param configToUse Auditor configuration to use @param contextToUse Auditor context to use @return Instance of an IHE Auditor
[ "Get", "an", "auditor", "instance", "for", "the", "specified", "auditor", "class", "auditor", "configuration", "and", "auditor", "context", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/AuditorFactory.java#L42-L52
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java
ConfigurationReader.parseLoggingConfig
private void parseLoggingConfig(final Node node, final ConfigSettings config) { """ Parses the logging parameter section. @param node Reference to the current used xml node @param config Reference to the ConfigSettings """ String name; String value; Node nnode; NodeList list = node.getChildNodes(); int length = list.getLength(); for (int i = 0; i < length; i++) { nnode = list.item(i); name = nnode.getNodeName().toUpperCase(); if (name.equals(KEY_ROOT_FOLDER)) { value = nnode.getChildNodes().item(0).getNodeValue(); value = value.substring(1, value.length() - 1); config.setConfigParameter( ConfigurationKeys.LOGGING_PATH_DIFFTOOL, value); } else if (name.equals(SUBSUBSECTION_DIFF_TOOL)) { parseLoggerConfig(nnode, config, null, ConfigurationKeys.LOGGING_LOGLEVEL_DIFFTOOL); } } }
java
private void parseLoggingConfig(final Node node, final ConfigSettings config) { String name; String value; Node nnode; NodeList list = node.getChildNodes(); int length = list.getLength(); for (int i = 0; i < length; i++) { nnode = list.item(i); name = nnode.getNodeName().toUpperCase(); if (name.equals(KEY_ROOT_FOLDER)) { value = nnode.getChildNodes().item(0).getNodeValue(); value = value.substring(1, value.length() - 1); config.setConfigParameter( ConfigurationKeys.LOGGING_PATH_DIFFTOOL, value); } else if (name.equals(SUBSUBSECTION_DIFF_TOOL)) { parseLoggerConfig(nnode, config, null, ConfigurationKeys.LOGGING_LOGLEVEL_DIFFTOOL); } } }
[ "private", "void", "parseLoggingConfig", "(", "final", "Node", "node", ",", "final", "ConfigSettings", "config", ")", "{", "String", "name", ";", "String", "value", ";", "Node", "nnode", ";", "NodeList", "list", "=", "node", ".", "getChildNodes", "(", ")", ";", "int", "length", "=", "list", ".", "getLength", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "nnode", "=", "list", ".", "item", "(", "i", ")", ";", "name", "=", "nnode", ".", "getNodeName", "(", ")", ".", "toUpperCase", "(", ")", ";", "if", "(", "name", ".", "equals", "(", "KEY_ROOT_FOLDER", ")", ")", "{", "value", "=", "nnode", ".", "getChildNodes", "(", ")", ".", "item", "(", "0", ")", ".", "getNodeValue", "(", ")", ";", "value", "=", "value", ".", "substring", "(", "1", ",", "value", ".", "length", "(", ")", "-", "1", ")", ";", "config", ".", "setConfigParameter", "(", "ConfigurationKeys", ".", "LOGGING_PATH_DIFFTOOL", ",", "value", ")", ";", "}", "else", "if", "(", "name", ".", "equals", "(", "SUBSUBSECTION_DIFF_TOOL", ")", ")", "{", "parseLoggerConfig", "(", "nnode", ",", "config", ",", "null", ",", "ConfigurationKeys", ".", "LOGGING_LOGLEVEL_DIFFTOOL", ")", ";", "}", "}", "}" ]
Parses the logging parameter section. @param node Reference to the current used xml node @param config Reference to the ConfigSettings
[ "Parses", "the", "logging", "parameter", "section", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java#L684-L713
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWriterDriver.java
KMLWriterDriver.writeKMLDocument
private void writeKMLDocument(ProgressVisitor progress, OutputStream outputStream) throws SQLException { """ Write the KML document Note the document stores only the first geometry column in the placeMark element. The other geomtry columns are ignored. @param progress @param outputStream @throws SQLException """ // Read Geometry Index and type List<String> spatialFieldNames = SFSUtilities.getGeometryFields(connection, TableLocation.parse(tableName, JDBCUtilities.isH2DataBase(connection.getMetaData()))); if (spatialFieldNames.isEmpty()) { throw new SQLException(String.format("The table %s does not contain a geometry field", tableName)); } try { final XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory(); streamWriterFactory.setProperty("escapeCharacters", false); XMLStreamWriter xmlOut = streamWriterFactory.createXMLStreamWriter( new BufferedOutputStream(outputStream), "UTF-8"); xmlOut.writeStartDocument("UTF-8", "1.0"); xmlOut.writeStartElement("kml"); xmlOut.writeDefaultNamespace("http://www.opengis.net/kml/2.2"); xmlOut.writeNamespace("atom", "http://www.w3.org/2005/Atom"); xmlOut.writeNamespace("kml", "http://www.opengis.net/kml/2.2"); xmlOut.writeNamespace("gx", "http://www.google.com/kml/ext/2.2"); xmlOut.writeNamespace("xal", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"); xmlOut.writeStartElement("Document"); try ( // Read table content Statement st = connection.createStatement()) { ResultSet rs = st.executeQuery(String.format("select * from %s", tableName)); try { int recordCount = JDBCUtilities.getRowCount(connection, tableName); ProgressVisitor copyProgress = progress.subProcess(recordCount); ResultSetMetaData resultSetMetaData = rs.getMetaData(); int geoFieldIndex = JDBCUtilities.getFieldIndex(resultSetMetaData, spatialFieldNames.get(0)); writeSchema(xmlOut, resultSetMetaData); xmlOut.writeStartElement("Folder"); xmlOut.writeStartElement("name"); xmlOut.writeCharacters(tableName); xmlOut.writeEndElement();//Name while (rs.next()) { writePlacemark(xmlOut, rs, geoFieldIndex, spatialFieldNames.get(0)); copyProgress.endStep(); } } finally { rs.close(); } } xmlOut.writeEndElement();//Folder xmlOut.writeEndElement();//KML xmlOut.writeEndDocument();//DOC xmlOut.close(); } catch (XMLStreamException ex) { throw new SQLException(ex); } }
java
private void writeKMLDocument(ProgressVisitor progress, OutputStream outputStream) throws SQLException { // Read Geometry Index and type List<String> spatialFieldNames = SFSUtilities.getGeometryFields(connection, TableLocation.parse(tableName, JDBCUtilities.isH2DataBase(connection.getMetaData()))); if (spatialFieldNames.isEmpty()) { throw new SQLException(String.format("The table %s does not contain a geometry field", tableName)); } try { final XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory(); streamWriterFactory.setProperty("escapeCharacters", false); XMLStreamWriter xmlOut = streamWriterFactory.createXMLStreamWriter( new BufferedOutputStream(outputStream), "UTF-8"); xmlOut.writeStartDocument("UTF-8", "1.0"); xmlOut.writeStartElement("kml"); xmlOut.writeDefaultNamespace("http://www.opengis.net/kml/2.2"); xmlOut.writeNamespace("atom", "http://www.w3.org/2005/Atom"); xmlOut.writeNamespace("kml", "http://www.opengis.net/kml/2.2"); xmlOut.writeNamespace("gx", "http://www.google.com/kml/ext/2.2"); xmlOut.writeNamespace("xal", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"); xmlOut.writeStartElement("Document"); try ( // Read table content Statement st = connection.createStatement()) { ResultSet rs = st.executeQuery(String.format("select * from %s", tableName)); try { int recordCount = JDBCUtilities.getRowCount(connection, tableName); ProgressVisitor copyProgress = progress.subProcess(recordCount); ResultSetMetaData resultSetMetaData = rs.getMetaData(); int geoFieldIndex = JDBCUtilities.getFieldIndex(resultSetMetaData, spatialFieldNames.get(0)); writeSchema(xmlOut, resultSetMetaData); xmlOut.writeStartElement("Folder"); xmlOut.writeStartElement("name"); xmlOut.writeCharacters(tableName); xmlOut.writeEndElement();//Name while (rs.next()) { writePlacemark(xmlOut, rs, geoFieldIndex, spatialFieldNames.get(0)); copyProgress.endStep(); } } finally { rs.close(); } } xmlOut.writeEndElement();//Folder xmlOut.writeEndElement();//KML xmlOut.writeEndDocument();//DOC xmlOut.close(); } catch (XMLStreamException ex) { throw new SQLException(ex); } }
[ "private", "void", "writeKMLDocument", "(", "ProgressVisitor", "progress", ",", "OutputStream", "outputStream", ")", "throws", "SQLException", "{", "// Read Geometry Index and type", "List", "<", "String", ">", "spatialFieldNames", "=", "SFSUtilities", ".", "getGeometryFields", "(", "connection", ",", "TableLocation", ".", "parse", "(", "tableName", ",", "JDBCUtilities", ".", "isH2DataBase", "(", "connection", ".", "getMetaData", "(", ")", ")", ")", ")", ";", "if", "(", "spatialFieldNames", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "SQLException", "(", "String", ".", "format", "(", "\"The table %s does not contain a geometry field\"", ",", "tableName", ")", ")", ";", "}", "try", "{", "final", "XMLOutputFactory", "streamWriterFactory", "=", "XMLOutputFactory", ".", "newFactory", "(", ")", ";", "streamWriterFactory", ".", "setProperty", "(", "\"escapeCharacters\"", ",", "false", ")", ";", "XMLStreamWriter", "xmlOut", "=", "streamWriterFactory", ".", "createXMLStreamWriter", "(", "new", "BufferedOutputStream", "(", "outputStream", ")", ",", "\"UTF-8\"", ")", ";", "xmlOut", ".", "writeStartDocument", "(", "\"UTF-8\"", ",", "\"1.0\"", ")", ";", "xmlOut", ".", "writeStartElement", "(", "\"kml\"", ")", ";", "xmlOut", ".", "writeDefaultNamespace", "(", "\"http://www.opengis.net/kml/2.2\"", ")", ";", "xmlOut", ".", "writeNamespace", "(", "\"atom\"", ",", "\"http://www.w3.org/2005/Atom\"", ")", ";", "xmlOut", ".", "writeNamespace", "(", "\"kml\"", ",", "\"http://www.opengis.net/kml/2.2\"", ")", ";", "xmlOut", ".", "writeNamespace", "(", "\"gx\"", ",", "\"http://www.google.com/kml/ext/2.2\"", ")", ";", "xmlOut", ".", "writeNamespace", "(", "\"xal\"", ",", "\"urn:oasis:names:tc:ciq:xsdschema:xAL:2.0\"", ")", ";", "xmlOut", ".", "writeStartElement", "(", "\"Document\"", ")", ";", "try", "(", "// Read table content", "Statement", "st", "=", "connection", ".", "createStatement", "(", ")", ")", "{", "ResultSet", "rs", "=", "st", ".", "executeQuery", "(", "String", ".", "format", "(", "\"select * from %s\"", ",", "tableName", ")", ")", ";", "try", "{", "int", "recordCount", "=", "JDBCUtilities", ".", "getRowCount", "(", "connection", ",", "tableName", ")", ";", "ProgressVisitor", "copyProgress", "=", "progress", ".", "subProcess", "(", "recordCount", ")", ";", "ResultSetMetaData", "resultSetMetaData", "=", "rs", ".", "getMetaData", "(", ")", ";", "int", "geoFieldIndex", "=", "JDBCUtilities", ".", "getFieldIndex", "(", "resultSetMetaData", ",", "spatialFieldNames", ".", "get", "(", "0", ")", ")", ";", "writeSchema", "(", "xmlOut", ",", "resultSetMetaData", ")", ";", "xmlOut", ".", "writeStartElement", "(", "\"Folder\"", ")", ";", "xmlOut", ".", "writeStartElement", "(", "\"name\"", ")", ";", "xmlOut", ".", "writeCharacters", "(", "tableName", ")", ";", "xmlOut", ".", "writeEndElement", "(", ")", ";", "//Name", "while", "(", "rs", ".", "next", "(", ")", ")", "{", "writePlacemark", "(", "xmlOut", ",", "rs", ",", "geoFieldIndex", ",", "spatialFieldNames", ".", "get", "(", "0", ")", ")", ";", "copyProgress", ".", "endStep", "(", ")", ";", "}", "}", "finally", "{", "rs", ".", "close", "(", ")", ";", "}", "}", "xmlOut", ".", "writeEndElement", "(", ")", ";", "//Folder", "xmlOut", ".", "writeEndElement", "(", ")", ";", "//KML", "xmlOut", ".", "writeEndDocument", "(", ")", ";", "//DOC", "xmlOut", ".", "close", "(", ")", ";", "}", "catch", "(", "XMLStreamException", "ex", ")", "{", "throw", "new", "SQLException", "(", "ex", ")", ";", "}", "}" ]
Write the KML document Note the document stores only the first geometry column in the placeMark element. The other geomtry columns are ignored. @param progress @param outputStream @throws SQLException
[ "Write", "the", "KML", "document", "Note", "the", "document", "stores", "only", "the", "first", "geometry", "column", "in", "the", "placeMark", "element", ".", "The", "other", "geomtry", "columns", "are", "ignored", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWriterDriver.java#L150-L201