repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java
ObjectArrayList.beforeInsert
public void beforeInsert(int index, Object element) { // overridden for performance only. if (index > size || index < 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); ensureCapacity(size + 1); System.arraycopy(elements, index, elements, index+1, size-index); elements[index] = element; size++; }
java
public void beforeInsert(int index, Object element) { // overridden for performance only. if (index > size || index < 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); ensureCapacity(size + 1); System.arraycopy(elements, index, elements, index+1, size-index); elements[index] = element; size++; }
[ "public", "void", "beforeInsert", "(", "int", "index", ",", "Object", "element", ")", "{", "// overridden for performance only.\r", "if", "(", "index", ">", "size", "||", "index", "<", "0", ")", "throw", "new", "IndexOutOfBoundsException", "(", "\"Index: \"", "+...
Inserts the specified element before the specified position into the receiver. Shifts the element currently at that position (if any) and any subsequent elements to the right. @param index index before which the specified element is to be inserted (must be in [0,size]). @param element element to be inserted. @exception IndexOutOfBoundsException index is out of range (<tt>index &lt; 0 || index &gt; size()</tt>).
[ "Inserts", "the", "specified", "element", "before", "the", "specified", "position", "into", "the", "receiver", ".", "Shifts", "the", "element", "currently", "at", "that", "position", "(", "if", "any", ")", "and", "any", "subsequent", "elements", "to", "the", ...
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L85-L93
couchbase/couchbase-lite-java-core
src/main/java/com/couchbase/lite/support/action/Action.java
Action.moveAndReplaceFile
public static Action moveAndReplaceFile(String srcPath, String destPath, String tempDir) { Action seq = new Action(); seq.add(deleteFile(destPath, tempDir)); seq.add(moveFileToEmptyPath(srcPath, destPath)); return seq; }
java
public static Action moveAndReplaceFile(String srcPath, String destPath, String tempDir) { Action seq = new Action(); seq.add(deleteFile(destPath, tempDir)); seq.add(moveFileToEmptyPath(srcPath, destPath)); return seq; }
[ "public", "static", "Action", "moveAndReplaceFile", "(", "String", "srcPath", ",", "String", "destPath", ",", "String", "tempDir", ")", "{", "Action", "seq", "=", "new", "Action", "(", ")", ";", "seq", ".", "add", "(", "deleteFile", "(", "destPath", ",", ...
Moves the file/directory to a new location, replacing anything that already exists there. @param srcPath Source path @param destPath Destination path to be replaced @param tempDir Path to a temp directory used for backing out file deletion @return A moveAndReplaceFile action
[ "Moves", "the", "file", "/", "directory", "to", "a", "new", "location", "replacing", "anything", "that", "already", "exists", "there", "." ]
train
https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/support/action/Action.java#L336-L341
jbundle/jbundle
thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TableProxy.java
TableProxy.set
public void set(Object data, int iOpenMode) throws DBException, RemoteException { BaseTransport transport = this.createProxyTransport(SET); transport.addParam(DATA, data); transport.addParam(OPEN_MODE, iOpenMode); Object strReturn = transport.sendMessageAndGetReply(); Object objReturn = transport.convertReturnObject(strReturn); this.checkDBException(objReturn); }
java
public void set(Object data, int iOpenMode) throws DBException, RemoteException { BaseTransport transport = this.createProxyTransport(SET); transport.addParam(DATA, data); transport.addParam(OPEN_MODE, iOpenMode); Object strReturn = transport.sendMessageAndGetReply(); Object objReturn = transport.convertReturnObject(strReturn); this.checkDBException(objReturn); }
[ "public", "void", "set", "(", "Object", "data", ",", "int", "iOpenMode", ")", "throws", "DBException", ",", "RemoteException", "{", "BaseTransport", "transport", "=", "this", ".", "createProxyTransport", "(", "SET", ")", ";", "transport", ".", "addParam", "(",...
Update the current record. @param The data to update. @exception Exception File exception.
[ "Update", "the", "current", "record", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TableProxy.java#L122-L130
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getRunePagesMultipleUsers
public Future<Map<Integer, Set<RunePage>>> getRunePagesMultipleUsers(int... ids) { return new ApiFuture<>(() -> handler.getRunePagesMultipleUsers(ids)); }
java
public Future<Map<Integer, Set<RunePage>>> getRunePagesMultipleUsers(int... ids) { return new ApiFuture<>(() -> handler.getRunePagesMultipleUsers(ids)); }
[ "public", "Future", "<", "Map", "<", "Integer", ",", "Set", "<", "RunePage", ">", ">", ">", "getRunePagesMultipleUsers", "(", "int", "...", "ids", ")", "{", "return", "new", "ApiFuture", "<>", "(", "(", ")", "->", "handler", ".", "getRunePagesMultipleUsers...
Retrieve runes pages for multiple users @param ids The ids of the users @return A map, mapping user ids to their respective runes pages @see <a href=https://developer.riotgames.com/api/methods#!/620/1932>Official API documentation</a>
[ "Retrieve", "runes", "pages", "for", "multiple", "users" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L1171-L1173
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/ConfigurationParserUtils.java
ConfigurationParserUtils.checkConfigParameter
public static void checkConfigParameter(boolean condition, Object parameter, String name, String errorMessage) throws IllegalConfigurationException { if (!condition) { throw new IllegalConfigurationException("Invalid configuration value for " + name + " : " + parameter + " - " + errorMessage); } }
java
public static void checkConfigParameter(boolean condition, Object parameter, String name, String errorMessage) throws IllegalConfigurationException { if (!condition) { throw new IllegalConfigurationException("Invalid configuration value for " + name + " : " + parameter + " - " + errorMessage); } }
[ "public", "static", "void", "checkConfigParameter", "(", "boolean", "condition", ",", "Object", "parameter", ",", "String", "name", ",", "String", "errorMessage", ")", "throws", "IllegalConfigurationException", "{", "if", "(", "!", "condition", ")", "{", "throw", ...
Validates a condition for a config parameter and displays a standard exception, if the the condition does not hold. @param condition The condition that must hold. If the condition is false, an exception is thrown. @param parameter The parameter value. Will be shown in the exception message. @param name The name of the config parameter. Will be shown in the exception message. @param errorMessage The optional custom error message to append to the exception message. @throws IllegalConfigurationException if the condition does not hold
[ "Validates", "a", "condition", "for", "a", "config", "parameter", "and", "displays", "a", "standard", "exception", "if", "the", "the", "condition", "does", "not", "hold", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/util/ConfigurationParserUtils.java#L127-L133
querydsl/querydsl
querydsl-sql/src/main/java/com/querydsl/sql/Configuration.java
Configuration.registerTableOverride
@Deprecated public String registerTableOverride(String schema, String oldTable, String newTable) { SchemaAndTable st = registerTableOverride(schema, oldTable, schema, newTable); return st != null ? st.getTable() : null; }
java
@Deprecated public String registerTableOverride(String schema, String oldTable, String newTable) { SchemaAndTable st = registerTableOverride(schema, oldTable, schema, newTable); return st != null ? st.getTable() : null; }
[ "@", "Deprecated", "public", "String", "registerTableOverride", "(", "String", "schema", ",", "String", "oldTable", ",", "String", "newTable", ")", "{", "SchemaAndTable", "st", "=", "registerTableOverride", "(", "schema", ",", "oldTable", ",", "schema", ",", "ne...
Register a schema specific table override @param schema schema of table @param oldTable table to override @param newTable override @return previous override value @deprecated Use {@link #setDynamicNameMapping(NameMapping)} instead.
[ "Register", "a", "schema", "specific", "table", "override" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/Configuration.java#L351-L355
LAW-Unimi/BUbiNG
src/it/unimi/di/law/bubing/frontier/VisitStateSet.java
VisitStateSet.get
public VisitState get(final byte[] array, final int offset, final int length) { // The starting point. int pos = (int)(MurmurHash3.hash(array, offset, length) & mask); // There's always an unused entry. while(visitState[pos] != null) { if (visitState[pos].schemeAuthority.length == length && equals(visitState[pos].schemeAuthority, array, offset, length)) return visitState[pos]; pos = (pos + 1) & mask; } return null; }
java
public VisitState get(final byte[] array, final int offset, final int length) { // The starting point. int pos = (int)(MurmurHash3.hash(array, offset, length) & mask); // There's always an unused entry. while(visitState[pos] != null) { if (visitState[pos].schemeAuthority.length == length && equals(visitState[pos].schemeAuthority, array, offset, length)) return visitState[pos]; pos = (pos + 1) & mask; } return null; }
[ "public", "VisitState", "get", "(", "final", "byte", "[", "]", "array", ",", "final", "int", "offset", ",", "final", "int", "length", ")", "{", "// The starting point.", "int", "pos", "=", "(", "int", ")", "(", "MurmurHash3", ".", "hash", "(", "array", ...
Returns the visit state associated to a given scheme+authority specified as a byte-array fragment, or {@code null}. @param array a byte array. @param offset the first valid byte in {@code array}. @param length the number of valid elements in {@code array}. @return the visit state associated to a given scheme+authority, or {@code null}.
[ "Returns", "the", "visit", "state", "associated", "to", "a", "given", "scheme", "+", "authority", "specified", "as", "a", "byte", "-", "array", "fragment", "or", "{", "@code", "null", "}", "." ]
train
https://github.com/LAW-Unimi/BUbiNG/blob/e148acc90031a4f3967422705a9fb07ddaf155e4/src/it/unimi/di/law/bubing/frontier/VisitStateSet.java#L167-L176
EasyinnovaSL/Tiff-Library-4J
src/main/java/com/easyinnova/tiff/profiles/BaselineProfile.java
BaselineProfile.CheckCMYK
private void CheckCMYK(IfdTags metadata, int n) { // Samples per pixel if (!metadata.containsTagId(TiffTags.getTagId("SamplesPerPixel"))) { validation.addErrorLoc("Missing Samples Per Pixel", "IFD" + n); } // BitsPerSample if (!metadata.containsTagId(TiffTags.getTagId("BitsPerSample"))) { validation.addErrorLoc("Missing BitsPerSample", "IFD" + n); } }
java
private void CheckCMYK(IfdTags metadata, int n) { // Samples per pixel if (!metadata.containsTagId(TiffTags.getTagId("SamplesPerPixel"))) { validation.addErrorLoc("Missing Samples Per Pixel", "IFD" + n); } // BitsPerSample if (!metadata.containsTagId(TiffTags.getTagId("BitsPerSample"))) { validation.addErrorLoc("Missing BitsPerSample", "IFD" + n); } }
[ "private", "void", "CheckCMYK", "(", "IfdTags", "metadata", ",", "int", "n", ")", "{", "// Samples per pixel", "if", "(", "!", "metadata", ".", "containsTagId", "(", "TiffTags", ".", "getTagId", "(", "\"SamplesPerPixel\"", ")", ")", ")", "{", "validation", "...
Check CMYK. @param metadata the metadata @param n the ifd number
[ "Check", "CMYK", "." ]
train
https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/profiles/BaselineProfile.java#L346-L356
beanshell/beanshell
src/main/java/bsh/NameSpace.java
NameSpace.getImportedMethod
protected BshMethod getImportedMethod(final String name, final Class<?>[] sig) throws UtilEvalError { // Try object imports for (final Object object : this.importedObjects) { final Invocable method = Reflect.resolveJavaMethod( object.getClass(), name, sig, false/* onlyStatic */); if (method != null) return new BshMethod(method, object); } // Try static imports for (final Class<?> stat : this.importedStatic) { final Invocable method = Reflect.resolveJavaMethod( stat, name, sig, true/* onlyStatic */); if (method != null) return new BshMethod(method, null/* object */); } return null; }
java
protected BshMethod getImportedMethod(final String name, final Class<?>[] sig) throws UtilEvalError { // Try object imports for (final Object object : this.importedObjects) { final Invocable method = Reflect.resolveJavaMethod( object.getClass(), name, sig, false/* onlyStatic */); if (method != null) return new BshMethod(method, object); } // Try static imports for (final Class<?> stat : this.importedStatic) { final Invocable method = Reflect.resolveJavaMethod( stat, name, sig, true/* onlyStatic */); if (method != null) return new BshMethod(method, null/* object */); } return null; }
[ "protected", "BshMethod", "getImportedMethod", "(", "final", "String", "name", ",", "final", "Class", "<", "?", ">", "[", "]", "sig", ")", "throws", "UtilEvalError", "{", "// Try object imports", "for", "(", "final", "Object", "object", ":", "this", ".", "im...
Gets the imported method. @param name the name @param sig the sig @return the imported method @throws UtilEvalError the util eval error
[ "Gets", "the", "imported", "method", "." ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/NameSpace.java#L888-L905
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/inbound/HttpInboundServiceContextImpl.java
HttpInboundServiceContextImpl.skipWhiteSpace
private int skipWhiteSpace(byte[] data, int start) { int index = start; while (index < data.length && (' ' == data[index] || '\t' == data[index])) { index++; } return index; }
java
private int skipWhiteSpace(byte[] data, int start) { int index = start; while (index < data.length && (' ' == data[index] || '\t' == data[index])) { index++; } return index; }
[ "private", "int", "skipWhiteSpace", "(", "byte", "[", "]", "data", ",", "int", "start", ")", "{", "int", "index", "=", "start", ";", "while", "(", "index", "<", "data", ".", "length", "&&", "(", "'", "'", "==", "data", "[", "index", "]", "||", "'...
Skip whitespace found in the input data starting at the given index. It will return an index value that points to the first non-space byte found or end of data if it ran out. @param data @param start @return int
[ "Skip", "whitespace", "found", "in", "the", "input", "data", "starting", "at", "the", "given", "index", ".", "It", "will", "return", "an", "index", "value", "that", "points", "to", "the", "first", "non", "-", "space", "byte", "found", "or", "end", "of", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/inbound/HttpInboundServiceContextImpl.java#L242-L248
mangstadt/biweekly
src/main/java/biweekly/component/VFreeBusy.java
VFreeBusy.addFreeBusy
public FreeBusy addFreeBusy(FreeBusyType type, Date start, Date end) { FreeBusy found = findByFreeBusyType(type); found.getValues().add(new Period(start, end)); return found; }
java
public FreeBusy addFreeBusy(FreeBusyType type, Date start, Date end) { FreeBusy found = findByFreeBusyType(type); found.getValues().add(new Period(start, end)); return found; }
[ "public", "FreeBusy", "addFreeBusy", "(", "FreeBusyType", "type", ",", "Date", "start", ",", "Date", "end", ")", "{", "FreeBusy", "found", "=", "findByFreeBusyType", "(", "type", ")", ";", "found", ".", "getValues", "(", ")", ".", "add", "(", "new", "Per...
Adds a single time period for which the person is free or busy (for example, "free" between 1pm-3pm). This method will look for an existing property that has the given {@link FreeBusyType} and add the time period to it, or create a new property is one cannot be found. @param type the availability type (e.g. "free" or "busy") @param start the start date-time @param end the end date-time @return the property that was created/modified @see <a href="http://tools.ietf.org/html/rfc5545#page-100">RFC 5545 p.100-1</a> @see <a href="http://tools.ietf.org/html/rfc2445#page-95">RFC 2445 p.95-6</a>
[ "Adds", "a", "single", "time", "period", "for", "which", "the", "person", "is", "free", "or", "busy", "(", "for", "example", "free", "between", "1pm", "-", "3pm", ")", ".", "This", "method", "will", "look", "for", "an", "existing", "property", "that", ...
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/component/VFreeBusy.java#L552-L556
likethecolor/Alchemy-API
src/main/java/com/likethecolor/alchemy/api/parser/json/KeywordParser.java
KeywordParser.isValidSentiment
private boolean isValidSentiment(final String type, final Double score, final Integer mixed) { return !StringUtils.isBlank(type) || score != null || mixed != null; }
java
private boolean isValidSentiment(final String type, final Double score, final Integer mixed) { return !StringUtils.isBlank(type) || score != null || mixed != null; }
[ "private", "boolean", "isValidSentiment", "(", "final", "String", "type", ",", "final", "Double", "score", ",", "final", "Integer", "mixed", ")", "{", "return", "!", "StringUtils", ".", "isBlank", "(", "type", ")", "||", "score", "!=", "null", "||", "mixed...
Return true if at least one of the values is not null/empty. @param type the sentiment type @param score the sentiment score @param mixed whether the sentiment is mixed @return true if at least one of the values is not null/empty
[ "Return", "true", "if", "at", "least", "one", "of", "the", "values", "is", "not", "null", "/", "empty", "." ]
train
https://github.com/likethecolor/Alchemy-API/blob/5208cfc92a878ceeaff052787af29da92d98db7e/src/main/java/com/likethecolor/alchemy/api/parser/json/KeywordParser.java#L128-L132
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java
DateFormat.getDateTimeInstance
static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle, int timeStyle, Locale locale) { return getDateTimeInstance(dateStyle, timeStyle, ULocale.forLocale(locale)); }
java
static final public DateFormat getDateTimeInstance(Calendar cal, int dateStyle, int timeStyle, Locale locale) { return getDateTimeInstance(dateStyle, timeStyle, ULocale.forLocale(locale)); }
[ "static", "final", "public", "DateFormat", "getDateTimeInstance", "(", "Calendar", "cal", ",", "int", "dateStyle", ",", "int", "timeStyle", ",", "Locale", "locale", ")", "{", "return", "getDateTimeInstance", "(", "dateStyle", ",", "timeStyle", ",", "ULocale", "....
Creates a {@link DateFormat} object that can be used to format dates and times in the calendar system specified by <code>cal</code>. @param cal The calendar system for which a date/time format is desired. @param dateStyle The type of date format desired. This can be {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM}, etc. @param timeStyle The type of time format desired. This can be {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM}, etc. @param locale The locale for which the date/time format is desired. @see DateFormat#getDateTimeInstance
[ "Creates", "a", "{", "@link", "DateFormat", "}", "object", "that", "can", "be", "used", "to", "format", "dates", "and", "times", "in", "the", "calendar", "system", "specified", "by", "<code", ">", "cal<", "/", "code", ">", ".", "@param", "cal", "The", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java#L1828-L1832
alkacon/opencms-core
src/org/opencms/relations/CmsLinkUpdateUtil.java
CmsLinkUpdateUtil.updateAttribute
private static void updateAttribute(Element parent, String attrName, String value) { if (parent != null) { Attribute attribute = parent.attribute(attrName); if (value != null) { if (attribute == null) { parent.addAttribute(attrName, value); } else { attribute.setValue(value); } } else { // remove only if exists if (attribute != null) { parent.remove(attribute); } } } }
java
private static void updateAttribute(Element parent, String attrName, String value) { if (parent != null) { Attribute attribute = parent.attribute(attrName); if (value != null) { if (attribute == null) { parent.addAttribute(attrName, value); } else { attribute.setValue(value); } } else { // remove only if exists if (attribute != null) { parent.remove(attribute); } } } }
[ "private", "static", "void", "updateAttribute", "(", "Element", "parent", ",", "String", "attrName", ",", "String", "value", ")", "{", "if", "(", "parent", "!=", "null", ")", "{", "Attribute", "attribute", "=", "parent", ".", "attribute", "(", "attrName", ...
Updates the given xml element attribute with the given value.<p> @param parent the element to set the attribute for @param attrName the attribute name @param value the value to set, or <code>null</code> to remove
[ "Updates", "the", "given", "xml", "element", "attribute", "with", "the", "given", "value", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsLinkUpdateUtil.java#L142-L159
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/TimeMeasure.java
TimeMeasure.getElapsedFormatted
String getElapsedFormatted(DateFormat _dateFormat, long _elapsedTime) { Date elapsedTime = new Date(_elapsedTime); DateFormat sdf = _dateFormat; if (_dateFormat == null) { sdf = new SimpleDateFormat("HH:mm:ss.SSS"); } sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // always use UTC so we get the correct time without timezone offset on it return sdf.format(elapsedTime); }
java
String getElapsedFormatted(DateFormat _dateFormat, long _elapsedTime) { Date elapsedTime = new Date(_elapsedTime); DateFormat sdf = _dateFormat; if (_dateFormat == null) { sdf = new SimpleDateFormat("HH:mm:ss.SSS"); } sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // always use UTC so we get the correct time without timezone offset on it return sdf.format(elapsedTime); }
[ "String", "getElapsedFormatted", "(", "DateFormat", "_dateFormat", ",", "long", "_elapsedTime", ")", "{", "Date", "elapsedTime", "=", "new", "Date", "(", "_elapsedTime", ")", ";", "DateFormat", "sdf", "=", "_dateFormat", ";", "if", "(", "_dateFormat", "==", "n...
Same as above, used for proper unit testing. @param _dateFormat @param _elapsedTime @return formatted string
[ "Same", "as", "above", "used", "for", "proper", "unit", "testing", "." ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/TimeMeasure.java#L89-L99
google/closure-compiler
src/com/google/javascript/jscomp/ProcessTweaks.java
ProcessTweaks.collectTweaks
private CollectTweaksResult collectTweaks(Node root) { CollectTweaks pass = new CollectTweaks(); NodeTraversal.traverse(compiler, root, pass); Map<String, TweakInfo> tweakInfos = pass.allTweaks; for (TweakInfo tweakInfo : tweakInfos.values()) { tweakInfo.emitAllWarnings(); } return new CollectTweaksResult(tweakInfos, pass.getOverridesCalls); }
java
private CollectTweaksResult collectTweaks(Node root) { CollectTweaks pass = new CollectTweaks(); NodeTraversal.traverse(compiler, root, pass); Map<String, TweakInfo> tweakInfos = pass.allTweaks; for (TweakInfo tweakInfo : tweakInfos.values()) { tweakInfo.emitAllWarnings(); } return new CollectTweaksResult(tweakInfos, pass.getOverridesCalls); }
[ "private", "CollectTweaksResult", "collectTweaks", "(", "Node", "root", ")", "{", "CollectTweaks", "pass", "=", "new", "CollectTweaks", "(", ")", ";", "NodeTraversal", ".", "traverse", "(", "compiler", ",", "root", ",", "pass", ")", ";", "Map", "<", "String"...
Finds all calls to goog.tweak functions and emits warnings/errors if any of the calls have issues. @return A map of {@link TweakInfo} structures, keyed by tweak ID.
[ "Finds", "all", "calls", "to", "goog", ".", "tweak", "functions", "and", "emits", "warnings", "/", "errors", "if", "any", "of", "the", "calls", "have", "issues", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ProcessTweaks.java#L310-L319
agmip/translator-agmip
src/main/java/org/agmip/translators/agmip/AceWeatherAdaptor.java
AceWeatherAdaptor.formatNumStr
private String formatNumStr(int bits, String str) { String ret; String[] inputStr = str.split("\\."); if (str.trim().equals("")) { ret = String.format("%" + bits + "s", ""); } else if (str.length() <= bits) { ret = String.format("%1$" + bits + "s", str); } else if (inputStr[0].length() > bits) { ret = String.format("%" + bits + "s", str); } else { int decimalLength = bits - inputStr[0].length() - 1; decimalLength = decimalLength < 0 ? 0 : decimalLength; ret = org.agmip.common.Functions.round(str, decimalLength); } return ret; }
java
private String formatNumStr(int bits, String str) { String ret; String[] inputStr = str.split("\\."); if (str.trim().equals("")) { ret = String.format("%" + bits + "s", ""); } else if (str.length() <= bits) { ret = String.format("%1$" + bits + "s", str); } else if (inputStr[0].length() > bits) { ret = String.format("%" + bits + "s", str); } else { int decimalLength = bits - inputStr[0].length() - 1; decimalLength = decimalLength < 0 ? 0 : decimalLength; ret = org.agmip.common.Functions.round(str, decimalLength); } return ret; }
[ "private", "String", "formatNumStr", "(", "int", "bits", ",", "String", "str", ")", "{", "String", "ret", ";", "String", "[", "]", "inputStr", "=", "str", ".", "split", "(", "\"\\\\.\"", ")", ";", "if", "(", "str", ".", "trim", "(", ")", ".", "equa...
Format the number with maximum length and type @param bits Maximum length of the output string @param str String for number value @return formated string of number
[ "Format", "the", "number", "with", "maximum", "length", "and", "type" ]
train
https://github.com/agmip/translator-agmip/blob/61cb6a16db927380b459eea6f8db12aade367573/src/main/java/org/agmip/translators/agmip/AceWeatherAdaptor.java#L186-L203
SonarSource/sonarqube
sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginInstaller.java
ScannerPluginInstaller.listInstalledPlugins
private InstalledPlugin[] listInstalledPlugins() { Profiler profiler = Profiler.create(LOG).startInfo("Load plugins index"); GetRequest getRequest = new GetRequest(PLUGINS_WS_URL); InstalledPlugins installedPlugins; try (Reader reader = wsClient.call(getRequest).contentReader()) { installedPlugins = new Gson().fromJson(reader, InstalledPlugins.class); } catch (Exception e) { throw new IllegalStateException("Fail to parse response of " + PLUGINS_WS_URL, e); } profiler.stopInfo(); return installedPlugins.plugins; }
java
private InstalledPlugin[] listInstalledPlugins() { Profiler profiler = Profiler.create(LOG).startInfo("Load plugins index"); GetRequest getRequest = new GetRequest(PLUGINS_WS_URL); InstalledPlugins installedPlugins; try (Reader reader = wsClient.call(getRequest).contentReader()) { installedPlugins = new Gson().fromJson(reader, InstalledPlugins.class); } catch (Exception e) { throw new IllegalStateException("Fail to parse response of " + PLUGINS_WS_URL, e); } profiler.stopInfo(); return installedPlugins.plugins; }
[ "private", "InstalledPlugin", "[", "]", "listInstalledPlugins", "(", ")", "{", "Profiler", "profiler", "=", "Profiler", ".", "create", "(", "LOG", ")", ".", "startInfo", "(", "\"Load plugins index\"", ")", ";", "GetRequest", "getRequest", "=", "new", "GetRequest...
Gets information about the plugins installed on server (filename, checksum)
[ "Gets", "information", "about", "the", "plugins", "installed", "on", "server", "(", "filename", "checksum", ")" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerPluginInstaller.java#L99-L111
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/datastyle/FloatStyle.java
FloatStyle.appendXMLHelper
void appendXMLHelper(final XMLUtil util, final Appendable appendable, final String numberStyleName, final CharSequence number) throws IOException { this.numberStyle.appendXMLHelper(util, appendable, numberStyleName, number); }
java
void appendXMLHelper(final XMLUtil util, final Appendable appendable, final String numberStyleName, final CharSequence number) throws IOException { this.numberStyle.appendXMLHelper(util, appendable, numberStyleName, number); }
[ "void", "appendXMLHelper", "(", "final", "XMLUtil", "util", ",", "final", "Appendable", "appendable", ",", "final", "String", "numberStyleName", ",", "final", "CharSequence", "number", ")", "throws", "IOException", "{", "this", ".", "numberStyle", ".", "appendXMLH...
A helper to create the XML representation of the float style @param util a util @param appendable the destination @param numberStyleName the style name ("currency-style", ...) @param number the number itslef @throws IOException if an I/O error occurs
[ "A", "helper", "to", "create", "the", "XML", "representation", "of", "the", "float", "style" ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/datastyle/FloatStyle.java#L104-L106
jlinn/quartz-redis-jobstore
src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java
AbstractRedisStorage.retrieveCalendar
public Calendar retrieveCalendar(String name, T jedis) throws JobPersistenceException{ final String calendarHashKey = redisSchema.calendarHashKey(name); Calendar calendar; try{ final Map<String, String> calendarMap = jedis.hgetAll(calendarHashKey); if(calendarMap == null || calendarMap.isEmpty()){ return null; } final Class<?> calendarClass = Class.forName(calendarMap.get(CALENDAR_CLASS)); calendar = (Calendar) mapper.readValue(calendarMap.get(CALENDAR_JSON), calendarClass); } catch (ClassNotFoundException e) { logger.error("Class not found for calendar " + name); throw new JobPersistenceException(e.getMessage(), e); } catch (IOException e) { logger.error("Unable to deserialize calendar json for calendar " + name); throw new JobPersistenceException(e.getMessage(), e); } return calendar; }
java
public Calendar retrieveCalendar(String name, T jedis) throws JobPersistenceException{ final String calendarHashKey = redisSchema.calendarHashKey(name); Calendar calendar; try{ final Map<String, String> calendarMap = jedis.hgetAll(calendarHashKey); if(calendarMap == null || calendarMap.isEmpty()){ return null; } final Class<?> calendarClass = Class.forName(calendarMap.get(CALENDAR_CLASS)); calendar = (Calendar) mapper.readValue(calendarMap.get(CALENDAR_JSON), calendarClass); } catch (ClassNotFoundException e) { logger.error("Class not found for calendar " + name); throw new JobPersistenceException(e.getMessage(), e); } catch (IOException e) { logger.error("Unable to deserialize calendar json for calendar " + name); throw new JobPersistenceException(e.getMessage(), e); } return calendar; }
[ "public", "Calendar", "retrieveCalendar", "(", "String", "name", ",", "T", "jedis", ")", "throws", "JobPersistenceException", "{", "final", "String", "calendarHashKey", "=", "redisSchema", ".", "calendarHashKey", "(", "name", ")", ";", "Calendar", "calendar", ";",...
Retrieve a calendar @param name the name of the calendar to be retrieved @param jedis a thread-safe Redis connection @return the desired calendar if it exists; null otherwise
[ "Retrieve", "a", "calendar" ]
train
https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/AbstractRedisStorage.java#L393-L411
square/phrase
src/main/java/com/squareup/phrase/Phrase.java
Phrase.put
public Phrase put(String key, CharSequence value) { if (!keys.contains(key)) { throw new IllegalArgumentException("Invalid key: " + key); } if (value == null) { throw new IllegalArgumentException("Null value for '" + key + "'"); } keysToValues.put(key, value); // Invalidate the cached formatted text. formatted = null; return this; }
java
public Phrase put(String key, CharSequence value) { if (!keys.contains(key)) { throw new IllegalArgumentException("Invalid key: " + key); } if (value == null) { throw new IllegalArgumentException("Null value for '" + key + "'"); } keysToValues.put(key, value); // Invalidate the cached formatted text. formatted = null; return this; }
[ "public", "Phrase", "put", "(", "String", "key", ",", "CharSequence", "value", ")", "{", "if", "(", "!", "keys", ".", "contains", "(", "key", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid key: \"", "+", "key", ")", ";", "}", ...
Replaces the given key with a non-null value. You may reuse Phrase instances and replace keys with new values. @throws IllegalArgumentException if the key is not in the pattern.
[ "Replaces", "the", "given", "key", "with", "a", "non", "-", "null", "value", ".", "You", "may", "reuse", "Phrase", "instances", "and", "replace", "keys", "with", "new", "values", "." ]
train
https://github.com/square/phrase/blob/d91f18e80790832db11b811c462f8e5cd492d97e/src/main/java/com/squareup/phrase/Phrase.java#L151-L163
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/messageresolver/StandardMessageResolver.java
StandardMessageResolver.addDefaultMessage
public final void addDefaultMessage(final String key, final String value) { Validate.notNull(key, "Key for default message cannot be null"); Validate.notNull(value, "Value for default message cannot be null"); this.defaultMessages.put(key, value); }
java
public final void addDefaultMessage(final String key, final String value) { Validate.notNull(key, "Key for default message cannot be null"); Validate.notNull(value, "Value for default message cannot be null"); this.defaultMessages.put(key, value); }
[ "public", "final", "void", "addDefaultMessage", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "Validate", ".", "notNull", "(", "key", ",", "\"Key for default message cannot be null\"", ")", ";", "Validate", ".", "notNull", "(", "value...
<p> Adds a new message to the set of default messages. </p> @param key the message key @param value the message value (text)
[ "<p", ">", "Adds", "a", "new", "message", "to", "the", "set", "of", "default", "messages", ".", "<", "/", "p", ">" ]
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/messageresolver/StandardMessageResolver.java#L203-L207
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java
BaseEnvelopeSchemaConverter.getPayloadBytes
@Deprecated protected byte[] getPayloadBytes(GenericRecord inputRecord) { try { return getFieldAsBytes(inputRecord, payloadField); } catch (Exception e) { return null; } }
java
@Deprecated protected byte[] getPayloadBytes(GenericRecord inputRecord) { try { return getFieldAsBytes(inputRecord, payloadField); } catch (Exception e) { return null; } }
[ "@", "Deprecated", "protected", "byte", "[", "]", "getPayloadBytes", "(", "GenericRecord", "inputRecord", ")", "{", "try", "{", "return", "getFieldAsBytes", "(", "inputRecord", ",", "payloadField", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "re...
Get payload field and convert to byte array @param inputRecord the input record which has the payload @return the byte array of the payload in the input record @deprecated use {@link #getFieldAsBytes(GenericRecord, String)}
[ "Get", "payload", "field", "and", "convert", "to", "byte", "array" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java#L117-L124
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java
TasksInner.listAsync
public Observable<Page<TaskInner>> listAsync(final String resourceGroupName, final String registryName) { return listWithServiceResponseAsync(resourceGroupName, registryName) .map(new Func1<ServiceResponse<Page<TaskInner>>, Page<TaskInner>>() { @Override public Page<TaskInner> call(ServiceResponse<Page<TaskInner>> response) { return response.body(); } }); }
java
public Observable<Page<TaskInner>> listAsync(final String resourceGroupName, final String registryName) { return listWithServiceResponseAsync(resourceGroupName, registryName) .map(new Func1<ServiceResponse<Page<TaskInner>>, Page<TaskInner>>() { @Override public Page<TaskInner> call(ServiceResponse<Page<TaskInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "TaskInner", ">", ">", "listAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "registryName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ")",...
Lists all the tasks for a specified container registry. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;TaskInner&gt; object
[ "Lists", "all", "the", "tasks", "for", "a", "specified", "container", "registry", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/TasksInner.java#L158-L166
bugsnag/bugsnag-java
bugsnag/src/main/java/com/bugsnag/serialization/Serializer.java
Serializer.writeToStream
public void writeToStream(OutputStream stream, Object object) throws SerializationException { try { mapper.writeValue(stream, object); } catch (IOException ex) { throw new SerializationException("Exception during serialization", ex); } }
java
public void writeToStream(OutputStream stream, Object object) throws SerializationException { try { mapper.writeValue(stream, object); } catch (IOException ex) { throw new SerializationException("Exception during serialization", ex); } }
[ "public", "void", "writeToStream", "(", "OutputStream", "stream", ",", "Object", "object", ")", "throws", "SerializationException", "{", "try", "{", "mapper", ".", "writeValue", "(", "stream", ",", "object", ")", ";", "}", "catch", "(", "IOException", "ex", ...
Write the object to the stream. @param stream the stream to write the object to. @param object the object to write to the stream. @throws SerializationException the object could not be serialized.
[ "Write", "the", "object", "to", "the", "stream", "." ]
train
https://github.com/bugsnag/bugsnag-java/blob/11817d63949bcf2b2b6b765a1d37305cdec356f2/bugsnag/src/main/java/com/bugsnag/serialization/Serializer.java#L32-L38
apptik/jus
android/jus-android/src/main/java/io/apptik/comm/jus/ui/ImageLoader.java
ImageLoader.onGetImageSuccess
protected void onGetImageSuccess(String cacheKey, Bitmap response) { // cache the image that was fetched. imageCache.putBitmap(cacheKey, response); // remove the request from the list of in-flight requests. BatchedImageRequest request = inFlightRequests.remove(cacheKey); if (request != null) { // Update the response bitmap. request.mResponseBitmap = response; // Send the batched response batchResponse(cacheKey, request); } }
java
protected void onGetImageSuccess(String cacheKey, Bitmap response) { // cache the image that was fetched. imageCache.putBitmap(cacheKey, response); // remove the request from the list of in-flight requests. BatchedImageRequest request = inFlightRequests.remove(cacheKey); if (request != null) { // Update the response bitmap. request.mResponseBitmap = response; // Send the batched response batchResponse(cacheKey, request); } }
[ "protected", "void", "onGetImageSuccess", "(", "String", "cacheKey", ",", "Bitmap", "response", ")", "{", "// cache the image that was fetched.", "imageCache", ".", "putBitmap", "(", "cacheKey", ",", "response", ")", ";", "// remove the request from the list of in-flight re...
Handler for when an image was successfully loaded. @param cacheKey The cache key that is associated with the image request. @param response The bitmap that was returned from the network.
[ "Handler", "for", "when", "an", "image", "was", "successfully", "loaded", "." ]
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/android/jus-android/src/main/java/io/apptik/comm/jus/ui/ImageLoader.java#L343-L357
mgm-tp/jfunk
jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java
WebDriverTool.dragAndDrop
public void dragAndDrop(final By sourceBy, final By targetBy) { checkTopmostElement(sourceBy); checkTopmostElement(targetBy); WebElement source = findElement(sourceBy); WebElement target = findElement(targetBy); new Actions(webDriver).dragAndDrop(source, target).perform(); }
java
public void dragAndDrop(final By sourceBy, final By targetBy) { checkTopmostElement(sourceBy); checkTopmostElement(targetBy); WebElement source = findElement(sourceBy); WebElement target = findElement(targetBy); new Actions(webDriver).dragAndDrop(source, target).perform(); }
[ "public", "void", "dragAndDrop", "(", "final", "By", "sourceBy", ",", "final", "By", "targetBy", ")", "{", "checkTopmostElement", "(", "sourceBy", ")", ";", "checkTopmostElement", "(", "targetBy", ")", ";", "WebElement", "source", "=", "findElement", "(", "sou...
Performs a drag'n'drop operation of the element located by {@code sourceBy} to the location of the element located by {@code targetBy}. @param sourceBy the {@link By} used to locate the source element @param targetBy the {@link By} used to locate the element representing the target location
[ "Performs", "a", "drag", "n", "drop", "operation", "of", "the", "element", "located", "by", "{", "@code", "sourceBy", "}", "to", "the", "location", "of", "the", "element", "located", "by", "{", "@code", "targetBy", "}", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java#L254-L260
aws/aws-sdk-java
aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/SamplingRuleUpdate.java
SamplingRuleUpdate.withAttributes
public SamplingRuleUpdate withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
public SamplingRuleUpdate withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
[ "public", "SamplingRuleUpdate", "withAttributes", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "attributes", ")", "{", "setAttributes", "(", "attributes", ")", ";", "return", "this", ";", "}" ]
<p> Matches attributes derived from the request. </p> @param attributes Matches attributes derived from the request. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Matches", "attributes", "derived", "from", "the", "request", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/SamplingRuleUpdate.java#L586-L589
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/quantiles/Util.java
Util.checkPreLongsFlagsCap
static boolean checkPreLongsFlagsCap(final int preambleLongs, final int flags, final long memCapBytes) { final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state final int minPre = Family.QUANTILES.getMinPreLongs(); //1 final int maxPre = Family.QUANTILES.getMaxPreLongs(); //2 final boolean valid = ((preambleLongs == minPre) && empty) || ((preambleLongs == maxPre) && !empty); if (!valid) { throw new SketchesArgumentException( "Possible corruption: PreambleLongs inconsistent with empty state: " + preambleLongs); } checkHeapFlags(flags); if (memCapBytes < (preambleLongs << 3)) { throw new SketchesArgumentException( "Possible corruption: Insufficient capacity for preamble: " + memCapBytes); } return empty; }
java
static boolean checkPreLongsFlagsCap(final int preambleLongs, final int flags, final long memCapBytes) { final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state final int minPre = Family.QUANTILES.getMinPreLongs(); //1 final int maxPre = Family.QUANTILES.getMaxPreLongs(); //2 final boolean valid = ((preambleLongs == minPre) && empty) || ((preambleLongs == maxPre) && !empty); if (!valid) { throw new SketchesArgumentException( "Possible corruption: PreambleLongs inconsistent with empty state: " + preambleLongs); } checkHeapFlags(flags); if (memCapBytes < (preambleLongs << 3)) { throw new SketchesArgumentException( "Possible corruption: Insufficient capacity for preamble: " + memCapBytes); } return empty; }
[ "static", "boolean", "checkPreLongsFlagsCap", "(", "final", "int", "preambleLongs", ",", "final", "int", "flags", ",", "final", "long", "memCapBytes", ")", "{", "final", "boolean", "empty", "=", "(", "flags", "&", "EMPTY_FLAG_MASK", ")", ">", "0", ";", "//Pr...
Checks the consistency of the flag bits and the state of preambleLong and the memory capacity and returns the empty state. @param preambleLongs the size of preamble in longs @param flags the flags field @param memCapBytes the memory capacity @return the value of the empty state
[ "Checks", "the", "consistency", "of", "the", "flag", "bits", "and", "the", "state", "of", "preambleLong", "and", "the", "memory", "capacity", "and", "returns", "the", "empty", "state", "." ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/Util.java#L241-L256
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.identity_user_POST
public void identity_user_POST(String description, String email, String group, String login, String password) throws IOException { String qPath = "/me/identity/user"; StringBuilder sb = path(qPath); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "email", email); addBody(o, "group", group); addBody(o, "login", login); addBody(o, "password", password); exec(qPath, "POST", sb.toString(), o); }
java
public void identity_user_POST(String description, String email, String group, String login, String password) throws IOException { String qPath = "/me/identity/user"; StringBuilder sb = path(qPath); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "email", email); addBody(o, "group", group); addBody(o, "login", login); addBody(o, "password", password); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "identity_user_POST", "(", "String", "description", ",", "String", "email", ",", "String", "group", ",", "String", "login", ",", "String", "password", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/identity/user\"", ";", "Str...
Create a new user REST: POST /me/identity/user @param login [required] User's login @param description [required] User's description @param email [required] User's email @param password [required] User's password @param group [required] User's group
[ "Create", "a", "new", "user" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L186-L196
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/Error.java
Error.printSystemOut
public static void printSystemOut(String message1, long message2) { if (TRACESYSTEMOUT) { System.out.print(message1); System.out.println(message2); } }
java
public static void printSystemOut(String message1, long message2) { if (TRACESYSTEMOUT) { System.out.print(message1); System.out.println(message2); } }
[ "public", "static", "void", "printSystemOut", "(", "String", "message1", ",", "long", "message2", ")", "{", "if", "(", "TRACESYSTEMOUT", ")", "{", "System", ".", "out", ".", "print", "(", "message1", ")", ";", "System", ".", "out", ".", "println", "(", ...
Used to print messages to System.out @param message1 message to print @param message2 message to print
[ "Used", "to", "print", "messages", "to", "System", ".", "out" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/Error.java#L264-L270
jbundle/jbundle
base/screen/model/src/main/java/org/jbundle/base/screen/model/BasePanel.java
BasePanel.setSFieldToProperty
public int setSFieldToProperty(String strSuffix, boolean bDisplayOption, int iMoveMode) { int iErrorCode = Constant.NORMAL_RETURN; for (int iIndex = 0; iIndex < this.getSFieldCount(); iIndex++) { ScreenField sField = this.getSField(iIndex); int iErrorCode2 = sField.setSFieldToProperty(strSuffix, bDisplayOption, iMoveMode); if (iErrorCode2 != Constant.NORMAL_RETURN) iErrorCode = iErrorCode2; } return iErrorCode; }
java
public int setSFieldToProperty(String strSuffix, boolean bDisplayOption, int iMoveMode) { int iErrorCode = Constant.NORMAL_RETURN; for (int iIndex = 0; iIndex < this.getSFieldCount(); iIndex++) { ScreenField sField = this.getSField(iIndex); int iErrorCode2 = sField.setSFieldToProperty(strSuffix, bDisplayOption, iMoveMode); if (iErrorCode2 != Constant.NORMAL_RETURN) iErrorCode = iErrorCode2; } return iErrorCode; }
[ "public", "int", "setSFieldToProperty", "(", "String", "strSuffix", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "int", "iErrorCode", "=", "Constant", ".", "NORMAL_RETURN", ";", "for", "(", "int", "iIndex", "=", "0", ";", "iIndex", "<...
Move the HTML input to the screen record fields. @param strSuffix Only move fields with the suffix. @return true if one was moved. @exception DBException File exception.
[ "Move", "the", "HTML", "input", "to", "the", "screen", "record", "fields", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/BasePanel.java#L1496-L1508
OpenLiberty/open-liberty
dev/com.ibm.ws.clientcontainer/src/com/ibm/ws/clientcontainer/internal/LifecycleCallbackHelper.java
LifecycleCallbackHelper.doPostConstruct
@SuppressWarnings("rawtypes") private void doPostConstruct(Class clazz, List<LifecycleCallback> postConstructs, Object instance) throws InjectionException { if (!metadataComplete && clazz.getSuperclass() != null) { doPostConstruct(clazz.getSuperclass(), postConstructs, instance); } String classname = clazz.getName(); String methodName = getMethodNameFromDD(postConstructs, classname); if (methodName != null) { invokeMethod(clazz, methodName, instance); } else if (!metadataComplete) { Method method = getAnnotatedPostConstructMethod(clazz); if (method != null) { invokeMethod(clazz, method.getName(), instance); } } }
java
@SuppressWarnings("rawtypes") private void doPostConstruct(Class clazz, List<LifecycleCallback> postConstructs, Object instance) throws InjectionException { if (!metadataComplete && clazz.getSuperclass() != null) { doPostConstruct(clazz.getSuperclass(), postConstructs, instance); } String classname = clazz.getName(); String methodName = getMethodNameFromDD(postConstructs, classname); if (methodName != null) { invokeMethod(clazz, methodName, instance); } else if (!metadataComplete) { Method method = getAnnotatedPostConstructMethod(clazz); if (method != null) { invokeMethod(clazz, method.getName(), instance); } } }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "private", "void", "doPostConstruct", "(", "Class", "clazz", ",", "List", "<", "LifecycleCallback", ">", "postConstructs", ",", "Object", "instance", ")", "throws", "InjectionException", "{", "if", "(", "!", "me...
Processes the PostConstruct callback method @param clazz the callback class object @param postConstructs a list of PostConstruct application client module deployment descriptor. @param instance the instance object of the callback class. It can be null for static method. @throws InjectionException
[ "Processes", "the", "PostConstruct", "callback", "method" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.clientcontainer/src/com/ibm/ws/clientcontainer/internal/LifecycleCallbackHelper.java#L83-L99
jMetal/jMetal
jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/wasfga/util/WeightVectors.java
WeightVectors.readFromFile
public static double[][] readFromFile(String filePath) { double[][] weights; Vector<double[]> listOfWeights = new Vector<>(); try { // Open the file FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); int numberOfObjectives = 0; int j; String aux = br.readLine(); while (aux != null) { StringTokenizer st = new StringTokenizer(aux); j = 0; numberOfObjectives = st.countTokens(); double[] weight = new double[numberOfObjectives]; while (st.hasMoreTokens()) { weight[j] = new Double(st.nextToken()); j++; } listOfWeights.add(weight); aux = br.readLine(); } br.close(); weights = new double[listOfWeights.size()][numberOfObjectives]; for (int indexWeight = 0; indexWeight < listOfWeights.size(); indexWeight++) { System.arraycopy(listOfWeights.get(indexWeight), 0, weights[indexWeight], 0, numberOfObjectives); } } catch (Exception e) { throw new JMetalException("readFromFile: failed when reading for file: " + filePath + "", e); } return weights; }
java
public static double[][] readFromFile(String filePath) { double[][] weights; Vector<double[]> listOfWeights = new Vector<>(); try { // Open the file FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); int numberOfObjectives = 0; int j; String aux = br.readLine(); while (aux != null) { StringTokenizer st = new StringTokenizer(aux); j = 0; numberOfObjectives = st.countTokens(); double[] weight = new double[numberOfObjectives]; while (st.hasMoreTokens()) { weight[j] = new Double(st.nextToken()); j++; } listOfWeights.add(weight); aux = br.readLine(); } br.close(); weights = new double[listOfWeights.size()][numberOfObjectives]; for (int indexWeight = 0; indexWeight < listOfWeights.size(); indexWeight++) { System.arraycopy(listOfWeights.get(indexWeight), 0, weights[indexWeight], 0, numberOfObjectives); } } catch (Exception e) { throw new JMetalException("readFromFile: failed when reading for file: " + filePath + "", e); } return weights; }
[ "public", "static", "double", "[", "]", "[", "]", "readFromFile", "(", "String", "filePath", ")", "{", "double", "[", "]", "[", "]", "weights", ";", "Vector", "<", "double", "[", "]", ">", "listOfWeights", "=", "new", "Vector", "<>", "(", ")", ";", ...
Read a set of weight vector from a file @param filePath A file containing the weight vectors @return A set of weight vectors
[ "Read", "a", "set", "of", "weight", "vector", "from", "a", "file" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/wasfga/util/WeightVectors.java#L122-L161
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java
SqlQueryStatement.getFieldDescriptor
protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo) { FieldDescriptor fld = null; String colName = aPathInfo.column; if (aTableAlias != null) { fld = aTableAlias.cld.getFieldDescriptorByName(colName); if (fld == null) { ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName); if (ord != null) { fld = getFldFromReference(aTableAlias, ord); } else { fld = getFldFromJoin(aTableAlias, colName); } } } return fld; }
java
protected FieldDescriptor getFieldDescriptor(TableAlias aTableAlias, PathInfo aPathInfo) { FieldDescriptor fld = null; String colName = aPathInfo.column; if (aTableAlias != null) { fld = aTableAlias.cld.getFieldDescriptorByName(colName); if (fld == null) { ObjectReferenceDescriptor ord = aTableAlias.cld.getObjectReferenceDescriptorByName(colName); if (ord != null) { fld = getFldFromReference(aTableAlias, ord); } else { fld = getFldFromJoin(aTableAlias, colName); } } } return fld; }
[ "protected", "FieldDescriptor", "getFieldDescriptor", "(", "TableAlias", "aTableAlias", ",", "PathInfo", "aPathInfo", ")", "{", "FieldDescriptor", "fld", "=", "null", ";", "String", "colName", "=", "aPathInfo", ".", "column", ";", "if", "(", "aTableAlias", "!=", ...
Get the FieldDescriptor for the PathInfo @param aTableAlias @param aPathInfo @return FieldDescriptor
[ "Get", "the", "FieldDescriptor", "for", "the", "PathInfo" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L342-L365
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsTemplate.java
HalFormsTemplate.andContentType
public HalFormsTemplate andContentType(MediaType mediaType) { Assert.notNull(mediaType, "Media type must not be null!"); List<MediaType> contentTypes = new ArrayList<>(this.contentTypes); contentTypes.add(mediaType); return new HalFormsTemplate(title, httpMethod, properties, contentTypes); }
java
public HalFormsTemplate andContentType(MediaType mediaType) { Assert.notNull(mediaType, "Media type must not be null!"); List<MediaType> contentTypes = new ArrayList<>(this.contentTypes); contentTypes.add(mediaType); return new HalFormsTemplate(title, httpMethod, properties, contentTypes); }
[ "public", "HalFormsTemplate", "andContentType", "(", "MediaType", "mediaType", ")", "{", "Assert", ".", "notNull", "(", "mediaType", ",", "\"Media type must not be null!\"", ")", ";", "List", "<", "MediaType", ">", "contentTypes", "=", "new", "ArrayList", "<>", "(...
Returns a new {@link HalFormsTemplate} with the given {@link MediaType} added as content type. @param mediaType must not be {@literal null}. @return
[ "Returns", "a", "new", "{", "@link", "HalFormsTemplate", "}", "with", "the", "given", "{", "@link", "MediaType", "}", "added", "as", "content", "type", "." ]
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsTemplate.java#L99-L107
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ObjectDataTypesInner.java
ObjectDataTypesInner.listFieldsByTypeAsync
public Observable<List<TypeFieldInner>> listFieldsByTypeAsync(String resourceGroupName, String automationAccountName, String typeName) { return listFieldsByTypeWithServiceResponseAsync(resourceGroupName, automationAccountName, typeName).map(new Func1<ServiceResponse<List<TypeFieldInner>>, List<TypeFieldInner>>() { @Override public List<TypeFieldInner> call(ServiceResponse<List<TypeFieldInner>> response) { return response.body(); } }); }
java
public Observable<List<TypeFieldInner>> listFieldsByTypeAsync(String resourceGroupName, String automationAccountName, String typeName) { return listFieldsByTypeWithServiceResponseAsync(resourceGroupName, automationAccountName, typeName).map(new Func1<ServiceResponse<List<TypeFieldInner>>, List<TypeFieldInner>>() { @Override public List<TypeFieldInner> call(ServiceResponse<List<TypeFieldInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "TypeFieldInner", ">", ">", "listFieldsByTypeAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "typeName", ")", "{", "return", "listFieldsByTypeWithServiceResponseAsync", "(", "re...
Retrieve a list of fields of a given type across all accessible modules. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param typeName The name of type. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;TypeFieldInner&gt; object
[ "Retrieve", "a", "list", "of", "fields", "of", "a", "given", "type", "across", "all", "accessible", "modules", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ObjectDataTypesInner.java#L206-L213
radkovo/jStyleParser
src/main/java/cz/vutbr/web/domassign/DeclarationTransformerImpl.java
DeclarationTransformerImpl.genericTermLength
protected <T extends CSSProperty> boolean genericTermLength(Term<?> term, String propertyName, T lengthIdentification, ValueRange range, Map<String, CSSProperty> properties, Map<String, Term<?>> values) { if (term instanceof TermInteger && ((TermInteger) term).getUnit().equals(TermNumber.Unit.none)) { if (CSSFactory.getImplyPixelLength() || ((TermInteger) term).getValue() == 0) { //0 is always allowed with no units // convert to length with units of px TermLength tl = tf.createLength(((TermInteger) term).getValue(), TermNumber.Unit.px); return genericTerm(TermLength.class, tl, propertyName, lengthIdentification, range, properties, values); } else { return false; } } else if (term instanceof TermLength) { return genericTerm(TermLength.class, term, propertyName, lengthIdentification, range, properties, values); } return false; }
java
protected <T extends CSSProperty> boolean genericTermLength(Term<?> term, String propertyName, T lengthIdentification, ValueRange range, Map<String, CSSProperty> properties, Map<String, Term<?>> values) { if (term instanceof TermInteger && ((TermInteger) term).getUnit().equals(TermNumber.Unit.none)) { if (CSSFactory.getImplyPixelLength() || ((TermInteger) term).getValue() == 0) { //0 is always allowed with no units // convert to length with units of px TermLength tl = tf.createLength(((TermInteger) term).getValue(), TermNumber.Unit.px); return genericTerm(TermLength.class, tl, propertyName, lengthIdentification, range, properties, values); } else { return false; } } else if (term instanceof TermLength) { return genericTerm(TermLength.class, term, propertyName, lengthIdentification, range, properties, values); } return false; }
[ "protected", "<", "T", "extends", "CSSProperty", ">", "boolean", "genericTermLength", "(", "Term", "<", "?", ">", "term", ",", "String", "propertyName", ",", "T", "lengthIdentification", ",", "ValueRange", "range", ",", "Map", "<", "String", ",", "CSSProperty"...
Converts term into TermLength and stores values and types in maps @param <T> CSSProperty @param term Term to be parsed @param propertyName How to store colorIdentificiton @param lengthIdentification What to store under propertyName @param properties Map to store property types @param values Map to store property values @return <code>true</code> in case of success, <code>false</code> otherwise
[ "Converts", "term", "into", "TermLength", "and", "stores", "values", "and", "types", "in", "maps" ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/domassign/DeclarationTransformerImpl.java#L337-L356
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/VirtualHost.java
VirtualHost.removeWebApplication
public void removeWebApplication(DeployedModule deployedModule, String contextRoot) { //boolean restarting = deployedModule.isRestarting(); if (TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) logger.logp(Level.FINE, CLASS_NAME, "removeWebApplication", "ContextRoot : " + contextRoot); String ct = makeProperContextRoot(deployedModule.getContextRoot()); // proper String mapRoot = makeMappingContextRoot(ct); //PK37449 adding synchronization block // removeMappedObject uses the mapped root (the same format that was used to add it) // removeMappedObject is synchronized, and returns the object that was removed from the map (if there was one) WebGroup webGroup = (WebGroup) removeMappedObject(mapRoot); if (webGroup != null) { // Begin 284644, reverse removal of web applications from map to prevent requests from coming in after app removed // Liberty: removed redundant call to remove mapping: call to removeMappedObject does what is needed webGroup.removeWebApplication(deployedModule); // End 284644, reverse removal of web applications from map to prevent requests from coming in after app removed //PK37449 adding trace and call to removeSubContainer() from AbstractContainer. // The call that was in WebGroup was removed. if (TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) logger.logp(Level.FINE, CLASS_NAME, "removeWebApplication", "name: " + webGroup.getName()); //if (!restarting) removeSubContainer(webGroup.getName()); //PK37449 end } }
java
public void removeWebApplication(DeployedModule deployedModule, String contextRoot) { //boolean restarting = deployedModule.isRestarting(); if (TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) logger.logp(Level.FINE, CLASS_NAME, "removeWebApplication", "ContextRoot : " + contextRoot); String ct = makeProperContextRoot(deployedModule.getContextRoot()); // proper String mapRoot = makeMappingContextRoot(ct); //PK37449 adding synchronization block // removeMappedObject uses the mapped root (the same format that was used to add it) // removeMappedObject is synchronized, and returns the object that was removed from the map (if there was one) WebGroup webGroup = (WebGroup) removeMappedObject(mapRoot); if (webGroup != null) { // Begin 284644, reverse removal of web applications from map to prevent requests from coming in after app removed // Liberty: removed redundant call to remove mapping: call to removeMappedObject does what is needed webGroup.removeWebApplication(deployedModule); // End 284644, reverse removal of web applications from map to prevent requests from coming in after app removed //PK37449 adding trace and call to removeSubContainer() from AbstractContainer. // The call that was in WebGroup was removed. if (TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) logger.logp(Level.FINE, CLASS_NAME, "removeWebApplication", "name: " + webGroup.getName()); //if (!restarting) removeSubContainer(webGroup.getName()); //PK37449 end } }
[ "public", "void", "removeWebApplication", "(", "DeployedModule", "deployedModule", ",", "String", "contextRoot", ")", "{", "//boolean restarting = deployedModule.isRestarting();", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "logger", ".", "isL...
begin 280649 SERVICE: clean up separation of core and shell WASCC.web.webcontainer : reuse with other VirtualHost impls.
[ "begin", "280649", "SERVICE", ":", "clean", "up", "separation", "of", "core", "and", "shell", "WASCC", ".", "web", ".", "webcontainer", ":", "reuse", "with", "other", "VirtualHost", "impls", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/VirtualHost.java#L247-L276
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/renderer/CSSHTMLBundleLinkRenderer.java
CSSHTMLBundleLinkRenderer.renderIeCssBundleLink
private void renderIeCssBundleLink(BundleRendererContext ctx, Writer out, BundlePath bundlePath) throws IOException { Random randomSeed = new Random(); int random = randomSeed.nextInt(); if (random < 0) random *= -1; String path = GeneratorRegistry.IE_CSS_GENERATOR_PREFIX + GeneratorRegistry.PREFIX_SEPARATOR + bundlePath.getPath(); path = PathNormalizer.createGenerationPath(path, bundler.getConfig().getGeneratorRegistry(), "d=" + random); out.write(createBundleLink(path, null, null, ctx.getContextPath(), ctx.isSslRequest())); }
java
private void renderIeCssBundleLink(BundleRendererContext ctx, Writer out, BundlePath bundlePath) throws IOException { Random randomSeed = new Random(); int random = randomSeed.nextInt(); if (random < 0) random *= -1; String path = GeneratorRegistry.IE_CSS_GENERATOR_PREFIX + GeneratorRegistry.PREFIX_SEPARATOR + bundlePath.getPath(); path = PathNormalizer.createGenerationPath(path, bundler.getConfig().getGeneratorRegistry(), "d=" + random); out.write(createBundleLink(path, null, null, ctx.getContextPath(), ctx.isSslRequest())); }
[ "private", "void", "renderIeCssBundleLink", "(", "BundleRendererContext", "ctx", ",", "Writer", "out", ",", "BundlePath", "bundlePath", ")", "throws", "IOException", "{", "Random", "randomSeed", "=", "new", "Random", "(", ")", ";", "int", "random", "=", "randomS...
Renders the CSS link to retrieve the CSS bundle for IE in debug mode. @param ctx the context @param out the writer @param bundle the bundle @throws IOException if an IOException occurs
[ "Renders", "the", "CSS", "link", "to", "retrieve", "the", "CSS", "bundle", "for", "IE", "in", "debug", "mode", "." ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/renderer/CSSHTMLBundleLinkRenderer.java#L350-L360
gallandarakhneorg/afc
core/vmutils/src/main/java/org/arakhne/afc/vmutil/ReflectionUtil.java
ReflectionUtil.isAssignableFrom
@Pure public static boolean isAssignableFrom(Class<?> assignementTarget, Class<?> assignementSource) { assert assignementSource != null; assert assignementTarget != null; // Test according to the Class's behaviour if (assignementTarget.isAssignableFrom(assignementSource)) { return true; } // Test according to autoboxing if (assignementTarget.isPrimitive() && assignementSource.isPrimitive() && assignementTarget != Void.class && assignementTarget != void.class && assignementSource != Void.class && assignementSource != void.class) { return true; } return false; }
java
@Pure public static boolean isAssignableFrom(Class<?> assignementTarget, Class<?> assignementSource) { assert assignementSource != null; assert assignementTarget != null; // Test according to the Class's behaviour if (assignementTarget.isAssignableFrom(assignementSource)) { return true; } // Test according to autoboxing if (assignementTarget.isPrimitive() && assignementSource.isPrimitive() && assignementTarget != Void.class && assignementTarget != void.class && assignementSource != Void.class && assignementSource != void.class) { return true; } return false; }
[ "@", "Pure", "public", "static", "boolean", "isAssignableFrom", "(", "Class", "<", "?", ">", "assignementTarget", ",", "Class", "<", "?", ">", "assignementSource", ")", "{", "assert", "assignementSource", "!=", "null", ";", "assert", "assignementTarget", "!=", ...
Determines if the <code>assignmentTarget</code> object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified <code>assignementSource</code> parameter. This method extends {@link Class#isAssignableFrom(Class)} with autoboxing support. @param assignementTarget is the class that is tested to be a super class. @param assignementSource is the class that is tested to be a sub class. @return <code>true</code> if an object of the {@code assignementSource} type could be assigned to a variable of {@code assignementTarget} type, otherwise <code>false</code>.
[ "Determines", "if", "the", "<code", ">", "assignmentTarget<", "/", "code", ">", "object", "is", "either", "the", "same", "as", "or", "is", "a", "superclass", "or", "superinterface", "of", "the", "class", "or", "interface", "represented", "by", "the", "specif...
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/ReflectionUtil.java#L168-L186
twilio/twilio-java
src/main/java/com/twilio/rest/wireless/v1/RatePlanReader.java
RatePlanReader.firstPage
@Override @SuppressWarnings("checkstyle:linelength") public Page<RatePlan> firstPage(final TwilioRestClient client) { Request request = new Request( HttpMethod.GET, Domains.WIRELESS.toString(), "/v1/RatePlans", client.getRegion() ); addQueryParams(request); return pageForRequest(client, request); }
java
@Override @SuppressWarnings("checkstyle:linelength") public Page<RatePlan> firstPage(final TwilioRestClient client) { Request request = new Request( HttpMethod.GET, Domains.WIRELESS.toString(), "/v1/RatePlans", client.getRegion() ); addQueryParams(request); return pageForRequest(client, request); }
[ "@", "Override", "@", "SuppressWarnings", "(", "\"checkstyle:linelength\"", ")", "public", "Page", "<", "RatePlan", ">", "firstPage", "(", "final", "TwilioRestClient", "client", ")", "{", "Request", "request", "=", "new", "Request", "(", "HttpMethod", ".", "GET"...
Make the request to the Twilio API to perform the read. @param client TwilioRestClient with which to make the request @return RatePlan ResourceSet
[ "Make", "the", "request", "to", "the", "Twilio", "API", "to", "perform", "the", "read", "." ]
train
https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/wireless/v1/RatePlanReader.java#L40-L52
glyptodon/guacamole-client
extensions/guacamole-auth-totp/src/main/java/org/apache/guacamole/auth/totp/user/UserVerificationService.java
UserVerificationService.getKey
private UserTOTPKey getKey(UserContext context, String username) throws GuacamoleException { // Retrieve attributes from current user User self = context.self(); Map<String, String> attributes = context.self().getAttributes(); // If no key is defined, attempt to generate a new key String secret = attributes.get(TOTPUser.TOTP_KEY_SECRET_ATTRIBUTE_NAME); if (secret == null) { // Generate random key for user TOTPGenerator.Mode mode = confService.getMode(); UserTOTPKey generated = new UserTOTPKey(username,mode.getRecommendedKeyLength()); if (setKey(context, generated)) return generated; // Fail if key cannot be set return null; } // Parse retrieved base32 key value byte[] key; try { key = BASE32.decode(secret); } // If key is not valid base32, warn but otherwise pretend the key does // not exist catch (IllegalArgumentException e) { logger.warn("TOTP key of user \"{}\" is not valid base32.", self.getIdentifier()); logger.debug("TOTP key is not valid base32.", e); return null; } // Otherwise, parse value from attributes boolean confirmed = "true".equals(attributes.get(TOTPUser.TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME)); return new UserTOTPKey(username, key, confirmed); }
java
private UserTOTPKey getKey(UserContext context, String username) throws GuacamoleException { // Retrieve attributes from current user User self = context.self(); Map<String, String> attributes = context.self().getAttributes(); // If no key is defined, attempt to generate a new key String secret = attributes.get(TOTPUser.TOTP_KEY_SECRET_ATTRIBUTE_NAME); if (secret == null) { // Generate random key for user TOTPGenerator.Mode mode = confService.getMode(); UserTOTPKey generated = new UserTOTPKey(username,mode.getRecommendedKeyLength()); if (setKey(context, generated)) return generated; // Fail if key cannot be set return null; } // Parse retrieved base32 key value byte[] key; try { key = BASE32.decode(secret); } // If key is not valid base32, warn but otherwise pretend the key does // not exist catch (IllegalArgumentException e) { logger.warn("TOTP key of user \"{}\" is not valid base32.", self.getIdentifier()); logger.debug("TOTP key is not valid base32.", e); return null; } // Otherwise, parse value from attributes boolean confirmed = "true".equals(attributes.get(TOTPUser.TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME)); return new UserTOTPKey(username, key, confirmed); }
[ "private", "UserTOTPKey", "getKey", "(", "UserContext", "context", ",", "String", "username", ")", "throws", "GuacamoleException", "{", "// Retrieve attributes from current user", "User", "self", "=", "context", ".", "self", "(", ")", ";", "Map", "<", "String", ",...
Retrieves and decodes the base32-encoded TOTP key associated with user having the given UserContext. If no TOTP key is associated with the user, a random key is generated and associated with the user. If the extension storing the user does not support storage of the TOTP key, null is returned. @param context The UserContext of the user whose TOTP key should be retrieved. @param username The username of the user associated with the given UserContext. @return The TOTP key associated with the user having the given UserContext, or null if the extension storing the user does not support storage of the TOTP key. @throws GuacamoleException If a new key is generated, but the extension storing the associated user fails while updating the user account.
[ "Retrieves", "and", "decodes", "the", "base32", "-", "encoded", "TOTP", "key", "associated", "with", "user", "having", "the", "given", "UserContext", ".", "If", "no", "TOTP", "key", "is", "associated", "with", "the", "user", "a", "random", "key", "is", "ge...
train
https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-totp/src/main/java/org/apache/guacamole/auth/totp/user/UserVerificationService.java#L102-L142
apache/incubator-druid
extensions-contrib/thrift-extensions/src/main/java/org/apache/druid/data/input/thrift/ThriftDeserialization.java
ThriftDeserialization.detectAndDeserialize
public static <T extends TBase> T detectAndDeserialize(final byte[] bytes, final T thriftObj) throws TException { Preconditions.checkNotNull(thriftObj); try { final byte[] src = decodeB64IfNeeded(bytes); final TProtocolFactory protocolFactory = TProtocolUtil.guessProtocolFactory(src, null); Preconditions.checkNotNull(protocolFactory); if (protocolFactory instanceof TCompactProtocol.Factory) { DESERIALIZER_COMPACT.get().deserialize(thriftObj, src); } else if (protocolFactory instanceof TBinaryProtocol.Factory) { DESERIALIZER_BINARY.get().deserialize(thriftObj, src); } else { DESERIALIZER_JSON.get().deserialize(thriftObj, src); } } catch (final IllegalArgumentException e) { throw new TException(e); } return thriftObj; }
java
public static <T extends TBase> T detectAndDeserialize(final byte[] bytes, final T thriftObj) throws TException { Preconditions.checkNotNull(thriftObj); try { final byte[] src = decodeB64IfNeeded(bytes); final TProtocolFactory protocolFactory = TProtocolUtil.guessProtocolFactory(src, null); Preconditions.checkNotNull(protocolFactory); if (protocolFactory instanceof TCompactProtocol.Factory) { DESERIALIZER_COMPACT.get().deserialize(thriftObj, src); } else if (protocolFactory instanceof TBinaryProtocol.Factory) { DESERIALIZER_BINARY.get().deserialize(thriftObj, src); } else { DESERIALIZER_JSON.get().deserialize(thriftObj, src); } } catch (final IllegalArgumentException e) { throw new TException(e); } return thriftObj; }
[ "public", "static", "<", "T", "extends", "TBase", ">", "T", "detectAndDeserialize", "(", "final", "byte", "[", "]", "bytes", ",", "final", "T", "thriftObj", ")", "throws", "TException", "{", "Preconditions", ".", "checkNotNull", "(", "thriftObj", ")", ";", ...
Deserializes byte-array into thrift object. <p> Supporting binary, compact and json protocols, and the byte array could be or not be encoded by Base64. @param bytes the byte-array to deserialize @param thriftObj the output thrift object @return the output thrift object, or null if error occurs
[ "Deserializes", "byte", "-", "array", "into", "thrift", "object", ".", "<p", ">", "Supporting", "binary", "compact", "and", "json", "protocols", "and", "the", "byte", "array", "could", "be", "or", "not", "be", "encoded", "by", "Base64", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-contrib/thrift-extensions/src/main/java/org/apache/druid/data/input/thrift/ThriftDeserialization.java#L102-L121
geomajas/geomajas-project-client-gwt2
plugin/editing/impl/src/main/java/org/geomajas/gwt2/plugin/editing/client/gfx/GeometryRendererImpl.java
GeometryRendererImpl.onTentativeMove
public void onTentativeMove(GeometryEditTentativeMoveEvent event) { try { Coordinate[] vertices = editService.getIndexService().getSiblingVertices(editService.getGeometry(), editService.getInsertIndex()); String geometryType = editService.getIndexService().getGeometryType(editService.getGeometry(), editService.getInsertIndex()); if (vertices != null && (Geometry.LINE_STRING.equals(geometryType) || Geometry.LINEAR_RING.equals(geometryType))) { Coordinate temp1 = event.getOrigin(); Coordinate temp2 = event.getCurrentPosition(); Coordinate c1 = mapPresenter.getViewPort().getTransformationService() .transform(temp1, RenderSpace.WORLD, RenderSpace.SCREEN); Coordinate c2 = mapPresenter.getViewPort().getTransformationService() .transform(temp2, RenderSpace.WORLD, RenderSpace.SCREEN); tentativeMoveLine.setStep(0, new MoveTo(false, c1.getX(), c1.getY())); tentativeMoveLine.setStep(1, new LineTo(false, c2.getX(), c2.getY())); } else if (vertices != null && Geometry.LINEAR_RING.equals(geometryType)) { // Draw the second line (as an option...) } } catch (GeometryIndexNotFoundException e) { throw new IllegalStateException(e); } }
java
public void onTentativeMove(GeometryEditTentativeMoveEvent event) { try { Coordinate[] vertices = editService.getIndexService().getSiblingVertices(editService.getGeometry(), editService.getInsertIndex()); String geometryType = editService.getIndexService().getGeometryType(editService.getGeometry(), editService.getInsertIndex()); if (vertices != null && (Geometry.LINE_STRING.equals(geometryType) || Geometry.LINEAR_RING.equals(geometryType))) { Coordinate temp1 = event.getOrigin(); Coordinate temp2 = event.getCurrentPosition(); Coordinate c1 = mapPresenter.getViewPort().getTransformationService() .transform(temp1, RenderSpace.WORLD, RenderSpace.SCREEN); Coordinate c2 = mapPresenter.getViewPort().getTransformationService() .transform(temp2, RenderSpace.WORLD, RenderSpace.SCREEN); tentativeMoveLine.setStep(0, new MoveTo(false, c1.getX(), c1.getY())); tentativeMoveLine.setStep(1, new LineTo(false, c2.getX(), c2.getY())); } else if (vertices != null && Geometry.LINEAR_RING.equals(geometryType)) { // Draw the second line (as an option...) } } catch (GeometryIndexNotFoundException e) { throw new IllegalStateException(e); } }
[ "public", "void", "onTentativeMove", "(", "GeometryEditTentativeMoveEvent", "event", ")", "{", "try", "{", "Coordinate", "[", "]", "vertices", "=", "editService", ".", "getIndexService", "(", ")", ".", "getSiblingVertices", "(", "editService", ".", "getGeometry", ...
Renders a line from the last inserted point to the current mouse position, indicating what the new situation would look like if a vertex where to be inserted at the mouse location.
[ "Renders", "a", "line", "from", "the", "last", "inserted", "point", "to", "the", "current", "mouse", "position", "indicating", "what", "the", "new", "situation", "would", "look", "like", "if", "a", "vertex", "where", "to", "be", "inserted", "at", "the", "m...
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/editing/impl/src/main/java/org/geomajas/gwt2/plugin/editing/client/gfx/GeometryRendererImpl.java#L417-L441
undertow-io/undertow
core/src/main/java/io/undertow/websockets/core/WebSockets.java
WebSockets.sendText
public static void sendText(final ByteBuffer message, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) { sendInternal(message, WebSocketFrameType.TEXT, wsChannel, callback, null, -1); }
java
public static void sendText(final ByteBuffer message, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) { sendInternal(message, WebSocketFrameType.TEXT, wsChannel, callback, null, -1); }
[ "public", "static", "void", "sendText", "(", "final", "ByteBuffer", "message", ",", "final", "WebSocketChannel", "wsChannel", ",", "final", "WebSocketCallback", "<", "Void", ">", "callback", ")", "{", "sendInternal", "(", "message", ",", "WebSocketFrameType", ".",...
Sends a complete text message, invoking the callback when complete @param message The text to send @param wsChannel The web socket channel @param callback The callback to invoke on completion
[ "Sends", "a", "complete", "text", "message", "invoking", "the", "callback", "when", "complete" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L99-L101
googleapis/google-cloud-java
google-cloud-clients/google-cloud-recaptchaenterprise/src/main/java/com/google/cloud/recaptchaenterprise/v1beta1/RecaptchaEnterpriseServiceV1Beta1Client.java
RecaptchaEnterpriseServiceV1Beta1Client.createAssessment
public final Assessment createAssessment(String parent, Assessment assessment) { CreateAssessmentRequest request = CreateAssessmentRequest.newBuilder().setParent(parent).setAssessment(assessment).build(); return createAssessment(request); }
java
public final Assessment createAssessment(String parent, Assessment assessment) { CreateAssessmentRequest request = CreateAssessmentRequest.newBuilder().setParent(parent).setAssessment(assessment).build(); return createAssessment(request); }
[ "public", "final", "Assessment", "createAssessment", "(", "String", "parent", ",", "Assessment", "assessment", ")", "{", "CreateAssessmentRequest", "request", "=", "CreateAssessmentRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", ")", ".", "...
Creates an Assessment of the likelihood an event is legitimate. <p>Sample code: <pre><code> try (RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.create()) { ProjectName parent = ProjectName.of("[PROJECT]"); Assessment assessment = Assessment.newBuilder().build(); Assessment response = recaptchaEnterpriseServiceV1Beta1Client.createAssessment(parent.toString(), assessment); } </code></pre> @param parent Required. The name of the project in which the assessment will be created, in the format "projects/{project_number}". @param assessment The asessment details. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "an", "Assessment", "of", "the", "likelihood", "an", "event", "is", "legitimate", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-recaptchaenterprise/src/main/java/com/google/cloud/recaptchaenterprise/v1beta1/RecaptchaEnterpriseServiceV1Beta1Client.java#L208-L213
NessComputing/components-ness-lifecycle
src/main/java/com/nesscomputing/lifecycle/AbstractLifecycle.java
AbstractLifecycle.addListener
@Override public void addListener(@Nonnull final LifecycleStage lifecycleStage, @Nonnull final LifecycleListener lifecycleListener) { if (!listeners.containsKey(lifecycleStage)) { throw illegalStage(lifecycleStage); } listeners.get(lifecycleStage).add(lifecycleListener); }
java
@Override public void addListener(@Nonnull final LifecycleStage lifecycleStage, @Nonnull final LifecycleListener lifecycleListener) { if (!listeners.containsKey(lifecycleStage)) { throw illegalStage(lifecycleStage); } listeners.get(lifecycleStage).add(lifecycleListener); }
[ "@", "Override", "public", "void", "addListener", "(", "@", "Nonnull", "final", "LifecycleStage", "lifecycleStage", ",", "@", "Nonnull", "final", "LifecycleListener", "lifecycleListener", ")", "{", "if", "(", "!", "listeners", ".", "containsKey", "(", "lifecycleSt...
Adds a listener to a lifecycle stage. @param lifecycleStage The Lifecycle stage on which to be notified. @param lifecycleListener Callback to be invoked when the lifecycle stage is executed.
[ "Adds", "a", "listener", "to", "a", "lifecycle", "stage", "." ]
train
https://github.com/NessComputing/components-ness-lifecycle/blob/6c8ae8ec8fdcd16b30383092ce9e70424a6760f1/src/main/java/com/nesscomputing/lifecycle/AbstractLifecycle.java#L66-L73
santhosh-tekuri/jlibs
core/src/main/java/jlibs/core/io/FileUtil.java
FileUtil.findFreeFile
public static File findFreeFile(final File dir, String pattern, boolean tryEmptyVar){ String name = StringUtil.suggest(new Filter<String>(){ @Override public boolean select(String name){ return !new File(dir, name).exists(); } }, pattern, tryEmptyVar); return new File(dir, name); }
java
public static File findFreeFile(final File dir, String pattern, boolean tryEmptyVar){ String name = StringUtil.suggest(new Filter<String>(){ @Override public boolean select(String name){ return !new File(dir, name).exists(); } }, pattern, tryEmptyVar); return new File(dir, name); }
[ "public", "static", "File", "findFreeFile", "(", "final", "File", "dir", ",", "String", "pattern", ",", "boolean", "tryEmptyVar", ")", "{", "String", "name", "=", "StringUtil", ".", "suggest", "(", "new", "Filter", "<", "String", ">", "(", ")", "{", "@",...
Finds a free file (i.e non-existing) in specified directory, using specified pattern. for example: findFreeFile(myDir, "sample${i}.xml", false) will search for free file in order: sample1.xml, sample2.xml, sample3.xml and so on if tryEmptyVar is true, it it seaches for free file in order: sample.xml, sample2.xml, sample3.xml and so on the given pattern must have variable part ${i}
[ "Finds", "a", "free", "file", "(", "i", ".", "e", "non", "-", "existing", ")", "in", "specified", "directory", "using", "specified", "pattern", ".", "for", "example", ":", "findFreeFile", "(", "myDir", "sample$", "{", "i", "}", ".", "xml", "false", ")"...
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/core/src/main/java/jlibs/core/io/FileUtil.java#L93-L102
google/closure-compiler
src/com/google/javascript/jscomp/ExpressionDecomposer.java
ExpressionDecomposer.rewriteCallExpression
private Node rewriteCallExpression(Node call, DecompositionState state) { checkArgument(call.isCall(), call); Node first = call.getFirstChild(); checkArgument(NodeUtil.isGet(first), first); // Find the type of (fn expression).call JSType fnType = first.getJSType(); JSType fnCallType = null; if (fnType != null) { fnCallType = fnType.isFunctionType() ? fnType.toMaybeFunctionType().getPropertyType("call") : unknownType; } // Extracts the expression representing the function to call. For example: // "a['b'].c" from "a['b'].c()" Node getVarNode = extractExpression(first, state.extractBeforeStatement); state.extractBeforeStatement = getVarNode; // Extracts the object reference to be used as "this". For example: // "a['b']" from "a['b'].c" Node getExprNode = getVarNode.getFirstFirstChild(); checkArgument(NodeUtil.isGet(getExprNode), getExprNode); Node thisVarNode = extractExpression(getExprNode.getFirstChild(), state.extractBeforeStatement); state.extractBeforeStatement = thisVarNode; // Rewrite the CALL expression. Node thisNameNode = thisVarNode.getFirstChild(); Node functionNameNode = getVarNode.getFirstChild(); // CALL // GETPROP // functionName // "call" // thisName // original-parameter1 // original-parameter2 // ... Node newCall = IR.call( withType( IR.getprop( functionNameNode.cloneNode(), withType(IR.string("call"), stringType)), fnCallType), thisNameNode.cloneNode()) .setJSType(call.getJSType()) .useSourceInfoIfMissingFromForTree(call); // Throw away the call name call.removeFirstChild(); if (call.hasChildren()) { // Add the call parameters to the new call. newCall.addChildrenToBack(call.removeChildren()); } call.replaceWith(newCall); return newCall; }
java
private Node rewriteCallExpression(Node call, DecompositionState state) { checkArgument(call.isCall(), call); Node first = call.getFirstChild(); checkArgument(NodeUtil.isGet(first), first); // Find the type of (fn expression).call JSType fnType = first.getJSType(); JSType fnCallType = null; if (fnType != null) { fnCallType = fnType.isFunctionType() ? fnType.toMaybeFunctionType().getPropertyType("call") : unknownType; } // Extracts the expression representing the function to call. For example: // "a['b'].c" from "a['b'].c()" Node getVarNode = extractExpression(first, state.extractBeforeStatement); state.extractBeforeStatement = getVarNode; // Extracts the object reference to be used as "this". For example: // "a['b']" from "a['b'].c" Node getExprNode = getVarNode.getFirstFirstChild(); checkArgument(NodeUtil.isGet(getExprNode), getExprNode); Node thisVarNode = extractExpression(getExprNode.getFirstChild(), state.extractBeforeStatement); state.extractBeforeStatement = thisVarNode; // Rewrite the CALL expression. Node thisNameNode = thisVarNode.getFirstChild(); Node functionNameNode = getVarNode.getFirstChild(); // CALL // GETPROP // functionName // "call" // thisName // original-parameter1 // original-parameter2 // ... Node newCall = IR.call( withType( IR.getprop( functionNameNode.cloneNode(), withType(IR.string("call"), stringType)), fnCallType), thisNameNode.cloneNode()) .setJSType(call.getJSType()) .useSourceInfoIfMissingFromForTree(call); // Throw away the call name call.removeFirstChild(); if (call.hasChildren()) { // Add the call parameters to the new call. newCall.addChildrenToBack(call.removeChildren()); } call.replaceWith(newCall); return newCall; }
[ "private", "Node", "rewriteCallExpression", "(", "Node", "call", ",", "DecompositionState", "state", ")", "{", "checkArgument", "(", "call", ".", "isCall", "(", ")", ",", "call", ")", ";", "Node", "first", "=", "call", ".", "getFirstChild", "(", ")", ";", ...
Rewrite the call so "this" is preserved. <pre>a.b(c);</pre> becomes: <pre> var temp1 = a; var temp0 = temp1.b; temp0.call(temp1,c); </pre> @return The replacement node.
[ "Rewrite", "the", "call", "so", "this", "is", "preserved", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ExpressionDecomposer.java#L606-L666
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/LdapConnection.java
LdapConnection.addAttributes
@Trivial private void addAttributes(Attributes sourceAttrs, Attributes descAttrs) { for (NamingEnumeration<?> neu = sourceAttrs.getAll(); neu.hasMoreElements();) { descAttrs.put((Attribute) neu.nextElement()); } }
java
@Trivial private void addAttributes(Attributes sourceAttrs, Attributes descAttrs) { for (NamingEnumeration<?> neu = sourceAttrs.getAll(); neu.hasMoreElements();) { descAttrs.put((Attribute) neu.nextElement()); } }
[ "@", "Trivial", "private", "void", "addAttributes", "(", "Attributes", "sourceAttrs", ",", "Attributes", "descAttrs", ")", "{", "for", "(", "NamingEnumeration", "<", "?", ">", "neu", "=", "sourceAttrs", ".", "getAll", "(", ")", ";", "neu", ".", "hasMoreEleme...
Add attributes new attributes to an existing {@link Attributes} instance. @param sourceAttrs The attributes to add. @param descAttrs The attributes to add to.
[ "Add", "attributes", "new", "attributes", "to", "an", "existing", "{", "@link", "Attributes", "}", "instance", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/LdapConnection.java#L1056-L1061
m-m-m/util
pojopath/src/main/java/net/sf/mmm/util/pojo/path/base/AbstractPojoPathNavigator.java
AbstractPojoPathNavigator.createStateByType
@SuppressWarnings("rawtypes") protected PojoPathState createStateByType(GenericType initialPojoType, String pojoPath, PojoPathMode mode, PojoPathContext context) { Class<?> initialPojoClass = initialPojoType.getRetrievalClass(); Map<Object, Object> rawCache = context.getCache(); if (rawCache == null) { CachingPojoPath rootPath = new CachingPojoPath(null, initialPojoClass, initialPojoType); return new PojoPathState(rootPath, mode, pojoPath); } PojoPathCache masterCache = (PojoPathCache) rawCache.get(initialPojoType); if (masterCache == null) { masterCache = new PojoPathCache(initialPojoClass, initialPojoType); rawCache.put(initialPojoType, masterCache); } return masterCache.createState(mode, pojoPath); }
java
@SuppressWarnings("rawtypes") protected PojoPathState createStateByType(GenericType initialPojoType, String pojoPath, PojoPathMode mode, PojoPathContext context) { Class<?> initialPojoClass = initialPojoType.getRetrievalClass(); Map<Object, Object> rawCache = context.getCache(); if (rawCache == null) { CachingPojoPath rootPath = new CachingPojoPath(null, initialPojoClass, initialPojoType); return new PojoPathState(rootPath, mode, pojoPath); } PojoPathCache masterCache = (PojoPathCache) rawCache.get(initialPojoType); if (masterCache == null) { masterCache = new PojoPathCache(initialPojoClass, initialPojoType); rawCache.put(initialPojoType, masterCache); } return masterCache.createState(mode, pojoPath); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "protected", "PojoPathState", "createStateByType", "(", "GenericType", "initialPojoType", ",", "String", "pojoPath", ",", "PojoPathMode", "mode", ",", "PojoPathContext", "context", ")", "{", "Class", "<", "?", ">", ...
This method gets the {@link PojoPathState} for the given {@code context}. @param initialPojoType is the initial pojo-type this {@link PojoPathNavigator} was invoked with. @param pojoPath is the {@link net.sf.mmm.util.pojo.path.api.PojoPath} to navigate. @param mode is the {@link PojoPathMode mode} that determines how to deal with <em>unsafe</em> {@link net.sf.mmm.util.pojo.path.api.PojoPath} s. @param context is the {@link PojoPathContext context} for this operation. @return the {@link PojoPathState} or {@code null} if caching is disabled.
[ "This", "method", "gets", "the", "{", "@link", "PojoPathState", "}", "for", "the", "given", "{", "@code", "context", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojopath/src/main/java/net/sf/mmm/util/pojo/path/base/AbstractPojoPathNavigator.java#L248-L263
wdullaer/MaterialDateTimePicker
library/src/main/java/com/wdullaer/materialdatetimepicker/time/TimePickerDialog.java
TimePickerDialog.newInstance
@SuppressWarnings({"unused", "SameParameterValue"}) public static TimePickerDialog newInstance(OnTimeSetListener callback, boolean is24HourMode) { Calendar now = Calendar.getInstance(); return TimePickerDialog.newInstance(callback, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), is24HourMode); }
java
@SuppressWarnings({"unused", "SameParameterValue"}) public static TimePickerDialog newInstance(OnTimeSetListener callback, boolean is24HourMode) { Calendar now = Calendar.getInstance(); return TimePickerDialog.newInstance(callback, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), is24HourMode); }
[ "@", "SuppressWarnings", "(", "{", "\"unused\"", ",", "\"SameParameterValue\"", "}", ")", "public", "static", "TimePickerDialog", "newInstance", "(", "OnTimeSetListener", "callback", ",", "boolean", "is24HourMode", ")", "{", "Calendar", "now", "=", "Calendar", ".", ...
Create a new TimePickerDialog instance initialized to the current system time @param callback How the parent is notified that the time is set. @param is24HourMode True to render 24 hour mode, false to render AM / PM selectors. @return a new TimePickerDialog instance.
[ "Create", "a", "new", "TimePickerDialog", "instance", "initialized", "to", "the", "current", "system", "time" ]
train
https://github.com/wdullaer/MaterialDateTimePicker/blob/0a8fe28f19db4f5a5a6cfc525a852416232873a8/library/src/main/java/com/wdullaer/materialdatetimepicker/time/TimePickerDialog.java#L224-L228
voldemort/voldemort
src/java/voldemort/rest/coordinator/CoordinatorProxyService.java
CoordinatorProxyService.initializeFatClient
private synchronized void initializeFatClient(String storeName, Properties storeClientProps) { // updates the coordinator metadata with recent stores and cluster xml updateCoordinatorMetadataWithLatestState(); logger.info("Creating a Fat client for store: " + storeName); SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(), storeClientProps); if(this.fatClientMap == null) { this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>(); } DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName, fatClientFactory, 1, this.coordinatorMetadata.getStoreDefs(), this.coordinatorMetadata.getClusterXmlStr()); this.fatClientMap.put(storeName, fatClient); }
java
private synchronized void initializeFatClient(String storeName, Properties storeClientProps) { // updates the coordinator metadata with recent stores and cluster xml updateCoordinatorMetadataWithLatestState(); logger.info("Creating a Fat client for store: " + storeName); SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(), storeClientProps); if(this.fatClientMap == null) { this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>(); } DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName, fatClientFactory, 1, this.coordinatorMetadata.getStoreDefs(), this.coordinatorMetadata.getClusterXmlStr()); this.fatClientMap.put(storeName, fatClient); }
[ "private", "synchronized", "void", "initializeFatClient", "(", "String", "storeName", ",", "Properties", "storeClientProps", ")", "{", "// updates the coordinator metadata with recent stores and cluster xml", "updateCoordinatorMetadataWithLatestState", "(", ")", ";", "logger", "....
Initialize the fat client for the given store. 1. Updates the coordinatorMetadata 2.Gets the new store configs from the config file 3.Creates a new @SocketStoreClientFactory 4. Subsequently caches the @StoreClient obtained from the factory. This is synchronized because if Coordinator Admin is already doing some change we want the AsyncMetadataVersionManager to wait. @param storeName
[ "Initialize", "the", "fat", "client", "for", "the", "given", "store", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/coordinator/CoordinatorProxyService.java#L104-L122
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.ovhAccount_ovhAccountId_movements_movementId_GET
public net.minidev.ovh.api.billing.OvhMovement ovhAccount_ovhAccountId_movements_movementId_GET(String ovhAccountId, Long movementId) throws IOException { String qPath = "/me/ovhAccount/{ovhAccountId}/movements/{movementId}"; StringBuilder sb = path(qPath, ovhAccountId, movementId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, net.minidev.ovh.api.billing.OvhMovement.class); }
java
public net.minidev.ovh.api.billing.OvhMovement ovhAccount_ovhAccountId_movements_movementId_GET(String ovhAccountId, Long movementId) throws IOException { String qPath = "/me/ovhAccount/{ovhAccountId}/movements/{movementId}"; StringBuilder sb = path(qPath, ovhAccountId, movementId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, net.minidev.ovh.api.billing.OvhMovement.class); }
[ "public", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "billing", ".", "OvhMovement", "ovhAccount_ovhAccountId_movements_movementId_GET", "(", "String", "ovhAccountId", ",", "Long", "movementId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\...
Get this object properties REST: GET /me/ovhAccount/{ovhAccountId}/movements/{movementId} @param ovhAccountId [required] @param movementId [required]
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L3348-L3353
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/ErrorHandling.java
ErrorHandling.reportCollectedErrors
public static void reportCollectedErrors(PageContext pc, JspTag tag) { IErrorReporter er = getErrorReporter(tag); if (er == null) return; assert (pc != null); ArrayList errors = er.returnErrors(); if (errors == null || errors.size() == 0) return; assert(errors.size() > 0); String s; // write the error header s = Bundle.getString("Footer_Error_Header"); write(pc, s); int cnt = errors.size(); Object[] args = new Object[5]; for (int i = 0; i < cnt; i++) { Object o = errors.get(i); assert (o != null); if (o instanceof EvalErrorInfo) { EvalErrorInfo err = (EvalErrorInfo) o; args[0] = Integer.toString(err.errorNo); args[1] = err.tagType; args[2] = err.attr; args[3] = err.expression; args[4] = err.evalExcp.getMessage(); s = Bundle.getString("Footer_Error_Expr_Body", args); write(pc, s); } else if (o instanceof TagErrorInfo) { TagErrorInfo tei = (TagErrorInfo) o; args[0] = Integer.toString(tei.errorNo); args[1] = tei.tagType; args[2] = tei.message; s = Bundle.getString("Footer_Error_Tag_Body", args); write(pc, s); } } // write the error footer s = Bundle.getString("Footer_Error_Footer"); write(pc, s); }
java
public static void reportCollectedErrors(PageContext pc, JspTag tag) { IErrorReporter er = getErrorReporter(tag); if (er == null) return; assert (pc != null); ArrayList errors = er.returnErrors(); if (errors == null || errors.size() == 0) return; assert(errors.size() > 0); String s; // write the error header s = Bundle.getString("Footer_Error_Header"); write(pc, s); int cnt = errors.size(); Object[] args = new Object[5]; for (int i = 0; i < cnt; i++) { Object o = errors.get(i); assert (o != null); if (o instanceof EvalErrorInfo) { EvalErrorInfo err = (EvalErrorInfo) o; args[0] = Integer.toString(err.errorNo); args[1] = err.tagType; args[2] = err.attr; args[3] = err.expression; args[4] = err.evalExcp.getMessage(); s = Bundle.getString("Footer_Error_Expr_Body", args); write(pc, s); } else if (o instanceof TagErrorInfo) { TagErrorInfo tei = (TagErrorInfo) o; args[0] = Integer.toString(tei.errorNo); args[1] = tei.tagType; args[2] = tei.message; s = Bundle.getString("Footer_Error_Tag_Body", args); write(pc, s); } } // write the error footer s = Bundle.getString("Footer_Error_Footer"); write(pc, s); }
[ "public", "static", "void", "reportCollectedErrors", "(", "PageContext", "pc", ",", "JspTag", "tag", ")", "{", "IErrorReporter", "er", "=", "getErrorReporter", "(", "tag", ")", ";", "if", "(", "er", "==", "null", ")", "return", ";", "assert", "(", "pc", ...
This method get the current errors and write the formated output @param pc
[ "This", "method", "get", "the", "current", "errors", "and", "write", "the", "formated", "output" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/ErrorHandling.java#L287-L333
twitter/cloudhopper-commons
ch-commons-xbean/src/main/java/com/cloudhopper/commons/xbean/util/PropertiesReplacementUtil.java
PropertiesReplacementUtil.replaceProperties
static public InputStream replaceProperties(InputStream source, Properties props) throws IOException, SubstitutionException { return replaceProperties(source, props, "${", "}"); }
java
static public InputStream replaceProperties(InputStream source, Properties props) throws IOException, SubstitutionException { return replaceProperties(source, props, "${", "}"); }
[ "static", "public", "InputStream", "replaceProperties", "(", "InputStream", "source", ",", "Properties", "props", ")", "throws", "IOException", ",", "SubstitutionException", "{", "return", "replaceProperties", "(", "source", ",", "props", ",", "\"${\"", ",", "\"}\""...
Creates an InputStream containing the document resulting from replacing template parameters in the given InputStream source. @param source The source stream @param props The properties @return An InputStream containing the resulting document.
[ "Creates", "an", "InputStream", "containing", "the", "document", "resulting", "from", "replacing", "template", "parameters", "in", "the", "given", "InputStream", "source", "." ]
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-xbean/src/main/java/com/cloudhopper/commons/xbean/util/PropertiesReplacementUtil.java#L110-L112
rzwitserloot/lombok
src/core/lombok/javac/handlers/HandleGetter.java
HandleGetter.generateGetterForField
public void generateGetterForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level, boolean lazy, List<JCAnnotation> onMethod) { if (hasAnnotation(Getter.class, fieldNode)) { //The annotation will make it happen, so we can skip it. return; } createGetterForField(level, fieldNode, fieldNode, false, lazy, onMethod); }
java
public void generateGetterForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level, boolean lazy, List<JCAnnotation> onMethod) { if (hasAnnotation(Getter.class, fieldNode)) { //The annotation will make it happen, so we can skip it. return; } createGetterForField(level, fieldNode, fieldNode, false, lazy, onMethod); }
[ "public", "void", "generateGetterForField", "(", "JavacNode", "fieldNode", ",", "DiagnosticPosition", "pos", ",", "AccessLevel", "level", ",", "boolean", "lazy", ",", "List", "<", "JCAnnotation", ">", "onMethod", ")", "{", "if", "(", "hasAnnotation", "(", "Gette...
Generates a getter on the stated field. Used by {@link HandleData}. The difference between this call and the handle method is as follows: If there is a {@code lombok.Getter} annotation on the field, it is used and the same rules apply (e.g. warning if the method already exists, stated access level applies). If not, the getter is still generated if it isn't already there, though there will not be a warning if its already there. The default access level is used. @param fieldNode The node representing the field you want a getter for. @param pos The node responsible for generating the getter (the {@code @Data} or {@code @Getter} annotation).
[ "Generates", "a", "getter", "on", "the", "stated", "field", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/javac/handlers/HandleGetter.java#L122-L128
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.scheduleBlastFromBlast
public JsonResponse scheduleBlastFromBlast(Integer blastId, Date scheduleTime, Blast blast) throws IOException { blast.setCopyBlast(blastId); blast.setScheduleTime(scheduleTime); return apiPost(blast); }
java
public JsonResponse scheduleBlastFromBlast(Integer blastId, Date scheduleTime, Blast blast) throws IOException { blast.setCopyBlast(blastId); blast.setScheduleTime(scheduleTime); return apiPost(blast); }
[ "public", "JsonResponse", "scheduleBlastFromBlast", "(", "Integer", "blastId", ",", "Date", "scheduleTime", ",", "Blast", "blast", ")", "throws", "IOException", "{", "blast", ".", "setCopyBlast", "(", "blastId", ")", ";", "blast", ".", "setScheduleTime", "(", "s...
Schedule a mass mail blast from previous blast @param blastId blast ID @param scheduleTime schedule time for the blast @param blast Blast object @return JsonResponse @throws IOException
[ "Schedule", "a", "mass", "mail", "blast", "from", "previous", "blast" ]
train
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L210-L214
landawn/AbacusUtil
src/com/landawn/abacus/util/CouchbaseExecutor.java
CouchbaseExecutor.exists
@SafeVarargs public final boolean exists(final String query, final Object... parameters) { final QueryResult resultSet = execute(query, parameters); return resultSet.iterator().hasNext(); }
java
@SafeVarargs public final boolean exists(final String query, final Object... parameters) { final QueryResult resultSet = execute(query, parameters); return resultSet.iterator().hasNext(); }
[ "@", "SafeVarargs", "public", "final", "boolean", "exists", "(", "final", "String", "query", ",", "final", "Object", "...", "parameters", ")", "{", "final", "QueryResult", "resultSet", "=", "execute", "(", "query", ",", "parameters", ")", ";", "return", "res...
Always remember to set "<code>LIMIT 1</code>" in the sql statement for better performance. @param query @param parameters @return
[ "Always", "remember", "to", "set", "<code", ">", "LIMIT", "1<", "/", "code", ">", "in", "the", "sql", "statement", "for", "better", "performance", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/CouchbaseExecutor.java#L759-L764
wdullaer/MaterialDateTimePicker
library/src/main/java/com/wdullaer/materialdatetimepicker/date/TextViewWithCircularIndicator.java
TextViewWithCircularIndicator.createTextColor
private ColorStateList createTextColor(int accentColor, boolean darkMode) { int[][] states = new int[][]{ new int[]{android.R.attr.state_pressed}, // pressed new int[]{android.R.attr.state_selected}, // selected new int[]{} }; int[] colors = new int[]{ accentColor, Color.WHITE, darkMode ? Color.WHITE : Color.BLACK }; return new ColorStateList(states, colors); }
java
private ColorStateList createTextColor(int accentColor, boolean darkMode) { int[][] states = new int[][]{ new int[]{android.R.attr.state_pressed}, // pressed new int[]{android.R.attr.state_selected}, // selected new int[]{} }; int[] colors = new int[]{ accentColor, Color.WHITE, darkMode ? Color.WHITE : Color.BLACK }; return new ColorStateList(states, colors); }
[ "private", "ColorStateList", "createTextColor", "(", "int", "accentColor", ",", "boolean", "darkMode", ")", "{", "int", "[", "]", "[", "]", "states", "=", "new", "int", "[", "]", "[", "]", "{", "new", "int", "[", "]", "{", "android", ".", "R", ".", ...
Programmatically set the color state list (see mdtp_date_picker_year_selector) @param accentColor pressed state text color @param darkMode current theme mode @return ColorStateList with pressed state
[ "Programmatically", "set", "the", "color", "state", "list", "(", "see", "mdtp_date_picker_year_selector", ")" ]
train
https://github.com/wdullaer/MaterialDateTimePicker/blob/0a8fe28f19db4f5a5a6cfc525a852416232873a8/library/src/main/java/com/wdullaer/materialdatetimepicker/date/TextViewWithCircularIndicator.java#L76-L88
FedericoPecora/meta-csp-framework
src/main/java/org/metacsp/utility/UI/CurvedArrow.java
CurvedArrow.isNear
public boolean isNear(Point point, int fudge) { if (needsRefresh) refreshCurve(); try { if (bounds.contains(affineToText.inverseTransform(point, null))) return true; } catch (java.awt.geom.NoninvertibleTransformException e) { } catch (NullPointerException e) { System.err.println(e + " : " + bounds + " : " + affineToText); return false; } return intersects(point, fudge, curve); }
java
public boolean isNear(Point point, int fudge) { if (needsRefresh) refreshCurve(); try { if (bounds.contains(affineToText.inverseTransform(point, null))) return true; } catch (java.awt.geom.NoninvertibleTransformException e) { } catch (NullPointerException e) { System.err.println(e + " : " + bounds + " : " + affineToText); return false; } return intersects(point, fudge, curve); }
[ "public", "boolean", "isNear", "(", "Point", "point", ",", "int", "fudge", ")", "{", "if", "(", "needsRefresh", ")", "refreshCurve", "(", ")", ";", "try", "{", "if", "(", "bounds", ".", "contains", "(", "affineToText", ".", "inverseTransform", "(", "poin...
Determines if a point is on/near the curved arrow. @param point the point to check @param fudge the radius around the point that should be checked for the presence of the curve @return <TT>true</TT> if the point is on the curve within a certain fudge factor, <TT>false</TT> otherwise
[ "Determines", "if", "a", "point", "is", "on", "/", "near", "the", "curved", "arrow", "." ]
train
https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/utility/UI/CurvedArrow.java#L332-L345
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/BooleanField.java
BooleanField.getSQLType
public String getSQLType(boolean bIncludeLength, Map<String, Object> properties) { String strType = (String)properties.get(DBSQLTypes.BOOLEAN); if (strType == null) strType = DBSQLTypes.BYTE; // The default SQL Type (Byte) return strType; }
java
public String getSQLType(boolean bIncludeLength, Map<String, Object> properties) { String strType = (String)properties.get(DBSQLTypes.BOOLEAN); if (strType == null) strType = DBSQLTypes.BYTE; // The default SQL Type (Byte) return strType; }
[ "public", "String", "getSQLType", "(", "boolean", "bIncludeLength", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "String", "strType", "=", "(", "String", ")", "properties", ".", "get", "(", "DBSQLTypes", ".", "BOOLEAN", ")", ";", ...
Get the SQL type of this field. Typically BOOLEAN or BYTE. @param bIncludeLength Include the field length in this description. @param properties Database properties to determine the SQL type.
[ "Get", "the", "SQL", "type", "of", "this", "field", ".", "Typically", "BOOLEAN", "or", "BYTE", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/BooleanField.java#L167-L173
JoeKerouac/utils
src/main/java/com/joe/utils/collection/CollectionUtil.java
CollectionUtil.permutations
public static <T> void permutations(List<List<T>> result, List<T> args, int index) { if (index == args.size() - 2) { List<T> temp1 = new ArrayList<>(args.size()); temp1.addAll(args); Collections.swap(temp1, index, index + 1); result.add(temp1); List<T> temp2 = new ArrayList<>(args.size()); temp2.addAll(args); result.add(temp2); return; } permutations(result, args, index + 1); for (int i = index; i < args.size() - 1; i++) { List<T> temp = new ArrayList<>(args.size()); temp.addAll(args); Collections.swap(temp, index, i + 1); permutations(result, temp, index + 1); } }
java
public static <T> void permutations(List<List<T>> result, List<T> args, int index) { if (index == args.size() - 2) { List<T> temp1 = new ArrayList<>(args.size()); temp1.addAll(args); Collections.swap(temp1, index, index + 1); result.add(temp1); List<T> temp2 = new ArrayList<>(args.size()); temp2.addAll(args); result.add(temp2); return; } permutations(result, args, index + 1); for (int i = index; i < args.size() - 1; i++) { List<T> temp = new ArrayList<>(args.size()); temp.addAll(args); Collections.swap(temp, index, i + 1); permutations(result, temp, index + 1); } }
[ "public", "static", "<", "T", ">", "void", "permutations", "(", "List", "<", "List", "<", "T", ">", ">", "result", ",", "List", "<", "T", ">", "args", ",", "int", "index", ")", "{", "if", "(", "index", "==", "args", ".", "size", "(", ")", "-", ...
计算全排列 @param result 全排列结果集 @param args 要进行全排列的队列 @param index 全排列开始位置,例如如果index等于3则表示从下标3位置开始往后的所有数据进行全排列 @param <T> 要全排列的数据的类型
[ "计算全排列" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/collection/CollectionUtil.java#L440-L458
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-ui-parent/deeplearning4j-play/src/main/java/org/deeplearning4j/ui/api/UIServer.java
UIServer.getInstance
public static synchronized UIServer getInstance(boolean multiSession, Function<String, StatsStorage> statsStorageProvider) throws RuntimeException { if (uiServer == null || uiServer.isStopped()) { PlayUIServer playUIServer = new PlayUIServer(PlayUIServer.DEFAULT_UI_PORT, multiSession); playUIServer.setMultiSession(multiSession); if (statsStorageProvider != null) { playUIServer.autoAttachStatsStorageBySessionId(statsStorageProvider); } playUIServer.runMain(new String[] {}); uiServer = playUIServer; } else if (!uiServer.isStopped()) { if (multiSession && !uiServer.isMultiSession()) { throw new RuntimeException("Cannot return multi-session instance." + " UIServer has already started in single-session mode at " + uiServer.getAddress() + " You may stop the UI server instance, and start a new one."); } else if (!multiSession && uiServer.isMultiSession()) { throw new RuntimeException("Cannot return single-session instance." + " UIServer has already started in multi-session mode at " + uiServer.getAddress() + " You may stop the UI server instance, and start a new one."); } } return uiServer; }
java
public static synchronized UIServer getInstance(boolean multiSession, Function<String, StatsStorage> statsStorageProvider) throws RuntimeException { if (uiServer == null || uiServer.isStopped()) { PlayUIServer playUIServer = new PlayUIServer(PlayUIServer.DEFAULT_UI_PORT, multiSession); playUIServer.setMultiSession(multiSession); if (statsStorageProvider != null) { playUIServer.autoAttachStatsStorageBySessionId(statsStorageProvider); } playUIServer.runMain(new String[] {}); uiServer = playUIServer; } else if (!uiServer.isStopped()) { if (multiSession && !uiServer.isMultiSession()) { throw new RuntimeException("Cannot return multi-session instance." + " UIServer has already started in single-session mode at " + uiServer.getAddress() + " You may stop the UI server instance, and start a new one."); } else if (!multiSession && uiServer.isMultiSession()) { throw new RuntimeException("Cannot return single-session instance." + " UIServer has already started in multi-session mode at " + uiServer.getAddress() + " You may stop the UI server instance, and start a new one."); } } return uiServer; }
[ "public", "static", "synchronized", "UIServer", "getInstance", "(", "boolean", "multiSession", ",", "Function", "<", "String", ",", "StatsStorage", ">", "statsStorageProvider", ")", "throws", "RuntimeException", "{", "if", "(", "uiServer", "==", "null", "||", "uiS...
Get (and, initialize if necessary) the UI server. Singleton pattern - all calls to getInstance() will return the same UI instance. @param multiSession in multi-session mode, multiple training sessions can be visualized in separate browser tabs. <br/>URL path will include session ID as a parameter, i.e.: /train becomes /train/:sessionId @param statsStorageProvider function that returns a StatsStorage containing the given session ID. <br/>Use this to auto-attach StatsStorage if an unknown session ID is passed as URL path parameter in multi-session mode, or leave it {@code null}. @return UI instance for this JVM @throws RuntimeException if the instance has already started in a different mode (multi/single-session)
[ "Get", "(", "and", "initialize", "if", "necessary", ")", "the", "UI", "server", ".", "Singleton", "pattern", "-", "all", "calls", "to", "getInstance", "()", "will", "return", "the", "same", "UI", "instance", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-ui-parent/deeplearning4j-play/src/main/java/org/deeplearning4j/ui/api/UIServer.java#L59-L81
alkacon/opencms-core
src/org/opencms/publish/CmsPublishManager.java
CmsPublishManager.getPublishList
public CmsPublishList getPublishList( CmsObject cms, List<CmsResource> directPublishResources, boolean directPublishSiblings) throws CmsException { return getPublishList(cms, directPublishResources, directPublishSiblings, true); }
java
public CmsPublishList getPublishList( CmsObject cms, List<CmsResource> directPublishResources, boolean directPublishSiblings) throws CmsException { return getPublishList(cms, directPublishResources, directPublishSiblings, true); }
[ "public", "CmsPublishList", "getPublishList", "(", "CmsObject", "cms", ",", "List", "<", "CmsResource", ">", "directPublishResources", ",", "boolean", "directPublishSiblings", ")", "throws", "CmsException", "{", "return", "getPublishList", "(", "cms", ",", "directPubl...
Returns a publish list with all new/changed/deleted resources of the current (offline) project that actually get published for a direct publish of a List of resources.<p> @param cms the cms request context @param directPublishResources the resources which will be directly published @param directPublishSiblings <code>true</code>, if all eventual siblings of the direct published resources should also get published. @return a publish list @throws CmsException if something goes wrong
[ "Returns", "a", "publish", "list", "with", "all", "new", "/", "changed", "/", "deleted", "resources", "of", "the", "current", "(", "offline", ")", "project", "that", "actually", "get", "published", "for", "a", "direct", "publish", "of", "a", "List", "of", ...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/publish/CmsPublishManager.java#L328-L334
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/code/Printer.java
Printer.createStandardPrinter
public static Printer createStandardPrinter(final Messages messages) { return new Printer() { @Override protected String localize(Locale locale, String key, Object... args) { return messages.getLocalizedString(locale, key, args); } @Override protected String capturedVarId(CapturedType t, Locale locale) { return (t.hashCode() & 0xFFFFFFFFL) % PRIME + ""; }}; }
java
public static Printer createStandardPrinter(final Messages messages) { return new Printer() { @Override protected String localize(Locale locale, String key, Object... args) { return messages.getLocalizedString(locale, key, args); } @Override protected String capturedVarId(CapturedType t, Locale locale) { return (t.hashCode() & 0xFFFFFFFFL) % PRIME + ""; }}; }
[ "public", "static", "Printer", "createStandardPrinter", "(", "final", "Messages", "messages", ")", "{", "return", "new", "Printer", "(", ")", "{", "@", "Override", "protected", "String", "localize", "(", "Locale", "locale", ",", "String", "key", ",", "Object",...
Create a printer with default i18n support provided by Messages. By default, captured types ids are generated using hashcode. @param messages Messages class to be used for i18n @return printer visitor instance
[ "Create", "a", "printer", "with", "default", "i18n", "support", "provided", "by", "Messages", ".", "By", "default", "captured", "types", "ids", "are", "generated", "using", "hashcode", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Printer.java#L85-L96
Stratio/bdt
src/main/java/com/stratio/qa/specs/CommandExecutionSpec.java
CommandExecutionSpec.copyToRemoteFile
@Given("^I outbound copy '(.+?)' through a ssh connection to '(.+?)'$") public void copyToRemoteFile(String localPath, String remotePath) throws Exception { commonspec.getRemoteSSHConnection().copyTo(localPath, remotePath); }
java
@Given("^I outbound copy '(.+?)' through a ssh connection to '(.+?)'$") public void copyToRemoteFile(String localPath, String remotePath) throws Exception { commonspec.getRemoteSSHConnection().copyTo(localPath, remotePath); }
[ "@", "Given", "(", "\"^I outbound copy '(.+?)' through a ssh connection to '(.+?)'$\"", ")", "public", "void", "copyToRemoteFile", "(", "String", "localPath", ",", "String", "remotePath", ")", "throws", "Exception", "{", "commonspec", ".", "getRemoteSSHConnection", "(", "...
Copies file/s from local system to remote system @param remotePath path where file is going to be copy @param localPath path where file is located @throws Exception exception
[ "Copies", "file", "/", "s", "from", "local", "system", "to", "remote", "system" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommandExecutionSpec.java#L91-L94
UrielCh/ovh-java-sdk
ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java
ApiOvhIpLoadbalancing.serviceName_tcp_farm_POST
public OvhBackendTcp serviceName_tcp_farm_POST(String serviceName, OvhBalanceTCPEnum balance, String displayName, Long port, OvhBackendProbe probe, OvhStickinessTCPEnum stickiness, Long vrackNetworkId, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/tcp/farm"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "balance", balance); addBody(o, "displayName", displayName); addBody(o, "port", port); addBody(o, "probe", probe); addBody(o, "stickiness", stickiness); addBody(o, "vrackNetworkId", vrackNetworkId); addBody(o, "zone", zone); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhBackendTcp.class); }
java
public OvhBackendTcp serviceName_tcp_farm_POST(String serviceName, OvhBalanceTCPEnum balance, String displayName, Long port, OvhBackendProbe probe, OvhStickinessTCPEnum stickiness, Long vrackNetworkId, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/tcp/farm"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "balance", balance); addBody(o, "displayName", displayName); addBody(o, "port", port); addBody(o, "probe", probe); addBody(o, "stickiness", stickiness); addBody(o, "vrackNetworkId", vrackNetworkId); addBody(o, "zone", zone); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhBackendTcp.class); }
[ "public", "OvhBackendTcp", "serviceName_tcp_farm_POST", "(", "String", "serviceName", ",", "OvhBalanceTCPEnum", "balance", ",", "String", "displayName", ",", "Long", "port", ",", "OvhBackendProbe", "probe", ",", "OvhStickinessTCPEnum", "stickiness", ",", "Long", "vrackN...
Add a new TCP Farm on your IP Load Balancing REST: POST /ipLoadbalancing/{serviceName}/tcp/farm @param balance [required] Load balancing algorithm. 'roundrobin' if null @param zone [required] Zone of your farm @param stickiness [required] Stickiness type. No stickiness if null @param port [required] Port attached to your farm ([1..49151]). Inherited from frontend if null @param displayName [required] Human readable name for your backend, this field is for you @param vrackNetworkId [required] Internal Load Balancer identifier of the vRack private network to attach to your farm, mandatory when your Load Balancer is attached to a vRack @param probe [required] Probe used to determine if a backend is alive and can handle requests @param serviceName [required] The internal name of your IP load balancing
[ "Add", "a", "new", "TCP", "Farm", "on", "your", "IP", "Load", "Balancing" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L1547-L1560
threerings/nenya
core/src/main/java/com/threerings/geom/GeomUtil.java
GeomUtil.nearestToLine
public static Point nearestToLine (Point p1, Point p2, Point p3, Point n) { // see http://astronomy.swin.edu.au/~pbourke/geometry/pointline/ for a (not very good) // explanation of the math int Ax = p2.x - p1.x, Ay = p2.y - p1.y; float u = (p3.x - p1.x) * Ax + (p3.y - p1.y) * Ay; u /= (Ax * Ax + Ay * Ay); n.x = p1.x + Math.round(Ax * u); n.y = p1.y + Math.round(Ay * u); return n; }
java
public static Point nearestToLine (Point p1, Point p2, Point p3, Point n) { // see http://astronomy.swin.edu.au/~pbourke/geometry/pointline/ for a (not very good) // explanation of the math int Ax = p2.x - p1.x, Ay = p2.y - p1.y; float u = (p3.x - p1.x) * Ax + (p3.y - p1.y) * Ay; u /= (Ax * Ax + Ay * Ay); n.x = p1.x + Math.round(Ax * u); n.y = p1.y + Math.round(Ay * u); return n; }
[ "public", "static", "Point", "nearestToLine", "(", "Point", "p1", ",", "Point", "p2", ",", "Point", "p3", ",", "Point", "n", ")", "{", "// see http://astronomy.swin.edu.au/~pbourke/geometry/pointline/ for a (not very good)", "// explanation of the math", "int", "Ax", "=",...
Computes the point nearest to the specified point <code>p3</code> on the line defined by the two points <code>p1</code> and <code>p2</code>. The computed point is stored into <code>n</code>. <em>Note:</em> <code>p1</code> and <code>p2</code> must not be coincident. @param p1 one point on the line. @param p2 another point on the line (not equal to <code>p1</code>). @param p3 the point to which we wish to be most near. @param n the point on the line defined by <code>p1</code> and <code>p2</code> that is nearest to <code>p</code>. @return the point object supplied via <code>n</code>.
[ "Computes", "the", "point", "nearest", "to", "the", "specified", "point", "<code", ">", "p3<", "/", "code", ">", "on", "the", "line", "defined", "by", "the", "two", "points", "<code", ">", "p1<", "/", "code", ">", "and", "<code", ">", "p2<", "/", "co...
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/geom/GeomUtil.java#L91-L101
jcuda/jcuda
JCudaJava/src/main/java/jcuda/runtime/JCuda.java
JCuda.cudaArrayGetInfo
public static int cudaArrayGetInfo(cudaChannelFormatDesc desc, cudaExtent extent, int flags[], cudaArray array) { return checkResult(cudaArrayGetInfoNative(desc, extent, flags, array)); }
java
public static int cudaArrayGetInfo(cudaChannelFormatDesc desc, cudaExtent extent, int flags[], cudaArray array) { return checkResult(cudaArrayGetInfoNative(desc, extent, flags, array)); }
[ "public", "static", "int", "cudaArrayGetInfo", "(", "cudaChannelFormatDesc", "desc", ",", "cudaExtent", "extent", ",", "int", "flags", "[", "]", ",", "cudaArray", "array", ")", "{", "return", "checkResult", "(", "cudaArrayGetInfoNative", "(", "desc", ",", "exten...
Gets info about the specified cudaArray. <pre> cudaError_t cudaArrayGetInfo ( cudaChannelFormatDesc* desc, cudaExtent* extent, unsigned int* flags, cudaArray_t array ) </pre> <div> <p>Gets info about the specified cudaArray. Returns in <tt>*desc</tt>, <tt>*extent</tt> and <tt>*flags</tt> respectively, the type, shape and flags of <tt>array</tt>. </p> <p>Any of <tt>*desc</tt>, <tt>*extent</tt> and <tt>*flags</tt> may be specified as NULL. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param desc Returned array type @param extent Returned array shape. 2D arrays will have depth of zero @param flags Returned array flags @param array The cudaArray to get info for @return cudaSuccess, cudaErrorInvalidValue
[ "Gets", "info", "about", "the", "specified", "cudaArray", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/runtime/JCuda.java#L3562-L3565
Stratio/stratio-cassandra
src/java/org/apache/cassandra/tools/SSTableImport.java
SSTableImport.getKeyValidator
private AbstractType<?> getKeyValidator(ColumnFamily columnFamily) { // this is a fix to support backward compatibility // which allows to skip the current key validator // please, take a look onto CASSANDRA-7498 for more details if ("true".equals(System.getProperty("skip.key.validator", "false"))) { return BytesType.instance; } return columnFamily.metadata().getKeyValidator(); }
java
private AbstractType<?> getKeyValidator(ColumnFamily columnFamily) { // this is a fix to support backward compatibility // which allows to skip the current key validator // please, take a look onto CASSANDRA-7498 for more details if ("true".equals(System.getProperty("skip.key.validator", "false"))) { return BytesType.instance; } return columnFamily.metadata().getKeyValidator(); }
[ "private", "AbstractType", "<", "?", ">", "getKeyValidator", "(", "ColumnFamily", "columnFamily", ")", "{", "// this is a fix to support backward compatibility", "// which allows to skip the current key validator", "// please, take a look onto CASSANDRA-7498 for more details", "if", "(...
Get key validator for column family @param columnFamily column family instance @return key validator for given column family
[ "Get", "key", "validator", "for", "column", "family" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/tools/SSTableImport.java#L435-L443
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/WikipediaTemplateInfo.java
WikipediaTemplateInfo.revisionContainsTemplateName
public boolean revisionContainsTemplateName(int revId, String templateName) throws WikiApiException{ return revisionContainsTemplateNames(revId, Arrays.asList(new String[]{templateName})); }
java
public boolean revisionContainsTemplateName(int revId, String templateName) throws WikiApiException{ return revisionContainsTemplateNames(revId, Arrays.asList(new String[]{templateName})); }
[ "public", "boolean", "revisionContainsTemplateName", "(", "int", "revId", ",", "String", "templateName", ")", "throws", "WikiApiException", "{", "return", "revisionContainsTemplateNames", "(", "revId", ",", "Arrays", ".", "asList", "(", "new", "String", "[", "]", ...
Determines whether a given revision contains a given template name @param revId @param templateName a template name @return @throws WikiApiException
[ "Determines", "whether", "a", "given", "revision", "contains", "a", "given", "template", "name" ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/WikipediaTemplateInfo.java#L1253-L1255
yanzhenjie/AndServer
api/src/main/java/com/yanzhenjie/andserver/util/DigestUtils.java
DigestUtils.appendMd5DigestAsHex
public static StringBuilder appendMd5DigestAsHex(InputStream inputStream, StringBuilder builder) throws IOException { return appendDigestAsHex(MD5_ALGORITHM_NAME, inputStream, builder); }
java
public static StringBuilder appendMd5DigestAsHex(InputStream inputStream, StringBuilder builder) throws IOException { return appendDigestAsHex(MD5_ALGORITHM_NAME, inputStream, builder); }
[ "public", "static", "StringBuilder", "appendMd5DigestAsHex", "(", "InputStream", "inputStream", ",", "StringBuilder", "builder", ")", "throws", "IOException", "{", "return", "appendDigestAsHex", "(", "MD5_ALGORITHM_NAME", ",", "inputStream", ",", "builder", ")", ";", ...
Append a hexadecimal string representation of the MD5 digest of the given inputStream to the given {@link StringBuilder}. @param inputStream the inputStream to calculate the digest over. @param builder the string builder to append the digest to. @return the given string builder.
[ "Append", "a", "hexadecimal", "string", "representation", "of", "the", "MD5", "digest", "of", "the", "given", "inputStream", "to", "the", "given", "{", "@link", "StringBuilder", "}", "." ]
train
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/util/DigestUtils.java#L121-L124
neoremind/navi
navi/src/main/java/com/baidu/beidou/navi/server/callback/CallFuture.java
CallFuture.await
public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { if (!latch.await(timeout, unit)) { throw new TimeoutException(); } }
java
public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { if (!latch.await(timeout, unit)) { throw new TimeoutException(); } }
[ "public", "void", "await", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", ",", "TimeoutException", "{", "if", "(", "!", "latch", ".", "await", "(", "timeout", ",", "unit", ")", ")", "{", "throw", "new", "TimeoutExce...
Waits for the CallFuture to complete without returning the result. @param timeout the maximum time to wait. @param unit the time unit of the timeout argument. @throws InterruptedException if interrupted. @throws TimeoutException if the wait timed out.
[ "Waits", "for", "the", "CallFuture", "to", "complete", "without", "returning", "the", "result", "." ]
train
https://github.com/neoremind/navi/blob/d37e4b46ef07d124be2740ad3d85d87e939acc84/navi/src/main/java/com/baidu/beidou/navi/server/callback/CallFuture.java#L136-L140
devcon5io/common
mixin/src/main/java/io/devcon5/mixin/Mixin.java
Mixin.loadScript
private static void loadScript(ScriptEngine engine, Supplier<Reader> scriptReader) { try (Reader reader = scriptReader.get()) { engine.eval(reader); } catch (ScriptException | IOException e) { throw new RuntimeException(e); } }
java
private static void loadScript(ScriptEngine engine, Supplier<Reader> scriptReader) { try (Reader reader = scriptReader.get()) { engine.eval(reader); } catch (ScriptException | IOException e) { throw new RuntimeException(e); } }
[ "private", "static", "void", "loadScript", "(", "ScriptEngine", "engine", ",", "Supplier", "<", "Reader", ">", "scriptReader", ")", "{", "try", "(", "Reader", "reader", "=", "scriptReader", ".", "get", "(", ")", ")", "{", "engine", ".", "eval", "(", "rea...
Loads a single script from an URL into the script engine @param engine the engine that should evaluate the script @param scriptReader the script source to be loaded into the script
[ "Loads", "a", "single", "script", "from", "an", "URL", "into", "the", "script", "engine" ]
train
https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/mixin/src/main/java/io/devcon5/mixin/Mixin.java#L156-L164
intuit/QuickBooks-V3-Java-SDK
oauth2-platform-api/src/main/java/com/intuit/oauth2/client/OAuth2PlatformClient.java
OAuth2PlatformClient.refreshToken
public BearerTokenResponse refreshToken(String refreshToken) throws OAuthException { logger.debug("Enter OAuth2PlatformClient::refreshToken"); try { HttpRequestClient client = new HttpRequestClient(oauth2Config.getProxyConfig()); Request request = new Request.RequestBuilder(MethodType.POST, oauth2Config.getIntuitBearerTokenEndpoint()) .requiresAuthentication(true) .authString(getAuthHeader()) .postParams(getUrlParameters("refresh", refreshToken, null)) .build(); Response response = client.makeRequest(request); logger.debug("Response Code : "+ response.getStatusCode()); if (response.getStatusCode() != 200) { logger.debug("failed getting access token"); throw new OAuthException("failed getting access token", response.getStatusCode() + ""); } ObjectReader reader = mapper.readerFor(BearerTokenResponse.class); BearerTokenResponse bearerTokenResponse = reader.readValue(response.getContent()); return bearerTokenResponse; } catch (Exception ex) { logger.error("Exception while calling refreshToken ", ex); throw new OAuthException(ex.getMessage(), ex); } }
java
public BearerTokenResponse refreshToken(String refreshToken) throws OAuthException { logger.debug("Enter OAuth2PlatformClient::refreshToken"); try { HttpRequestClient client = new HttpRequestClient(oauth2Config.getProxyConfig()); Request request = new Request.RequestBuilder(MethodType.POST, oauth2Config.getIntuitBearerTokenEndpoint()) .requiresAuthentication(true) .authString(getAuthHeader()) .postParams(getUrlParameters("refresh", refreshToken, null)) .build(); Response response = client.makeRequest(request); logger.debug("Response Code : "+ response.getStatusCode()); if (response.getStatusCode() != 200) { logger.debug("failed getting access token"); throw new OAuthException("failed getting access token", response.getStatusCode() + ""); } ObjectReader reader = mapper.readerFor(BearerTokenResponse.class); BearerTokenResponse bearerTokenResponse = reader.readValue(response.getContent()); return bearerTokenResponse; } catch (Exception ex) { logger.error("Exception while calling refreshToken ", ex); throw new OAuthException(ex.getMessage(), ex); } }
[ "public", "BearerTokenResponse", "refreshToken", "(", "String", "refreshToken", ")", "throws", "OAuthException", "{", "logger", ".", "debug", "(", "\"Enter OAuth2PlatformClient::refreshToken\"", ")", ";", "try", "{", "HttpRequestClient", "client", "=", "new", "HttpReque...
Method to renew OAuth2 tokens by passing the refreshToken @param refreshToken @return @throws OAuthException
[ "Method", "to", "renew", "OAuth2", "tokens", "by", "passing", "the", "refreshToken" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/oauth2-platform-api/src/main/java/com/intuit/oauth2/client/OAuth2PlatformClient.java#L126-L152
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java
ScriptfileUtils.writeReader
private static void writeReader(final Reader reader, final FileWriter writer) throws IOException { writeReader(reader, writer, LineEndingStyle.LOCAL); }
java
private static void writeReader(final Reader reader, final FileWriter writer) throws IOException { writeReader(reader, writer, LineEndingStyle.LOCAL); }
[ "private", "static", "void", "writeReader", "(", "final", "Reader", "reader", ",", "final", "FileWriter", "writer", ")", "throws", "IOException", "{", "writeReader", "(", "reader", ",", "writer", ",", "LineEndingStyle", ".", "LOCAL", ")", ";", "}" ]
Copy from a Reader to a FileWriter @param reader reader @param writer writer @throws IOException if an error occurs
[ "Copy", "from", "a", "Reader", "to", "a", "FileWriter" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/execution/script/ScriptfileUtils.java#L128-L130
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/EnaValidator.java
EnaValidator.initWriters
protected void initWriters() throws IOException { String summarywriter = prefix == null ? "VAL_SUMMARY.txt" : prefix + "_" + "VAL_SUMMARY.txt"; String infowriter = prefix == null ? "VAL_INFO.txt" : prefix + "_" + "VAL_INFO.txt"; String errorwriter = prefix == null ? "VAL_ERROR.txt" : prefix + "_" + "VAL_ERROR.txt"; String reportswriter = prefix == null ? "VAL_REPORTS.txt" : prefix + "_" + "VAL_REPORTS.txt"; String fixwriter = prefix == null ? "VAL_FIXES.txt" : prefix + "_" + "VAL_FIXES.txt"; summaryWriter = new PrintWriter(summarywriter,"UTF-8"); infoWriter = new PrintWriter(infowriter,"UTF-8"); errorWriter = new PrintWriter(errorwriter,"UTF-8"); reportWriter = new PrintWriter(reportswriter,"UTF-8"); fixWriter = new PrintWriter(fixwriter,"UTF-8"); }
java
protected void initWriters() throws IOException { String summarywriter = prefix == null ? "VAL_SUMMARY.txt" : prefix + "_" + "VAL_SUMMARY.txt"; String infowriter = prefix == null ? "VAL_INFO.txt" : prefix + "_" + "VAL_INFO.txt"; String errorwriter = prefix == null ? "VAL_ERROR.txt" : prefix + "_" + "VAL_ERROR.txt"; String reportswriter = prefix == null ? "VAL_REPORTS.txt" : prefix + "_" + "VAL_REPORTS.txt"; String fixwriter = prefix == null ? "VAL_FIXES.txt" : prefix + "_" + "VAL_FIXES.txt"; summaryWriter = new PrintWriter(summarywriter,"UTF-8"); infoWriter = new PrintWriter(infowriter,"UTF-8"); errorWriter = new PrintWriter(errorwriter,"UTF-8"); reportWriter = new PrintWriter(reportswriter,"UTF-8"); fixWriter = new PrintWriter(fixwriter,"UTF-8"); }
[ "protected", "void", "initWriters", "(", ")", "throws", "IOException", "{", "String", "summarywriter", "=", "prefix", "==", "null", "?", "\"VAL_SUMMARY.txt\"", ":", "prefix", "+", "\"_\"", "+", "\"VAL_SUMMARY.txt\"", ";", "String", "infowriter", "=", "prefix", "...
separate method to instantiate so unit tests can call this @throws IOException
[ "separate", "method", "to", "instantiate", "so", "unit", "tests", "can", "call", "this" ]
train
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/EnaValidator.java#L472-L484
OpenLiberty/open-liberty
dev/com.ibm.ws.container.service/src/com/ibm/ws/container/service/metadata/MetaDataUtils.java
MetaDataUtils.copyModuleMetaDataSlot
public static boolean copyModuleMetaDataSlot(MetaDataEvent<ModuleMetaData> event, MetaDataSlot slot) { Container container = event.getContainer(); MetaData metaData = event.getMetaData(); try { // For now, we just need to copy from WebModuleInfo, and ClientModuleInfo // Supports EJB in WAR and ManagedBean in Client ExtendedModuleInfo moduleInfo = (ExtendedModuleInfo) container.adapt(NonPersistentCache.class).getFromCache(WebModuleInfo.class); if (moduleInfo == null) { moduleInfo = (ExtendedModuleInfo) container.adapt(NonPersistentCache.class).getFromCache(ClientModuleInfo.class); } if (moduleInfo != null) { ModuleMetaData primaryMetaData = moduleInfo.getMetaData(); if (metaData != primaryMetaData) { Object slotData = primaryMetaData.getMetaData(slot); if (slotData == null) { // The caller is required to populate slot data. throw new IllegalStateException(); } metaData.setMetaData(slot, slotData); return true; } } } catch (UnableToAdaptException e) { throw new UnsupportedOperationException(e); } return false; }
java
public static boolean copyModuleMetaDataSlot(MetaDataEvent<ModuleMetaData> event, MetaDataSlot slot) { Container container = event.getContainer(); MetaData metaData = event.getMetaData(); try { // For now, we just need to copy from WebModuleInfo, and ClientModuleInfo // Supports EJB in WAR and ManagedBean in Client ExtendedModuleInfo moduleInfo = (ExtendedModuleInfo) container.adapt(NonPersistentCache.class).getFromCache(WebModuleInfo.class); if (moduleInfo == null) { moduleInfo = (ExtendedModuleInfo) container.adapt(NonPersistentCache.class).getFromCache(ClientModuleInfo.class); } if (moduleInfo != null) { ModuleMetaData primaryMetaData = moduleInfo.getMetaData(); if (metaData != primaryMetaData) { Object slotData = primaryMetaData.getMetaData(slot); if (slotData == null) { // The caller is required to populate slot data. throw new IllegalStateException(); } metaData.setMetaData(slot, slotData); return true; } } } catch (UnableToAdaptException e) { throw new UnsupportedOperationException(e); } return false; }
[ "public", "static", "boolean", "copyModuleMetaDataSlot", "(", "MetaDataEvent", "<", "ModuleMetaData", ">", "event", ",", "MetaDataSlot", "slot", ")", "{", "Container", "container", "=", "event", ".", "getContainer", "(", ")", ";", "MetaData", "metaData", "=", "e...
Copy slot data from a primary module metadata to a nested module metadata. This is necessary for containers that want to share module-level data for all components in a module, because nested modules have their own distinct metadata. @param event event from {@link ModuleMetaDataListener#moduleMetaDataCreated} @param slot the slot to copy @return true if the data was copied, or false if this is the primary metadata and the caller must set the slot data @throws IllegalStateException if the primary metadata slot was not set
[ "Copy", "slot", "data", "from", "a", "primary", "module", "metadata", "to", "a", "nested", "module", "metadata", ".", "This", "is", "necessary", "for", "containers", "that", "want", "to", "share", "module", "-", "level", "data", "for", "all", "components", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.container.service/src/com/ibm/ws/container/service/metadata/MetaDataUtils.java#L36-L66
tractionsoftware/gwt-traction
src/main/java/com/tractionsoftware/gwt/user/client/ui/UTCDateTimeRangeController.java
UTCDateTimeRangeController.setCombinedValue
private void setCombinedValue(UTCDateBox date, UTCTimeBox time, long value, boolean setTimeValue) { date.setValue(datePartMillis(value), false); if (setTimeValue) { time.setValue(timePartMillis(value), false); } }
java
private void setCombinedValue(UTCDateBox date, UTCTimeBox time, long value, boolean setTimeValue) { date.setValue(datePartMillis(value), false); if (setTimeValue) { time.setValue(timePartMillis(value), false); } }
[ "private", "void", "setCombinedValue", "(", "UTCDateBox", "date", ",", "UTCTimeBox", "time", ",", "long", "value", ",", "boolean", "setTimeValue", ")", "{", "date", ".", "setValue", "(", "datePartMillis", "(", "value", ")", ",", "false", ")", ";", "if", "(...
This allows us to treat a datetime as a single value, making it easy for comparison and adjustment. We don't actually expose this because the timezone issues make it too confusing to clients. @param setTimeValue Sometimes we don't want to set the time value explicitly. Generally this is the case when we haven't specified a time.
[ "This", "allows", "us", "to", "treat", "a", "datetime", "as", "a", "single", "value", "making", "it", "easy", "for", "comparison", "and", "adjustment", ".", "We", "don", "t", "actually", "expose", "this", "because", "the", "timezone", "issues", "make", "it...
train
https://github.com/tractionsoftware/gwt-traction/blob/efc1423c619439763fb064b777b7235e9ce414a3/src/main/java/com/tractionsoftware/gwt/user/client/ui/UTCDateTimeRangeController.java#L234-L239
mojohaus/jaxb2-maven-plugin
src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java
DomHelper.getFieldLocation
public static FieldLocation getFieldLocation(final Node aNode, final Set<FieldLocation> fieldLocations) { FieldLocation toReturn = null; if (aNode != null) { if (CLASS_FIELD_METHOD_ELEMENT_NAMES.contains(aNode.getLocalName().toLowerCase())) { // This is a ComplexType which correspond to a Java class. toReturn = getFieldOrMethodLocationIfValid(aNode, getContainingClassOrNull(aNode), fieldLocations); } else if (ENUMERATION_FIELD_METHOD_ELEMENT_NAMES.contains(aNode.getLocalName().toLowerCase())) { // This is a SimpleType which correspond to a Java enum. toReturn = getFieldOrMethodLocationIfValid(aNode, getContainingClassOrNull(aNode), fieldLocations); } } // All done. return toReturn; }
java
public static FieldLocation getFieldLocation(final Node aNode, final Set<FieldLocation> fieldLocations) { FieldLocation toReturn = null; if (aNode != null) { if (CLASS_FIELD_METHOD_ELEMENT_NAMES.contains(aNode.getLocalName().toLowerCase())) { // This is a ComplexType which correspond to a Java class. toReturn = getFieldOrMethodLocationIfValid(aNode, getContainingClassOrNull(aNode), fieldLocations); } else if (ENUMERATION_FIELD_METHOD_ELEMENT_NAMES.contains(aNode.getLocalName().toLowerCase())) { // This is a SimpleType which correspond to a Java enum. toReturn = getFieldOrMethodLocationIfValid(aNode, getContainingClassOrNull(aNode), fieldLocations); } } // All done. return toReturn; }
[ "public", "static", "FieldLocation", "getFieldLocation", "(", "final", "Node", "aNode", ",", "final", "Set", "<", "FieldLocation", ">", "fieldLocations", ")", "{", "FieldLocation", "toReturn", "=", "null", ";", "if", "(", "aNode", "!=", "null", ")", "{", "if...
Retrieves a FieldLocation from the supplied Set, provided that the FieldLocation matches the supplied Node. @param aNode The non-null Node. @param fieldLocations The Set of known/found FieldLocation instances. @return The FieldLocation corresponding to the supplied DOM Node.
[ "Retrieves", "a", "FieldLocation", "from", "the", "supplied", "Set", "provided", "that", "the", "FieldLocation", "matches", "the", "supplied", "Node", "." ]
train
https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java#L281-L300
googleapis/google-http-java-client
google-http-client-xml/src/main/java/com/google/api/client/xml/XmlNamespaceDictionary.java
XmlNamespaceDictionary.getNamespaceUriForAliasHandlingUnknown
String getNamespaceUriForAliasHandlingUnknown(boolean errorOnUnknown, String alias) { String result = getUriForAlias(alias); if (result == null) { Preconditions.checkArgument( !errorOnUnknown, "unrecognized alias: %s", alias.length() == 0 ? "(default)" : alias); return "http://unknown/" + alias; } return result; }
java
String getNamespaceUriForAliasHandlingUnknown(boolean errorOnUnknown, String alias) { String result = getUriForAlias(alias); if (result == null) { Preconditions.checkArgument( !errorOnUnknown, "unrecognized alias: %s", alias.length() == 0 ? "(default)" : alias); return "http://unknown/" + alias; } return result; }
[ "String", "getNamespaceUriForAliasHandlingUnknown", "(", "boolean", "errorOnUnknown", ",", "String", "alias", ")", "{", "String", "result", "=", "getUriForAlias", "(", "alias", ")", ";", "if", "(", "result", "==", "null", ")", "{", "Preconditions", ".", "checkAr...
Returns the namespace URI to use for serialization for a given namespace alias, possibly using a predictable made-up namespace URI if the alias is not recognized. <p>Specifically, if the namespace alias is not recognized, the namespace URI returned will be {@code "http://unknown/"} plus the alias, unless {@code errorOnUnknown} is {@code true} in which case it will throw an {@link IllegalArgumentException}. @param errorOnUnknown whether to thrown an exception if the namespace alias is not recognized @param alias namespace alias @return namespace URI, using a predictable made-up namespace URI if the namespace alias is not recognized @throws IllegalArgumentException if the namespace alias is not recognized and {@code errorOnUnkown} is {@code true}
[ "Returns", "the", "namespace", "URI", "to", "use", "for", "serialization", "for", "a", "given", "namespace", "alias", "possibly", "using", "a", "predictable", "made", "-", "up", "namespace", "URI", "if", "the", "alias", "is", "not", "recognized", "." ]
train
https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client-xml/src/main/java/com/google/api/client/xml/XmlNamespaceDictionary.java#L288-L296
nikhaldi/android-view-selector
src/main/java/com/nikhaldimann/viewselector/attributes/ViewAttributes.java
ViewAttributes.callGetter
public static Object callGetter(View view, String methodName) { try { Method method = view.getClass().getMethod(methodName); return method.invoke(view); } catch (SecurityException ex) { throw new AttributeAccessException(ex); } catch (NoSuchMethodException ex) { throw new AttributeAccessException("No such attribute", ex); } catch (IllegalAccessException ex) { throw new AttributeAccessException(ex); } catch (InvocationTargetException ex) { throw new AttributeAccessException(ex); } }
java
public static Object callGetter(View view, String methodName) { try { Method method = view.getClass().getMethod(methodName); return method.invoke(view); } catch (SecurityException ex) { throw new AttributeAccessException(ex); } catch (NoSuchMethodException ex) { throw new AttributeAccessException("No such attribute", ex); } catch (IllegalAccessException ex) { throw new AttributeAccessException(ex); } catch (InvocationTargetException ex) { throw new AttributeAccessException(ex); } }
[ "public", "static", "Object", "callGetter", "(", "View", "view", ",", "String", "methodName", ")", "{", "try", "{", "Method", "method", "=", "view", ".", "getClass", "(", ")", ".", "getMethod", "(", "methodName", ")", ";", "return", "method", ".", "invok...
Calls the given method by name on the given view, assuming that it's a getter, i.e., it doesn't have arguments. @return the result of the method call @throws AttributeAccessException when the method doesn't exist or can't be called for various reasons
[ "Calls", "the", "given", "method", "by", "name", "on", "the", "given", "view", "assuming", "that", "it", "s", "a", "getter", "i", ".", "e", ".", "it", "doesn", "t", "have", "arguments", "." ]
train
https://github.com/nikhaldi/android-view-selector/blob/d3e4bf05f6111d116c6b0c1a8c51396e8bfae9b5/src/main/java/com/nikhaldimann/viewselector/attributes/ViewAttributes.java#L41-L54
prestodb/presto
presto-spi/src/main/java/com/facebook/presto/spi/type/MapType.java
MapType.createMapBlockInternal
public static Block createMapBlockInternal( TypeManager typeManager, Type keyType, int startOffset, int positionCount, Optional<boolean[]> mapIsNull, int[] offsets, Block keyBlock, Block valueBlock, HashTables hashTables) { // TypeManager caches types. Therefore, it is important that we go through it instead of coming up with the MethodHandles directly. // BIGINT is chosen arbitrarily here. Any type will do. MapType mapType = (MapType) typeManager.getType(new TypeSignature(StandardTypes.MAP, TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(BIGINT.getTypeSignature()))); return MapBlock.createMapBlockInternal(startOffset, positionCount, mapIsNull, offsets, keyBlock, valueBlock, hashTables, keyType, mapType.keyBlockNativeEquals, mapType.keyNativeHashCode, mapType.keyBlockHashCode); }
java
public static Block createMapBlockInternal( TypeManager typeManager, Type keyType, int startOffset, int positionCount, Optional<boolean[]> mapIsNull, int[] offsets, Block keyBlock, Block valueBlock, HashTables hashTables) { // TypeManager caches types. Therefore, it is important that we go through it instead of coming up with the MethodHandles directly. // BIGINT is chosen arbitrarily here. Any type will do. MapType mapType = (MapType) typeManager.getType(new TypeSignature(StandardTypes.MAP, TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(BIGINT.getTypeSignature()))); return MapBlock.createMapBlockInternal(startOffset, positionCount, mapIsNull, offsets, keyBlock, valueBlock, hashTables, keyType, mapType.keyBlockNativeEquals, mapType.keyNativeHashCode, mapType.keyBlockHashCode); }
[ "public", "static", "Block", "createMapBlockInternal", "(", "TypeManager", "typeManager", ",", "Type", "keyType", ",", "int", "startOffset", ",", "int", "positionCount", ",", "Optional", "<", "boolean", "[", "]", ">", "mapIsNull", ",", "int", "[", "]", "offset...
Create a map block directly without per element validations. <p> Internal use by com.facebook.presto.spi.Block only.
[ "Create", "a", "map", "block", "directly", "without", "per", "element", "validations", ".", "<p", ">", "Internal", "use", "by", "com", ".", "facebook", ".", "presto", ".", "spi", ".", "Block", "only", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-spi/src/main/java/com/facebook/presto/spi/type/MapType.java#L273-L288
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MedianOfWidestDimension.java
MedianOfWidestDimension.select
public int select(int attIdx, int[] indices, int left, int right, int k) { if (left == right) { return left; } else { int middle = partition(attIdx, indices, left, right); if ((middle - left + 1) >= k) { return select(attIdx, indices, left, middle, k); } else { return select(attIdx, indices, middle + 1, right, k - (middle - left + 1)); } } }
java
public int select(int attIdx, int[] indices, int left, int right, int k) { if (left == right) { return left; } else { int middle = partition(attIdx, indices, left, right); if ((middle - left + 1) >= k) { return select(attIdx, indices, left, middle, k); } else { return select(attIdx, indices, middle + 1, right, k - (middle - left + 1)); } } }
[ "public", "int", "select", "(", "int", "attIdx", ",", "int", "[", "]", "indices", ",", "int", "left", ",", "int", "right", ",", "int", "k", ")", "{", "if", "(", "left", "==", "right", ")", "{", "return", "left", ";", "}", "else", "{", "int", "m...
Implements computation of the kth-smallest element according to Manber's "Introduction to Algorithms". @param attIdx The dimension/attribute of the instances in which to find the kth-smallest element. @param indices The master index array containing indices of the instances. @param left The begining index of the portion of the master index array in which to find the kth-smallest element. @param right The end index of the portion of the master index array in which to find the kth-smallest element. @param k The value of k @return The index of the kth-smallest element
[ "Implements", "computation", "of", "the", "kth", "-", "smallest", "element", "according", "to", "Manber", "s", "Introduction", "to", "Algorithms", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MedianOfWidestDimension.java#L175-L187
Netflix/ribbon
ribbon-loadbalancer/src/main/java/com/netflix/client/ClientFactory.java
ClientFactory.getNamedClient
public static synchronized IClient getNamedClient(String name) { if (simpleClientMap.get(name) != null) { return simpleClientMap.get(name); } try { return registerClientFromProperties(name, getNamedConfig(name)); } catch (ClientException e) { throw new RuntimeException("Unable to create client", e); } }
java
public static synchronized IClient getNamedClient(String name) { if (simpleClientMap.get(name) != null) { return simpleClientMap.get(name); } try { return registerClientFromProperties(name, getNamedConfig(name)); } catch (ClientException e) { throw new RuntimeException("Unable to create client", e); } }
[ "public", "static", "synchronized", "IClient", "getNamedClient", "(", "String", "name", ")", "{", "if", "(", "simpleClientMap", ".", "get", "(", "name", ")", "!=", "null", ")", "{", "return", "simpleClientMap", ".", "get", "(", "name", ")", ";", "}", "tr...
Return the named client from map if already created. Otherwise creates the client using the configuration returned by {@link #getNamedConfig(String)}. @throws RuntimeException if an error occurs in creating the client.
[ "Return", "the", "named", "client", "from", "map", "if", "already", "created", ".", "Otherwise", "creates", "the", "client", "using", "the", "configuration", "returned", "by", "{", "@link", "#getNamedConfig", "(", "String", ")", "}", "." ]
train
https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-loadbalancer/src/main/java/com/netflix/client/ClientFactory.java#L95-L104
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringParser.java
StringParser.parseBool
public static boolean parseBool (@Nullable final String sStr, final boolean bDefault) { // Do we need to start thinking at all? if (sStr != null && sStr.length () > 0) { // Is it true? if (sStr.equalsIgnoreCase ("true")) return true; // Is it false? if (sStr.equalsIgnoreCase ("false")) return false; } // Neither true nor false return bDefault; }
java
public static boolean parseBool (@Nullable final String sStr, final boolean bDefault) { // Do we need to start thinking at all? if (sStr != null && sStr.length () > 0) { // Is it true? if (sStr.equalsIgnoreCase ("true")) return true; // Is it false? if (sStr.equalsIgnoreCase ("false")) return false; } // Neither true nor false return bDefault; }
[ "public", "static", "boolean", "parseBool", "(", "@", "Nullable", "final", "String", "sStr", ",", "final", "boolean", "bDefault", ")", "{", "// Do we need to start thinking at all?", "if", "(", "sStr", "!=", "null", "&&", "sStr", ".", "length", "(", ")", ">", ...
Parse the given {@link String} as boolean value. All values that are equal to "true" (ignoring case) will result in <code>true</code> return values. All values that are equal to "false" (ignoring case) will result in <code>false</code> return values. All other values will return the default. @param sStr The string to be interpreted. May be <code>null</code>. @param bDefault The default value to be returned if the passed string is neither "true" nor "false". @return <code>true</code> or <code>false</code> :)
[ "Parse", "the", "given", "{", "@link", "String", "}", "as", "boolean", "value", ".", "All", "values", "that", "are", "equal", "to", "true", "(", "ignoring", "case", ")", "will", "result", "in", "<code", ">", "true<", "/", "code", ">", "return", "values...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L132-L148
btaz/data-util
src/main/java/com/btaz/util/files/FileReducer.java
FileReducer.reduceItems
private static void reduceItems(FileOutputCollector collector, Reducer reducable, ArrayList<String> items) throws IOException { if(items != null) { // call reducer reducable.reduce(items, collector); } }
java
private static void reduceItems(FileOutputCollector collector, Reducer reducable, ArrayList<String> items) throws IOException { if(items != null) { // call reducer reducable.reduce(items, collector); } }
[ "private", "static", "void", "reduceItems", "(", "FileOutputCollector", "collector", ",", "Reducer", "reducable", ",", "ArrayList", "<", "String", ">", "items", ")", "throws", "IOException", "{", "if", "(", "items", "!=", "null", ")", "{", "// call reducer", "...
Call reducer @param writer writer @param reducable reducable callback @param items items @throws IOException IO exception
[ "Call", "reducer" ]
train
https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/files/FileReducer.java#L94-L100
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainTopicsInner.java
DomainTopicsInner.getAsync
public Observable<DomainTopicInner> getAsync(String resourceGroupName, String domainName, String topicName) { return getWithServiceResponseAsync(resourceGroupName, domainName, topicName).map(new Func1<ServiceResponse<DomainTopicInner>, DomainTopicInner>() { @Override public DomainTopicInner call(ServiceResponse<DomainTopicInner> response) { return response.body(); } }); }
java
public Observable<DomainTopicInner> getAsync(String resourceGroupName, String domainName, String topicName) { return getWithServiceResponseAsync(resourceGroupName, domainName, topicName).map(new Func1<ServiceResponse<DomainTopicInner>, DomainTopicInner>() { @Override public DomainTopicInner call(ServiceResponse<DomainTopicInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DomainTopicInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "domainName", ",", "String", "topicName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "domainName", ",", "topicNa...
Get a domain topic. Get properties of a domain topic. @param resourceGroupName The name of the resource group within the user's subscription. @param domainName Name of the domain @param topicName Name of the topic @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DomainTopicInner object
[ "Get", "a", "domain", "topic", ".", "Get", "properties", "of", "a", "domain", "topic", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainTopicsInner.java#L106-L113
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/HostName.java
HostName.asInetSocketAddress
public InetSocketAddress asInetSocketAddress(Function<String, Integer> serviceMapper) { if(isValid()) { Integer port = getPort(); if(port == null && serviceMapper != null) { String service = getService(); if(service != null) { port = serviceMapper.apply(service); } } if(port != null) { IPAddress ipAddr; if(isAddressString() && (ipAddr = asAddress()) != null) { return new InetSocketAddress(ipAddr.toInetAddress(), port); } else { return new InetSocketAddress(getHost(), port); } } } return null; }
java
public InetSocketAddress asInetSocketAddress(Function<String, Integer> serviceMapper) { if(isValid()) { Integer port = getPort(); if(port == null && serviceMapper != null) { String service = getService(); if(service != null) { port = serviceMapper.apply(service); } } if(port != null) { IPAddress ipAddr; if(isAddressString() && (ipAddr = asAddress()) != null) { return new InetSocketAddress(ipAddr.toInetAddress(), port); } else { return new InetSocketAddress(getHost(), port); } } } return null; }
[ "public", "InetSocketAddress", "asInetSocketAddress", "(", "Function", "<", "String", ",", "Integer", ">", "serviceMapper", ")", "{", "if", "(", "isValid", "(", ")", ")", "{", "Integer", "port", "=", "getPort", "(", ")", ";", "if", "(", "port", "==", "nu...
Returns the InetSocketAddress for this host. A host must have an associated port, or a service name string that is mapped to a port using the provided service mapper, to have a corresponding InetSocketAddress. <p> If there is on associated port, then this returns null. <p> Note that host name strings are not resolved when using this method. @param serviceMapper maps service name strings to ports. Returns null when a service string has no mapping, otherwise returns the port for a given service. You can use a project like netdb to provide a service mapper lambda, https://github.com/jnr/jnr-netdb @return the socket address, or null if no such address.
[ "Returns", "the", "InetSocketAddress", "for", "this", "host", ".", "A", "host", "must", "have", "an", "associated", "port", "or", "a", "service", "name", "string", "that", "is", "mapped", "to", "a", "port", "using", "the", "provided", "service", "mapper", ...
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/HostName.java#L822-L841
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/abst/fiducial/CalibrationFiducialDetector.java
CalibrationFiducialDetector.getCenter
@Override public void getCenter(int which, Point2D_F64 location) { CalibrationObservation view = detector.getDetectedPoints(); location.set(0,0); for (int i = 0; i < view.size(); i++) { PointIndex2D_F64 p = view.get(i); location.x += p.x; location.y += p.y; } location.x /= view.size(); location.y /= view.size(); }
java
@Override public void getCenter(int which, Point2D_F64 location) { CalibrationObservation view = detector.getDetectedPoints(); location.set(0,0); for (int i = 0; i < view.size(); i++) { PointIndex2D_F64 p = view.get(i); location.x += p.x; location.y += p.y; } location.x /= view.size(); location.y /= view.size(); }
[ "@", "Override", "public", "void", "getCenter", "(", "int", "which", ",", "Point2D_F64", "location", ")", "{", "CalibrationObservation", "view", "=", "detector", ".", "getDetectedPoints", "(", ")", ";", "location", ".", "set", "(", "0", ",", "0", ")", ";",...
Returns the detection point average location. This will NOT be the same as the geometric center. @param which Fiducial's index @param location (output) Storage for the transform. modified.
[ "Returns", "the", "detection", "point", "average", "location", ".", "This", "will", "NOT", "be", "the", "same", "as", "the", "geometric", "center", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/abst/fiducial/CalibrationFiducialDetector.java#L280-L293
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.deposit_depositId_GET
public OvhDeposit deposit_depositId_GET(String depositId) throws IOException { String qPath = "/me/deposit/{depositId}"; StringBuilder sb = path(qPath, depositId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDeposit.class); }
java
public OvhDeposit deposit_depositId_GET(String depositId) throws IOException { String qPath = "/me/deposit/{depositId}"; StringBuilder sb = path(qPath, depositId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDeposit.class); }
[ "public", "OvhDeposit", "deposit_depositId_GET", "(", "String", "depositId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/deposit/{depositId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "depositId", ")", ";", "String", "res...
Get this object properties REST: GET /me/deposit/{depositId} @param depositId [required]
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L3291-L3296
google/flogger
api/src/main/java/com/google/common/flogger/parser/MessageBuilder.java
MessageBuilder.addParameter
public final void addParameter(int termStart, int termEnd, Parameter param) { // Set a bit in the parameter mask according to which parameter was referenced. // Shifting wraps, so we must do a check here. if (param.getIndex() < 32) { pmask |= (1 << param.getIndex()); } maxIndex = Math.max(maxIndex, param.getIndex()); addParameterImpl(termStart, termEnd, param); }
java
public final void addParameter(int termStart, int termEnd, Parameter param) { // Set a bit in the parameter mask according to which parameter was referenced. // Shifting wraps, so we must do a check here. if (param.getIndex() < 32) { pmask |= (1 << param.getIndex()); } maxIndex = Math.max(maxIndex, param.getIndex()); addParameterImpl(termStart, termEnd, param); }
[ "public", "final", "void", "addParameter", "(", "int", "termStart", ",", "int", "termEnd", ",", "Parameter", "param", ")", "{", "// Set a bit in the parameter mask according to which parameter was referenced.", "// Shifting wraps, so we must do a check here.", "if", "(", "param...
Called by parser implementations to signify that the parsing of the next parameter is complete. This method will call {@link #addParameterImpl(int, int, Parameter)} with exactly the same arguments, but may also do additional work before or after that call. @param termStart the index of the first character in the log message string that was parsed to form the given parameter. @param termEnd the index after the last character in the log message string that was parsed to form the given parameter. @param param a parameter representing the format specified by the substring of the log message in the range {@code [termStart, termEnd)}.
[ "Called", "by", "parser", "implementations", "to", "signify", "that", "the", "parsing", "of", "the", "next", "parameter", "is", "complete", ".", "This", "method", "will", "call", "{", "@link", "#addParameterImpl", "(", "int", "int", "Parameter", ")", "}", "w...
train
https://github.com/google/flogger/blob/a164967a93a9f4ce92f34319fc0cc7c91a57321c/api/src/main/java/com/google/common/flogger/parser/MessageBuilder.java#L75-L83
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/compiler/JBBPCompiler.java
JBBPCompiler.assertName
private static void assertName(final String name, final JBBPToken token) { if (name.indexOf('.') >= 0) { throw new JBBPCompilationException("Detected disallowed char '.' in name [" + name + ']', token); } }
java
private static void assertName(final String name, final JBBPToken token) { if (name.indexOf('.') >= 0) { throw new JBBPCompilationException("Detected disallowed char '.' in name [" + name + ']', token); } }
[ "private", "static", "void", "assertName", "(", "final", "String", "name", ",", "final", "JBBPToken", "token", ")", "{", "if", "(", "name", ".", "indexOf", "(", "'", "'", ")", ">=", "0", ")", "{", "throw", "new", "JBBPCompilationException", "(", "\"Detec...
The Method check that a field name supports business rules. @param name the name to be checked @param token the token contains the name @throws JBBPCompilationException if the name doesn't support business rules
[ "The", "Method", "check", "that", "a", "field", "name", "supports", "business", "rules", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/compiler/JBBPCompiler.java#L495-L499
carewebframework/carewebframework-core
org.carewebframework.mvn-parent/org.carewebframework.mvn.plugin-parent/org.carewebframework.mvn.plugin.core/src/main/java/org/carewebframework/maven/plugin/core/ConfigTemplate.java
ConfigTemplate.addEntry
public void addEntry(String placeholder, String... params) { ConfigEntry entry = entries.get(placeholder); String line = entry.template; for (int i = 0; i < params.length; i++) { line = line.replace("{" + i + "}", StringUtils.defaultString(params[i])); } entry.buffer.add(line); }
java
public void addEntry(String placeholder, String... params) { ConfigEntry entry = entries.get(placeholder); String line = entry.template; for (int i = 0; i < params.length; i++) { line = line.replace("{" + i + "}", StringUtils.defaultString(params[i])); } entry.buffer.add(line); }
[ "public", "void", "addEntry", "(", "String", "placeholder", ",", "String", "...", "params", ")", "{", "ConfigEntry", "entry", "=", "entries", ".", "get", "(", "placeholder", ")", ";", "String", "line", "=", "entry", ".", "template", ";", "for", "(", "int...
Adds an entry to the config file. @param placeholder Placeholder identifying insertion point for entry. @param params Parameters to be applied to the template.
[ "Adds", "an", "entry", "to", "the", "config", "file", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.mvn-parent/org.carewebframework.mvn.plugin-parent/org.carewebframework.mvn.plugin.core/src/main/java/org/carewebframework/maven/plugin/core/ConfigTemplate.java#L110-L119
jwtk/jjwt
api/src/main/java/io/jsonwebtoken/lang/Collections.java
Collections.containsAny
public static boolean containsAny(Collection source, Collection candidates) { if (isEmpty(source) || isEmpty(candidates)) { return false; } for (Object candidate : candidates) { if (source.contains(candidate)) { return true; } } return false; }
java
public static boolean containsAny(Collection source, Collection candidates) { if (isEmpty(source) || isEmpty(candidates)) { return false; } for (Object candidate : candidates) { if (source.contains(candidate)) { return true; } } return false; }
[ "public", "static", "boolean", "containsAny", "(", "Collection", "source", ",", "Collection", "candidates", ")", "{", "if", "(", "isEmpty", "(", "source", ")", "||", "isEmpty", "(", "candidates", ")", ")", "{", "return", "false", ";", "}", "for", "(", "O...
Return <code>true</code> if any element in '<code>candidates</code>' is contained in '<code>source</code>'; otherwise returns <code>false</code>. @param source the source Collection @param candidates the candidates to search for @return whether any of the candidates has been found
[ "Return", "<code", ">", "true<", "/", "code", ">", "if", "any", "element", "in", "<code", ">", "candidates<", "/", "code", ">", "is", "contained", "in", "<code", ">", "source<", "/", "code", ">", ";", "otherwise", "returns", "<code", ">", "false<", "/"...
train
https://github.com/jwtk/jjwt/blob/86b6096946752cffcfbc9b0a5503f1ea195cc140/api/src/main/java/io/jsonwebtoken/lang/Collections.java#L191-L201
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java
CPDefinitionLinkPersistenceImpl.findByUUID_G
@Override public CPDefinitionLink findByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionLinkException { CPDefinitionLink cpDefinitionLink = fetchByUUID_G(uuid, groupId); if (cpDefinitionLink == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDefinitionLinkException(msg.toString()); } return cpDefinitionLink; }
java
@Override public CPDefinitionLink findByUUID_G(String uuid, long groupId) throws NoSuchCPDefinitionLinkException { CPDefinitionLink cpDefinitionLink = fetchByUUID_G(uuid, groupId); if (cpDefinitionLink == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("uuid="); msg.append(uuid); msg.append(", groupId="); msg.append(groupId); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPDefinitionLinkException(msg.toString()); } return cpDefinitionLink; }
[ "@", "Override", "public", "CPDefinitionLink", "findByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "throws", "NoSuchCPDefinitionLinkException", "{", "CPDefinitionLink", "cpDefinitionLink", "=", "fetchByUUID_G", "(", "uuid", ",", "groupId", ")", ";", ...
Returns the cp definition link where uuid = &#63; and groupId = &#63; or throws a {@link NoSuchCPDefinitionLinkException} if it could not be found. @param uuid the uuid @param groupId the group ID @return the matching cp definition link @throws NoSuchCPDefinitionLinkException if a matching cp definition link could not be found
[ "Returns", "the", "cp", "definition", "link", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchCPDefinitionLinkException", "}", "if", "it", "could", "not", "be", "found", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java#L666-L692
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/RobotiumUtils.java
RobotiumUtils.filterViewsByText
public static <T extends TextView> List<T> filterViewsByText(Iterable<T> views, String regex) { return filterViewsByText(views, Pattern.compile(regex)); }
java
public static <T extends TextView> List<T> filterViewsByText(Iterable<T> views, String regex) { return filterViewsByText(views, Pattern.compile(regex)); }
[ "public", "static", "<", "T", "extends", "TextView", ">", "List", "<", "T", ">", "filterViewsByText", "(", "Iterable", "<", "T", ">", "views", ",", "String", "regex", ")", "{", "return", "filterViewsByText", "(", "views", ",", "Pattern", ".", "compile", ...
Filters a collection of Views and returns a list that contains only Views with text that matches a specified regular expression. @param views The collection of views to scan @param regex The text pattern to search for @return A list of views whose text matches the given regex
[ "Filters", "a", "collection", "of", "Views", "and", "returns", "a", "list", "that", "contains", "only", "Views", "with", "text", "that", "matches", "a", "specified", "regular", "expression", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/RobotiumUtils.java#L158-L160
michael-rapp/AndroidBottomSheet
library/src/main/java/de/mrapp/android/bottomsheet/BottomSheet.java
BottomSheet.addItem
public final void addItem(final int id, @NonNull final CharSequence title) { Item item = new Item(id, title); adapter.add(item); adaptGridViewHeight(); }
java
public final void addItem(final int id, @NonNull final CharSequence title) { Item item = new Item(id, title); adapter.add(item); adaptGridViewHeight(); }
[ "public", "final", "void", "addItem", "(", "final", "int", "id", ",", "@", "NonNull", "final", "CharSequence", "title", ")", "{", "Item", "item", "=", "new", "Item", "(", "id", ",", "title", ")", ";", "adapter", ".", "add", "(", "item", ")", ";", "...
Adds a new item to the bottom sheet. @param id The id of the item, which should be added, as an {@link Integer} value. The id must be at least 0 @param title The title of the item, which should be added, as an instance of the type {@link CharSequence}. The title may neither be null, nor empty
[ "Adds", "a", "new", "item", "to", "the", "bottom", "sheet", "." ]
train
https://github.com/michael-rapp/AndroidBottomSheet/blob/6e4690ee9f63b14a7b143d3a3717b5f8a11ca503/library/src/main/java/de/mrapp/android/bottomsheet/BottomSheet.java#L1982-L1986