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
liyiorg/weixin-popular
src/main/java/weixin/popular/api/PayMchAPI.java
PayMchAPI.mmpaymkttransfersGethbinfo
public static GethbinfoResult mmpaymkttransfersGethbinfo(Gethbinfo gethbinfo,String key){ Map<String,String> map = MapUtil.objectToMap( gethbinfo); String sign = SignatureUtil.generateSign(map,gethbinfo.getSign_type(),key); gethbinfo.setSign(sign); String secapiPayRefundXML = XMLConverUtil.convertToXML( gethbinfo); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/mmpaymkttransfers/gethbinfo") .setEntity(new StringEntity(secapiPayRefundXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.keyStoreExecuteXmlResult(gethbinfo.getMch_id(),httpUriRequest,GethbinfoResult.class,gethbinfo.getSign_type(),key); }
java
public static GethbinfoResult mmpaymkttransfersGethbinfo(Gethbinfo gethbinfo,String key){ Map<String,String> map = MapUtil.objectToMap( gethbinfo); String sign = SignatureUtil.generateSign(map,gethbinfo.getSign_type(),key); gethbinfo.setSign(sign); String secapiPayRefundXML = XMLConverUtil.convertToXML( gethbinfo); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/mmpaymkttransfers/gethbinfo") .setEntity(new StringEntity(secapiPayRefundXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.keyStoreExecuteXmlResult(gethbinfo.getMch_id(),httpUriRequest,GethbinfoResult.class,gethbinfo.getSign_type(),key); }
[ "public", "static", "GethbinfoResult", "mmpaymkttransfersGethbinfo", "(", "Gethbinfo", "gethbinfo", ",", "String", "key", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "MapUtil", ".", "objectToMap", "(", "gethbinfo", ")", ";", "String", "sign...
查询红包记录 <br> 用于商户对已发放的红包进行查询红包的具体信息,可支持普通红包和裂变包。 @since 2.8.5 @param gethbinfo gethbinfo @param key key @return GethbinfoResult
[ "查询红包记录", "<br", ">", "用于商户对已发放的红包进行查询红包的具体信息,可支持普通红包和裂变包。" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/PayMchAPI.java#L543-L554
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/MultiColumnRelation.java
MultiColumnRelation.createNonInRelation
public static MultiColumnRelation createNonInRelation(List<ColumnIdentifier.Raw> entities, Operator relationType, Term.MultiColumnRaw valuesOrMarker) { assert relationType != Operator.IN; return new MultiColumnRelation(entities, relationType, valuesOrMarker, null, null); }
java
public static MultiColumnRelation createNonInRelation(List<ColumnIdentifier.Raw> entities, Operator relationType, Term.MultiColumnRaw valuesOrMarker) { assert relationType != Operator.IN; return new MultiColumnRelation(entities, relationType, valuesOrMarker, null, null); }
[ "public", "static", "MultiColumnRelation", "createNonInRelation", "(", "List", "<", "ColumnIdentifier", ".", "Raw", ">", "entities", ",", "Operator", "relationType", ",", "Term", ".", "MultiColumnRaw", "valuesOrMarker", ")", "{", "assert", "relationType", "!=", "Ope...
Creates a multi-column EQ, LT, LTE, GT, or GTE relation. For example: "SELECT ... WHERE (a, b) > (0, 1)" @param entities the columns on the LHS of the relation @param relationType the relation operator @param valuesOrMarker a Tuples.Literal instance or a Tuples.Raw marker
[ "Creates", "a", "multi", "-", "column", "EQ", "LT", "LTE", "GT", "or", "GTE", "relation", ".", "For", "example", ":", "SELECT", "...", "WHERE", "(", "a", "b", ")", ">", "(", "0", "1", ")" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/MultiColumnRelation.java#L59-L63
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Waiter.java
Waiter.waitForWebElement
public WebElement waitForWebElement(final By by, int minimumNumberOfMatches, int timeout, boolean scroll){ final long endTime = SystemClock.uptimeMillis() + timeout; while (true) { final boolean timedOut = SystemClock.uptimeMillis() > endTime; if (timedOut){ searcher.logMatchesFound(by.getValue()); return null; } sleeper.sleep(); WebElement webElementToReturn = searcher.searchForWebElement(by, minimumNumberOfMatches); if(webElementToReturn != null) return webElementToReturn; if(scroll) { scroller.scrollDown(); } } }
java
public WebElement waitForWebElement(final By by, int minimumNumberOfMatches, int timeout, boolean scroll){ final long endTime = SystemClock.uptimeMillis() + timeout; while (true) { final boolean timedOut = SystemClock.uptimeMillis() > endTime; if (timedOut){ searcher.logMatchesFound(by.getValue()); return null; } sleeper.sleep(); WebElement webElementToReturn = searcher.searchForWebElement(by, minimumNumberOfMatches); if(webElementToReturn != null) return webElementToReturn; if(scroll) { scroller.scrollDown(); } } }
[ "public", "WebElement", "waitForWebElement", "(", "final", "By", "by", ",", "int", "minimumNumberOfMatches", ",", "int", "timeout", ",", "boolean", "scroll", ")", "{", "final", "long", "endTime", "=", "SystemClock", ".", "uptimeMillis", "(", ")", "+", "timeout...
Waits for a web element. @param by the By object. Examples are By.id("id") and By.name("name") @param minimumNumberOfMatches the minimum number of matches that are expected to be shown. {@code 0} means any number of matches @param timeout the the amount of time in milliseconds to wait @param scroll {@code true} if scrolling should be performed
[ "Waits", "for", "a", "web", "element", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Waiter.java#L483-L505
alkacon/opencms-core
src-modules/org/opencms/workplace/tools/searchindex/CmsRebuildSearchIndexDialog.java
CmsRebuildSearchIndexDialog.createDialogHtml
@Override protected String createDialogHtml(String dialog) { StringBuffer result = new StringBuffer(512); result.append(createWidgetTableStart()); // show error header once if there were validation errors result.append(createWidgetErrorHeader()); if (dialog.equals(PAGES[0])) { // create the widgets for the first dialog page result.append(dialogBlockStart(key(Messages.GUI_LIST_SEARCHINDEX_ACTION_REBUILD_NAME_0))); result.append(createWidgetTableStart()); result.append(key( Messages.GUI_LIST_SEARCHINDEX_ACTION_REBUILD_NAME_CONF_1, new Object[] {getSearchIndexIndex().getName()})); result.append(createWidgetTableEnd()); result.append(dialogBlockEnd()); } result.append(createWidgetTableEnd()); // See CmsWidgetDialog.dialogButtonsCustom(): if no widgets are defined that are non-display-only widgets, // no dialog buttons (Ok, Cancel) will be visible.... result.append(dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[2])); return result.toString(); }
java
@Override protected String createDialogHtml(String dialog) { StringBuffer result = new StringBuffer(512); result.append(createWidgetTableStart()); // show error header once if there were validation errors result.append(createWidgetErrorHeader()); if (dialog.equals(PAGES[0])) { // create the widgets for the first dialog page result.append(dialogBlockStart(key(Messages.GUI_LIST_SEARCHINDEX_ACTION_REBUILD_NAME_0))); result.append(createWidgetTableStart()); result.append(key( Messages.GUI_LIST_SEARCHINDEX_ACTION_REBUILD_NAME_CONF_1, new Object[] {getSearchIndexIndex().getName()})); result.append(createWidgetTableEnd()); result.append(dialogBlockEnd()); } result.append(createWidgetTableEnd()); // See CmsWidgetDialog.dialogButtonsCustom(): if no widgets are defined that are non-display-only widgets, // no dialog buttons (Ok, Cancel) will be visible.... result.append(dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[2])); return result.toString(); }
[ "@", "Override", "protected", "String", "createDialogHtml", "(", "String", "dialog", ")", "{", "StringBuffer", "result", "=", "new", "StringBuffer", "(", "512", ")", ";", "result", ".", "append", "(", "createWidgetTableStart", "(", ")", ")", ";", "// show erro...
Creates the dialog HTML for all defined widgets of the named dialog (page).<p> This overwrites the method from the super class to create a layout variation for the widgets.<p> @param dialog the dialog (page) to get the HTML for @return the dialog HTML for all defined widgets of the named dialog (page)
[ "Creates", "the", "dialog", "HTML", "for", "all", "defined", "widgets", "of", "the", "named", "dialog", "(", "page", ")", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/searchindex/CmsRebuildSearchIndexDialog.java#L107-L133
canoo/dolphin-platform
platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/commons/lang/TypeUtils.java
TypeUtils.appendAllTo
private static <T> StringBuilder appendAllTo(final StringBuilder buf, final String sep, final T... types) { Assert.requireNonNullEntries(types, "types"); Assert.requireNotEmpty(types, "types"); if (types.length > 0) { buf.append(toString(types[0])); for (int i = 1; i < types.length; i++) { buf.append(sep).append(toString(types[i])); } } return buf; }
java
private static <T> StringBuilder appendAllTo(final StringBuilder buf, final String sep, final T... types) { Assert.requireNonNullEntries(types, "types"); Assert.requireNotEmpty(types, "types"); if (types.length > 0) { buf.append(toString(types[0])); for (int i = 1; i < types.length; i++) { buf.append(sep).append(toString(types[i])); } } return buf; }
[ "private", "static", "<", "T", ">", "StringBuilder", "appendAllTo", "(", "final", "StringBuilder", "buf", ",", "final", "String", "sep", ",", "final", "T", "...", "types", ")", "{", "Assert", ".", "requireNonNullEntries", "(", "types", ",", "\"types\"", ")",...
Append {@code types} to {@code buf} with separator {@code sep}. @param buf destination @param sep separator @param types to append @return {@code buf} @since 3.2
[ "Append", "{", "@code", "types", "}", "to", "{", "@code", "buf", "}", "with", "separator", "{", "@code", "sep", "}", "." ]
train
https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/commons/lang/TypeUtils.java#L1401-L1411
aol/cyclops
cyclops/src/main/java/com/oath/cyclops/internal/stream/FutureStreamUtils.java
FutureStreamUtils.forEachEvent
public static <T, X extends Throwable> Tuple3<CompletableFuture<Subscription>, Runnable, CompletableFuture<Boolean>> forEachEvent( final Stream<T> stream, final Consumer<? super T> consumerElement, final Consumer<? super Throwable> consumerError, final Runnable onComplete) { final CompletableFuture<Subscription> subscription = new CompletableFuture<>(); final CompletableFuture<Boolean> streamCompleted = new CompletableFuture<>(); return tuple(subscription, () -> { final Iterator<T> it = stream.iterator(); final Object UNSET = new Object(); Streams.stream(new Iterator<T>() { boolean errored = false; @Override public boolean hasNext() { boolean result = false; try { result = it.hasNext(); return result; } catch (final Throwable t) { consumerError.accept(t); errored = true; return true; } finally { if (!result && !errored) { try { onComplete.run(); } finally { streamCompleted.complete(true); } } } } @Override public T next() { try { if (errored) return (T) UNSET; else { try { return it.next(); }catch(Throwable t){ consumerError.accept(t); return (T) UNSET; } } } finally { errored = false; } } }) .filter(t -> t != UNSET) .forEach(consumerElement); } , streamCompleted); }
java
public static <T, X extends Throwable> Tuple3<CompletableFuture<Subscription>, Runnable, CompletableFuture<Boolean>> forEachEvent( final Stream<T> stream, final Consumer<? super T> consumerElement, final Consumer<? super Throwable> consumerError, final Runnable onComplete) { final CompletableFuture<Subscription> subscription = new CompletableFuture<>(); final CompletableFuture<Boolean> streamCompleted = new CompletableFuture<>(); return tuple(subscription, () -> { final Iterator<T> it = stream.iterator(); final Object UNSET = new Object(); Streams.stream(new Iterator<T>() { boolean errored = false; @Override public boolean hasNext() { boolean result = false; try { result = it.hasNext(); return result; } catch (final Throwable t) { consumerError.accept(t); errored = true; return true; } finally { if (!result && !errored) { try { onComplete.run(); } finally { streamCompleted.complete(true); } } } } @Override public T next() { try { if (errored) return (T) UNSET; else { try { return it.next(); }catch(Throwable t){ consumerError.accept(t); return (T) UNSET; } } } finally { errored = false; } } }) .filter(t -> t != UNSET) .forEach(consumerElement); } , streamCompleted); }
[ "public", "static", "<", "T", ",", "X", "extends", "Throwable", ">", "Tuple3", "<", "CompletableFuture", "<", "Subscription", ">", ",", "Runnable", ",", "CompletableFuture", "<", "Boolean", ">", ">", "forEachEvent", "(", "final", "Stream", "<", "T", ">", "...
Perform a forEach operation over the Stream capturing any elements and errors in the supplied consumers when the entire Stream has been processed an onComplete event will be recieved. <pre> {@code Subscription next = Streams.forEachEvents(Stream.of(()->1,()->2,()->throw new RuntimeException(),()->4) .map(Supplier::getValue),System.out::println, e->e.printStackTrace(),()->System.out.println("the take!")); System.out.println("processed!"); //prints 1 2 RuntimeException Stack Trace on System.err 4 processed! } </pre> @param stream - the Stream to consume data from @param consumerElement To accept incoming elements from the Stream @param consumerError To accept incoming processing errors from the Stream @param onComplete To run after an onComplete event @return A Tuple containing a Future with a Subscription to this publisher, a runnable to skip processing on a separate thread, and future that stores true / false depending on success
[ "Perform", "a", "forEach", "operation", "over", "the", "Stream", "capturing", "any", "elements", "and", "errors", "in", "the", "supplied", "consumers", "when", "the", "entire", "Stream", "has", "been", "processed", "an", "onComplete", "event", "will", "be", "r...
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/com/oath/cyclops/internal/stream/FutureStreamUtils.java#L233-L291
apache/reef
lang/java/reef-tang/tang/src/main/java/org/apache/reef/tang/util/walk/graphviz/GraphvizConfigVisitor.java
GraphvizConfigVisitor.getGraphvizString
public static String getGraphvizString(final Configuration config, final boolean showImpl, final boolean showLegend) { final GraphvizConfigVisitor visitor = new GraphvizConfigVisitor(config, showImpl, showLegend); final Node root = config.getClassHierarchy().getNamespace(); Walk.preorder(visitor, visitor, root); return visitor.toString(); }
java
public static String getGraphvizString(final Configuration config, final boolean showImpl, final boolean showLegend) { final GraphvizConfigVisitor visitor = new GraphvizConfigVisitor(config, showImpl, showLegend); final Node root = config.getClassHierarchy().getNamespace(); Walk.preorder(visitor, visitor, root); return visitor.toString(); }
[ "public", "static", "String", "getGraphvizString", "(", "final", "Configuration", "config", ",", "final", "boolean", "showImpl", ",", "final", "boolean", "showLegend", ")", "{", "final", "GraphvizConfigVisitor", "visitor", "=", "new", "GraphvizConfigVisitor", "(", "...
Produce a Graphviz DOT string for a given TANG configuration. @param config TANG configuration object. @param showImpl If true, plot IS-A edges for know implementations. @param showLegend If true, add legend to the plot. @return configuration graph represented as a string in Graphviz DOT format.
[ "Produce", "a", "Graphviz", "DOT", "string", "for", "a", "given", "TANG", "configuration", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-tang/tang/src/main/java/org/apache/reef/tang/util/walk/graphviz/GraphvizConfigVisitor.java#L105-L111
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/input/category/CmsDataValue.java
CmsDataValue.matchesFilter
public boolean matchesFilter(String filter, int param) { filter = filter.toLowerCase(); return m_parameters[param].toLowerCase().contains(filter); }
java
public boolean matchesFilter(String filter, int param) { filter = filter.toLowerCase(); return m_parameters[param].toLowerCase().contains(filter); }
[ "public", "boolean", "matchesFilter", "(", "String", "filter", ",", "int", "param", ")", "{", "filter", "=", "filter", ".", "toLowerCase", "(", ")", ";", "return", "m_parameters", "[", "param", "]", ".", "toLowerCase", "(", ")", ".", "contains", "(", "fi...
Returns if the category matches the given filter.<p> @param filter the filter to match @param param the search value @return <code>true</code> if the gallery matches the given filter.<p>
[ "Returns", "if", "the", "category", "matches", "the", "given", "filter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/category/CmsDataValue.java#L243-L247
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java
TableCellStyleBuilder.borderTop
public TableCellStyleBuilder borderTop(final Length size, final Color borderColor, final BorderAttribute.Style style) { final BorderAttribute bs = new BorderAttribute(size, borderColor, style); this.bordersBuilder.top(bs); return this; }
java
public TableCellStyleBuilder borderTop(final Length size, final Color borderColor, final BorderAttribute.Style style) { final BorderAttribute bs = new BorderAttribute(size, borderColor, style); this.bordersBuilder.top(bs); return this; }
[ "public", "TableCellStyleBuilder", "borderTop", "(", "final", "Length", "size", ",", "final", "Color", "borderColor", ",", "final", "BorderAttribute", ".", "Style", "style", ")", "{", "final", "BorderAttribute", "bs", "=", "new", "BorderAttribute", "(", "size", ...
Add a border style for the top border of this cell. @param size the size of the line @param borderColor the color to be used in format #rrggbb e.g. '#ff0000' for a red border @param style the style of the border line, either BorderAttribute.BORDER_SOLID or BorderAttribute.BORDER_DOUBLE @return this for fluent style
[ "Add", "a", "border", "style", "for", "the", "top", "border", "of", "this", "cell", "." ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/style/TableCellStyleBuilder.java#L158-L163
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java
CommonOps_DDF2.addEquals
public static void addEquals( DMatrix2x2 a , DMatrix2x2 b ) { a.a11 += b.a11; a.a12 += b.a12; a.a21 += b.a21; a.a22 += b.a22; }
java
public static void addEquals( DMatrix2x2 a , DMatrix2x2 b ) { a.a11 += b.a11; a.a12 += b.a12; a.a21 += b.a21; a.a22 += b.a22; }
[ "public", "static", "void", "addEquals", "(", "DMatrix2x2", "a", ",", "DMatrix2x2", "b", ")", "{", "a", ".", "a11", "+=", "b", ".", "a11", ";", "a", ".", "a12", "+=", "b", ".", "a12", ";", "a", ".", "a21", "+=", "b", ".", "a21", ";", "a", "."...
<p>Performs the following operation:<br> <br> a = a + b <br> a<sub>ij</sub> = a<sub>ij</sub> + b<sub>ij</sub> <br> </p> @param a A Matrix. Modified. @param b A Matrix. Not modified.
[ "<p", ">", "Performs", "the", "following", "operation", ":", "<br", ">", "<br", ">", "a", "=", "a", "+", "b", "<br", ">", "a<sub", ">", "ij<", "/", "sub", ">", "=", "a<sub", ">", "ij<", "/", "sub", ">", "+", "b<sub", ">", "ij<", "/", "sub", "...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF2.java#L84-L89
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Collectors.java
Collectors.averagingInt
@NotNull public static <T> Collector<T, ?, Double> averagingInt(@NotNull final ToIntFunction<? super T> mapper) { return averagingHelper(new BiConsumer<long[], T>() { @Override public void accept(long[] t, T u) { t[0]++; // count t[1] += mapper.applyAsInt(u); // sum } }); }
java
@NotNull public static <T> Collector<T, ?, Double> averagingInt(@NotNull final ToIntFunction<? super T> mapper) { return averagingHelper(new BiConsumer<long[], T>() { @Override public void accept(long[] t, T u) { t[0]++; // count t[1] += mapper.applyAsInt(u); // sum } }); }
[ "@", "NotNull", "public", "static", "<", "T", ">", "Collector", "<", "T", ",", "?", ",", "Double", ">", "averagingInt", "(", "@", "NotNull", "final", "ToIntFunction", "<", "?", "super", "T", ">", "mapper", ")", "{", "return", "averagingHelper", "(", "n...
Returns a {@code Collector} that calculates average of integer-valued input elements. @param <T> the type of the input elements @param mapper the mapping function which extracts value from element to calculate result @return a {@code Collector} @since 1.1.3
[ "Returns", "a", "{", "@code", "Collector", "}", "that", "calculates", "average", "of", "integer", "-", "valued", "input", "elements", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L487-L496
samskivert/samskivert
src/main/java/com/samskivert/swing/util/SwingUtil.java
SwingUtil.setFrameIcons
public static void setFrameIcons (Frame frame, List<? extends Image> icons) { try { Method m = frame.getClass().getMethod("setIconImages", List.class); m.invoke(frame, icons); return; } catch (SecurityException e) { // Fine, fine, no reflection for us } catch (NoSuchMethodException e) { // This is fine, we must be on a pre-1.6 JVM } catch (Exception e) { // Something else went awry? Log it log.warning("Error setting frame icons", "frame", frame, "icons", icons, "e", e); } // We couldn't find it, couldn't reflect, or something. // Just use whichever's at the top of the list frame.setIconImage(icons.get(0)); }
java
public static void setFrameIcons (Frame frame, List<? extends Image> icons) { try { Method m = frame.getClass().getMethod("setIconImages", List.class); m.invoke(frame, icons); return; } catch (SecurityException e) { // Fine, fine, no reflection for us } catch (NoSuchMethodException e) { // This is fine, we must be on a pre-1.6 JVM } catch (Exception e) { // Something else went awry? Log it log.warning("Error setting frame icons", "frame", frame, "icons", icons, "e", e); } // We couldn't find it, couldn't reflect, or something. // Just use whichever's at the top of the list frame.setIconImage(icons.get(0)); }
[ "public", "static", "void", "setFrameIcons", "(", "Frame", "frame", ",", "List", "<", "?", "extends", "Image", ">", "icons", ")", "{", "try", "{", "Method", "m", "=", "frame", ".", "getClass", "(", ")", ".", "getMethod", "(", "\"setIconImages\"", ",", ...
Sets the frame's icons. Unfortunately, the ability to pass multiple icons so the OS can choose the most size-appropriate one was added in 1.6; before that, you can only set one icon. This method attempts to find and use setIconImages, but if it can't, sets the frame's icon to the first image in the list passed in.
[ "Sets", "the", "frame", "s", "icons", ".", "Unfortunately", "the", "ability", "to", "pass", "multiple", "icons", "so", "the", "OS", "can", "choose", "the", "most", "size", "-", "appropriate", "one", "was", "added", "in", "1", ".", "6", ";", "before", "...
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/util/SwingUtil.java#L576-L594
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/index/service/TokenMapperGenericSorter.java
TokenMapperGenericSorter.compareValues
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public int compareValues(BytesRef val1, BytesRef val2) { if (val1 == null) { if (val2 == null) { return 0; } return -1; } else if (val2 == null) { return 1; } Token t1 = tokenMapperGeneric.token(val1); Token t2 = tokenMapperGeneric.token(val2); return t1.compareTo(t2); }
java
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public int compareValues(BytesRef val1, BytesRef val2) { if (val1 == null) { if (val2 == null) { return 0; } return -1; } else if (val2 == null) { return 1; } Token t1 = tokenMapperGeneric.token(val1); Token t2 = tokenMapperGeneric.token(val2); return t1.compareTo(t2); }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "@", "Override", "public", "int", "compareValues", "(", "BytesRef", "val1", ",", "BytesRef", "val2", ")", "{", "if", "(", "val1", "==", "null", ")", "{", "if", "(", "val2"...
Compares its two field value arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. @param val1 The first field value to be compared. @param val2 The second field value to be compared. @return A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
[ "Compares", "its", "two", "field", "value", "arguments", "for", "order", ".", "Returns", "a", "negative", "integer", "zero", "or", "a", "positive", "integer", "as", "the", "first", "argument", "is", "less", "than", "equal", "to", "or", "greater", "than", "...
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/TokenMapperGenericSorter.java#L53-L67
code4everything/util
src/main/java/com/zhazhapan/util/FileExecutor.java
FileExecutor.mergeFiles
public static void mergeFiles(File[] files, File destinationFile, String filterRegex) throws IOException { createNewFile(destinationFile); for (File file : files) { mergeFiles(file, destinationFile, filterRegex); } }
java
public static void mergeFiles(File[] files, File destinationFile, String filterRegex) throws IOException { createNewFile(destinationFile); for (File file : files) { mergeFiles(file, destinationFile, filterRegex); } }
[ "public", "static", "void", "mergeFiles", "(", "File", "[", "]", "files", ",", "File", "destinationFile", ",", "String", "filterRegex", ")", "throws", "IOException", "{", "createNewFile", "(", "destinationFile", ")", ";", "for", "(", "File", "file", ":", "fi...
合并文件 @param files 文件数组 @param destinationFile 目标文件 @param filterRegex 过滤规则(正则表达式,所有文件使用同一个过滤规则,为空时不过滤) @throws IOException 异常
[ "合并文件" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/FileExecutor.java#L690-L695
alibaba/Tangram-Android
tangram/src/main/java/com/tmall/wireless/tangram3/view/LinearScrollView.java
LinearScrollView.setIndicatorMeasure
private void setIndicatorMeasure(View indicator, int width, int height, int margin) { if (indicator != null) { ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams(); layoutParams.width = width; layoutParams.height = height; if (margin > 0) { if (layoutParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams frameLayoutParams = (FrameLayout.LayoutParams) layoutParams; frameLayoutParams.topMargin = margin; } else if (layoutParams instanceof LayoutParams) { LayoutParams linearLayoutParams = (LayoutParams) layoutParams; linearLayoutParams.topMargin = margin; } } indicator.setLayoutParams(layoutParams); } }
java
private void setIndicatorMeasure(View indicator, int width, int height, int margin) { if (indicator != null) { ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams(); layoutParams.width = width; layoutParams.height = height; if (margin > 0) { if (layoutParams instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams frameLayoutParams = (FrameLayout.LayoutParams) layoutParams; frameLayoutParams.topMargin = margin; } else if (layoutParams instanceof LayoutParams) { LayoutParams linearLayoutParams = (LayoutParams) layoutParams; linearLayoutParams.topMargin = margin; } } indicator.setLayoutParams(layoutParams); } }
[ "private", "void", "setIndicatorMeasure", "(", "View", "indicator", ",", "int", "width", ",", "int", "height", ",", "int", "margin", ")", "{", "if", "(", "indicator", "!=", "null", ")", "{", "ViewGroup", ".", "LayoutParams", "layoutParams", "=", "indicator",...
Set indicator measure @param indicator indicator view @param width indicator width @param height indicator height @param margin indicator top margin
[ "Set", "indicator", "measure" ]
train
https://github.com/alibaba/Tangram-Android/blob/caa57f54e009c8dacd34a2322d5761956ebed321/tangram/src/main/java/com/tmall/wireless/tangram3/view/LinearScrollView.java#L283-L300
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java
LinuxFile.mmap
public ByteBuffer mmap(int length, MMAPProt prot, MMAPFlags flags, int offset) throws IOException { long pointer = mmap(getFileDescriptor(), length, prot.flag, flags.flag, offset); if(pointer == -1) throw new LinuxFileException(); return newMappedByteBuffer(length, pointer, () -> { munmapDirect(pointer, length); }); }
java
public ByteBuffer mmap(int length, MMAPProt prot, MMAPFlags flags, int offset) throws IOException { long pointer = mmap(getFileDescriptor(), length, prot.flag, flags.flag, offset); if(pointer == -1) throw new LinuxFileException(); return newMappedByteBuffer(length, pointer, () -> { munmapDirect(pointer, length); }); }
[ "public", "ByteBuffer", "mmap", "(", "int", "length", ",", "MMAPProt", "prot", ",", "MMAPFlags", "flags", ",", "int", "offset", ")", "throws", "IOException", "{", "long", "pointer", "=", "mmap", "(", "getFileDescriptor", "(", ")", ",", "length", ",", "prot...
Direct memory mapping from a file descriptor. This is normally possible through the local FileChannel, but NIO will try to truncate files if they don't report a correct size. This will avoid that. @param length length of desired mapping @param prot protocol used for mapping @param flags flags for mapping @param offset offset in file for mapping @return direct mapped ByteBuffer @throws IOException
[ "Direct", "memory", "mapping", "from", "a", "file", "descriptor", ".", "This", "is", "normally", "possible", "through", "the", "local", "FileChannel", "but", "NIO", "will", "try", "to", "truncate", "files", "if", "they", "don", "t", "report", "a", "correct",...
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java#L284-L293
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/GuaranteedTargetStream.java
GuaranteedTargetStream.addAlarm
protected static void addAlarm(Object key, Object alarmObject) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "addAlarm", new Object[] { key, alarmObject }); synchronized (pendingAlarms) { Set alarms = null; if (pendingAlarms.containsKey(key)) alarms = (Set) pendingAlarms.get(key); else { alarms = new HashSet(); pendingAlarms.put(key, alarms); } alarms.add(alarmObject); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addAlarm"); }
java
protected static void addAlarm(Object key, Object alarmObject) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "addAlarm", new Object[] { key, alarmObject }); synchronized (pendingAlarms) { Set alarms = null; if (pendingAlarms.containsKey(key)) alarms = (Set) pendingAlarms.get(key); else { alarms = new HashSet(); pendingAlarms.put(key, alarms); } alarms.add(alarmObject); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "addAlarm"); }
[ "protected", "static", "void", "addAlarm", "(", "Object", "key", ",", "Object", "alarmObject", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ...
Utility method for adding an alarm which needs to be expired if a flush occurs. @param key The key for the set of alarms to which this alarm should be added. Normally this is a stream instance. @param alarmObject The alarm object to add to the set.
[ "Utility", "method", "for", "adding", "an", "alarm", "which", "needs", "to", "be", "expired", "if", "a", "flush", "occurs", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/gd/GuaranteedTargetStream.java#L1811-L1831
eFaps/eFaps-Kernel
src/main/java/org/efaps/update/version/ApplicationVersion.java
ApplicationVersion.getCompleteRootUrl
protected URL getCompleteRootUrl() throws InstallationException { try { final URL url; if (this.application.getRootPackageName() == null) { url = this.application.getRootUrl(); } else { url = new URL(this.application.getRootUrl(), this.application.getRootPackageName()); } return url; } catch (final MalformedURLException e) { throw new InstallationException("Root url could not be prepared", e); } }
java
protected URL getCompleteRootUrl() throws InstallationException { try { final URL url; if (this.application.getRootPackageName() == null) { url = this.application.getRootUrl(); } else { url = new URL(this.application.getRootUrl(), this.application.getRootPackageName()); } return url; } catch (final MalformedURLException e) { throw new InstallationException("Root url could not be prepared", e); } }
[ "protected", "URL", "getCompleteRootUrl", "(", ")", "throws", "InstallationException", "{", "try", "{", "final", "URL", "url", ";", "if", "(", "this", ".", "application", ".", "getRootPackageName", "(", ")", "==", "null", ")", "{", "url", "=", "this", ".",...
Returns the complete root URL so that resources in the installation package could be fetched. If an installation from the source directory is done, the {@link Application#getRootUrl() root URL} is directly returned, in the case that an installation is done from a JAR container the {@link Application#getRootUrl() root URL} is appended with the name of the {@link Application#getRootPackageName() root package name}. @return complete root URL @throws InstallationException if complete root URL could not be prepared
[ "Returns", "the", "complete", "root", "URL", "so", "that", "resources", "in", "the", "installation", "package", "could", "be", "fetched", ".", "If", "an", "installation", "from", "the", "source", "directory", "is", "done", "the", "{", "@link", "Application#get...
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/update/version/ApplicationVersion.java#L346-L360
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_service_serviceName_directory_fetchEntrepriseInformations_POST
public OvhEntrepriseNumberInformationsTask billingAccount_service_serviceName_directory_fetchEntrepriseInformations_POST(String billingAccount, String serviceName, String entrepriseNumber) throws IOException { String qPath = "/telephony/{billingAccount}/service/{serviceName}/directory/fetchEntrepriseInformations"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "entrepriseNumber", entrepriseNumber); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhEntrepriseNumberInformationsTask.class); }
java
public OvhEntrepriseNumberInformationsTask billingAccount_service_serviceName_directory_fetchEntrepriseInformations_POST(String billingAccount, String serviceName, String entrepriseNumber) throws IOException { String qPath = "/telephony/{billingAccount}/service/{serviceName}/directory/fetchEntrepriseInformations"; StringBuilder sb = path(qPath, billingAccount, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "entrepriseNumber", entrepriseNumber); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhEntrepriseNumberInformationsTask.class); }
[ "public", "OvhEntrepriseNumberInformationsTask", "billingAccount_service_serviceName_directory_fetchEntrepriseInformations_POST", "(", "String", "billingAccount", ",", "String", "serviceName", ",", "String", "entrepriseNumber", ")", "throws", "IOException", "{", "String", "qPath", ...
Get company entreprise informations by providing entreprise number REST: POST /telephony/{billingAccount}/service/{serviceName}/directory/fetchEntrepriseInformations @param entrepriseNumber [required] Entreprise number to fetch informations from @param billingAccount [required] The name of your billingAccount @param serviceName [required]
[ "Get", "company", "entreprise", "informations", "by", "providing", "entreprise", "number" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3978-L3985
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java
ImageModerationsImpl.oCRUrlInput
public OCR oCRUrlInput(String language, String contentType, BodyModelModel imageUrl, OCRUrlInputOptionalParameter oCRUrlInputOptionalParameter) { return oCRUrlInputWithServiceResponseAsync(language, contentType, imageUrl, oCRUrlInputOptionalParameter).toBlocking().single().body(); }
java
public OCR oCRUrlInput(String language, String contentType, BodyModelModel imageUrl, OCRUrlInputOptionalParameter oCRUrlInputOptionalParameter) { return oCRUrlInputWithServiceResponseAsync(language, contentType, imageUrl, oCRUrlInputOptionalParameter).toBlocking().single().body(); }
[ "public", "OCR", "oCRUrlInput", "(", "String", "language", ",", "String", "contentType", ",", "BodyModelModel", "imageUrl", ",", "OCRUrlInputOptionalParameter", "oCRUrlInputOptionalParameter", ")", "{", "return", "oCRUrlInputWithServiceResponseAsync", "(", "language", ",", ...
Returns any text found in the image for the language specified. If no language is specified in input then the detection defaults to English. @param language Language of the terms. @param contentType The content type. @param imageUrl The image url. @param oCRUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OCR object if successful.
[ "Returns", "any", "text", "found", "in", "the", "image", "for", "the", "language", "specified", ".", "If", "no", "language", "is", "specified", "in", "input", "then", "the", "detection", "defaults", "to", "English", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java#L1047-L1049
classgraph/classgraph
src/main/java/io/github/classgraph/ClasspathElement.java
ClasspathElement.checkResourcePathWhiteBlackList
protected void checkResourcePathWhiteBlackList(final String relativePath, final LogNode log) { // Whitelist/blacklist classpath elements based on file resource paths if (!scanSpec.classpathElementResourcePathWhiteBlackList.whitelistAndBlacklistAreEmpty()) { if (scanSpec.classpathElementResourcePathWhiteBlackList.isBlacklisted(relativePath)) { if (log != null) { log.log("Reached blacklisted classpath element resource path, stopping scanning: " + relativePath); } skipClasspathElement = true; return; } if (scanSpec.classpathElementResourcePathWhiteBlackList.isSpecificallyWhitelisted(relativePath)) { if (log != null) { log.log("Reached specifically whitelisted classpath element resource path: " + relativePath); } containsSpecificallyWhitelistedClasspathElementResourcePath = true; } } }
java
protected void checkResourcePathWhiteBlackList(final String relativePath, final LogNode log) { // Whitelist/blacklist classpath elements based on file resource paths if (!scanSpec.classpathElementResourcePathWhiteBlackList.whitelistAndBlacklistAreEmpty()) { if (scanSpec.classpathElementResourcePathWhiteBlackList.isBlacklisted(relativePath)) { if (log != null) { log.log("Reached blacklisted classpath element resource path, stopping scanning: " + relativePath); } skipClasspathElement = true; return; } if (scanSpec.classpathElementResourcePathWhiteBlackList.isSpecificallyWhitelisted(relativePath)) { if (log != null) { log.log("Reached specifically whitelisted classpath element resource path: " + relativePath); } containsSpecificallyWhitelistedClasspathElementResourcePath = true; } } }
[ "protected", "void", "checkResourcePathWhiteBlackList", "(", "final", "String", "relativePath", ",", "final", "LogNode", "log", ")", "{", "// Whitelist/blacklist classpath elements based on file resource paths", "if", "(", "!", "scanSpec", ".", "classpathElementResourcePathWhit...
Check relativePath against classpathElementResourcePathWhiteBlackList. @param relativePath the relative path @param log the log
[ "Check", "relativePath", "against", "classpathElementResourcePathWhiteBlackList", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/ClasspathElement.java#L153-L171
icode/ameba-utils
src/main/java/ameba/util/Assert.java
Assert.notEmpty
public static void notEmpty(Object[] array, String message) { if (ArrayUtils.isEmpty(array)) { throw new IllegalArgumentException(message); } }
java
public static void notEmpty(Object[] array, String message) { if (ArrayUtils.isEmpty(array)) { throw new IllegalArgumentException(message); } }
[ "public", "static", "void", "notEmpty", "(", "Object", "[", "]", "array", ",", "String", "message", ")", "{", "if", "(", "ArrayUtils", ".", "isEmpty", "(", "array", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "message", ")", ";", "}",...
Assert that an array has elements; that is, it must not be {@code null} and must have at least one element. <pre class="code">Assert.notEmpty(array, "The array must have elements");</pre> @param array the array to check @param message the exception message to use if the assertion fails @throws java.lang.IllegalArgumentException if the object array is {@code null} or has no elements
[ "Assert", "that", "an", "array", "has", "elements", ";", "that", "is", "it", "must", "not", "be", "{", "@code", "null", "}", "and", "must", "have", "at", "least", "one", "element", ".", "<pre", "class", "=", "code", ">", "Assert", ".", "notEmpty", "(...
train
https://github.com/icode/ameba-utils/blob/1aad5317a22e546c83dfe2dc0c80a1dc1fa0ea35/src/main/java/ameba/util/Assert.java#L212-L216
xmlunit/xmlunit
xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLAssert.java
XMLAssert.assertXMLEqual
public static void assertXMLEqual(InputSource control, InputSource test) throws SAXException, IOException { assertXMLEqual(null, control, test); }
java
public static void assertXMLEqual(InputSource control, InputSource test) throws SAXException, IOException { assertXMLEqual(null, control, test); }
[ "public", "static", "void", "assertXMLEqual", "(", "InputSource", "control", ",", "InputSource", "test", ")", "throws", "SAXException", ",", "IOException", "{", "assertXMLEqual", "(", "null", ",", "control", ",", "test", ")", ";", "}" ]
Assert that two XML documents are similar @param control XML to be compared against @param test XML to be tested @throws SAXException @throws IOException
[ "Assert", "that", "two", "XML", "documents", "are", "similar" ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLAssert.java#L169-L172
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/plugins/util/PropertyBuilder.java
PropertyBuilder.renderingOption
public PropertyBuilder renderingOption(final String optionKey, final Object optionValue) { this.renderingOptions.put(optionKey, optionValue); return this; }
java
public PropertyBuilder renderingOption(final String optionKey, final Object optionValue) { this.renderingOptions.put(optionKey, optionValue); return this; }
[ "public", "PropertyBuilder", "renderingOption", "(", "final", "String", "optionKey", ",", "final", "Object", "optionValue", ")", "{", "this", ".", "renderingOptions", ".", "put", "(", "optionKey", ",", "optionValue", ")", ";", "return", "this", ";", "}" ]
Adds the given renderingOption @param optionKey key @param optionValue value @return this builder @see StringRenderingConstants
[ "Adds", "the", "given", "renderingOption", "@param", "optionKey", "key", "@param", "optionValue", "value" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/plugins/util/PropertyBuilder.java#L306-L309
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.getAndDecryptArray
public JsonArray getAndDecryptArray(String name, String providerName) throws Exception { return (JsonArray) getAndDecrypt(name, providerName); }
java
public JsonArray getAndDecryptArray(String name, String providerName) throws Exception { return (JsonArray) getAndDecrypt(name, providerName); }
[ "public", "JsonArray", "getAndDecryptArray", "(", "String", "name", ",", "String", "providerName", ")", "throws", "Exception", "{", "return", "(", "JsonArray", ")", "getAndDecrypt", "(", "name", ",", "providerName", ")", ";", "}" ]
Retrieves the decrypted value from the field name and casts it to {@link JsonArray}. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the field. @param providerName crypto provider name for decryption. @return the result or null if it does not exist.
[ "Retrieves", "the", "decrypted", "value", "from", "the", "field", "name", "and", "casts", "it", "to", "{", "@link", "JsonArray", "}", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L886-L888
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.listMultiRoleMetricsAsync
public Observable<Page<ResourceMetricInner>> listMultiRoleMetricsAsync(final String resourceGroupName, final String name) { return listMultiRoleMetricsWithServiceResponseAsync(resourceGroupName, name) .map(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Page<ResourceMetricInner>>() { @Override public Page<ResourceMetricInner> call(ServiceResponse<Page<ResourceMetricInner>> response) { return response.body(); } }); }
java
public Observable<Page<ResourceMetricInner>> listMultiRoleMetricsAsync(final String resourceGroupName, final String name) { return listMultiRoleMetricsWithServiceResponseAsync(resourceGroupName, name) .map(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Page<ResourceMetricInner>>() { @Override public Page<ResourceMetricInner> call(ServiceResponse<Page<ResourceMetricInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ResourceMetricInner", ">", ">", "listMultiRoleMetricsAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ")", "{", "return", "listMultiRoleMetricsWithServiceResponseAsync", "(", "resourceGroupName...
Get metrics for a multi-role pool of an App Service Environment. Get metrics for a multi-role pool of an App Service Environment. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ResourceMetricInner&gt; object
[ "Get", "metrics", "for", "a", "multi", "-", "role", "pool", "of", "an", "App", "Service", "Environment", ".", "Get", "metrics", "for", "a", "multi", "-", "role", "pool", "of", "an", "App", "Service", "Environment", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L3133-L3141
Jasig/uPortal
uPortal-security/uPortal-security-permissions/src/main/java/org/apereo/portal/permission/target/PermissionTargetProviderRegistryImpl.java
PermissionTargetProviderRegistryImpl.setProviders
public void setProviders(Map<String, IPermissionTargetProvider> providers) { this.providers.clear(); for (Map.Entry<String, IPermissionTargetProvider> provider : providers.entrySet()) { this.providers.put(provider.getKey(), provider.getValue()); } }
java
public void setProviders(Map<String, IPermissionTargetProvider> providers) { this.providers.clear(); for (Map.Entry<String, IPermissionTargetProvider> provider : providers.entrySet()) { this.providers.put(provider.getKey(), provider.getValue()); } }
[ "public", "void", "setProviders", "(", "Map", "<", "String", ",", "IPermissionTargetProvider", ">", "providers", ")", "{", "this", ".", "providers", ".", "clear", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "IPermissionTargetProvider"...
Construct a new target provider registry and initialize it with the supplied map of key -> provider pairs. @param providers
[ "Construct", "a", "new", "target", "provider", "registry", "and", "initialize", "it", "with", "the", "supplied", "map", "of", "key", "-", ">", "provider", "pairs", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-permissions/src/main/java/org/apereo/portal/permission/target/PermissionTargetProviderRegistryImpl.java#L42-L47
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/file/FileHelper.java
FileHelper.getDirectoryContent
@Nonnull @ReturnsMutableCopy public static ICommonsList <File> getDirectoryContent (@Nonnull final File aDirectory, @Nonnull final FilenameFilter aFilenameFilter) { ValueEnforcer.notNull (aDirectory, "Directory"); ValueEnforcer.notNull (aFilenameFilter, "FilenameFilter"); return _getDirectoryContent (aDirectory, aDirectory.listFiles (aFilenameFilter)); }
java
@Nonnull @ReturnsMutableCopy public static ICommonsList <File> getDirectoryContent (@Nonnull final File aDirectory, @Nonnull final FilenameFilter aFilenameFilter) { ValueEnforcer.notNull (aDirectory, "Directory"); ValueEnforcer.notNull (aFilenameFilter, "FilenameFilter"); return _getDirectoryContent (aDirectory, aDirectory.listFiles (aFilenameFilter)); }
[ "@", "Nonnull", "@", "ReturnsMutableCopy", "public", "static", "ICommonsList", "<", "File", ">", "getDirectoryContent", "(", "@", "Nonnull", "final", "File", "aDirectory", ",", "@", "Nonnull", "final", "FilenameFilter", "aFilenameFilter", ")", "{", "ValueEnforcer", ...
This is a replacement for <code>File.listFiles(FilenameFilter)</code> doing some additional checks on permissions. The order of the returned files is defined by the underlying {@link File#listFiles(FilenameFilter)} method. @param aDirectory The directory to be listed. May not be <code>null</code>. @param aFilenameFilter The filename filter to be used. May not be <code>null</code>. @return Never <code>null</code>.
[ "This", "is", "a", "replacement", "for", "<code", ">", "File", ".", "listFiles", "(", "FilenameFilter", ")", "<", "/", "code", ">", "doing", "some", "additional", "checks", "on", "permissions", ".", "The", "order", "of", "the", "returned", "files", "is", ...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/file/FileHelper.java#L710-L719
Omertron/api-thetvdb
src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java
DOMHelper.writeDocumentToFile
public static boolean writeDocumentToFile(Document doc, String localFile) { try { TransformerFactory transfact = TransformerFactory.newInstance(); Transformer trans = transfact.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES); trans.setOutputProperty(OutputKeys.INDENT, YES); trans.transform(new DOMSource(doc), new StreamResult(new File(localFile))); return true; } catch (TransformerConfigurationException ex) { LOG.warn(ERROR_WRITING, localFile, ex); return false; } catch (TransformerException ex) { LOG.warn(ERROR_WRITING, localFile, ex); return false; } }
java
public static boolean writeDocumentToFile(Document doc, String localFile) { try { TransformerFactory transfact = TransformerFactory.newInstance(); Transformer trans = transfact.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES); trans.setOutputProperty(OutputKeys.INDENT, YES); trans.transform(new DOMSource(doc), new StreamResult(new File(localFile))); return true; } catch (TransformerConfigurationException ex) { LOG.warn(ERROR_WRITING, localFile, ex); return false; } catch (TransformerException ex) { LOG.warn(ERROR_WRITING, localFile, ex); return false; } }
[ "public", "static", "boolean", "writeDocumentToFile", "(", "Document", "doc", ",", "String", "localFile", ")", "{", "try", "{", "TransformerFactory", "transfact", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "trans", "=", "transfact...
Write the Document out to a file using nice formatting @param doc The document to save @param localFile The file to write to @return
[ "Write", "the", "Document", "out", "to", "a", "file", "using", "nice", "formatting" ]
train
https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java#L204-L219
googleapis/google-cloud-java
google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Value.java
Value.boolArray
public static Value boolArray(@Nullable boolean[] v) { return boolArray(v, 0, v == null ? 0 : v.length); }
java
public static Value boolArray(@Nullable boolean[] v) { return boolArray(v, 0, v == null ? 0 : v.length); }
[ "public", "static", "Value", "boolArray", "(", "@", "Nullable", "boolean", "[", "]", "v", ")", "{", "return", "boolArray", "(", "v", ",", "0", ",", "v", "==", "null", "?", "0", ":", "v", ".", "length", ")", ";", "}" ]
Returns an {@code ARRAY<BOOL>} value. @param v the source of element values, which may be null to produce a value for which {@code isNull()} is {@code true}
[ "Returns", "an", "{", "@code", "ARRAY<BOOL", ">", "}", "value", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Value.java#L189-L191
ThreeTen/threeten-extra
src/main/java/org/threeten/extra/chrono/BritishCutoverDate.java
BritishCutoverDate.ofYearDay
static BritishCutoverDate ofYearDay(int prolepticYear, int dayOfYear) { if (prolepticYear < CUTOVER_YEAR || (prolepticYear == CUTOVER_YEAR && dayOfYear <= 246)) { JulianDate julian = JulianDate.ofYearDay(prolepticYear, dayOfYear); return new BritishCutoverDate(julian); } else if (prolepticYear == CUTOVER_YEAR) { LocalDate iso = LocalDate.ofYearDay(prolepticYear, dayOfYear + CUTOVER_DAYS); return new BritishCutoverDate(iso); } else { LocalDate iso = LocalDate.ofYearDay(prolepticYear, dayOfYear); return new BritishCutoverDate(iso); } }
java
static BritishCutoverDate ofYearDay(int prolepticYear, int dayOfYear) { if (prolepticYear < CUTOVER_YEAR || (prolepticYear == CUTOVER_YEAR && dayOfYear <= 246)) { JulianDate julian = JulianDate.ofYearDay(prolepticYear, dayOfYear); return new BritishCutoverDate(julian); } else if (prolepticYear == CUTOVER_YEAR) { LocalDate iso = LocalDate.ofYearDay(prolepticYear, dayOfYear + CUTOVER_DAYS); return new BritishCutoverDate(iso); } else { LocalDate iso = LocalDate.ofYearDay(prolepticYear, dayOfYear); return new BritishCutoverDate(iso); } }
[ "static", "BritishCutoverDate", "ofYearDay", "(", "int", "prolepticYear", ",", "int", "dayOfYear", ")", "{", "if", "(", "prolepticYear", "<", "CUTOVER_YEAR", "||", "(", "prolepticYear", "==", "CUTOVER_YEAR", "&&", "dayOfYear", "<=", "246", ")", ")", "{", "Juli...
Obtains a {@code BritishCutoverDate} representing a date in the British Cutover calendar system from the proleptic-year and day-of-year fields. <p> This returns a {@code BritishCutoverDate} with the specified fields. The day must be valid for the year, otherwise an exception will be thrown. @param prolepticYear the British Cutover proleptic-year @param dayOfYear the British Cutover day-of-year, from 1 to 366 @return the date in British Cutover calendar system, not null @throws DateTimeException if the value of any field is out of range, or if the day-of-year is invalid for the year
[ "Obtains", "a", "{", "@code", "BritishCutoverDate", "}", "representing", "a", "date", "in", "the", "British", "Cutover", "calendar", "system", "from", "the", "proleptic", "-", "year", "and", "day", "-", "of", "-", "year", "fields", ".", "<p", ">", "This", ...
train
https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/chrono/BritishCutoverDate.java#L194-L205
js-lib-com/commons
src/main/java/js/util/Strings.java
Strings.injectProperties
public static String injectProperties(final String string) throws BugError { return Strings.replaceAll(string, VARIABLE_PATTERN, new Handler<String, String>() { @Override public String handle(String variableName) { String property = System.getProperty(variableName); if(property == null) { throw new BugError("Missing system property |%s|. String |%s| variable injection aborted.", variableName, string); } return property; } }); }
java
public static String injectProperties(final String string) throws BugError { return Strings.replaceAll(string, VARIABLE_PATTERN, new Handler<String, String>() { @Override public String handle(String variableName) { String property = System.getProperty(variableName); if(property == null) { throw new BugError("Missing system property |%s|. String |%s| variable injection aborted.", variableName, string); } return property; } }); }
[ "public", "static", "String", "injectProperties", "(", "final", "String", "string", ")", "throws", "BugError", "{", "return", "Strings", ".", "replaceAll", "(", "string", ",", "VARIABLE_PATTERN", ",", "new", "Handler", "<", "String", ",", "String", ">", "(", ...
Inject system properties into text with variables. Given text uses standard variable notation <code>${variable-name}</code> , as known from, for example, Ant or Log4j configuration. This method replace found variable with system property using <code>variable-name</code> as property key. It is a logic flaw if system property is missing. <p> For example, injecting system properties into <code>${log}/app.log</code> will return <code>/var/log/app.log</code> provided there is a system property named <code>log</code> with value <code>/var/log</code>. Note that there is no limit on the number of system properties and/or variables to replace. @param string text with variables. @return new string with variables replaces. @throws BugError if system property is missing.
[ "Inject", "system", "properties", "into", "text", "with", "variables", ".", "Given", "text", "uses", "standard", "variable", "notation", "<code", ">", "$", "{", "variable", "-", "name", "}", "<", "/", "code", ">", "as", "known", "from", "for", "example", ...
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Strings.java#L1209-L1223
julianhyde/sqlline
src/main/java/sqlline/SqlLine.java
SqlLine.isComment
boolean isComment(String line, boolean trim) { final String trimmedLine = trim ? line.trim() : line; for (String comment: getDialect().getSqlLineOneLineComments()) { if (trimmedLine.startsWith(comment)) { return true; } } return false; }
java
boolean isComment(String line, boolean trim) { final String trimmedLine = trim ? line.trim() : line; for (String comment: getDialect().getSqlLineOneLineComments()) { if (trimmedLine.startsWith(comment)) { return true; } } return false; }
[ "boolean", "isComment", "(", "String", "line", ",", "boolean", "trim", ")", "{", "final", "String", "trimmedLine", "=", "trim", "?", "line", ".", "trim", "(", ")", ":", "line", ";", "for", "(", "String", "comment", ":", "getDialect", "(", ")", ".", "...
Test whether a line is a comment. @param line the line to be tested @return true if a comment
[ "Test", "whether", "a", "line", "is", "a", "comment", "." ]
train
https://github.com/julianhyde/sqlline/blob/7577f3ebaca0897a9ff01d1553d4576487e1d2c3/src/main/java/sqlline/SqlLine.java#L766-L774
Impetus/Kundera
src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java
OracleNoSQLClient.initializeEntity
private Object initializeEntity(Object key, EntityMetadata entityMetadata) throws InstantiationException, IllegalAccessException { Object entity = null; entity = entityMetadata.getEntityClazz().newInstance(); if (key != null) { PropertyAccessorHelper.setId(entity, entityMetadata, key); } return entity; }
java
private Object initializeEntity(Object key, EntityMetadata entityMetadata) throws InstantiationException, IllegalAccessException { Object entity = null; entity = entityMetadata.getEntityClazz().newInstance(); if (key != null) { PropertyAccessorHelper.setId(entity, entityMetadata, key); } return entity; }
[ "private", "Object", "initializeEntity", "(", "Object", "key", ",", "EntityMetadata", "entityMetadata", ")", "throws", "InstantiationException", ",", "IllegalAccessException", "{", "Object", "entity", "=", "null", ";", "entity", "=", "entityMetadata", ".", "getEntityC...
Initialize entity. @param key the key @param entityMetadata the entity metadata @return the object @throws InstantiationException the instantiation exception @throws IllegalAccessException the illegal access exception
[ "Initialize", "entity", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java#L1402-L1412
infinispan/infinispan
spring/spring5/spring5-common/src/main/java/org/infinispan/spring/common/session/AbstractInfinispanSessionRepository.java
AbstractInfinispanSessionRepository.getSession
public MapSession getSession(String id, boolean updateTTL) { return Optional.ofNullable(cache.get(id)) .map(v -> (MapSession) v.get()) .map(v -> updateTTL(v, updateTTL)) .orElse(null); }
java
public MapSession getSession(String id, boolean updateTTL) { return Optional.ofNullable(cache.get(id)) .map(v -> (MapSession) v.get()) .map(v -> updateTTL(v, updateTTL)) .orElse(null); }
[ "public", "MapSession", "getSession", "(", "String", "id", ",", "boolean", "updateTTL", ")", "{", "return", "Optional", ".", "ofNullable", "(", "cache", ".", "get", "(", "id", ")", ")", ".", "map", "(", "v", "->", "(", "MapSession", ")", "v", ".", "g...
Returns session with optional parameter whether or not update time accessed. @param id Session ID. @param updateTTL <code>true</code> if time accessed needs to be updated. @return Session or <code>null</code> if it doesn't exist.
[ "Returns", "session", "with", "optional", "parameter", "whether", "or", "not", "update", "time", "accessed", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/spring/spring5/spring5-common/src/main/java/org/infinispan/spring/common/session/AbstractInfinispanSessionRepository.java#L92-L97
m-m-m/util
gwt/src/main/java/net/sf/mmm/util/gwt/base/rebind/AbstractIncrementalGenerator.java
AbstractIncrementalGenerator.generateSourcePublicMethodDeclaration
protected final void generateSourcePublicMethodDeclaration(SourceWriter sourceWriter, JMethod method) { StringBuilder arguments = new StringBuilder(); for (JParameter parameter : method.getParameters()) { if (arguments.length() > 0) { arguments.append(", "); } arguments.append(parameter.getType().getQualifiedSourceName()); arguments.append(" "); arguments.append(parameter.getName()); } generateSourcePublicMethodDeclaration(sourceWriter, method.getReturnType().getQualifiedSourceName(), method.getName(), arguments.toString(), false); }
java
protected final void generateSourcePublicMethodDeclaration(SourceWriter sourceWriter, JMethod method) { StringBuilder arguments = new StringBuilder(); for (JParameter parameter : method.getParameters()) { if (arguments.length() > 0) { arguments.append(", "); } arguments.append(parameter.getType().getQualifiedSourceName()); arguments.append(" "); arguments.append(parameter.getName()); } generateSourcePublicMethodDeclaration(sourceWriter, method.getReturnType().getQualifiedSourceName(), method.getName(), arguments.toString(), false); }
[ "protected", "final", "void", "generateSourcePublicMethodDeclaration", "(", "SourceWriter", "sourceWriter", ",", "JMethod", "method", ")", "{", "StringBuilder", "arguments", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "JParameter", "parameter", ":", "met...
This method generates the source code for a public method declaration including the opening brace and indentation. @param sourceWriter is the {@link SourceWriter}. @param method is the {@link JMethod} to implement.
[ "This", "method", "generates", "the", "source", "code", "for", "a", "public", "method", "declaration", "including", "the", "opening", "brace", "and", "indentation", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/gwt/src/main/java/net/sf/mmm/util/gwt/base/rebind/AbstractIncrementalGenerator.java#L193-L206
JodaOrg/joda-time
src/main/java/org/joda/time/base/BasePartial.java
BasePartial.setValue
protected void setValue(int index, int value) { DateTimeField field = getField(index); int[] values = field.set(this, index, iValues, value); System.arraycopy(values, 0, iValues, 0, iValues.length); }
java
protected void setValue(int index, int value) { DateTimeField field = getField(index); int[] values = field.set(this, index, iValues, value); System.arraycopy(values, 0, iValues, 0, iValues.length); }
[ "protected", "void", "setValue", "(", "int", "index", ",", "int", "value", ")", "{", "DateTimeField", "field", "=", "getField", "(", "index", ")", ";", "int", "[", "]", "values", "=", "field", ".", "set", "(", "this", ",", "index", ",", "iValues", ",...
Sets the value of the field at the specified index. <p> In version 2.0 and later, this method copies the array into the original. This is because the instance variable has been changed to be final to satisfy the Java Memory Model. This only impacts subclasses that are mutable. @param index the index @param value the value to set @throws IndexOutOfBoundsException if the index is invalid
[ "Sets", "the", "value", "of", "the", "field", "at", "the", "specified", "index", ".", "<p", ">", "In", "version", "2", ".", "0", "and", "later", "this", "method", "copies", "the", "array", "into", "the", "original", ".", "This", "is", "because", "the",...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/base/BasePartial.java#L264-L268
Erudika/para
para-server/src/main/java/com/erudika/para/rest/RestUtils.java
RestUtils.returnObjectResponse
public static void returnObjectResponse(HttpServletResponse response, Object obj) { if (response == null) { return; } PrintWriter out = null; try { response.setStatus(HttpServletResponse.SC_OK); response.setContentType(MediaType.APPLICATION_JSON); out = response.getWriter(); ParaObjectUtils.getJsonWriter().writeValue(out, obj); } catch (Exception ex) { logger.error(null, ex); } finally { if (out != null) { out.close(); } } }
java
public static void returnObjectResponse(HttpServletResponse response, Object obj) { if (response == null) { return; } PrintWriter out = null; try { response.setStatus(HttpServletResponse.SC_OK); response.setContentType(MediaType.APPLICATION_JSON); out = response.getWriter(); ParaObjectUtils.getJsonWriter().writeValue(out, obj); } catch (Exception ex) { logger.error(null, ex); } finally { if (out != null) { out.close(); } } }
[ "public", "static", "void", "returnObjectResponse", "(", "HttpServletResponse", "response", ",", "Object", "obj", ")", "{", "if", "(", "response", "==", "null", ")", "{", "return", ";", "}", "PrintWriter", "out", "=", "null", ";", "try", "{", "response", "...
A generic JSON response returning an object. Status code is always {@code 200}. @param response the response to write to @param obj an object
[ "A", "generic", "JSON", "response", "returning", "an", "object", ".", "Status", "code", "is", "always", "{" ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/rest/RestUtils.java#L967-L984
google/closure-compiler
src/com/google/javascript/jscomp/AstFactory.java
AstFactory.createGetProps
private Node createGetProps(Node receiver, Iterable<String> propertyNames) { Node result = receiver; for (String propertyName : propertyNames) { result = createGetProp(result, propertyName); } return result; }
java
private Node createGetProps(Node receiver, Iterable<String> propertyNames) { Node result = receiver; for (String propertyName : propertyNames) { result = createGetProp(result, propertyName); } return result; }
[ "private", "Node", "createGetProps", "(", "Node", "receiver", ",", "Iterable", "<", "String", ">", "propertyNames", ")", "{", "Node", "result", "=", "receiver", ";", "for", "(", "String", "propertyName", ":", "propertyNames", ")", "{", "result", "=", "create...
Creates a tree of nodes representing `receiver.name1.name2.etc`.
[ "Creates", "a", "tree", "of", "nodes", "representing", "receiver", ".", "name1", ".", "name2", ".", "etc", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AstFactory.java#L407-L413
zaproxy/zaproxy
src/org/zaproxy/zap/extension/api/API.java
API.getCallBackUrl
public String getCallBackUrl(ApiImplementor impl, String site) { String url = site + CALL_BACK_URL + random.nextLong(); this.callBacks.put(url, impl); logger.debug("Callback " + url + " registered for " + impl.getClass().getCanonicalName()); return url; }
java
public String getCallBackUrl(ApiImplementor impl, String site) { String url = site + CALL_BACK_URL + random.nextLong(); this.callBacks.put(url, impl); logger.debug("Callback " + url + " registered for " + impl.getClass().getCanonicalName()); return url; }
[ "public", "String", "getCallBackUrl", "(", "ApiImplementor", "impl", ",", "String", "site", ")", "{", "String", "url", "=", "site", "+", "CALL_BACK_URL", "+", "random", ".", "nextLong", "(", ")", ";", "this", ".", "callBacks", ".", "put", "(", "url", ","...
Gets (and registers) a new callback URL for the given implementor and site. @param impl the implementor that will handle the callback. @param site the site that will call the callback. @return the callback URL. @since 2.0.0 @see #removeCallBackUrl(String) @see #removeCallBackUrls(ApiImplementor) @see #removeApiImplementor(ApiImplementor)
[ "Gets", "(", "and", "registers", ")", "a", "new", "callback", "URL", "for", "the", "given", "implementor", "and", "site", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/api/API.java#L784-L789
alkacon/opencms-core
src/org/opencms/ui/apps/CmsWorkplaceAppManager.java
CmsWorkplaceAppManager.getAppSettings
public <T extends I_CmsAppSettings> T getAppSettings(CmsObject cms, Class<T> type) throws InstantiationException, IllegalAccessException { CmsUser user = cms.getRequestContext().getCurrentUser(); CmsUserSettings settings = new CmsUserSettings(user); String settingsString = settings.getAdditionalPreference(type.getName(), true); T result = type.newInstance(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(settingsString)) { result.restoreSettings(settingsString); } return result; }
java
public <T extends I_CmsAppSettings> T getAppSettings(CmsObject cms, Class<T> type) throws InstantiationException, IllegalAccessException { CmsUser user = cms.getRequestContext().getCurrentUser(); CmsUserSettings settings = new CmsUserSettings(user); String settingsString = settings.getAdditionalPreference(type.getName(), true); T result = type.newInstance(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(settingsString)) { result.restoreSettings(settingsString); } return result; }
[ "public", "<", "T", "extends", "I_CmsAppSettings", ">", "T", "getAppSettings", "(", "CmsObject", "cms", ",", "Class", "<", "T", ">", "type", ")", "throws", "InstantiationException", ",", "IllegalAccessException", "{", "CmsUser", "user", "=", "cms", ".", "getRe...
Returns the user app setting of the given type.<p> @param cms the cms context @param type the app setting type @return the app setting @throws InstantiationException in case instantiating the settings type fails @throws IllegalAccessException in case the settings default constructor is not accessible
[ "Returns", "the", "user", "app", "setting", "of", "the", "given", "type", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/CmsWorkplaceAppManager.java#L369-L384
GoogleCloudPlatform/google-cloud-datastore
java/datastore/src/main/java/com/google/datastore/v1/client/QuerySplitterImpl.java
QuerySplitterImpl.createScatterQuery
private Query.Builder createScatterQuery(Query query, int numSplits) { // TODO(pcostello): We can potentially support better splits with equality filters in our query // if there exists a composite index on property, __scatter__, __key__. Until an API for // metadata exists, this isn't possible. Note that ancestor and inequality queries fall into // the same category. Query.Builder scatterPointQuery = Query.newBuilder(); scatterPointQuery.addAllKind(query.getKindList()); scatterPointQuery.addOrder(DatastoreHelper.makeOrder( DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING)); // There is a split containing entities before and after each scatter entity: // ||---*------*------*------*------*------*------*---|| = scatter entity // If we represent each split as a region before a scatter entity, there is an extra region // following the last scatter point. Thus, we do not need the scatter entities for the last // region. scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT); scatterPointQuery.addProjection(Projection.newBuilder().setProperty( PropertyReference.newBuilder().setName("__key__"))); return scatterPointQuery; }
java
private Query.Builder createScatterQuery(Query query, int numSplits) { // TODO(pcostello): We can potentially support better splits with equality filters in our query // if there exists a composite index on property, __scatter__, __key__. Until an API for // metadata exists, this isn't possible. Note that ancestor and inequality queries fall into // the same category. Query.Builder scatterPointQuery = Query.newBuilder(); scatterPointQuery.addAllKind(query.getKindList()); scatterPointQuery.addOrder(DatastoreHelper.makeOrder( DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING)); // There is a split containing entities before and after each scatter entity: // ||---*------*------*------*------*------*------*---|| = scatter entity // If we represent each split as a region before a scatter entity, there is an extra region // following the last scatter point. Thus, we do not need the scatter entities for the last // region. scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT); scatterPointQuery.addProjection(Projection.newBuilder().setProperty( PropertyReference.newBuilder().setName("__key__"))); return scatterPointQuery; }
[ "private", "Query", ".", "Builder", "createScatterQuery", "(", "Query", "query", ",", "int", "numSplits", ")", "{", "// TODO(pcostello): We can potentially support better splits with equality filters in our query", "// if there exists a composite index on property, __scatter__, __key__. ...
Creates a scatter query from the given user query @param query the user's query. @param numSplits the number of splits to create.
[ "Creates", "a", "scatter", "query", "from", "the", "given", "user", "query" ]
train
https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/a23940d0634d7f537faf01ad9e60598046bcb40a/java/datastore/src/main/java/com/google/datastore/v1/client/QuerySplitterImpl.java#L210-L228
jpelzer/pelzer-util
src/main/java/com/pelzer/util/OverridableFields.java
OverridableFields.getObjectForString
private Object getObjectForString(Class<?> type, String values[]) throws Exception{ if(values == null || values.length == 0) throw new Exception("getObjectForString: values was null or of zero length"); Object array = Array.newInstance(type.getComponentType(), values.length); // Now fill in the values for the empty array we just created. for(int i = 0; i < values.length; i++) Array.set(array, i, getObjectForString(type, values[i])); return array; }
java
private Object getObjectForString(Class<?> type, String values[]) throws Exception{ if(values == null || values.length == 0) throw new Exception("getObjectForString: values was null or of zero length"); Object array = Array.newInstance(type.getComponentType(), values.length); // Now fill in the values for the empty array we just created. for(int i = 0; i < values.length; i++) Array.set(array, i, getObjectForString(type, values[i])); return array; }
[ "private", "Object", "getObjectForString", "(", "Class", "<", "?", ">", "type", ",", "String", "values", "[", "]", ")", "throws", "Exception", "{", "if", "(", "values", "==", "null", "||", "values", ".", "length", "==", "0", ")", "throw", "new", "Excep...
This method is similar to {@link #getObjectForString(Class, String[])} except that it returns an array of type objects. Expects the type variable to be an array.
[ "This", "method", "is", "similar", "to", "{" ]
train
https://github.com/jpelzer/pelzer-util/blob/ec14f2573fd977d1442dba5d1507a264f5ea9aa6/src/main/java/com/pelzer/util/OverridableFields.java#L131-L139
cdk/cdk
legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
GeometryTools.sortBy2DDistance
public static void sortBy2DDistance(IAtom[] atoms, Point2d point) { double distance1; double distance2; IAtom atom1; IAtom atom2; boolean doneSomething; do { doneSomething = false; for (int f = 0; f < atoms.length - 1; f++) { atom1 = atoms[f]; atom2 = atoms[f + 1]; distance1 = point.distance(atom1.getPoint2d()); distance2 = point.distance(atom2.getPoint2d()); if (distance2 < distance1) { atoms[f] = atom2; atoms[f + 1] = atom1; doneSomething = true; } } } while (doneSomething); }
java
public static void sortBy2DDistance(IAtom[] atoms, Point2d point) { double distance1; double distance2; IAtom atom1; IAtom atom2; boolean doneSomething; do { doneSomething = false; for (int f = 0; f < atoms.length - 1; f++) { atom1 = atoms[f]; atom2 = atoms[f + 1]; distance1 = point.distance(atom1.getPoint2d()); distance2 = point.distance(atom2.getPoint2d()); if (distance2 < distance1) { atoms[f] = atom2; atoms[f + 1] = atom1; doneSomething = true; } } } while (doneSomething); }
[ "public", "static", "void", "sortBy2DDistance", "(", "IAtom", "[", "]", "atoms", ",", "Point2d", "point", ")", "{", "double", "distance1", ";", "double", "distance2", ";", "IAtom", "atom1", ";", "IAtom", "atom2", ";", "boolean", "doneSomething", ";", "do", ...
Sorts a Vector of atoms such that the 2D distances of the atom locations from a given point are smallest for the first atoms in the vector. See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets @param point The point from which the distances to the atoms are measured @param atoms The atoms for which the distances to point are measured
[ "Sorts", "a", "Vector", "of", "atoms", "such", "that", "the", "2D", "distances", "of", "the", "atom", "locations", "from", "a", "given", "point", "are", "smallest", "for", "the", "first", "atoms", "in", "the", "vector", ".", "See", "comment", "for", "cen...
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L855-L875
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/MasterSlave.java
MasterSlave.getConnection
private static <T> T getConnection(CompletableFuture<T> connectionFuture, Object context) { try { return connectionFuture.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw RedisConnectionException.create(context.toString(), e); } catch (Exception e) { if (e instanceof ExecutionException) { // filter intermediate RedisConnectionException exceptions that bloat the stack trace if (e.getCause() instanceof RedisConnectionException && e.getCause().getCause() instanceof RedisConnectionException) { throw RedisConnectionException.create(context.toString(), e.getCause().getCause()); } throw RedisConnectionException.create(context.toString(), e.getCause()); } throw RedisConnectionException.create(context.toString(), e); } }
java
private static <T> T getConnection(CompletableFuture<T> connectionFuture, Object context) { try { return connectionFuture.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw RedisConnectionException.create(context.toString(), e); } catch (Exception e) { if (e instanceof ExecutionException) { // filter intermediate RedisConnectionException exceptions that bloat the stack trace if (e.getCause() instanceof RedisConnectionException && e.getCause().getCause() instanceof RedisConnectionException) { throw RedisConnectionException.create(context.toString(), e.getCause().getCause()); } throw RedisConnectionException.create(context.toString(), e.getCause()); } throw RedisConnectionException.create(context.toString(), e); } }
[ "private", "static", "<", "T", ">", "T", "getConnection", "(", "CompletableFuture", "<", "T", ">", "connectionFuture", ",", "Object", "context", ")", "{", "try", "{", "return", "connectionFuture", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedE...
Retrieve the connection from {@link ConnectionFuture}. Performs a blocking {@link ConnectionFuture#get()} to synchronize the channel/connection initialization. Any exception is rethrown as {@link RedisConnectionException}. @param connectionFuture must not be null. @param context context information (single RedisURI, multiple URIs), used as connection target in the reported exception. @param <T> Connection type. @return the connection. @throws RedisConnectionException in case of connection failures.
[ "Retrieve", "the", "connection", "from", "{", "@link", "ConnectionFuture", "}", ".", "Performs", "a", "blocking", "{", "@link", "ConnectionFuture#get", "()", "}", "to", "synchronize", "the", "channel", "/", "connection", "initialization", ".", "Any", "exception", ...
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/MasterSlave.java#L230-L252
cdk/cdk
descriptor/fingerprint/src/main/java/org/openscience/cdk/similarity/Tanimoto.java
Tanimoto.method2
public static double method2(ICountFingerprint fp1, ICountFingerprint fp2) { long maxSum = 0, minSum = 0; int i = 0, j = 0; while (i < fp1.numOfPopulatedbins() || j < fp2.numOfPopulatedbins()) { Integer hash1 = i < fp1.numOfPopulatedbins() ? fp1.getHash(i) : null; Integer hash2 = j < fp2.numOfPopulatedbins() ? fp2.getHash(j) : null; Integer count1 = i < fp1.numOfPopulatedbins() ? fp1.getCount(i) : null; Integer count2 = j < fp2.numOfPopulatedbins() ? fp2.getCount(j) : null; if (count2 == null || (hash1 != null && hash1 < hash2)) { maxSum += count1; i++; continue; } if (count1 == null || (hash2 != null && hash1 > hash2)) { maxSum += count2; j++; continue; } if (hash1.equals(hash2)) { maxSum += Math.max(count1, count2); minSum += Math.min(count1, count2); i++; j++; } } return ((double) minSum) / maxSum; }
java
public static double method2(ICountFingerprint fp1, ICountFingerprint fp2) { long maxSum = 0, minSum = 0; int i = 0, j = 0; while (i < fp1.numOfPopulatedbins() || j < fp2.numOfPopulatedbins()) { Integer hash1 = i < fp1.numOfPopulatedbins() ? fp1.getHash(i) : null; Integer hash2 = j < fp2.numOfPopulatedbins() ? fp2.getHash(j) : null; Integer count1 = i < fp1.numOfPopulatedbins() ? fp1.getCount(i) : null; Integer count2 = j < fp2.numOfPopulatedbins() ? fp2.getCount(j) : null; if (count2 == null || (hash1 != null && hash1 < hash2)) { maxSum += count1; i++; continue; } if (count1 == null || (hash2 != null && hash1 > hash2)) { maxSum += count2; j++; continue; } if (hash1.equals(hash2)) { maxSum += Math.max(count1, count2); minSum += Math.min(count1, count2); i++; j++; } } return ((double) minSum) / maxSum; }
[ "public", "static", "double", "method2", "(", "ICountFingerprint", "fp1", ",", "ICountFingerprint", "fp2", ")", "{", "long", "maxSum", "=", "0", ",", "minSum", "=", "0", ";", "int", "i", "=", "0", ",", "j", "=", "0", ";", "while", "(", "i", "<", "f...
Calculates Tanimoto distance for two count fingerprints using method 2 {@cdk.cite Grant06}. @param fp1 count fingerprint 1 @param fp2 count fingerprint 2 @return a Tanimoto distance
[ "Calculates", "Tanimoto", "distance", "for", "two", "count", "fingerprints", "using", "method", "2", "{", "@cdk", ".", "cite", "Grant06", "}", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/descriptor/fingerprint/src/main/java/org/openscience/cdk/similarity/Tanimoto.java#L219-L248
calrissian/mango
mango-core/src/main/java/org/calrissian/mango/collect/CloseableIterables.java
CloseableIterables.groupBy
public static <T> CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction) { return wrap(Iterables2.groupBy(iterable, groupingFunction), iterable); }
java
public static <T> CloseableIterable<List<T>> groupBy(final CloseableIterable<? extends T> iterable, final Function<? super T, ?> groupingFunction) { return wrap(Iterables2.groupBy(iterable, groupingFunction), iterable); }
[ "public", "static", "<", "T", ">", "CloseableIterable", "<", "List", "<", "T", ">", ">", "groupBy", "(", "final", "CloseableIterable", "<", "?", "extends", "T", ">", "iterable", ",", "final", "Function", "<", "?", "super", "T", ",", "?", ">", "grouping...
Divides an iterable into unmodifiable sublists of equivalent elements. The iterable groups elements in consecutive order, forming a new partition when the value from the provided function changes. For example, grouping the iterable {@code [1, 3, 2, 4, 5]} with a function grouping even and odd numbers yields {@code [[1, 3], [2, 4], [5]} all in the original order. <p/> <p>The returned lists implement {@link java.util.RandomAccess}.
[ "Divides", "an", "iterable", "into", "unmodifiable", "sublists", "of", "equivalent", "elements", ".", "The", "iterable", "groups", "elements", "in", "consecutive", "order", "forming", "a", "new", "partition", "when", "the", "value", "from", "the", "provided", "f...
train
https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-core/src/main/java/org/calrissian/mango/collect/CloseableIterables.java#L103-L105
grpc/grpc-java
api/src/main/java/io/grpc/ServerInterceptors.java
ServerInterceptors.useInputStreamMessages
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1712") public static ServerServiceDefinition useInputStreamMessages( final ServerServiceDefinition serviceDef) { final MethodDescriptor.Marshaller<InputStream> marshaller = new MethodDescriptor.Marshaller<InputStream>() { @Override public InputStream stream(final InputStream value) { return value; } @Override public InputStream parse(final InputStream stream) { if (stream.markSupported()) { return stream; } else { return new BufferedInputStream(stream); } } }; return useMarshalledMessages(serviceDef, marshaller); }
java
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1712") public static ServerServiceDefinition useInputStreamMessages( final ServerServiceDefinition serviceDef) { final MethodDescriptor.Marshaller<InputStream> marshaller = new MethodDescriptor.Marshaller<InputStream>() { @Override public InputStream stream(final InputStream value) { return value; } @Override public InputStream parse(final InputStream stream) { if (stream.markSupported()) { return stream; } else { return new BufferedInputStream(stream); } } }; return useMarshalledMessages(serviceDef, marshaller); }
[ "@", "ExperimentalApi", "(", "\"https://github.com/grpc/grpc-java/issues/1712\"", ")", "public", "static", "ServerServiceDefinition", "useInputStreamMessages", "(", "final", "ServerServiceDefinition", "serviceDef", ")", "{", "final", "MethodDescriptor", ".", "Marshaller", "<", ...
Create a new {@code ServerServiceDefinition} whose {@link MethodDescriptor} serializes to and from InputStream for all methods. The InputStream is guaranteed return true for markSupported(). The {@code ServerCallHandler} created will automatically convert back to the original types for request and response before calling the existing {@code ServerCallHandler}. Calling this method combined with the intercept methods will allow the developer to choose whether to intercept messages of InputStream, or the modeled types of their application. @param serviceDef the service definition to convert messages to InputStream @return a wrapped version of {@code serviceDef} with the InputStream conversion applied.
[ "Create", "a", "new", "{", "@code", "ServerServiceDefinition", "}", "whose", "{", "@link", "MethodDescriptor", "}", "serializes", "to", "and", "from", "InputStream", "for", "all", "methods", ".", "The", "InputStream", "is", "guaranteed", "return", "true", "for",...
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/api/src/main/java/io/grpc/ServerInterceptors.java#L137-L158
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/wrapper/PAbstractObject.java
PAbstractObject.optDouble
@Override public final Double optDouble(final String key, final Double defaultValue) { Double result = optDouble(key); return result == null ? defaultValue : result; }
java
@Override public final Double optDouble(final String key, final Double defaultValue) { Double result = optDouble(key); return result == null ? defaultValue : result; }
[ "@", "Override", "public", "final", "Double", "optDouble", "(", "final", "String", "key", ",", "final", "Double", "defaultValue", ")", "{", "Double", "result", "=", "optDouble", "(", "key", ")", ";", "return", "result", "==", "null", "?", "defaultValue", "...
Get a property as a double or defaultValue. @param key the property name @param defaultValue the default value
[ "Get", "a", "property", "as", "a", "double", "or", "defaultValue", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/wrapper/PAbstractObject.java#L117-L121
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/grammars/grammar/AbstractBuiltInGrammar.java
AbstractBuiltInGrammar.addProduction
public void addProduction(Event event, Grammar grammar) { containers.add(new SchemaLessProduction(this, grammar, event, getNumberOfEvents())); // pre-calculate count for log2 (Note: always 2nd level productions // available) // Note: BuiltInDocContent and BuiltInFragmentContent do not use this // variable this.ec1Length = MethodsBag.getCodingLength(containers.size() + 1); }
java
public void addProduction(Event event, Grammar grammar) { containers.add(new SchemaLessProduction(this, grammar, event, getNumberOfEvents())); // pre-calculate count for log2 (Note: always 2nd level productions // available) // Note: BuiltInDocContent and BuiltInFragmentContent do not use this // variable this.ec1Length = MethodsBag.getCodingLength(containers.size() + 1); }
[ "public", "void", "addProduction", "(", "Event", "event", ",", "Grammar", "grammar", ")", "{", "containers", ".", "add", "(", "new", "SchemaLessProduction", "(", "this", ",", "grammar", ",", "event", ",", "getNumberOfEvents", "(", ")", ")", ")", ";", "// p...
/* a leading rule for performance reason is added to the tail
[ "/", "*", "a", "leading", "rule", "for", "performance", "reason", "is", "added", "to", "the", "tail" ]
train
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/grammars/grammar/AbstractBuiltInGrammar.java#L86-L95
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLReadServiceContext.java
SSLReadServiceContext.handleAsyncComplete
private void handleAsyncComplete(boolean forceQueue, TCPReadCompletedCallback inCallback) { boolean fireHere = true; if (forceQueue) { // Complete must be returned on a separate thread. // Reuse queuedWork object (performance), but reset the error parameters. queuedWork.setCompleteParameters(getConnLink().getVirtualConnection(), this, inCallback); EventEngine events = SSLChannelProvider.getEventService(); if (null == events) { Exception e = new Exception("missing event service"); FFDCFilter.processException(e, getClass().getName(), "471", this); // fall-thru below and use callback here regardless } else { // fire an event to continue this queued work Event event = events.createEvent(SSLEventHandler.TOPIC_QUEUED_WORK); event.setProperty(SSLEventHandler.KEY_RUNNABLE, this.queuedWork); events.postEvent(event); fireHere = false; } } if (fireHere) { // Call the callback right here. inCallback.complete(getConnLink().getVirtualConnection(), this); } }
java
private void handleAsyncComplete(boolean forceQueue, TCPReadCompletedCallback inCallback) { boolean fireHere = true; if (forceQueue) { // Complete must be returned on a separate thread. // Reuse queuedWork object (performance), but reset the error parameters. queuedWork.setCompleteParameters(getConnLink().getVirtualConnection(), this, inCallback); EventEngine events = SSLChannelProvider.getEventService(); if (null == events) { Exception e = new Exception("missing event service"); FFDCFilter.processException(e, getClass().getName(), "471", this); // fall-thru below and use callback here regardless } else { // fire an event to continue this queued work Event event = events.createEvent(SSLEventHandler.TOPIC_QUEUED_WORK); event.setProperty(SSLEventHandler.KEY_RUNNABLE, this.queuedWork); events.postEvent(event); fireHere = false; } } if (fireHere) { // Call the callback right here. inCallback.complete(getConnLink().getVirtualConnection(), this); } }
[ "private", "void", "handleAsyncComplete", "(", "boolean", "forceQueue", ",", "TCPReadCompletedCallback", "inCallback", ")", "{", "boolean", "fireHere", "=", "true", ";", "if", "(", "forceQueue", ")", "{", "// Complete must be returned on a separate thread.", "// Reuse que...
This method handles calling the complete method of the callback as required by an async read. Appropriate action is taken based on the setting of the forceQueue parameter. If it is true, the complete callback is called on a separate thread. Otherwise it is called right here. @param forceQueue @param inCallback
[ "This", "method", "handles", "calling", "the", "complete", "method", "of", "the", "callback", "as", "required", "by", "an", "async", "read", ".", "Appropriate", "action", "is", "taken", "based", "on", "the", "setting", "of", "the", "forceQueue", "parameter", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLReadServiceContext.java#L576-L600
xiancloud/xian
xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/SessionFailRetryLoop.java
SessionFailRetryLoop.callWithRetry
public static<T> T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable<T> proc) throws Exception { T result = null; SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode); retryLoop.start(); try { while ( retryLoop.shouldContinue() ) { try { result = proc.call(); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); retryLoop.takeException(e); } } } finally { retryLoop.close(); } return result; }
java
public static<T> T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable<T> proc) throws Exception { T result = null; SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode); retryLoop.start(); try { while ( retryLoop.shouldContinue() ) { try { result = proc.call(); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); retryLoop.takeException(e); } } } finally { retryLoop.close(); } return result; }
[ "public", "static", "<", "T", ">", "T", "callWithRetry", "(", "CuratorZookeeperClient", "client", ",", "Mode", "mode", ",", "Callable", "<", "T", ">", "proc", ")", "throws", "Exception", "{", "T", "result", "=", "null", ";", "SessionFailRetryLoop", "retryLoo...
Convenience utility: creates a "session fail" retry loop calling the given proc @param client Zookeeper @param mode how to handle session failures @param proc procedure to call with retry @param <T> return type @return procedure result @throws Exception any non-retriable errors
[ "Convenience", "utility", ":", "creates", "a", "session", "fail", "retry", "loop", "calling", "the", "given", "proc" ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-client/src/main/java/org/apache/curator/SessionFailRetryLoop.java#L148-L173
google/Accessibility-Test-Framework-for-Android
src/main/java/com/googlecode/eyesfree/utils/AccessibilityNodeInfoUtils.java
AccessibilityNodeInfoUtils.isTopLevelScrollItem
public static boolean isTopLevelScrollItem(Context context, AccessibilityNodeInfoCompat node) { if (node == null) { return false; } AccessibilityNodeInfoCompat parent = null; try { parent = node.getParent(); if (parent == null) { // Not a child node of anything. return false; } if (isScrollable(node)) { return true; } // AdapterView, ScrollView, and HorizontalScrollView are focusable // containers, but Spinner is a special case. // TODO: Rename or break up this method, since it actually returns // whether the parent is scrollable OR is a focusable container that // should not block its children from receiving focus. if (nodeMatchesAnyClassByType(context, parent, android.widget.AdapterView.class, android.widget.ScrollView.class, android.widget.HorizontalScrollView.class, CLASS_TOUCHWIZ_TWADAPTERVIEW) && !nodeMatchesAnyClassByType(context, parent, android.widget.Spinner.class)) { return true; } return false; } finally { recycleNodes(parent); } }
java
public static boolean isTopLevelScrollItem(Context context, AccessibilityNodeInfoCompat node) { if (node == null) { return false; } AccessibilityNodeInfoCompat parent = null; try { parent = node.getParent(); if (parent == null) { // Not a child node of anything. return false; } if (isScrollable(node)) { return true; } // AdapterView, ScrollView, and HorizontalScrollView are focusable // containers, but Spinner is a special case. // TODO: Rename or break up this method, since it actually returns // whether the parent is scrollable OR is a focusable container that // should not block its children from receiving focus. if (nodeMatchesAnyClassByType(context, parent, android.widget.AdapterView.class, android.widget.ScrollView.class, android.widget.HorizontalScrollView.class, CLASS_TOUCHWIZ_TWADAPTERVIEW) && !nodeMatchesAnyClassByType(context, parent, android.widget.Spinner.class)) { return true; } return false; } finally { recycleNodes(parent); } }
[ "public", "static", "boolean", "isTopLevelScrollItem", "(", "Context", "context", ",", "AccessibilityNodeInfoCompat", "node", ")", "{", "if", "(", "node", "==", "null", ")", "{", "return", "false", ";", "}", "AccessibilityNodeInfoCompat", "parent", "=", "null", ...
Determines whether a node is a top-level item in a scrollable container. @param node The node to test. @return {@code true} if {@code node} is a top-level item in a scrollable container.
[ "Determines", "whether", "a", "node", "is", "a", "top", "-", "level", "item", "in", "a", "scrollable", "container", "." ]
train
https://github.com/google/Accessibility-Test-Framework-for-Android/blob/a6117fe0059c82dd764fa628d3817d724570f69e/src/main/java/com/googlecode/eyesfree/utils/AccessibilityNodeInfoUtils.java#L513-L547
sebastiangraf/perfidix
src/main/java/org/perfidix/ouput/TabularSummaryOutput.java
TabularSummaryOutput.generateMeterResult
private NiceTable generateMeterResult(final String columnDesc, final AbstractMeter meter, final AbstractResult result, final NiceTable input) { input.addRow(new String[]{columnDesc, meter.getUnit(), AbstractOutput.format(result.sum(meter)), AbstractOutput.format(result.min(meter)), AbstractOutput.format(result.max(meter)), AbstractOutput.format(result.mean(meter)), AbstractOutput.format(result.getStandardDeviation(meter)), new StringBuilder("[").append(AbstractOutput.format(result.getConf05(meter))).append("-").append(AbstractOutput.format(result.getConf95(meter))).append("]").toString(), AbstractOutput.format(result.getResultSet(meter).size())}); return input; }
java
private NiceTable generateMeterResult(final String columnDesc, final AbstractMeter meter, final AbstractResult result, final NiceTable input) { input.addRow(new String[]{columnDesc, meter.getUnit(), AbstractOutput.format(result.sum(meter)), AbstractOutput.format(result.min(meter)), AbstractOutput.format(result.max(meter)), AbstractOutput.format(result.mean(meter)), AbstractOutput.format(result.getStandardDeviation(meter)), new StringBuilder("[").append(AbstractOutput.format(result.getConf05(meter))).append("-").append(AbstractOutput.format(result.getConf95(meter))).append("]").toString(), AbstractOutput.format(result.getResultSet(meter).size())}); return input; }
[ "private", "NiceTable", "generateMeterResult", "(", "final", "String", "columnDesc", ",", "final", "AbstractMeter", "meter", ",", "final", "AbstractResult", "result", ",", "final", "NiceTable", "input", ")", "{", "input", ".", "addRow", "(", "new", "String", "["...
Generating the results for a given table. @param columnDesc the description for the row @param meter the corresponding {@link AbstractMeter} instance @param result the corresponding {@link AbstractResult} instance @param input the {@link NiceTable} to be print to @return the modified {@link NiceTable} instance
[ "Generating", "the", "results", "for", "a", "given", "table", "." ]
train
https://github.com/sebastiangraf/perfidix/blob/f13aa793b6a3055215ed4edbb946c1bb5d564886/src/main/java/org/perfidix/ouput/TabularSummaryOutput.java#L132-L135
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/ServiceUtils.java
ServiceUtils.convertRequestToUrl
@Deprecated public static URL convertRequestToUrl(Request<?> request, boolean removeLeadingSlashInResourcePath) { return convertRequestToUrl(request, removeLeadingSlashInResourcePath, true); }
java
@Deprecated public static URL convertRequestToUrl(Request<?> request, boolean removeLeadingSlashInResourcePath) { return convertRequestToUrl(request, removeLeadingSlashInResourcePath, true); }
[ "@", "Deprecated", "public", "static", "URL", "convertRequestToUrl", "(", "Request", "<", "?", ">", "request", ",", "boolean", "removeLeadingSlashInResourcePath", ")", "{", "return", "convertRequestToUrl", "(", "request", ",", "removeLeadingSlashInResourcePath", ",", ...
Converts the specified request object into a URL, containing all the specified parameters, the specified request endpoint, etc. @param request The request to convert into a URL. @param removeLeadingSlashInResourcePath Whether the leading slash in resource-path should be removed before appending to the endpoint. @return A new URL representing the specified request. @throws SdkClientException If the request cannot be converted to a well formed URL. @deprecated No longer used. May be removed in a future major version.
[ "Converts", "the", "specified", "request", "object", "into", "a", "URL", "containing", "all", "the", "specified", "parameters", "the", "specified", "request", "endpoint", "etc", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/ServiceUtils.java#L166-L169
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/impl/JcrBinary.java
JcrBinary.isNt
private static boolean isNt(Resource resource, String nodeTypeName) { if (resource != null) { return StringUtils.equals(resource.getResourceType(), nodeTypeName); } return false; }
java
private static boolean isNt(Resource resource, String nodeTypeName) { if (resource != null) { return StringUtils.equals(resource.getResourceType(), nodeTypeName); } return false; }
[ "private", "static", "boolean", "isNt", "(", "Resource", "resource", ",", "String", "nodeTypeName", ")", "{", "if", "(", "resource", "!=", "null", ")", "{", "return", "StringUtils", ".", "equals", "(", "resource", ".", "getResourceType", "(", ")", ",", "no...
Checks if the given resource is a node with the given node type name @param resource Resource @param nodeTypeName Node type name @return true if resource is of the given node type
[ "Checks", "if", "the", "given", "resource", "is", "a", "node", "with", "the", "given", "node", "type", "name" ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/impl/JcrBinary.java#L86-L91
apache/incubator-gobblin
gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/FileFailureEventReporter.java
FileFailureEventReporter.setupOutputStream
private void setupOutputStream() { synchronized (failureLogFile) { // Setup is done by some thread if (hasSetupOutputStream) { return; } try { boolean append = false; if (fs.exists(failureLogFile)) { log.info("Failure log file %s already exists, appending to it", failureLogFile); append = true; } OutputStream outputStream = append ? fs.append(failureLogFile) : fs.create(failureLogFile); output = this.closer.register(new PrintStream(outputStream, false, Charsets.UTF_8.toString())); } catch (IOException e) { throw new RuntimeException(e); } finally { hasSetupOutputStream = true; } } }
java
private void setupOutputStream() { synchronized (failureLogFile) { // Setup is done by some thread if (hasSetupOutputStream) { return; } try { boolean append = false; if (fs.exists(failureLogFile)) { log.info("Failure log file %s already exists, appending to it", failureLogFile); append = true; } OutputStream outputStream = append ? fs.append(failureLogFile) : fs.create(failureLogFile); output = this.closer.register(new PrintStream(outputStream, false, Charsets.UTF_8.toString())); } catch (IOException e) { throw new RuntimeException(e); } finally { hasSetupOutputStream = true; } } }
[ "private", "void", "setupOutputStream", "(", ")", "{", "synchronized", "(", "failureLogFile", ")", "{", "// Setup is done by some thread", "if", "(", "hasSetupOutputStream", ")", "{", "return", ";", "}", "try", "{", "boolean", "append", "=", "false", ";", "if", ...
Set up the {@link OutputStream} to the {@link #failureLogFile} only once
[ "Set", "up", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/FileFailureEventReporter.java#L72-L93
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javac/tree/TreeInfo.java
TreeInfo.finalizerPos
public static int finalizerPos(JCTree tree, PosKind posKind) { if (tree.hasTag(TRY)) { JCTry t = (JCTry) tree; Assert.checkNonNull(t.finalizer); return posKind.toPos(t.finalizer); } else if (tree.hasTag(SYNCHRONIZED)) { return endPos(((JCSynchronized) tree).body); } else { throw new AssertionError(); } }
java
public static int finalizerPos(JCTree tree, PosKind posKind) { if (tree.hasTag(TRY)) { JCTry t = (JCTry) tree; Assert.checkNonNull(t.finalizer); return posKind.toPos(t.finalizer); } else if (tree.hasTag(SYNCHRONIZED)) { return endPos(((JCSynchronized) tree).body); } else { throw new AssertionError(); } }
[ "public", "static", "int", "finalizerPos", "(", "JCTree", "tree", ",", "PosKind", "posKind", ")", "{", "if", "(", "tree", ".", "hasTag", "(", "TRY", ")", ")", "{", "JCTry", "t", "=", "(", "JCTry", ")", "tree", ";", "Assert", ".", "checkNonNull", "(",...
The position of the finalizer of given try/synchronized statement.
[ "The", "position", "of", "the", "finalizer", "of", "given", "try", "/", "synchronized", "statement", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/tree/TreeInfo.java#L625-L635
morimekta/utils
io-util/src/main/java/net/morimekta/util/io/IOUtils.java
IOUtils.skipUntil
public static boolean skipUntil(Reader in, String separator) throws IOException { if (separator == null) { throw new NullPointerException("Null separator given"); } final int len = separator.length(); if(len > 0) { if(len == 1) { return skipUntil(in, separator.charAt(0)); } return skipUntilInternal(in, separator.toCharArray(), new char[len]); } return true; }
java
public static boolean skipUntil(Reader in, String separator) throws IOException { if (separator == null) { throw new NullPointerException("Null separator given"); } final int len = separator.length(); if(len > 0) { if(len == 1) { return skipUntil(in, separator.charAt(0)); } return skipUntilInternal(in, separator.toCharArray(), new char[len]); } return true; }
[ "public", "static", "boolean", "skipUntil", "(", "Reader", "in", ",", "String", "separator", ")", "throws", "IOException", "{", "if", "(", "separator", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Null separator given\"", ")", ";", "...
Skip all bytes in stream until (and including) given separator is found. @param in Input stream to read from. @param separator Separator bytes to skip until. @return True iff the separator was encountered. @throws IOException if unable to read from stream.
[ "Skip", "all", "bytes", "in", "stream", "until", "(", "and", "including", ")", "given", "separator", "is", "found", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/io/IOUtils.java#L81-L91
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsPreferences.java
CmsPreferences.buildSelectProject
public String buildSelectProject(String htmlAttributes) { SelectOptions selectOptions = getProjectSelectOptions(); return buildSelect(htmlAttributes, selectOptions); }
java
public String buildSelectProject(String htmlAttributes) { SelectOptions selectOptions = getProjectSelectOptions(); return buildSelect(htmlAttributes, selectOptions); }
[ "public", "String", "buildSelectProject", "(", "String", "htmlAttributes", ")", "{", "SelectOptions", "selectOptions", "=", "getProjectSelectOptions", "(", ")", ";", "return", "buildSelect", "(", "htmlAttributes", ",", "selectOptions", ")", ";", "}" ]
Builds the html for the project select box of the start settings.<p> @param htmlAttributes optional html attributes for the &lgt;select&gt; tag @return the html for the project select box
[ "Builds", "the", "html", "for", "the", "project", "select", "box", "of", "the", "start", "settings", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsPreferences.java#L797-L802
OpenLiberty/open-liberty
dev/com.ibm.ws.springboot.utility/src/com/ibm/ws/springboot/utility/tasks/BaseCommandTask.java
BaseCommandTask.getArgumentValue
protected String getArgumentValue(String arg, String[] args, ConsoleWrapper stdin, PrintStream stdout) { for (int i = 1; i < args.length; i++) { String key = args[i].split("=")[0]; if (key.equals(arg)) { return getValue(args[i]); } } return null; }
java
protected String getArgumentValue(String arg, String[] args, ConsoleWrapper stdin, PrintStream stdout) { for (int i = 1; i < args.length; i++) { String key = args[i].split("=")[0]; if (key.equals(arg)) { return getValue(args[i]); } } return null; }
[ "protected", "String", "getArgumentValue", "(", "String", "arg", ",", "String", "[", "]", "args", ",", "ConsoleWrapper", "stdin", ",", "PrintStream", "stdout", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<", "args", ".", "length", ";", "i", ...
Gets the value for the specified argument String. No validation is done in the format of args as it is assumed to have been done previously. @param arg Argument name to resolve a value for @param args List of arguments. Assumes the script name is included and therefore minimum length is 2. @param stdin Standard in interface @param stdout Standard out interface @return Value of the argument @throws IllegalArgumentException if the argument is defined but no value is given.
[ "Gets", "the", "value", "for", "the", "specified", "argument", "String", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.springboot.utility/src/com/ibm/ws/springboot/utility/tasks/BaseCommandTask.java#L163-L171
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java
SharesInner.createOrUpdate
public ShareInner createOrUpdate(String deviceName, String name, String resourceGroupName, ShareInner share) { return createOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, share).toBlocking().last().body(); }
java
public ShareInner createOrUpdate(String deviceName, String name, String resourceGroupName, ShareInner share) { return createOrUpdateWithServiceResponseAsync(deviceName, name, resourceGroupName, share).toBlocking().last().body(); }
[ "public", "ShareInner", "createOrUpdate", "(", "String", "deviceName", ",", "String", "name", ",", "String", "resourceGroupName", ",", "ShareInner", "share", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "deviceName", ",", "name", ",", "resourceGr...
Creates a new share or updates an existing share on the device. @param deviceName The device name. @param name The share name. @param resourceGroupName The resource group name. @param share The share properties. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ShareInner object if successful.
[ "Creates", "a", "new", "share", "or", "updates", "an", "existing", "share", "on", "the", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/SharesInner.java#L331-L333
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/fit/OurColumnFixture.java
OurColumnFixture.parseIntArg
protected Integer parseIntArg(int index, Integer defaultValue) { Integer result = defaultValue; try { String argValue = getStringArg(index); if (argValue != null && !"".equals(argValue)) { result = Integer.valueOf(argValue); } } catch (NumberFormatException e) { // don't show just ignore, we will return null } return result; }
java
protected Integer parseIntArg(int index, Integer defaultValue) { Integer result = defaultValue; try { String argValue = getStringArg(index); if (argValue != null && !"".equals(argValue)) { result = Integer.valueOf(argValue); } } catch (NumberFormatException e) { // don't show just ignore, we will return null } return result; }
[ "protected", "Integer", "parseIntArg", "(", "int", "index", ",", "Integer", "defaultValue", ")", "{", "Integer", "result", "=", "defaultValue", ";", "try", "{", "String", "argValue", "=", "getStringArg", "(", "index", ")", ";", "if", "(", "argValue", "!=", ...
Gets fixture parameter (i.e. extra column in header row). Please note this can not be called from a constructor, as the parameters will not have been initialized yet! @param index index (zero based) to get value from. @param defaultValue value to use if parameter is not present or was no int. @return parameter value, if present and an integer, defaultValue otherwise.
[ "Gets", "fixture", "parameter", "(", "i", ".", "e", ".", "extra", "column", "in", "header", "row", ")", ".", "Please", "note", "this", "can", "not", "be", "called", "from", "a", "constructor", "as", "the", "parameters", "will", "not", "have", "been", "...
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/fit/OurColumnFixture.java#L45-L56
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Notification.java
Notification.setCooldownExpirationByTriggerAndMetric
public void setCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric, long cooldownExpiration) { requireArgument(cooldownExpiration >= 0, "Cool down expiration time cannot be negative."); String key = _hashTriggerAndMetric(trigger, metric); this.cooldownExpirationByTriggerAndMetric.put(key, cooldownExpiration); }
java
public void setCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric, long cooldownExpiration) { requireArgument(cooldownExpiration >= 0, "Cool down expiration time cannot be negative."); String key = _hashTriggerAndMetric(trigger, metric); this.cooldownExpirationByTriggerAndMetric.put(key, cooldownExpiration); }
[ "public", "void", "setCooldownExpirationByTriggerAndMetric", "(", "Trigger", "trigger", ",", "Metric", "metric", ",", "long", "cooldownExpiration", ")", "{", "requireArgument", "(", "cooldownExpiration", ">=", "0", ",", "\"Cool down expiration time cannot be negative.\"", "...
Sets the cool down expiration time of the notification given a metric,trigger combination. @param trigger The trigger @param metric The metric @param cooldownExpiration cool down expiration time in milliseconds
[ "Sets", "the", "cool", "down", "expiration", "time", "of", "the", "notification", "given", "a", "metric", "trigger", "combination", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Notification.java#L510-L515
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfContentByte.java
PdfContentByte.setLineDash
public final void setLineDash(float[] array, float phase) { content.append("["); for (int i = 0; i < array.length; i++) { content.append(array[i]); if (i < array.length - 1) content.append(' '); } content.append("] ").append(phase).append(" d").append_i(separator); }
java
public final void setLineDash(float[] array, float phase) { content.append("["); for (int i = 0; i < array.length; i++) { content.append(array[i]); if (i < array.length - 1) content.append(' '); } content.append("] ").append(phase).append(" d").append_i(separator); }
[ "public", "final", "void", "setLineDash", "(", "float", "[", "]", "array", ",", "float", "phase", ")", "{", "content", ".", "append", "(", "\"[\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++",...
Changes the value of the <VAR>line dash pattern</VAR>. <P> The line dash pattern controls the pattern of dashes and gaps used to stroke paths. It is specified by an <I>array</I> and a <I>phase</I>. The array specifies the length of the alternating dashes and gaps. The phase specifies the distance into the dash pattern to start the dash.<BR> @param array length of the alternating dashes and gaps @param phase the value of the phase
[ "Changes", "the", "value", "of", "the", "<VAR", ">", "line", "dash", "pattern<", "/", "VAR", ">", ".", "<P", ">", "The", "line", "dash", "pattern", "controls", "the", "pattern", "of", "dashes", "and", "gaps", "used", "to", "stroke", "paths", ".", "It",...
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L415-L422
OpenTSDB/opentsdb
src/utils/DateTime.java
DateTime.msFromNanoDiff
public static double msFromNanoDiff(final long end, final long start) { if (end < start) { throw new IllegalArgumentException("End (" + end + ") cannot be less " + "than start (" + start + ")"); } return ((double) end - (double) start) / 1000000; }
java
public static double msFromNanoDiff(final long end, final long start) { if (end < start) { throw new IllegalArgumentException("End (" + end + ") cannot be less " + "than start (" + start + ")"); } return ((double) end - (double) start) / 1000000; }
[ "public", "static", "double", "msFromNanoDiff", "(", "final", "long", "end", ",", "final", "long", "start", ")", "{", "if", "(", "end", "<", "start", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"End (\"", "+", "end", "+", "\") cannot be less...
Calculates the difference between two values and returns the time in milliseconds as a double. @param end The end timestamp @param start The start timestamp @return The value in milliseconds @throws IllegalArgumentException if end is less than start @since 2.2
[ "Calculates", "the", "difference", "between", "two", "values", "and", "returns", "the", "time", "in", "milliseconds", "as", "a", "double", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/utils/DateTime.java#L385-L391
hellosign/hellosign-java-sdk
src/main/java/com/hellosign/sdk/resource/TemplateSignatureRequest.java
TemplateSignatureRequest.setCustomFields
public void setCustomFields(Map<String, String> fields) { clearCustomFields(); for (String key : fields.keySet()) { CustomField f = new CustomField(); f.setName(key); f.setValue(fields.get(key)); customFields.add(f); } }
java
public void setCustomFields(Map<String, String> fields) { clearCustomFields(); for (String key : fields.keySet()) { CustomField f = new CustomField(); f.setName(key); f.setValue(fields.get(key)); customFields.add(f); } }
[ "public", "void", "setCustomFields", "(", "Map", "<", "String", ",", "String", ">", "fields", ")", "{", "clearCustomFields", "(", ")", ";", "for", "(", "String", "key", ":", "fields", ".", "keySet", "(", ")", ")", "{", "CustomField", "f", "=", "new", ...
Overwrites the current map of custom fields to the provided map. This is a map of String field names to String field values. @param fields Map
[ "Overwrites", "the", "current", "map", "of", "custom", "fields", "to", "the", "provided", "map", ".", "This", "is", "a", "map", "of", "String", "field", "names", "to", "String", "field", "values", "." ]
train
https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/resource/TemplateSignatureRequest.java#L238-L246
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java
BatchTask.constructLogString
public static String constructLogString(String message, String taskName, AbstractInvokable parent) { return message + ": " + taskName + " (" + (parent.getEnvironment().getTaskInfo().getIndexOfThisSubtask() + 1) + '/' + parent.getEnvironment().getTaskInfo().getNumberOfParallelSubtasks() + ')'; }
java
public static String constructLogString(String message, String taskName, AbstractInvokable parent) { return message + ": " + taskName + " (" + (parent.getEnvironment().getTaskInfo().getIndexOfThisSubtask() + 1) + '/' + parent.getEnvironment().getTaskInfo().getNumberOfParallelSubtasks() + ')'; }
[ "public", "static", "String", "constructLogString", "(", "String", "message", ",", "String", "taskName", ",", "AbstractInvokable", "parent", ")", "{", "return", "message", "+", "\": \"", "+", "taskName", "+", "\" (\"", "+", "(", "parent", ".", "getEnvironment",...
Utility function that composes a string for logging purposes. The string includes the given message, the given name of the task and the index in its subtask group as well as the number of instances that exist in its subtask group. @param message The main message for the log. @param taskName The name of the task. @param parent The task that contains the code producing the message. @return The string for logging.
[ "Utility", "function", "that", "composes", "a", "string", "for", "logging", "purposes", ".", "The", "string", "includes", "the", "given", "message", "the", "given", "name", "of", "the", "task", "and", "the", "index", "in", "its", "subtask", "group", "as", ...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java#L1172-L1175
aspectran/aspectran
with-freemarker/src/main/java/com/aspectran/freemarker/directive/AbstractTrimDirectiveModel.java
AbstractTrimDirectiveModel.parseStringParameter
@SuppressWarnings("rawtypes") protected String parseStringParameter(Map params, String paramName) { Object paramModel = params.get(paramName); if (paramModel == null) { return null; } if (!(paramModel instanceof SimpleScalar)) { throw new IllegalArgumentException(paramName + " must be string"); } return ((SimpleScalar)paramModel).getAsString(); }
java
@SuppressWarnings("rawtypes") protected String parseStringParameter(Map params, String paramName) { Object paramModel = params.get(paramName); if (paramModel == null) { return null; } if (!(paramModel instanceof SimpleScalar)) { throw new IllegalArgumentException(paramName + " must be string"); } return ((SimpleScalar)paramModel).getAsString(); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "protected", "String", "parseStringParameter", "(", "Map", "params", ",", "String", "paramName", ")", "{", "Object", "paramModel", "=", "params", ".", "get", "(", "paramName", ")", ";", "if", "(", "paramModel"...
Parse string parameter. @param params the params @param paramName the param name @return the string
[ "Parse", "string", "parameter", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/with-freemarker/src/main/java/com/aspectran/freemarker/directive/AbstractTrimDirectiveModel.java#L77-L87
reactor/reactor-netty
src/main/java/reactor/netty/http/client/HttpClient.java
HttpClient.doOnRequestError
public final HttpClient doOnRequestError(BiConsumer<? super HttpClientRequest, ? super Throwable> doOnRequest) { Objects.requireNonNull(doOnRequest, "doOnRequest"); return new HttpClientDoOnError(this, doOnRequest, null); }
java
public final HttpClient doOnRequestError(BiConsumer<? super HttpClientRequest, ? super Throwable> doOnRequest) { Objects.requireNonNull(doOnRequest, "doOnRequest"); return new HttpClientDoOnError(this, doOnRequest, null); }
[ "public", "final", "HttpClient", "doOnRequestError", "(", "BiConsumer", "<", "?", "super", "HttpClientRequest", ",", "?", "super", "Throwable", ">", "doOnRequest", ")", "{", "Objects", ".", "requireNonNull", "(", "doOnRequest", ",", "\"doOnRequest\"", ")", ";", ...
Setup a callback called when {@link HttpClientRequest} has not been sent. Note that some mutation of {@link HttpClientRequest} performed late in lifecycle {@link #doOnRequest(BiConsumer)} or {@link RequestSender#send(BiFunction)} might not be visible if the error results from a connection failure. @param doOnRequest a consumer observing connected events @return a new {@link HttpClient}
[ "Setup", "a", "callback", "called", "when", "{", "@link", "HttpClientRequest", "}", "has", "not", "been", "sent", ".", "Note", "that", "some", "mutation", "of", "{", "@link", "HttpClientRequest", "}", "performed", "late", "in", "lifecycle", "{", "@link", "#d...
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L531-L534
mapsforge/mapsforge
mapsforge-map-reader/src/main/java/org/mapsforge/map/reader/header/MapFileHeader.java
MapFileHeader.readHeader
public void readHeader(ReadBuffer readBuffer, long fileSize) throws IOException { RequiredFields.readMagicByte(readBuffer); RequiredFields.readRemainingHeader(readBuffer); MapFileInfoBuilder mapFileInfoBuilder = new MapFileInfoBuilder(); RequiredFields.readFileVersion(readBuffer, mapFileInfoBuilder); RequiredFields.readFileSize(readBuffer, fileSize, mapFileInfoBuilder); RequiredFields.readMapDate(readBuffer, mapFileInfoBuilder); RequiredFields.readBoundingBox(readBuffer, mapFileInfoBuilder); RequiredFields.readTilePixelSize(readBuffer, mapFileInfoBuilder); RequiredFields.readProjectionName(readBuffer, mapFileInfoBuilder); OptionalFields.readOptionalFields(readBuffer, mapFileInfoBuilder); RequiredFields.readPoiTags(readBuffer, mapFileInfoBuilder); RequiredFields.readWayTags(readBuffer, mapFileInfoBuilder); readSubFileParameters(readBuffer, fileSize, mapFileInfoBuilder); this.mapFileInfo = mapFileInfoBuilder.build(); }
java
public void readHeader(ReadBuffer readBuffer, long fileSize) throws IOException { RequiredFields.readMagicByte(readBuffer); RequiredFields.readRemainingHeader(readBuffer); MapFileInfoBuilder mapFileInfoBuilder = new MapFileInfoBuilder(); RequiredFields.readFileVersion(readBuffer, mapFileInfoBuilder); RequiredFields.readFileSize(readBuffer, fileSize, mapFileInfoBuilder); RequiredFields.readMapDate(readBuffer, mapFileInfoBuilder); RequiredFields.readBoundingBox(readBuffer, mapFileInfoBuilder); RequiredFields.readTilePixelSize(readBuffer, mapFileInfoBuilder); RequiredFields.readProjectionName(readBuffer, mapFileInfoBuilder); OptionalFields.readOptionalFields(readBuffer, mapFileInfoBuilder); RequiredFields.readPoiTags(readBuffer, mapFileInfoBuilder); RequiredFields.readWayTags(readBuffer, mapFileInfoBuilder); readSubFileParameters(readBuffer, fileSize, mapFileInfoBuilder); this.mapFileInfo = mapFileInfoBuilder.build(); }
[ "public", "void", "readHeader", "(", "ReadBuffer", "readBuffer", ",", "long", "fileSize", ")", "throws", "IOException", "{", "RequiredFields", ".", "readMagicByte", "(", "readBuffer", ")", ";", "RequiredFields", ".", "readRemainingHeader", "(", "readBuffer", ")", ...
Reads and validates the header block from the map file. @param readBuffer the ReadBuffer for the file data. @param fileSize the size of the map file in bytes. @throws IOException if an error occurs while reading the file.
[ "Reads", "and", "validates", "the", "header", "block", "from", "the", "map", "file", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-reader/src/main/java/org/mapsforge/map/reader/header/MapFileHeader.java#L86-L113
micronaut-projects/micronaut-core
cli/src/main/groovy/io/micronaut/cli/console/logging/MicronautConsole.java
MicronautConsole.userInput
public String userInput(String message, String[] validResponses) { if (validResponses == null) { return userInput(message); } String question = createQuestion(message, validResponses); String response = userInput(question); for (String validResponse : validResponses) { if (validResponse.equalsIgnoreCase(response)) { return response; } } cursorMove = 0; return userInput("Invalid input. Must be one of ", validResponses); }
java
public String userInput(String message, String[] validResponses) { if (validResponses == null) { return userInput(message); } String question = createQuestion(message, validResponses); String response = userInput(question); for (String validResponse : validResponses) { if (validResponse.equalsIgnoreCase(response)) { return response; } } cursorMove = 0; return userInput("Invalid input. Must be one of ", validResponses); }
[ "public", "String", "userInput", "(", "String", "message", ",", "String", "[", "]", "validResponses", ")", "{", "if", "(", "validResponses", "==", "null", ")", "{", "return", "userInput", "(", "message", ")", ";", "}", "String", "question", "=", "createQue...
Replacement for AntBuilder.input() to eliminate dependency of GrailsScriptRunner on the Ant libraries. Prints a message and list of valid responses, then returns whatever the user enters (once they press &lt;return&gt;). If the user enters something that is not in the array of valid responses, the message is displayed again and the method waits for more input. It will display the message a maximum of three times before it gives up and returns <code>null</code>. @param message The message/question to display. @param validResponses An array of responses that the user is allowed to enter. Displayed after the message. @return The line of text entered by the user, or <code>null</code> if the user never entered a valid string.
[ "Replacement", "for", "AntBuilder", ".", "input", "()", "to", "eliminate", "dependency", "of", "GrailsScriptRunner", "on", "the", "Ant", "libraries", ".", "Prints", "a", "message", "and", "list", "of", "valid", "responses", "then", "returns", "whatever", "the", ...
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/cli/src/main/groovy/io/micronaut/cli/console/logging/MicronautConsole.java#L1058-L1072
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/BibTeXConverter.java
BibTeXConverter.loadDatabase
public BibTeXDatabase loadDatabase(InputStream is) throws IOException, ParseException { Reader reader = new InputStreamReader(is, "UTF-8"); BibTeXParser parser = new BibTeXParser() { @Override public void checkStringResolution(Key key, BibTeXString string) { if (string == null) { //ignore } } }; try { return parser.parse(reader); } catch (TokenMgrException err) { throw new ParseException("Could not parse BibTeX library: " + err.getMessage()); } }
java
public BibTeXDatabase loadDatabase(InputStream is) throws IOException, ParseException { Reader reader = new InputStreamReader(is, "UTF-8"); BibTeXParser parser = new BibTeXParser() { @Override public void checkStringResolution(Key key, BibTeXString string) { if (string == null) { //ignore } } }; try { return parser.parse(reader); } catch (TokenMgrException err) { throw new ParseException("Could not parse BibTeX library: " + err.getMessage()); } }
[ "public", "BibTeXDatabase", "loadDatabase", "(", "InputStream", "is", ")", "throws", "IOException", ",", "ParseException", "{", "Reader", "reader", "=", "new", "InputStreamReader", "(", "is", ",", "\"UTF-8\"", ")", ";", "BibTeXParser", "parser", "=", "new", "Bib...
<p>Loads a BibTeX database from a stream.</p> <p>This method does not close the given stream. The caller is responsible for closing it.</p> @param is the input stream to read from @return the BibTeX database @throws IOException if the database could not be read @throws ParseException if the database is invalid
[ "<p", ">", "Loads", "a", "BibTeX", "database", "from", "a", "stream", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "does", "not", "close", "the", "given", "stream", ".", "The", "caller", "is", "responsible", "for", "closing", "it", ".", "<",...
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/BibTeXConverter.java#L139-L155
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.server/src/com/ibm/ws/sib/comms/server/CommonServerReceiveListener.java
CommonServerReceiveListener.rejectHandshake
private void rejectHandshake(Conversation conversation, int requestNumber, String rejectedField) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "rejectHandshake", new Object[] { conversation, requestNumber, rejectedField }); SIConnectionLostException exception = new SIConnectionLostException( nls.getFormattedMessage("INVALID_PROP_SICO8012", null, null) ); FFDCFilter.processException(exception, CLASS_NAME + ".rejectHandshake", CommsConstants.COMMONSERVERRECEIVELISTENER_HSREJCT_01, this); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Invalid handshake type received - rejecting field:", rejectedField); StaticCATHelper.sendExceptionToClient(exception, CommsConstants.COMMONSERVERRECEIVELISTENER_HSREJCT_01, conversation, requestNumber); // At this point we really don't want anything more to do with this client - so close him closeConnection(conversation); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "rejectHandshake"); }
java
private void rejectHandshake(Conversation conversation, int requestNumber, String rejectedField) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "rejectHandshake", new Object[] { conversation, requestNumber, rejectedField }); SIConnectionLostException exception = new SIConnectionLostException( nls.getFormattedMessage("INVALID_PROP_SICO8012", null, null) ); FFDCFilter.processException(exception, CLASS_NAME + ".rejectHandshake", CommsConstants.COMMONSERVERRECEIVELISTENER_HSREJCT_01, this); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Invalid handshake type received - rejecting field:", rejectedField); StaticCATHelper.sendExceptionToClient(exception, CommsConstants.COMMONSERVERRECEIVELISTENER_HSREJCT_01, conversation, requestNumber); // At this point we really don't want anything more to do with this client - so close him closeConnection(conversation); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "rejectHandshake"); }
[ "private", "void", "rejectHandshake", "(", "Conversation", "conversation", ",", "int", "requestNumber", ",", "String", "rejectedField", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")",...
This method is used to inform the client that we are rejecting their handshake. Typically this will never happen unless a third party client is written, or an internal error occurs. However, we should check for an inproperly formatted handshake and inform the client if such an error occurs. @param conversation @param requestNumber @param rejectedField A String that indicates the field that was rejected.
[ "This", "method", "is", "used", "to", "inform", "the", "client", "that", "we", "are", "rejecting", "their", "handshake", ".", "Typically", "this", "will", "never", "happen", "unless", "a", "third", "party", "client", "is", "written", "or", "an", "internal", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.server/src/com/ibm/ws/sib/comms/server/CommonServerReceiveListener.java#L768-L796
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSDirectory.java
FSDirectory.getHdfsFileInfo
HdfsFileStatus getHdfsFileInfo(String src) { String srcs = normalizePath(src); byte[][] components = INodeDirectory.getPathComponents(srcs); readLock(); try { INode targetNode = rootDir.getNode(components); if (targetNode == null) { return null; } else { return createHdfsFileStatus(HdfsFileStatus.EMPTY_NAME, targetNode); } } finally { readUnlock(); } }
java
HdfsFileStatus getHdfsFileInfo(String src) { String srcs = normalizePath(src); byte[][] components = INodeDirectory.getPathComponents(srcs); readLock(); try { INode targetNode = rootDir.getNode(components); if (targetNode == null) { return null; } else { return createHdfsFileStatus(HdfsFileStatus.EMPTY_NAME, targetNode); } } finally { readUnlock(); } }
[ "HdfsFileStatus", "getHdfsFileInfo", "(", "String", "src", ")", "{", "String", "srcs", "=", "normalizePath", "(", "src", ")", ";", "byte", "[", "]", "[", "]", "components", "=", "INodeDirectory", ".", "getPathComponents", "(", "srcs", ")", ";", "readLock", ...
Get the file info for a specific file. @param src The string representation of the path to the file @return object containing information regarding the file or null if file not found
[ "Get", "the", "file", "info", "for", "a", "specific", "file", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSDirectory.java#L1852-L1867
line/armeria
core/src/main/java/com/linecorp/armeria/server/docs/DocServiceBuilder.java
DocServiceBuilder.exampleRequestForMethod
public DocServiceBuilder exampleRequestForMethod(Class<?> serviceType, String methodName, Object... exampleRequests) { requireNonNull(exampleRequests, "exampleRequests"); return exampleRequestForMethod(serviceType, methodName, ImmutableList.copyOf(exampleRequests)); }
java
public DocServiceBuilder exampleRequestForMethod(Class<?> serviceType, String methodName, Object... exampleRequests) { requireNonNull(exampleRequests, "exampleRequests"); return exampleRequestForMethod(serviceType, methodName, ImmutableList.copyOf(exampleRequests)); }
[ "public", "DocServiceBuilder", "exampleRequestForMethod", "(", "Class", "<", "?", ">", "serviceType", ",", "String", "methodName", ",", "Object", "...", "exampleRequests", ")", "{", "requireNonNull", "(", "exampleRequests", ",", "\"exampleRequests\"", ")", ";", "ret...
Adds the example requests for the method with the specified service type and method name. This method is a shortcut to: <pre>{@code exampleRequest(serviceType.getName(), exampleRequests); }</pre>
[ "Adds", "the", "example", "requests", "for", "the", "method", "with", "the", "specified", "service", "type", "and", "method", "name", ".", "This", "method", "is", "a", "shortcut", "to", ":", "<pre", ">", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/docs/DocServiceBuilder.java#L186-L190
mockito/mockito
src/main/java/org/mockito/internal/util/JavaEightUtil.java
JavaEightUtil.invokeNullaryFactoryMethod
private static Object invokeNullaryFactoryMethod(final String fqcn, final String methodName) { try { final Class<?> type = Class.forName(fqcn); final Method method = type.getMethod(methodName); return method.invoke(null); // any exception is really unexpected since the type name has // already been verified } catch (final Exception e) { throw new InstantiationException( String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e); } }
java
private static Object invokeNullaryFactoryMethod(final String fqcn, final String methodName) { try { final Class<?> type = Class.forName(fqcn); final Method method = type.getMethod(methodName); return method.invoke(null); // any exception is really unexpected since the type name has // already been verified } catch (final Exception e) { throw new InstantiationException( String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e); } }
[ "private", "static", "Object", "invokeNullaryFactoryMethod", "(", "final", "String", "fqcn", ",", "final", "String", "methodName", ")", "{", "try", "{", "final", "Class", "<", "?", ">", "type", "=", "Class", ".", "forName", "(", "fqcn", ")", ";", "final", ...
Invokes a nullary static factory method using reflection to stay backwards-compatible with older JDKs. @param fqcn The fully qualified class name of the type to be produced. @param methodName The name of the factory method. @return the object produced.
[ "Invokes", "a", "nullary", "static", "factory", "method", "using", "reflection", "to", "stay", "backwards", "-", "compatible", "with", "older", "JDKs", "." ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/internal/util/JavaEightUtil.java#L131-L143
h2oai/h2o-3
h2o-core/src/main/java/jsr166y/ForkJoinPool.java
ForkJoinPool.helpJoinOnce
final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) { int s; while ((s = task.status) >= 0 && (joiner.isEmpty() ? tryHelpStealer(joiner, task) : joiner.tryRemoveAndExec(task)) != 0) ; return s; }
java
final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) { int s; while ((s = task.status) >= 0 && (joiner.isEmpty() ? tryHelpStealer(joiner, task) : joiner.tryRemoveAndExec(task)) != 0) ; return s; }
[ "final", "int", "helpJoinOnce", "(", "WorkQueue", "joiner", ",", "ForkJoinTask", "<", "?", ">", "task", ")", "{", "int", "s", ";", "while", "(", "(", "s", "=", "task", ".", "status", ")", ">=", "0", "&&", "(", "joiner", ".", "isEmpty", "(", ")", ...
Stripped-down variant of awaitJoin used by timed joins. Tries to help join only while there is continuous progress. (Caller will then enter a timed wait.) @param joiner the joining worker @param task the task @return task status on exit
[ "Stripped", "-", "down", "variant", "of", "awaitJoin", "used", "by", "timed", "joins", ".", "Tries", "to", "help", "join", "only", "while", "there", "is", "continuous", "progress", ".", "(", "Caller", "will", "then", "enter", "a", "timed", "wait", ".", "...
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/jsr166y/ForkJoinPool.java#L1879-L1887
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/engine/bcel/AnalysisFactory.java
AnalysisFactory.getCFG
protected CFG getCFG(IAnalysisCache analysisCache, MethodDescriptor methodDescriptor) throws CheckedAnalysisException { return analysisCache.getMethodAnalysis(CFG.class, methodDescriptor); }
java
protected CFG getCFG(IAnalysisCache analysisCache, MethodDescriptor methodDescriptor) throws CheckedAnalysisException { return analysisCache.getMethodAnalysis(CFG.class, methodDescriptor); }
[ "protected", "CFG", "getCFG", "(", "IAnalysisCache", "analysisCache", ",", "MethodDescriptor", "methodDescriptor", ")", "throws", "CheckedAnalysisException", "{", "return", "analysisCache", ".", "getMethodAnalysis", "(", "CFG", ".", "class", ",", "methodDescriptor", ")"...
/* ---------------------------------------------------------------------- Helper methods to get required analysis objects. ----------------------------------------------------------------------
[ "/", "*", "----------------------------------------------------------------------", "Helper", "methods", "to", "get", "required", "analysis", "objects", ".", "----------------------------------------------------------------------" ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/classfile/engine/bcel/AnalysisFactory.java#L92-L94
mfornos/humanize
humanize-icu/src/main/java/humanize/ICUHumanize.java
ICUHumanize.compactDecimal
public static String compactDecimal(final Number value, final Locale locale) { return compactDecimal(value, CompactStyle.SHORT, locale); }
java
public static String compactDecimal(final Number value, final Locale locale) { return compactDecimal(value, CompactStyle.SHORT, locale); }
[ "public", "static", "String", "compactDecimal", "(", "final", "Number", "value", ",", "final", "Locale", "locale", ")", "{", "return", "compactDecimal", "(", "value", ",", "CompactStyle", ".", "SHORT", ",", "locale", ")", ";", "}" ]
<p> Same as {@link #compactDecimal(Number) compactDecimal} for the specified locale. </p> @param value The number to be abbreviated @param locale The locale @return a compact textual representation of the given value
[ "<p", ">", "Same", "as", "{", "@link", "#compactDecimal", "(", "Number", ")", "compactDecimal", "}", "for", "the", "specified", "locale", ".", "<", "/", "p", ">" ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-icu/src/main/java/humanize/ICUHumanize.java#L143-L146
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MembershipManager.java
MembershipManager.getMissingMember
MemberImpl getMissingMember(Address address, String uuid) { Map<Object, MemberImpl> m = missingMembersRef.get(); return isHotRestartEnabled() ? m.get(uuid) : m.get(address); }
java
MemberImpl getMissingMember(Address address, String uuid) { Map<Object, MemberImpl> m = missingMembersRef.get(); return isHotRestartEnabled() ? m.get(uuid) : m.get(address); }
[ "MemberImpl", "getMissingMember", "(", "Address", "address", ",", "String", "uuid", ")", "{", "Map", "<", "Object", ",", "MemberImpl", ">", "m", "=", "missingMembersRef", ".", "get", "(", ")", ";", "return", "isHotRestartEnabled", "(", ")", "?", "m", ".", ...
Returns the missing member using either its {@code UUID} or its {@code Address} depending on Hot Restart is enabled or not. @param address Address of the missing member @param uuid Uuid of the missing member @return the missing member
[ "Returns", "the", "missing", "member", "using", "either", "its", "{", "@code", "UUID", "}", "or", "its", "{", "@code", "Address", "}", "depending", "on", "Hot", "Restart", "is", "enabled", "or", "not", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MembershipManager.java#L966-L969
google/j2objc
jre_emul/Classes/com/google/j2objc/net/IosHttpURLConnection.java
IosHttpURLConnection.addHeader
private void addHeader(String k, String v) { if (k != null && (k.equalsIgnoreCase("Set-Cookie") || k.equalsIgnoreCase("Set-Cookie2"))) { CookieSplitter cs = new CookieSplitter(v); while (cs.hasNext()) { headers.add(new HeaderEntry(k, cs.next())); } } else { headers.add(new HeaderEntry(k, v)); } }
java
private void addHeader(String k, String v) { if (k != null && (k.equalsIgnoreCase("Set-Cookie") || k.equalsIgnoreCase("Set-Cookie2"))) { CookieSplitter cs = new CookieSplitter(v); while (cs.hasNext()) { headers.add(new HeaderEntry(k, cs.next())); } } else { headers.add(new HeaderEntry(k, v)); } }
[ "private", "void", "addHeader", "(", "String", "k", ",", "String", "v", ")", "{", "if", "(", "k", "!=", "null", "&&", "(", "k", ".", "equalsIgnoreCase", "(", "\"Set-Cookie\"", ")", "||", "k", ".", "equalsIgnoreCase", "(", "\"Set-Cookie2\"", ")", ")", "...
/*-[ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler { if (self->instanceFollowRedirects_ && [response.URL.scheme isEqualToString:request.URL.scheme]) { completionHandler(request); } else { completionHandler(nil); } } ]-
[ "/", "*", "-", "[", "-", "(", "void", ")", "URLSession", ":", "(", "NSURLSession", "*", ")", "session", "task", ":", "(", "NSURLSessionTask", "*", ")", "task", "willPerformHTTPRedirection", ":", "(", "NSHTTPURLResponse", "*", ")", "response", "newRequest", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/Classes/com/google/j2objc/net/IosHttpURLConnection.java#L786-L795
CloudSlang/cs-actions
cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java
WSManUtils.verifyScriptExecutionStatus
public static void verifyScriptExecutionStatus(final Map<String, String> resultMap) { if (ZERO_SCRIPT_EXIT_CODE.equals(resultMap.get(SCRIPT_EXIT_CODE))) { resultMap.put(RETURN_CODE, RETURN_CODE_SUCCESS); } else { resultMap.put(RETURN_CODE, RETURN_CODE_FAILURE); } }
java
public static void verifyScriptExecutionStatus(final Map<String, String> resultMap) { if (ZERO_SCRIPT_EXIT_CODE.equals(resultMap.get(SCRIPT_EXIT_CODE))) { resultMap.put(RETURN_CODE, RETURN_CODE_SUCCESS); } else { resultMap.put(RETURN_CODE, RETURN_CODE_FAILURE); } }
[ "public", "static", "void", "verifyScriptExecutionStatus", "(", "final", "Map", "<", "String", ",", "String", ">", "resultMap", ")", "{", "if", "(", "ZERO_SCRIPT_EXIT_CODE", ".", "equals", "(", "resultMap", ".", "get", "(", "SCRIPT_EXIT_CODE", ")", ")", ")", ...
Checks the scriptExitCode value of the script execution and fails the operation if exit code is different than zero. @param resultMap
[ "Checks", "the", "scriptExitCode", "value", "of", "the", "script", "execution", "and", "fails", "the", "operation", "if", "exit", "code", "is", "different", "than", "zero", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/utils/WSManUtils.java#L162-L168
Angads25/android-filepicker
app/src/main/java/com/github/angads25/filepickerdemo/MainActivity.java
MainActivity.onRequestPermissionsResult
@Override public void onRequestPermissionsResult(int requestCode,@NonNull String permissions[],@NonNull int[] grantResults) { switch (requestCode) { case FilePickerDialog.EXTERNAL_READ_PERMISSION_GRANT: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if(dialog!=null) { //Show dialog if the read permission has been granted. dialog.show(); } } else { //Permission has not been granted. Notify the user. Toast.makeText(MainActivity.this,"Permission is Required for getting list of files",Toast.LENGTH_SHORT).show(); } } } }
java
@Override public void onRequestPermissionsResult(int requestCode,@NonNull String permissions[],@NonNull int[] grantResults) { switch (requestCode) { case FilePickerDialog.EXTERNAL_READ_PERMISSION_GRANT: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if(dialog!=null) { //Show dialog if the read permission has been granted. dialog.show(); } } else { //Permission has not been granted. Notify the user. Toast.makeText(MainActivity.this,"Permission is Required for getting list of files",Toast.LENGTH_SHORT).show(); } } } }
[ "@", "Override", "public", "void", "onRequestPermissionsResult", "(", "int", "requestCode", ",", "@", "NonNull", "String", "permissions", "[", "]", ",", "@", "NonNull", "int", "[", "]", "grantResults", ")", "{", "switch", "(", "requestCode", ")", "{", "case"...
Add this method to show Dialog when the required permission has been granted to the app.
[ "Add", "this", "method", "to", "show", "Dialog", "when", "the", "required", "permission", "has", "been", "granted", "to", "the", "app", "." ]
train
https://github.com/Angads25/android-filepicker/blob/46fd8825e6d88c69462078a0300d905739a803ea/app/src/main/java/com/github/angads25/filepickerdemo/MainActivity.java#L217-L233
JodaOrg/joda-time
src/main/java/org/joda/time/convert/ReadableInstantConverter.java
ReadableInstantConverter.getChronology
public Chronology getChronology(Object object, DateTimeZone zone) { Chronology chrono = ((ReadableInstant) object).getChronology(); if (chrono == null) { return ISOChronology.getInstance(zone); } DateTimeZone chronoZone = chrono.getZone(); if (chronoZone != zone) { chrono = chrono.withZone(zone); if (chrono == null) { return ISOChronology.getInstance(zone); } } return chrono; }
java
public Chronology getChronology(Object object, DateTimeZone zone) { Chronology chrono = ((ReadableInstant) object).getChronology(); if (chrono == null) { return ISOChronology.getInstance(zone); } DateTimeZone chronoZone = chrono.getZone(); if (chronoZone != zone) { chrono = chrono.withZone(zone); if (chrono == null) { return ISOChronology.getInstance(zone); } } return chrono; }
[ "public", "Chronology", "getChronology", "(", "Object", "object", ",", "DateTimeZone", "zone", ")", "{", "Chronology", "chrono", "=", "(", "(", "ReadableInstant", ")", "object", ")", ".", "getChronology", "(", ")", ";", "if", "(", "chrono", "==", "null", "...
Gets the chronology, which is taken from the ReadableInstant. If the chronology on the instant is null, the ISOChronology in the specified time zone is used. If the chronology on the instant is not in the specified zone, it is adapted. @param object the ReadableInstant to convert, must not be null @param zone the specified zone to use, null means default zone @return the chronology, never null
[ "Gets", "the", "chronology", "which", "is", "taken", "from", "the", "ReadableInstant", ".", "If", "the", "chronology", "on", "the", "instant", "is", "null", "the", "ISOChronology", "in", "the", "specified", "time", "zone", "is", "used", ".", "If", "the", "...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/convert/ReadableInstantConverter.java#L57-L70
ag-gipp/MathMLTools
mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/MathPlag.java
MathPlag.compareIdenticalMathML
public static List<Match> compareIdenticalMathML(String refMathML, String compMathML) throws MathNodeException { // switch from a string > CMMLInfo document > MathNode tree MathNode refMathNode; MathNode compMathNode; try { refMathNode = MathNodeGenerator.generateMathNode(new CMMLInfo(refMathML)); } catch (MathNodeException e) { throw new MathNodeException("could not create math node for reference mathml: " + refMathML, e); } try { compMathNode = MathNodeGenerator.generateMathNode(new CMMLInfo(compMathML)); } catch (MathNodeException e) { throw new MathNodeException("could not create math node for comparison mathml: " + compMathML, e); } return new SubTreeComparison(SimilarityType.identical).getSimilarities(refMathNode, compMathNode, true); }
java
public static List<Match> compareIdenticalMathML(String refMathML, String compMathML) throws MathNodeException { // switch from a string > CMMLInfo document > MathNode tree MathNode refMathNode; MathNode compMathNode; try { refMathNode = MathNodeGenerator.generateMathNode(new CMMLInfo(refMathML)); } catch (MathNodeException e) { throw new MathNodeException("could not create math node for reference mathml: " + refMathML, e); } try { compMathNode = MathNodeGenerator.generateMathNode(new CMMLInfo(compMathML)); } catch (MathNodeException e) { throw new MathNodeException("could not create math node for comparison mathml: " + compMathML, e); } return new SubTreeComparison(SimilarityType.identical).getSimilarities(refMathNode, compMathNode, true); }
[ "public", "static", "List", "<", "Match", ">", "compareIdenticalMathML", "(", "String", "refMathML", ",", "String", "compMathML", ")", "throws", "MathNodeException", "{", "// switch from a string > CMMLInfo document > MathNode tree", "MathNode", "refMathNode", ";", "MathNod...
Compare two MathML formulas against each other. The MathML string will be transformed into a {@link CMMLInfo} document and then to a {@link MathNode} tree. <br/> The formulas are compared to find identical structures. @param refMathML Reference MathML string (must contain pMML and cMML) @param compMathML Comparison MathML string (must contain pMML and cMML) @return list of matches / similarities, list can be empty.
[ "Compare", "two", "MathML", "formulas", "against", "each", "other", ".", "The", "MathML", "string", "will", "be", "transformed", "into", "a", "{", "@link", "CMMLInfo", "}", "document", "and", "then", "to", "a", "{", "@link", "MathNode", "}", "tree", ".", ...
train
https://github.com/ag-gipp/MathMLTools/blob/77c69b6366a5b8720796d1cd9d155ba26c2f1b20/mathml-similarity/src/main/java/com/formulasearchengine/mathmltools/similarity/MathPlag.java#L45-L60
facebookarchive/hadoop-20
src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/AvatarZooKeeperClient.java
AvatarZooKeeperClient.getPrimarySsId
public Long getPrimarySsId(String address, boolean sync) throws IOException, KeeperException, InterruptedException, ClassNotFoundException { Stat stat = new Stat(); String node = getSsIdNode(address); byte[] data = getNodeData(node, stat, false, sync); if (data == null) { return null; } return (Long) SerializableUtils.getFromBytes(data, Long.class); }
java
public Long getPrimarySsId(String address, boolean sync) throws IOException, KeeperException, InterruptedException, ClassNotFoundException { Stat stat = new Stat(); String node = getSsIdNode(address); byte[] data = getNodeData(node, stat, false, sync); if (data == null) { return null; } return (Long) SerializableUtils.getFromBytes(data, Long.class); }
[ "public", "Long", "getPrimarySsId", "(", "String", "address", ",", "boolean", "sync", ")", "throws", "IOException", ",", "KeeperException", ",", "InterruptedException", ",", "ClassNotFoundException", "{", "Stat", "stat", "=", "new", "Stat", "(", ")", ";", "Strin...
Retrieves the current session id for the cluster from zookeeper. @param address the address of the cluster @param sync whether or not to perform a sync before read @throws IOException @throws KeeperException @throws InterruptedException
[ "Retrieves", "the", "current", "session", "id", "for", "the", "cluster", "from", "zookeeper", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/AvatarZooKeeperClient.java#L329-L338
apache/flink
flink-core/src/main/java/org/apache/flink/api/common/io/FileInputFormat.java
FileInputFormat.decorateInputStream
protected FSDataInputStream decorateInputStream(FSDataInputStream inputStream, FileInputSplit fileSplit) throws Throwable { // Wrap stream in a extracting (decompressing) stream if file ends with a known compression file extension. InflaterInputStreamFactory<?> inflaterInputStreamFactory = getInflaterInputStreamFactory(fileSplit.getPath()); if (inflaterInputStreamFactory != null) { return new InputStreamFSInputWrapper(inflaterInputStreamFactory.create(stream)); } return inputStream; }
java
protected FSDataInputStream decorateInputStream(FSDataInputStream inputStream, FileInputSplit fileSplit) throws Throwable { // Wrap stream in a extracting (decompressing) stream if file ends with a known compression file extension. InflaterInputStreamFactory<?> inflaterInputStreamFactory = getInflaterInputStreamFactory(fileSplit.getPath()); if (inflaterInputStreamFactory != null) { return new InputStreamFSInputWrapper(inflaterInputStreamFactory.create(stream)); } return inputStream; }
[ "protected", "FSDataInputStream", "decorateInputStream", "(", "FSDataInputStream", "inputStream", ",", "FileInputSplit", "fileSplit", ")", "throws", "Throwable", "{", "// Wrap stream in a extracting (decompressing) stream if file ends with a known compression file extension.", "InflaterI...
This method allows to wrap/decorate the raw {@link FSDataInputStream} for a certain file split, e.g., for decoding. When overriding this method, also consider adapting {@link FileInputFormat#testForUnsplittable} if your stream decoration renders the input file unsplittable. Also consider calling existing superclass implementations. @param inputStream is the input stream to decorated @param fileSplit is the file split for which the input stream shall be decorated @return the decorated input stream @throws Throwable if the decoration fails @see org.apache.flink.api.common.io.InputStreamFSInputWrapper
[ "This", "method", "allows", "to", "wrap", "/", "decorate", "the", "raw", "{", "@link", "FSDataInputStream", "}", "for", "a", "certain", "file", "split", "e", ".", "g", ".", "for", "decoding", ".", "When", "overriding", "this", "method", "also", "consider",...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/common/io/FileInputFormat.java#L844-L852
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java
MasterWorkerInfo.updateUsedBytes
public void updateUsedBytes(String tierAlias, long usedBytesOnTier) { mUsedBytes += usedBytesOnTier - mUsedBytesOnTiers.get(tierAlias); mUsedBytesOnTiers.put(tierAlias, usedBytesOnTier); }
java
public void updateUsedBytes(String tierAlias, long usedBytesOnTier) { mUsedBytes += usedBytesOnTier - mUsedBytesOnTiers.get(tierAlias); mUsedBytesOnTiers.put(tierAlias, usedBytesOnTier); }
[ "public", "void", "updateUsedBytes", "(", "String", "tierAlias", ",", "long", "usedBytesOnTier", ")", "{", "mUsedBytes", "+=", "usedBytesOnTier", "-", "mUsedBytesOnTiers", ".", "get", "(", "tierAlias", ")", ";", "mUsedBytesOnTiers", ".", "put", "(", "tierAlias", ...
Sets the used space of the worker in bytes. @param tierAlias alias of storage tier @param usedBytesOnTier used bytes on certain storage tier
[ "Sets", "the", "used", "space", "of", "the", "worker", "in", "bytes", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/block/meta/MasterWorkerInfo.java#L439-L442
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/bagofwords/vectorizer/TfidfVectorizer.java
TfidfVectorizer.vectorize
@Override public DataSet vectorize(InputStream is, String label) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = ""; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line); } return vectorize(builder.toString(), label); } catch (Exception e) { throw new RuntimeException(e); } }
java
@Override public DataSet vectorize(InputStream is, String label) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = ""; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line); } return vectorize(builder.toString(), label); } catch (Exception e) { throw new RuntimeException(e); } }
[ "@", "Override", "public", "DataSet", "vectorize", "(", "InputStream", "is", ",", "String", "label", ")", "{", "try", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "is", ",", "\"UTF-8\"", ")", ")", ";", ...
Text coming from an input stream considered as one document @param is the input stream to read from @param label the label to assign @return a dataset with a applyTransformToDestination of weights(relative to impl; could be word counts or tfidf scores)
[ "Text", "coming", "from", "an", "input", "stream", "considered", "as", "one", "document" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/bagofwords/vectorizer/TfidfVectorizer.java#L58-L71
mikepenz/Materialize
library/src/main/java/com/mikepenz/materialize/util/UIUtils.java
UIUtils.getStatusBarHeight
public static int getStatusBarHeight(Context context, boolean force) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding); //if our dimension is 0 return 0 because on those devices we don't need the height if (dimenResult == 0 && !force) { return 0; } else { //if our dimens is > 0 && the result == 0 use the dimenResult else the result; return result == 0 ? dimenResult : result; } }
java
public static int getStatusBarHeight(Context context, boolean force) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding); //if our dimension is 0 return 0 because on those devices we don't need the height if (dimenResult == 0 && !force) { return 0; } else { //if our dimens is > 0 && the result == 0 use the dimenResult else the result; return result == 0 ? dimenResult : result; } }
[ "public", "static", "int", "getStatusBarHeight", "(", "Context", "context", ",", "boolean", "force", ")", "{", "int", "result", "=", "0", ";", "int", "resourceId", "=", "context", ".", "getResources", "(", ")", ".", "getIdentifier", "(", "\"status_bar_height\"...
helper to calculate the statusBar height @param context @param force pass true to get the height even if the device has no translucent statusBar @return
[ "helper", "to", "calculate", "the", "statusBar", "height" ]
train
https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L150-L165
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/vector/AmortizedSparseVector.java
AmortizedSparseVector.set
public void set(int index, double value) { checkIndex(index); IndexValue item = new IndexValue(index, 0); int valueIndex = Collections.binarySearch(values, item, comp); if (valueIndex >= 0 && value != 0d) { // Replace a currently existing item with a non zero value. values.get(valueIndex).value = value; } else if (value != 0d) { // Add a new cell item into this row. item.value = value; values.add((valueIndex + 1) * -1, item); } else if (valueIndex >= 0) { // Remove the value since it's now zero. values.remove(valueIndex); } }
java
public void set(int index, double value) { checkIndex(index); IndexValue item = new IndexValue(index, 0); int valueIndex = Collections.binarySearch(values, item, comp); if (valueIndex >= 0 && value != 0d) { // Replace a currently existing item with a non zero value. values.get(valueIndex).value = value; } else if (value != 0d) { // Add a new cell item into this row. item.value = value; values.add((valueIndex + 1) * -1, item); } else if (valueIndex >= 0) { // Remove the value since it's now zero. values.remove(valueIndex); } }
[ "public", "void", "set", "(", "int", "index", ",", "double", "value", ")", "{", "checkIndex", "(", "index", ")", ";", "IndexValue", "item", "=", "new", "IndexValue", "(", "index", ",", "0", ")", ";", "int", "valueIndex", "=", "Collections", ".", "binar...
{@inheritDoc} All read operations, and writes to indices which already exist are of time O(log n). Writers to new indices are of time O(log n).
[ "{", "@inheritDoc", "}" ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/vector/AmortizedSparseVector.java#L140-L156
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/VoiceApi.java
VoiceApi.startRecording
public ApiSuccessResponse startRecording(String id, StartRecordingBody startRecordingBody) throws ApiException { ApiResponse<ApiSuccessResponse> resp = startRecordingWithHttpInfo(id, startRecordingBody); return resp.getData(); }
java
public ApiSuccessResponse startRecording(String id, StartRecordingBody startRecordingBody) throws ApiException { ApiResponse<ApiSuccessResponse> resp = startRecordingWithHttpInfo(id, startRecordingBody); return resp.getData(); }
[ "public", "ApiSuccessResponse", "startRecording", "(", "String", "id", ",", "StartRecordingBody", "startRecordingBody", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "startRecordingWithHttpInfo", "(", "id", ",", "startRe...
Start recording a call Start recording the specified call. Recording stops when the call is completed or you send [/voice/calls/{id}/stop-recording](/reference/workspace/Voice/index.html#stopRecording) on either the call or the DN. @param id The connection ID of the call. (required) @param startRecordingBody Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Start", "recording", "a", "call", "Start", "recording", "the", "specified", "call", ".", "Recording", "stops", "when", "the", "call", "is", "completed", "or", "you", "send", "[", "/", "voice", "/", "calls", "/", "{", "id", "}", "/", "stop", "-", "reco...
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/VoiceApi.java#L4596-L4599
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/authentication/authenticationauthnprofile.java
authenticationauthnprofile.get
public static authenticationauthnprofile get(nitro_service service, String name) throws Exception{ authenticationauthnprofile obj = new authenticationauthnprofile(); obj.set_name(name); authenticationauthnprofile response = (authenticationauthnprofile) obj.get_resource(service); return response; }
java
public static authenticationauthnprofile get(nitro_service service, String name) throws Exception{ authenticationauthnprofile obj = new authenticationauthnprofile(); obj.set_name(name); authenticationauthnprofile response = (authenticationauthnprofile) obj.get_resource(service); return response; }
[ "public", "static", "authenticationauthnprofile", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "authenticationauthnprofile", "obj", "=", "new", "authenticationauthnprofile", "(", ")", ";", "obj", ".", "set_name", "(...
Use this API to fetch authenticationauthnprofile resource of given name .
[ "Use", "this", "API", "to", "fetch", "authenticationauthnprofile", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/authentication/authenticationauthnprofile.java#L356-L361
Whiley/WhileyCompiler
src/main/java/wyil/transform/VerificationConditionGenerator.java
VerificationConditionGenerator.translateRecordAssign
private Context translateRecordAssign(WyilFile.Expr.RecordAccess lval, Expr rval, Context context) { // Translate src expression Pair<Expr, Context> p1 = translateExpressionWithChecks(lval.getOperand(), null, context); Expr source = p1.first(); WyalFile.Identifier field = new WyalFile.Identifier(lval.getField().toString()); // Construct record update for "pass thru" Expr update = new Expr.RecordUpdate(source, field, rval); return translateSingleAssignment((WyilFile.LVal) lval.getOperand(), update, p1.second()); }
java
private Context translateRecordAssign(WyilFile.Expr.RecordAccess lval, Expr rval, Context context) { // Translate src expression Pair<Expr, Context> p1 = translateExpressionWithChecks(lval.getOperand(), null, context); Expr source = p1.first(); WyalFile.Identifier field = new WyalFile.Identifier(lval.getField().toString()); // Construct record update for "pass thru" Expr update = new Expr.RecordUpdate(source, field, rval); return translateSingleAssignment((WyilFile.LVal) lval.getOperand(), update, p1.second()); }
[ "private", "Context", "translateRecordAssign", "(", "WyilFile", ".", "Expr", ".", "RecordAccess", "lval", ",", "Expr", "rval", ",", "Context", "context", ")", "{", "// Translate src expression", "Pair", "<", "Expr", ",", "Context", ">", "p1", "=", "translateExpr...
Translate an assignment to a field. @param lval The field access expression @param result The value being assigned to the given array element @param context The enclosing context @return
[ "Translate", "an", "assignment", "to", "a", "field", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L621-L629
tzaeschke/zoodb
src/org/zoodb/internal/server/DiskAccessOneFile.java
DiskAccessOneFile.readObject
@Override public ZooPC readObject(DataDeSerializer dds, long oid) { FilePos oie = oidIndex.findOid(oid); if (oie == null) { throw DBLogger.newObjectNotFoundException("OID not found: " + Util.oidToString(oid)); } return dds.readObject(oie.getPage(), oie.getOffs(), false); }
java
@Override public ZooPC readObject(DataDeSerializer dds, long oid) { FilePos oie = oidIndex.findOid(oid); if (oie == null) { throw DBLogger.newObjectNotFoundException("OID not found: " + Util.oidToString(oid)); } return dds.readObject(oie.getPage(), oie.getOffs(), false); }
[ "@", "Override", "public", "ZooPC", "readObject", "(", "DataDeSerializer", "dds", ",", "long", "oid", ")", "{", "FilePos", "oie", "=", "oidIndex", ".", "findOid", "(", "oid", ")", ";", "if", "(", "oie", "==", "null", ")", "{", "throw", "DBLogger", ".",...
Locate an object. This version allows providing a data de-serializer. This will be handy later if we want to implement some concurrency, which requires using multiple of the stateful DeSerializers. @param dds DataDeSerializer @param oid Object ID @return Path name of the object (later: position of obj)
[ "Locate", "an", "object", ".", "This", "version", "allows", "providing", "a", "data", "de", "-", "serializer", ".", "This", "will", "be", "handy", "later", "if", "we", "want", "to", "implement", "some", "concurrency", "which", "requires", "using", "multiple"...
train
https://github.com/tzaeschke/zoodb/blob/058d0ff161a8ee9d53244c433aca97ee9c654410/src/org/zoodb/internal/server/DiskAccessOneFile.java#L391-L399
Impetus/Kundera
src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/DocumentIndexer.java
DocumentIndexer.addFieldToDocument
private void addFieldToDocument(Object object, Document document, java.lang.reflect.Field field, String colName, String indexName) { try { Object obj = PropertyAccessorHelper.getObject(object, field); // String str = // String value = (obj == null) ? null : obj.toString(); if (obj != null) { Field luceneField = new Field(getCannonicalPropertyName(indexName, colName), obj.toString(), Field.Store.YES, Field.Index.ANALYZED_NO_NORMS); document.add(luceneField); } else { LOG.warn("value is null for field" + field.getName()); } } catch (PropertyAccessException e) { LOG.error("Error in accessing field, Caused by:" + e.getMessage()); throw new LuceneIndexingException("Error in accessing field:" + field.getName(), e); } }
java
private void addFieldToDocument(Object object, Document document, java.lang.reflect.Field field, String colName, String indexName) { try { Object obj = PropertyAccessorHelper.getObject(object, field); // String str = // String value = (obj == null) ? null : obj.toString(); if (obj != null) { Field luceneField = new Field(getCannonicalPropertyName(indexName, colName), obj.toString(), Field.Store.YES, Field.Index.ANALYZED_NO_NORMS); document.add(luceneField); } else { LOG.warn("value is null for field" + field.getName()); } } catch (PropertyAccessException e) { LOG.error("Error in accessing field, Caused by:" + e.getMessage()); throw new LuceneIndexingException("Error in accessing field:" + field.getName(), e); } }
[ "private", "void", "addFieldToDocument", "(", "Object", "object", ",", "Document", "document", ",", "java", ".", "lang", ".", "reflect", ".", "Field", "field", ",", "String", "colName", ",", "String", "indexName", ")", "{", "try", "{", "Object", "obj", "="...
Index field. @param object the object @param document the document @param field the field @param colName the col name @param indexName the index name
[ "Index", "field", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/DocumentIndexer.java#L427-L446
jmchilton/galaxy-bootstrap
src/main/java/com/github/jmchilton/galaxybootstrap/GalaxyProperties.java
GalaxyProperties.getConfigIni
private File getConfigIni(File galaxyRoot) { if (isPre20141006Release(galaxyRoot)) { return new File(galaxyRoot, "universe_wsgi.ini"); } else { File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); return new File(configDirectory, "galaxy.ini"); } }
java
private File getConfigIni(File galaxyRoot) { if (isPre20141006Release(galaxyRoot)) { return new File(galaxyRoot, "universe_wsgi.ini"); } else { File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); return new File(configDirectory, "galaxy.ini"); } }
[ "private", "File", "getConfigIni", "(", "File", "galaxyRoot", ")", "{", "if", "(", "isPre20141006Release", "(", "galaxyRoot", ")", ")", "{", "return", "new", "File", "(", "galaxyRoot", ",", "\"universe_wsgi.ini\"", ")", ";", "}", "else", "{", "File", "config...
Gets the config ini for this Galaxy installation. @param galaxyRoot The root directory of Galaxy. @return A File object for the config ini for Galaxy.
[ "Gets", "the", "config", "ini", "for", "this", "Galaxy", "installation", "." ]
train
https://github.com/jmchilton/galaxy-bootstrap/blob/4a899f5e6ec0c9f6f4b9b21d5a0320e5925ec649/src/main/java/com/github/jmchilton/galaxybootstrap/GalaxyProperties.java#L156-L163
michael-rapp/AndroidBottomSheet
library/src/main/java/de/mrapp/android/bottomsheet/BottomSheet.java
BottomSheet.setItem
public final void setItem(final int index, final int id, @NonNull final CharSequence title) { Item item = new Item(id, title); adapter.set(index, item); adaptGridViewHeight(); }
java
public final void setItem(final int index, final int id, @NonNull final CharSequence title) { Item item = new Item(id, title); adapter.set(index, item); adaptGridViewHeight(); }
[ "public", "final", "void", "setItem", "(", "final", "int", "index", ",", "final", "int", "id", ",", "@", "NonNull", "final", "CharSequence", "title", ")", "{", "Item", "item", "=", "new", "Item", "(", "id", ",", "title", ")", ";", "adapter", ".", "se...
Replaces the item at a specific index with another item. @param index The index of the item, which should be replaced, as an {@link Integer} value @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
[ "Replaces", "the", "item", "at", "a", "specific", "index", "with", "another", "item", "." ]
train
https://github.com/michael-rapp/AndroidBottomSheet/blob/6e4690ee9f63b14a7b143d3a3717b5f8a11ca503/library/src/main/java/de/mrapp/android/bottomsheet/BottomSheet.java#L2058-L2062
gallandarakhneorg/afc
core/maths/mathgeom/tobeincluded/src/d3/continuous/AbstractTriangle3F.java
AbstractTriangle3F.toPlane
@Pure protected static Plane3D<?> toPlane( double tx1, double ty1, double tz1, double tx2, double ty2, double tz2, double tx3, double ty3, double tz3) { Vector3f norm = new Vector3f(); FunctionalVector3D.crossProduct( tx2 - tx1, ty2 - ty1, tz2 - tz1, tx3 - tx1, ty3 - ty1, tz3 - tz1, norm); assert(norm!=null); if (norm.getY()==0. && norm.getZ()==0.) return new PlaneYZ4f(tx1); if (norm.getX()==0. && norm.getZ()==0.) return new PlaneXZ4f(ty1); if (norm.getX()==0. && norm.getY()==0.) return new PlaneXY4f(tz1); return new Plane4f(tx1, ty1, tz1, tx2, ty2, tz2, tx3, ty3, tz3); }
java
@Pure protected static Plane3D<?> toPlane( double tx1, double ty1, double tz1, double tx2, double ty2, double tz2, double tx3, double ty3, double tz3) { Vector3f norm = new Vector3f(); FunctionalVector3D.crossProduct( tx2 - tx1, ty2 - ty1, tz2 - tz1, tx3 - tx1, ty3 - ty1, tz3 - tz1, norm); assert(norm!=null); if (norm.getY()==0. && norm.getZ()==0.) return new PlaneYZ4f(tx1); if (norm.getX()==0. && norm.getZ()==0.) return new PlaneXZ4f(ty1); if (norm.getX()==0. && norm.getY()==0.) return new PlaneXY4f(tz1); return new Plane4f(tx1, ty1, tz1, tx2, ty2, tz2, tx3, ty3, tz3); }
[ "@", "Pure", "protected", "static", "Plane3D", "<", "?", ">", "toPlane", "(", "double", "tx1", ",", "double", "ty1", ",", "double", "tz1", ",", "double", "tx2", ",", "double", "ty2", ",", "double", "tz2", ",", "double", "tx3", ",", "double", "ty3", "...
Compute the plane of the given triangle. @param tx1 x coordinate of the first point of the triangle. @param ty1 y coordinate of the first point of the triangle. @param tz1 z coordinate of the first point of the triangle. @param tx2 x coordinate of the second point of the triangle. @param ty2 y coordinate of the second point of the triangle. @param tz2 z coordinate of the second point of the triangle. @param tx3 x coordinate of the third point of the triangle. @param ty3 y coordinate of the third point of the triangle. @param tz3 z coordinate of the third point of the triangle. @return the plane.
[ "Compute", "the", "plane", "of", "the", "given", "triangle", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/AbstractTriangle3F.java#L407-L429