repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/ResourceBundleELResolver.java
ResourceBundleELResolver.getValue
@Override public Object getValue(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException("context is null"); } Object result = null; if (isResolvable(base)) { if (property != null) { try { result = ((ResourceBundle) base).getObject(property.toString()); } catch (MissingResourceException e) { result = "???" + property + "???"; } } context.setPropertyResolved(true); } return result; }
java
@Override public Object getValue(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException("context is null"); } Object result = null; if (isResolvable(base)) { if (property != null) { try { result = ((ResourceBundle) base).getObject(property.toString()); } catch (MissingResourceException e) { result = "???" + property + "???"; } } context.setPropertyResolved(true); } return result; }
[ "@", "Override", "public", "Object", "getValue", "(", "ELContext", "context", ",", "Object", "base", ",", "Object", "property", ")", "{", "if", "(", "context", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"context is null\"", ")", "...
If the base object is an instance of ResourceBundle, the provided property will first be coerced to a String. The Object returned by getObject on the base ResourceBundle will be returned. If the base is ResourceBundle, the propertyResolved property of the ELContext object must be set to true by this resolver, before returning. If this property is not true after this method is called, the caller should ignore the return value. @param context The context of this evaluation. @param base The bundle to analyze. Only bases of type ResourceBundle are handled by this resolver. @param property The name of the property to analyze. Will be coerced to a String. @return If the propertyResolved property of ELContext was set to true, then null if property is null; otherwise the Object for the given key (property coerced to String) from the ResourceBundle. If no object for the given key can be found, then the String "???" + key + "???". @throws NullPointerException if context is null. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
[ "If", "the", "base", "object", "is", "an", "instance", "of", "ResourceBundle", "the", "provided", "property", "will", "first", "be", "coerced", "to", "a", "String", ".", "The", "Object", "returned", "by", "getObject", "on", "the", "base", "ResourceBundle", "...
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/javax/el/ResourceBundleELResolver.java#L161-L178
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java
SqlQueryStatement.createTableAlias
private TableAlias createTableAlias(ClassDescriptor aCld, String aPath, String aUserAlias, List hints) { if (aUserAlias == null) { return createTableAlias(aCld, hints, aPath); } else { return createTableAlias(aCld, hints, aUserAlias + ALIAS_SEPARATOR + aPath); } }
java
private TableAlias createTableAlias(ClassDescriptor aCld, String aPath, String aUserAlias, List hints) { if (aUserAlias == null) { return createTableAlias(aCld, hints, aPath); } else { return createTableAlias(aCld, hints, aUserAlias + ALIAS_SEPARATOR + aPath); } }
[ "private", "TableAlias", "createTableAlias", "(", "ClassDescriptor", "aCld", ",", "String", "aPath", ",", "String", "aUserAlias", ",", "List", "hints", ")", "{", "if", "(", "aUserAlias", "==", "null", ")", "{", "return", "createTableAlias", "(", "aCld", ",", ...
Create a TableAlias for path or userAlias @param aCld @param aPath @param aUserAlias @param hints a List os Class objects to be used as hints for path expressions @return TableAlias
[ "Create", "a", "TableAlias", "for", "path", "or", "userAlias", "@param", "aCld", "@param", "aPath", "@param", "aUserAlias", "@param", "hints", "a", "List", "os", "Class", "objects", "to", "be", "used", "as", "hints", "for", "path", "expressions", "@return", ...
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L1277-L1287
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java
Execution.sendCancelRpcCall
private void sendCancelRpcCall(int numberRetries) { final LogicalSlot slot = assignedResource; if (slot != null) { final TaskManagerGateway taskManagerGateway = slot.getTaskManagerGateway(); final ComponentMainThreadExecutor jobMasterMainThreadExecutor = getVertex().getExecutionGraph().getJobMasterMainThreadExecutor(); CompletableFuture<Acknowledge> cancelResultFuture = FutureUtils.retry( () -> taskManagerGateway.cancelTask(attemptId, rpcTimeout), numberRetries, jobMasterMainThreadExecutor); cancelResultFuture.whenComplete( (ack, failure) -> { if (failure != null) { fail(new Exception("Task could not be canceled.", failure)); } }); } }
java
private void sendCancelRpcCall(int numberRetries) { final LogicalSlot slot = assignedResource; if (slot != null) { final TaskManagerGateway taskManagerGateway = slot.getTaskManagerGateway(); final ComponentMainThreadExecutor jobMasterMainThreadExecutor = getVertex().getExecutionGraph().getJobMasterMainThreadExecutor(); CompletableFuture<Acknowledge> cancelResultFuture = FutureUtils.retry( () -> taskManagerGateway.cancelTask(attemptId, rpcTimeout), numberRetries, jobMasterMainThreadExecutor); cancelResultFuture.whenComplete( (ack, failure) -> { if (failure != null) { fail(new Exception("Task could not be canceled.", failure)); } }); } }
[ "private", "void", "sendCancelRpcCall", "(", "int", "numberRetries", ")", "{", "final", "LogicalSlot", "slot", "=", "assignedResource", ";", "if", "(", "slot", "!=", "null", ")", "{", "final", "TaskManagerGateway", "taskManagerGateway", "=", "slot", ".", "getTas...
This method sends a CancelTask message to the instance of the assigned slot. <p>The sending is tried up to NUM_CANCEL_CALL_TRIES times.
[ "This", "method", "sends", "a", "CancelTask", "message", "to", "the", "instance", "of", "the", "assigned", "slot", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java#L1184-L1204
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/pipeline/common/docker/utils/DockerUtils.java
DockerUtils.getImageIdFromTag
public static String getImageIdFromTag(String imageTag, String host) throws IOException { DockerClient dockerClient = null; try { dockerClient = getDockerClient(host); return dockerClient.inspectImageCmd(imageTag).exec().getId(); } finally { closeQuietly(dockerClient); } }
java
public static String getImageIdFromTag(String imageTag, String host) throws IOException { DockerClient dockerClient = null; try { dockerClient = getDockerClient(host); return dockerClient.inspectImageCmd(imageTag).exec().getId(); } finally { closeQuietly(dockerClient); } }
[ "public", "static", "String", "getImageIdFromTag", "(", "String", "imageTag", ",", "String", "host", ")", "throws", "IOException", "{", "DockerClient", "dockerClient", "=", "null", ";", "try", "{", "dockerClient", "=", "getDockerClient", "(", "host", ")", ";", ...
Get image Id from imageTag using DockerBuildInfoHelper client. @param imageTag @param host @return
[ "Get", "image", "Id", "from", "imageTag", "using", "DockerBuildInfoHelper", "client", "." ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/pipeline/common/docker/utils/DockerUtils.java#L34-L42
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java
Check.notEmpty
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(@Nonnull final T chars, @Nullable final String name) { notNull(chars, name); notEmpty(chars, chars.length() == 0, name); return chars; }
java
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends CharSequence> T notEmpty(@Nonnull final T chars, @Nullable final String name) { notNull(chars, name); notEmpty(chars, chars.length() == 0, name); return chars; }
[ "@", "ArgumentsChecked", "@", "Throws", "(", "{", "IllegalNullArgumentException", ".", "class", ",", "IllegalEmptyArgumentException", ".", "class", "}", ")", "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "notEmpty", "(", "@", "Nonnull", "fin...
Ensures that a passed string as a parameter of the calling method is not empty. <p> The following example describes how to use it. <pre> &#064;ArgumentsChecked public setText(String text) { this.text = Check.notEmpty(text, &quot;text&quot;); } </pre> @param chars a readable sequence of {@code char} values which should not be empty @param name name of object reference (in source code) @return the passed reference that is not empty @throws IllegalNullArgumentException if the given argument {@code string} is {@code null} @throws IllegalEmptyArgumentException if the given argument {@code string} is empty
[ "Ensures", "that", "a", "passed", "string", "as", "a", "parameter", "of", "the", "calling", "method", "is", "not", "empty", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L2091-L2097
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.Cosine
public static double Cosine(IntPoint p, IntPoint q) { return Cosine(p.x, p.y, q.x, q.y); }
java
public static double Cosine(IntPoint p, IntPoint q) { return Cosine(p.x, p.y, q.x, q.y); }
[ "public", "static", "double", "Cosine", "(", "IntPoint", "p", ",", "IntPoint", "q", ")", "{", "return", "Cosine", "(", "p", ".", "x", ",", "p", ".", "y", ",", "q", ".", "x", ",", "q", ".", "y", ")", ";", "}" ]
Gets the Cosine distance between two points. @param p IntPoint with X and Y axis coordinates. @param q IntPoint with X and Y axis coordinates. @return The Cosine distance between x and y.
[ "Gets", "the", "Cosine", "distance", "between", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L363-L365
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTableRenderer.java
WTableRenderer.paintColumnHeadings
private void paintColumnHeadings(final WTable table, final WebXmlRenderContext renderContext) { XmlStringBuilder xml = renderContext.getWriter(); int[] columnOrder = table.getColumnOrder(); TableModel model = table.getTableModel(); final int columnCount = columnOrder == null ? table.getColumnCount() : columnOrder.length; xml.appendTagOpen("ui:thead"); xml.appendOptionalAttribute("hidden", !table.isShowColumnHeaders(), "true"); xml.appendClose(); for (int i = 0; i < columnCount; i++) { int colIndex = columnOrder == null ? i : columnOrder[i]; WTableColumn col = table.getColumn(colIndex); if (col.isVisible()) { boolean sortable = model.isSortable(colIndex); paintColumnHeading(col, sortable, renderContext); } } xml.appendEndTag("ui:thead"); }
java
private void paintColumnHeadings(final WTable table, final WebXmlRenderContext renderContext) { XmlStringBuilder xml = renderContext.getWriter(); int[] columnOrder = table.getColumnOrder(); TableModel model = table.getTableModel(); final int columnCount = columnOrder == null ? table.getColumnCount() : columnOrder.length; xml.appendTagOpen("ui:thead"); xml.appendOptionalAttribute("hidden", !table.isShowColumnHeaders(), "true"); xml.appendClose(); for (int i = 0; i < columnCount; i++) { int colIndex = columnOrder == null ? i : columnOrder[i]; WTableColumn col = table.getColumn(colIndex); if (col.isVisible()) { boolean sortable = model.isSortable(colIndex); paintColumnHeading(col, sortable, renderContext); } } xml.appendEndTag("ui:thead"); }
[ "private", "void", "paintColumnHeadings", "(", "final", "WTable", "table", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "int", "[", "]", "columnOrder", "=", "tab...
Paints the column headings for the given table. @param table the table to paint the headings for. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "column", "headings", "for", "the", "given", "table", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTableRenderer.java#L417-L438
kiswanij/jk-util
src/main/java/com/jk/util/datatypes/JKTypeMapping.java
JKTypeMapping.processOtherMappings
private static void processOtherMappings() { codeToJavaMapping.clear(); codeToJKTypeMapping.clear(); shortListOfJKTypes.clear(); Set<Class<?>> keySet = javaToCodeMapping.keySet(); for (Class<?> clas : keySet) { List<Integer> codes = javaToCodeMapping.get(clas); for (Integer code : codes) { codeToJavaMapping.put(code, clas); logger.debug(" Code ({}) class ({}) name ({})", code, clas.getSimpleName(), namesMapping.get(code)); codeToJKTypeMapping.put(code, new JKType(code, clas, namesMapping.get(code))); } shortListOfJKTypes.add(new JKType(codes.get(0), clas, namesMapping.get(codes.get(0)))); } }
java
private static void processOtherMappings() { codeToJavaMapping.clear(); codeToJKTypeMapping.clear(); shortListOfJKTypes.clear(); Set<Class<?>> keySet = javaToCodeMapping.keySet(); for (Class<?> clas : keySet) { List<Integer> codes = javaToCodeMapping.get(clas); for (Integer code : codes) { codeToJavaMapping.put(code, clas); logger.debug(" Code ({}) class ({}) name ({})", code, clas.getSimpleName(), namesMapping.get(code)); codeToJKTypeMapping.put(code, new JKType(code, clas, namesMapping.get(code))); } shortListOfJKTypes.add(new JKType(codes.get(0), clas, namesMapping.get(codes.get(0)))); } }
[ "private", "static", "void", "processOtherMappings", "(", ")", "{", "codeToJavaMapping", ".", "clear", "(", ")", ";", "codeToJKTypeMapping", ".", "clear", "(", ")", ";", "shortListOfJKTypes", ".", "clear", "(", ")", ";", "Set", "<", "Class", "<", "?", ">",...
This method is used to avoid reconigure the mapping in the otherside again.
[ "This", "method", "is", "used", "to", "avoid", "reconigure", "the", "mapping", "in", "the", "otherside", "again", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/datatypes/JKTypeMapping.java#L101-L115
JM-Lab/utils-java8
src/main/java/kr/jm/utils/stats/collector/WordNumberCollectorBundle.java
WordNumberCollectorBundle.addData
public WordNumberCollectorBundle addData(String key, String data) { if (JMString.isNumber(data)) addNumber(key, Double.valueOf(data)); else addWord(key, data); return this; }
java
public WordNumberCollectorBundle addData(String key, String data) { if (JMString.isNumber(data)) addNumber(key, Double.valueOf(data)); else addWord(key, data); return this; }
[ "public", "WordNumberCollectorBundle", "addData", "(", "String", "key", ",", "String", "data", ")", "{", "if", "(", "JMString", ".", "isNumber", "(", "data", ")", ")", "addNumber", "(", "key", ",", "Double", ".", "valueOf", "(", "data", ")", ")", ";", ...
Add data word number collector bundle. @param key the key @param data the data @return the word number collector bundle
[ "Add", "data", "word", "number", "collector", "bundle", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/stats/collector/WordNumberCollectorBundle.java#L113-L119
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/RuntimeExceptionsFactory.java
RuntimeExceptionsFactory.newIndexOutOfBoundsException
public static IndexOutOfBoundsException newIndexOutOfBoundsException(Throwable cause, String message, Object... args) { return (IndexOutOfBoundsException) new IndexOutOfBoundsException(format(message, args)).initCause(cause); }
java
public static IndexOutOfBoundsException newIndexOutOfBoundsException(Throwable cause, String message, Object... args) { return (IndexOutOfBoundsException) new IndexOutOfBoundsException(format(message, args)).initCause(cause); }
[ "public", "static", "IndexOutOfBoundsException", "newIndexOutOfBoundsException", "(", "Throwable", "cause", ",", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "(", "IndexOutOfBoundsException", ")", "new", "IndexOutOfBoundsException", "(", "forma...
Constructs and initializes a new {@link IndexOutOfBoundsException} with the given {@link Throwable cause} and {@link String message} formatted with the given {@link Object[] arguments}. @param cause {@link Throwable} identified as the reason this {@link IndexOutOfBoundsException} was thrown. @param message {@link String} describing the {@link IndexOutOfBoundsException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link IndexOutOfBoundsException} with the given {@link Throwable cause} and {@link String message}. @see java.lang.IndexOutOfBoundsException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "IndexOutOfBoundsException", "}", "with", "the", "given", "{", "@link", "Throwable", "cause", "}", "and", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", ...
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/RuntimeExceptionsFactory.java#L118-L122
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/AccordionExample.java
AccordionExample.constructExample
private void constructExample() { add(new WHeading(HeadingLevel.H3, "ACCORDION tabs")); WTabSet tabset1c = new SampleWTabset(TabSetType.ACCORDION); add(tabset1c); /* Content height */ add(new WHeading(HeadingLevel.H2, "Examples showing content height property.")); add(new WHeading(HeadingLevel.H3, "Tall content.")); WTabSet htabset1c = new SampleWTabset(TabSetType.ACCORDION); htabset1c.setContentHeight(TALL_CONTENT); add(htabset1c); add(new WHeading(HeadingLevel.H3, "Short content.")); WTabSet htabset1g = new SampleWTabset(TabSetType.ACCORDION); htabset1g.setContentHeight(SHORT_CONTENT); add(htabset1g); add(new WHeading(HeadingLevel.H2, "Examples showing accordion's single property.")); WTabSet singleOpenAccordionabset = new SampleWTabset(WTabSet.TYPE_ACCORDION); singleOpenAccordionabset.setSingle(true); add(singleOpenAccordionabset); add(new WHeading(HeadingLevel.H2, "Using WSubordinateControl")); WTabSet targetTabset = new SampleWTabset(TabSetType.ACCORDION); add(targetTabset); WFieldLayout layout = new WFieldLayout(WFieldLayout.LAYOUT_STACKED); add(layout); final WCheckBox disabledControllerCb = new WCheckBox(); final WCheckBox hiddenControllerCb = new WCheckBox(); layout.addField("disable tabset", disabledControllerCb); layout.addField("hide tabset", hiddenControllerCb); // Build & add the subordinate SubordinateBuilder builder = new SubordinateBuilder(); builder.condition().equals(hiddenControllerCb, String.valueOf(true)); builder.whenTrue().hide(targetTabset); builder.whenFalse().show(targetTabset); add(builder.build()); builder = new SubordinateBuilder(); builder.condition().equals(disabledControllerCb, String.valueOf(true)); builder.whenTrue().disable(targetTabset); builder.whenFalse().enable(targetTabset); add(builder.build()); }
java
private void constructExample() { add(new WHeading(HeadingLevel.H3, "ACCORDION tabs")); WTabSet tabset1c = new SampleWTabset(TabSetType.ACCORDION); add(tabset1c); /* Content height */ add(new WHeading(HeadingLevel.H2, "Examples showing content height property.")); add(new WHeading(HeadingLevel.H3, "Tall content.")); WTabSet htabset1c = new SampleWTabset(TabSetType.ACCORDION); htabset1c.setContentHeight(TALL_CONTENT); add(htabset1c); add(new WHeading(HeadingLevel.H3, "Short content.")); WTabSet htabset1g = new SampleWTabset(TabSetType.ACCORDION); htabset1g.setContentHeight(SHORT_CONTENT); add(htabset1g); add(new WHeading(HeadingLevel.H2, "Examples showing accordion's single property.")); WTabSet singleOpenAccordionabset = new SampleWTabset(WTabSet.TYPE_ACCORDION); singleOpenAccordionabset.setSingle(true); add(singleOpenAccordionabset); add(new WHeading(HeadingLevel.H2, "Using WSubordinateControl")); WTabSet targetTabset = new SampleWTabset(TabSetType.ACCORDION); add(targetTabset); WFieldLayout layout = new WFieldLayout(WFieldLayout.LAYOUT_STACKED); add(layout); final WCheckBox disabledControllerCb = new WCheckBox(); final WCheckBox hiddenControllerCb = new WCheckBox(); layout.addField("disable tabset", disabledControllerCb); layout.addField("hide tabset", hiddenControllerCb); // Build & add the subordinate SubordinateBuilder builder = new SubordinateBuilder(); builder.condition().equals(hiddenControllerCb, String.valueOf(true)); builder.whenTrue().hide(targetTabset); builder.whenFalse().show(targetTabset); add(builder.build()); builder = new SubordinateBuilder(); builder.condition().equals(disabledControllerCb, String.valueOf(true)); builder.whenTrue().disable(targetTabset); builder.whenFalse().enable(targetTabset); add(builder.build()); }
[ "private", "void", "constructExample", "(", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H3", ",", "\"ACCORDION tabs\"", ")", ")", ";", "WTabSet", "tabset1c", "=", "new", "SampleWTabset", "(", "TabSetType", ".", "ACCORDION", ")", ";", ...
Helper to do the work of the constructor since we do not really want to call over-rideable methods in a constructor.
[ "Helper", "to", "do", "the", "work", "of", "the", "constructor", "since", "we", "do", "not", "really", "want", "to", "call", "over", "-", "rideable", "methods", "in", "a", "constructor", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/AccordionExample.java#L54-L106
yegor256/takes
src/main/java/org/takes/rs/RsWithType.java
RsWithType.make
private static Response make(final Response res, final CharSequence type, final Opt<Charset> charset) { final Response response; if (charset.has()) { response = new RsWithHeader( new RsWithoutHeader(res, RsWithType.HEADER), RsWithType.HEADER, String.format( "%s; %s=%s", type, RsWithType.CHARSET, charset.get().name() ) ); } else { response = new RsWithHeader( new RsWithoutHeader(res, RsWithType.HEADER), RsWithType.HEADER, type ); } return response; }
java
private static Response make(final Response res, final CharSequence type, final Opt<Charset> charset) { final Response response; if (charset.has()) { response = new RsWithHeader( new RsWithoutHeader(res, RsWithType.HEADER), RsWithType.HEADER, String.format( "%s; %s=%s", type, RsWithType.CHARSET, charset.get().name() ) ); } else { response = new RsWithHeader( new RsWithoutHeader(res, RsWithType.HEADER), RsWithType.HEADER, type ); } return response; }
[ "private", "static", "Response", "make", "(", "final", "Response", "res", ",", "final", "CharSequence", "type", ",", "final", "Opt", "<", "Charset", ">", "charset", ")", "{", "final", "Response", "response", ";", "if", "(", "charset", ".", "has", "(", ")...
Factory allowing to create {@code Response} with the corresponding content type and character set. @param res Original response @param type Content type @param charset The character set to add to the content type header. If absent no character set will be added to the content type header @return Response
[ "Factory", "allowing", "to", "create", "{" ]
train
https://github.com/yegor256/takes/blob/a4f4d939c8f8e0af190025716ad7f22b7de40e70/src/main/java/org/takes/rs/RsWithType.java#L102-L124
moparisthebest/beehive
beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.java
JMSControlImpl.getSession
public Session getSession() throws ControlException { if (_session == null) { try { switch (getDestinationType()) { case Auto: determineDestination(); return getSession(); case Topic: createTopicSession(); break; case Queue: createQueueSession(); break; } } catch (JMSException e) { throw new ControlException("Failure to get JMS connection or session", e); } } return _session; }
java
public Session getSession() throws ControlException { if (_session == null) { try { switch (getDestinationType()) { case Auto: determineDestination(); return getSession(); case Topic: createTopicSession(); break; case Queue: createQueueSession(); break; } } catch (JMSException e) { throw new ControlException("Failure to get JMS connection or session", e); } } return _session; }
[ "public", "Session", "getSession", "(", ")", "throws", "ControlException", "{", "if", "(", "_session", "==", "null", ")", "{", "try", "{", "switch", "(", "getDestinationType", "(", ")", ")", "{", "case", "Auto", ":", "determineDestination", "(", ")", ";", ...
Implementation of the {@link org.apache.beehive.controls.system.jms.JMSControl#getSession()} method. @return the {@link Session} @throws ControlException when an error occurs trying to create a JMS session
[ "Implementation", "of", "the", "{", "@link", "org", ".", "apache", ".", "beehive", ".", "controls", ".", "system", ".", "jms", ".", "JMSControl#getSession", "()", "}", "method", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-jms-control/src/main/java/org/apache/beehive/controls/system/jms/impl/JMSControlImpl.java#L81-L101
romannurik/muzei
muzei-api/src/main/java/com/google/android/apps/muzei/api/provider/MuzeiArtProvider.java
MuzeiArtProvider.getDescription
@NonNull protected String getDescription() { Context context = getContext(); if (context == null) { return ""; } try { @SuppressLint("InlinedApi") ProviderInfo info = context.getPackageManager().getProviderInfo( new ComponentName(context, getClass()), PackageManager.MATCH_DISABLED_COMPONENTS); return info.descriptionRes != 0 ? context.getString(info.descriptionRes) : ""; } catch (PackageManager.NameNotFoundException e) { // Wtf? return ""; } }
java
@NonNull protected String getDescription() { Context context = getContext(); if (context == null) { return ""; } try { @SuppressLint("InlinedApi") ProviderInfo info = context.getPackageManager().getProviderInfo( new ComponentName(context, getClass()), PackageManager.MATCH_DISABLED_COMPONENTS); return info.descriptionRes != 0 ? context.getString(info.descriptionRes) : ""; } catch (PackageManager.NameNotFoundException e) { // Wtf? return ""; } }
[ "@", "NonNull", "protected", "String", "getDescription", "(", ")", "{", "Context", "context", "=", "getContext", "(", ")", ";", "if", "(", "context", "==", "null", ")", "{", "return", "\"\"", ";", "}", "try", "{", "@", "SuppressLint", "(", "\"InlinedApi\...
Gets the longer description for the current state of this MuzeiArtProvider. For example, 'Popular photos tagged "landscape"'). The default implementation returns the <code>android:description</code> element of the provider element in the manifest. @return The description that should be shown when this provider is selected
[ "Gets", "the", "longer", "description", "for", "the", "current", "state", "of", "this", "MuzeiArtProvider", ".", "For", "example", "Popular", "photos", "tagged", "landscape", ")", ".", "The", "default", "implementation", "returns", "the", "<code", ">", "android"...
train
https://github.com/romannurik/muzei/blob/d00777a5fc59f34471be338c814ea85ddcbde304/muzei-api/src/main/java/com/google/android/apps/muzei/api/provider/MuzeiArtProvider.java#L557-L573
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/wrapper/PAbstractObject.java
PAbstractObject.optBool
@Override public final Boolean optBool(final String key, final Boolean defaultValue) { Boolean result = optBool(key); return result == null ? defaultValue : result; }
java
@Override public final Boolean optBool(final String key, final Boolean defaultValue) { Boolean result = optBool(key); return result == null ? defaultValue : result; }
[ "@", "Override", "public", "final", "Boolean", "optBool", "(", "final", "String", "key", ",", "final", "Boolean", "defaultValue", ")", "{", "Boolean", "result", "=", "optBool", "(", "key", ")", ";", "return", "result", "==", "null", "?", "defaultValue", ":...
Get a property as a boolean or default value. @param key the property name @param defaultValue the default
[ "Get", "a", "property", "as", "a", "boolean", "or", "default", "value", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/wrapper/PAbstractObject.java#L169-L173
eurekaclinical/eurekaclinical-common
src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java
EurekaClinicalClient.doPostForProxy
protected ClientResponse doPostForProxy(String path, InputStream inputStream, MultivaluedMap<String, String> parameterMap, MultivaluedMap<String, String> headers) throws ClientException { this.readLock.lock(); try { WebResource.Builder requestBuilder = getResourceWrapper().rewritten(path, HttpMethod.POST, parameterMap).getRequestBuilder(); copyHeaders(headers, requestBuilder); return requestBuilder.post(ClientResponse.class, inputStream); } catch (ClientHandlerException ex) { throw new ClientException(ClientResponse.Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } finally { this.readLock.unlock(); } }
java
protected ClientResponse doPostForProxy(String path, InputStream inputStream, MultivaluedMap<String, String> parameterMap, MultivaluedMap<String, String> headers) throws ClientException { this.readLock.lock(); try { WebResource.Builder requestBuilder = getResourceWrapper().rewritten(path, HttpMethod.POST, parameterMap).getRequestBuilder(); copyHeaders(headers, requestBuilder); return requestBuilder.post(ClientResponse.class, inputStream); } catch (ClientHandlerException ex) { throw new ClientException(ClientResponse.Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } finally { this.readLock.unlock(); } }
[ "protected", "ClientResponse", "doPostForProxy", "(", "String", "path", ",", "InputStream", "inputStream", ",", "MultivaluedMap", "<", "String", ",", "String", ">", "parameterMap", ",", "MultivaluedMap", "<", "String", ",", "String", ">", "headers", ")", "throws",...
Passes a new resource, form or other POST body to a proxied server. @param path the path to the resource. Cannot be <code>null</code>. @param inputStream the contents of the POST body. Cannot be <code>null</code>. @param parameterMap query parameters. May be <code>null</code>. @param headers any request headers to add. May be <code>null</code>. @return ClientResponse the proxied server's response information. @throws ClientException if the proxied server responds with an "error" status code, which is dependent on the server being called. @see #getResourceUrl() for the URL of the proxied server.
[ "Passes", "a", "new", "resource", "form", "or", "other", "POST", "body", "to", "a", "proxied", "server", "." ]
train
https://github.com/eurekaclinical/eurekaclinical-common/blob/1867102ff43fe94e519f76a074d5f5923e9be61c/src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java#L868-L879
JoeKerouac/utils
src/main/java/com/joe/utils/common/Algorithm.java
Algorithm.lcs
public static <T extends Comparable<T>> List<T> lcs(List<T> arg0, List<T> arg1) { if (arg0 == null || arg1 == null) { return Collections.emptyList(); } return lcs(arg0, arg1, 0, 0); }
java
public static <T extends Comparable<T>> List<T> lcs(List<T> arg0, List<T> arg1) { if (arg0 == null || arg1 == null) { return Collections.emptyList(); } return lcs(arg0, arg1, 0, 0); }
[ "public", "static", "<", "T", "extends", "Comparable", "<", "T", ">", ">", "List", "<", "T", ">", "lcs", "(", "List", "<", "T", ">", "arg0", ",", "List", "<", "T", ">", "arg1", ")", "{", "if", "(", "arg0", "==", "null", "||", "arg1", "==", "n...
求最长公共子序列(序列中的元素需要实现Comparable接口)(有可能有多种解,该方法只返回其中一种) @param arg0 第一个序列 @param arg1 第二个序列 @param <T> 数组中数据的实际类型 @return 两个序列的公共子序列(返回的是原队列中的倒序) (集合{1 , 2 , 3 , 4}和集合{2 , 3 , 4 , 1}的公共子序列返回值为{4 , 3 , 2})
[ "求最长公共子序列(序列中的元素需要实现Comparable接口)(有可能有多种解,该方法只返回其中一种)" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/common/Algorithm.java#L69-L74
micronaut-projects/micronaut-core
http/src/main/java/io/micronaut/http/uri/QueryStringDecoder.java
QueryStringDecoder.decodeComponent
private static String decodeComponent(final String s, final Charset charset) { if (s == null) { return EMPTY_STRING; } return decodeComponent(s, 0, s.length(), charset, false); }
java
private static String decodeComponent(final String s, final Charset charset) { if (s == null) { return EMPTY_STRING; } return decodeComponent(s, 0, s.length(), charset, false); }
[ "private", "static", "String", "decodeComponent", "(", "final", "String", "s", ",", "final", "Charset", "charset", ")", "{", "if", "(", "s", "==", "null", ")", "{", "return", "EMPTY_STRING", ";", "}", "return", "decodeComponent", "(", "s", ",", "0", ",",...
Decodes a bit of an URL encoded by a browser. <p> The string is expected to be encoded as per RFC 3986, Section 2. This is the encoding used by JavaScript functions {@code encodeURI} and {@code encodeURIComponent}, but not {@code escape}. For example in this encoding, &eacute; (in Unicode {@code U+00E9} or in UTF-8 {@code 0xC3 0xA9}) is encoded as {@code %C3%A9} or {@code %c3%a9}. <p> This is essentially equivalent to calling {@link java.net.URLDecoder#decode(String, String)} except that it's over 2x faster and generates less garbage for the GC. Actually this function doesn't allocate any memory if there's nothing to decode, the argument itself is returned. @param s The string to decode (can be empty). @param charset The charset to use to decode the string (should really be {@link StandardCharsets#UTF_8}. @return The decoded string, or {@code s} if there's nothing to decode. If the string to decode is {@code null}, returns an empty string. @throws IllegalArgumentException if the string contains a malformed escape sequence.
[ "Decodes", "a", "bit", "of", "an", "URL", "encoded", "by", "a", "browser", ".", "<p", ">", "The", "string", "is", "expected", "to", "be", "encoded", "as", "per", "RFC", "3986", "Section", "2", ".", "This", "is", "the", "encoding", "used", "by", "Java...
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http/src/main/java/io/micronaut/http/uri/QueryStringDecoder.java#L307-L312
alkacon/opencms-core
src-setup/org/opencms/setup/db/update6to7/CmsUpdateDBCmsUsers.java
CmsUpdateDBCmsUsers.writeUserInfo
protected void writeUserInfo(CmsSetupDb dbCon, String id, String key, Object value) { String query = readQuery(QUERY_INSERT_CMS_USERDATA); try { // Generate the list of parameters to add into the user info table List<Object> params = new ArrayList<Object>(); params.add(id); params.add(key); params.add(value); params.add(value.getClass().getName()); dbCon.updateSqlStatement(query, null, params); } catch (SQLException e) { e.printStackTrace(); } }
java
protected void writeUserInfo(CmsSetupDb dbCon, String id, String key, Object value) { String query = readQuery(QUERY_INSERT_CMS_USERDATA); try { // Generate the list of parameters to add into the user info table List<Object> params = new ArrayList<Object>(); params.add(id); params.add(key); params.add(value); params.add(value.getClass().getName()); dbCon.updateSqlStatement(query, null, params); } catch (SQLException e) { e.printStackTrace(); } }
[ "protected", "void", "writeUserInfo", "(", "CmsSetupDb", "dbCon", ",", "String", "id", ",", "String", "key", ",", "Object", "value", ")", "{", "String", "query", "=", "readQuery", "(", "QUERY_INSERT_CMS_USERDATA", ")", ";", "try", "{", "// Generate the list of p...
Writes one set of additional user info (key and its value) to the CMS_USERDATA table.<p> @param dbCon the db connection interface @param id the user id @param key the data key @param value the data value
[ "Writes", "one", "set", "of", "additional", "user", "info", "(", "key", "and", "its", "value", ")", "to", "the", "CMS_USERDATA", "table", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/db/update6to7/CmsUpdateDBCmsUsers.java#L369-L385
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/requests/RestAction.java
RestAction.queue
@SuppressWarnings("unchecked") public void queue(Consumer<? super T> success, Consumer<? super Throwable> failure) { Route.CompiledRoute route = finalizeRoute(); Checks.notNull(route, "Route"); RequestBody data = finalizeData(); CaseInsensitiveMap<String, String> headers = finalizeHeaders(); BooleanSupplier finisher = getFinisher(); if (success == null) success = DEFAULT_SUCCESS == null ? FALLBACK_CONSUMER : DEFAULT_SUCCESS; if (failure == null) failure = DEFAULT_FAILURE == null ? FALLBACK_CONSUMER : DEFAULT_FAILURE; api.get().getRequester().request(new Request<>(this, success, failure, finisher, true, data, rawData, route, headers)); }
java
@SuppressWarnings("unchecked") public void queue(Consumer<? super T> success, Consumer<? super Throwable> failure) { Route.CompiledRoute route = finalizeRoute(); Checks.notNull(route, "Route"); RequestBody data = finalizeData(); CaseInsensitiveMap<String, String> headers = finalizeHeaders(); BooleanSupplier finisher = getFinisher(); if (success == null) success = DEFAULT_SUCCESS == null ? FALLBACK_CONSUMER : DEFAULT_SUCCESS; if (failure == null) failure = DEFAULT_FAILURE == null ? FALLBACK_CONSUMER : DEFAULT_FAILURE; api.get().getRequester().request(new Request<>(this, success, failure, finisher, true, data, rawData, route, headers)); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "void", "queue", "(", "Consumer", "<", "?", "super", "T", ">", "success", ",", "Consumer", "<", "?", "super", "Throwable", ">", "failure", ")", "{", "Route", ".", "CompiledRoute", "route", "=", ...
Submits a Request for execution. <p><b>This method is asynchronous</b> @param success The success callback that will be called at a convenient time for the API. (can be null) @param failure The failure callback that will be called if the Request encounters an exception at its execution point.
[ "Submits", "a", "Request", "for", "execution", "." ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/requests/RestAction.java#L332-L345
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.parseDateWithLeniency
@GwtIncompatible("incompatible method") private static Date parseDateWithLeniency( final String str, final Locale locale, final String[] parsePatterns, final boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } final TimeZone tz = TimeZone.getDefault(); final Locale lcl = locale==null ?Locale.getDefault() : locale; final ParsePosition pos = new ParsePosition(0); final Calendar calendar = Calendar.getInstance(tz, lcl); calendar.setLenient(lenient); for (final String parsePattern : parsePatterns) { final FastDateParser fdp = new FastDateParser(parsePattern, tz, lcl); calendar.clear(); try { if (fdp.parse(str, pos, calendar) && pos.getIndex()==str.length()) { return calendar.getTime(); } } catch(final IllegalArgumentException ignore) { // leniency is preventing calendar from being set } pos.setIndex(0); } throw new ParseException("Unable to parse the date: " + str, -1); }
java
@GwtIncompatible("incompatible method") private static Date parseDateWithLeniency( final String str, final Locale locale, final String[] parsePatterns, final boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } final TimeZone tz = TimeZone.getDefault(); final Locale lcl = locale==null ?Locale.getDefault() : locale; final ParsePosition pos = new ParsePosition(0); final Calendar calendar = Calendar.getInstance(tz, lcl); calendar.setLenient(lenient); for (final String parsePattern : parsePatterns) { final FastDateParser fdp = new FastDateParser(parsePattern, tz, lcl); calendar.clear(); try { if (fdp.parse(str, pos, calendar) && pos.getIndex()==str.length()) { return calendar.getTime(); } } catch(final IllegalArgumentException ignore) { // leniency is preventing calendar from being set } pos.setIndex(0); } throw new ParseException("Unable to parse the date: " + str, -1); }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "private", "static", "Date", "parseDateWithLeniency", "(", "final", "String", "str", ",", "final", "Locale", "locale", ",", "final", "String", "[", "]", "parsePatterns", ",", "final", "boolean", "lenient...
<p>Parses a string representing a date by trying a variety of different parsers.</p> <p>The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.</p> @param str the date to parse, not null @param locale the locale to use when interpretting the pattern, can be null in which case the default system locale is used @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null @param lenient Specify whether or not date/time parsing is to be lenient. @return the parsed date @throws IllegalArgumentException if the date string or pattern array is null @throws ParseException if none of the date patterns were suitable @see java.util.Calendar#isLenient()
[ "<p", ">", "Parses", "a", "string", "representing", "a", "date", "by", "trying", "a", "variety", "of", "different", "parsers", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L370-L396
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/shared/core/types/Color.java
Color.hueToRGB
private static double hueToRGB(final double m1, final double m2, double h) { // see http://www.w3.org/TR/css3-color/ // // HOW TO RETURN hue.to.rgb(m1, m2, h): // IF h<0: PUT h+1 IN h // IF h>1: PUT h-1 IN h // IF h*6<1: RETURN m1+(m2-m1)*h*6 // IF h*2<1: RETURN m2 // IF h*3<2: RETURN m1+(m2-m1)*(2/3-h)*6 // RETURN m1 if (h < 0) { h++; } if (h > 1) { h--; } if ((h * 6) < 1) { return m1 + ((m2 - m1) * h * 6); } if ((h * 2) < 1) { return m2; } if ((h * 3) < 2) { return m1 + ((m2 - m1) * ((2.0 / 3) - h) * 6); } return m1; }
java
private static double hueToRGB(final double m1, final double m2, double h) { // see http://www.w3.org/TR/css3-color/ // // HOW TO RETURN hue.to.rgb(m1, m2, h): // IF h<0: PUT h+1 IN h // IF h>1: PUT h-1 IN h // IF h*6<1: RETURN m1+(m2-m1)*h*6 // IF h*2<1: RETURN m2 // IF h*3<2: RETURN m1+(m2-m1)*(2/3-h)*6 // RETURN m1 if (h < 0) { h++; } if (h > 1) { h--; } if ((h * 6) < 1) { return m1 + ((m2 - m1) * h * 6); } if ((h * 2) < 1) { return m2; } if ((h * 3) < 2) { return m1 + ((m2 - m1) * ((2.0 / 3) - h) * 6); } return m1; }
[ "private", "static", "double", "hueToRGB", "(", "final", "double", "m1", ",", "final", "double", "m2", ",", "double", "h", ")", "{", "// see http://www.w3.org/TR/css3-color/", "//", "// HOW TO RETURN hue.to.rgb(m1, m2, h):", "// IF h<0: PUT h+1 IN h", "// IF h>1: PUT h-1 IN...
Used by {@link #fromNormalizedHSL(double, double, double)} @param m1 @param m2 @param h @return
[ "Used", "by", "{", "@link", "#fromNormalizedHSL", "(", "double", "double", "double", ")", "}" ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/shared/core/types/Color.java#L750-L783
GoSimpleLLC/nbvcxz
src/main/java/me/gosimple/nbvcxz/resources/DictionaryUtil.java
DictionaryUtil.loadUnrankedDictionary
public static Map<String, Integer> loadUnrankedDictionary(final String fileName) { Map<String, Integer> unranked = new HashMap<>(); Set<String> unranked_set = new HashSet<>(); String path = "/dictionaries/" + fileName; try (InputStream is = DictionaryUtil.class.getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { String line; int i = 0; while ((line = br.readLine()) != null) { unranked_set.add(line); i++; } i = i / 2; for (String value : unranked_set) { unranked.put(value, i); } } catch (IOException e) { System.out.println("Error while reading " + fileName); } return unranked; }
java
public static Map<String, Integer> loadUnrankedDictionary(final String fileName) { Map<String, Integer> unranked = new HashMap<>(); Set<String> unranked_set = new HashSet<>(); String path = "/dictionaries/" + fileName; try (InputStream is = DictionaryUtil.class.getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { String line; int i = 0; while ((line = br.readLine()) != null) { unranked_set.add(line); i++; } i = i / 2; for (String value : unranked_set) { unranked.put(value, i); } } catch (IOException e) { System.out.println("Error while reading " + fileName); } return unranked; }
[ "public", "static", "Map", "<", "String", ",", "Integer", ">", "loadUnrankedDictionary", "(", "final", "String", "fileName", ")", "{", "Map", "<", "String", ",", "Integer", ">", "unranked", "=", "new", "HashMap", "<>", "(", ")", ";", "Set", "<", "String"...
Read a resource file with a list of entries (sorted by frequency) and use it to create a ranked dictionary. <p> The dictionary must contain only lower case values for the matching to work properly. @param fileName the name of the file @return the ranked dictionary (a {@code HashMap} which associated a rank to each entry
[ "Read", "a", "resource", "file", "with", "a", "list", "of", "entries", "(", "sorted", "by", "frequency", ")", "and", "use", "it", "to", "create", "a", "ranked", "dictionary", ".", "<p", ">", "The", "dictionary", "must", "contain", "only", "lower", "case"...
train
https://github.com/GoSimpleLLC/nbvcxz/blob/a86fb24680e646efdf78d6fda9d68a5410145f56/src/main/java/me/gosimple/nbvcxz/resources/DictionaryUtil.java#L57-L87
killme2008/gecko
src/main/java/com/taobao/gecko/core/buffer/IoBufferHexDumper.java
IoBufferHexDumper.getHexdump
public static String getHexdump(IoBuffer in, int lengthLimit) { if (lengthLimit == 0) { throw new IllegalArgumentException("lengthLimit: " + lengthLimit + " (expected: 1+)"); } boolean truncate = in.remaining() > lengthLimit; int size; if (truncate) { size = lengthLimit; } else { size = in.remaining(); } if (size == 0) { return "empty"; } StringBuilder out = new StringBuilder(in.remaining() * 3 - 1); int mark = in.position(); // fill the first int byteValue = in.get() & 0xFF; out.append((char) highDigits[byteValue]); out.append((char) lowDigits[byteValue]); size--; // and the others, too for (; size > 0; size--) { out.append(' '); byteValue = in.get() & 0xFF; out.append((char) highDigits[byteValue]); out.append((char) lowDigits[byteValue]); } in.position(mark); if (truncate) { out.append("..."); } return out.toString(); }
java
public static String getHexdump(IoBuffer in, int lengthLimit) { if (lengthLimit == 0) { throw new IllegalArgumentException("lengthLimit: " + lengthLimit + " (expected: 1+)"); } boolean truncate = in.remaining() > lengthLimit; int size; if (truncate) { size = lengthLimit; } else { size = in.remaining(); } if (size == 0) { return "empty"; } StringBuilder out = new StringBuilder(in.remaining() * 3 - 1); int mark = in.position(); // fill the first int byteValue = in.get() & 0xFF; out.append((char) highDigits[byteValue]); out.append((char) lowDigits[byteValue]); size--; // and the others, too for (; size > 0; size--) { out.append(' '); byteValue = in.get() & 0xFF; out.append((char) highDigits[byteValue]); out.append((char) lowDigits[byteValue]); } in.position(mark); if (truncate) { out.append("..."); } return out.toString(); }
[ "public", "static", "String", "getHexdump", "(", "IoBuffer", "in", ",", "int", "lengthLimit", ")", "{", "if", "(", "lengthLimit", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"lengthLimit: \"", "+", "lengthLimit", "+", "\" (expected: 1...
Dumps an {@link IoBuffer} to a hex formatted string. @param in the buffer to dump @param lengthLimit the limit at which hex dumping will stop @return a hex formatted string representation of the <i>in</i> {@link Iobuffer}.
[ "Dumps", "an", "{", "@link", "IoBuffer", "}", "to", "a", "hex", "formatted", "string", "." ]
train
https://github.com/killme2008/gecko/blob/0873b690ffde51e40e6eadfcd5d599eb4e3b642d/src/main/java/com/taobao/gecko/core/buffer/IoBufferHexDumper.java#L87-L130
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_mailingList_mailingListAddress_member_contact_POST
public OvhTask organizationName_service_exchangeService_mailingList_mailingListAddress_member_contact_POST(String organizationName, String exchangeService, String mailingListAddress, Long memberAccountId, Long memberContactId) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress}/member/contact"; StringBuilder sb = path(qPath, organizationName, exchangeService, mailingListAddress); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "memberAccountId", memberAccountId); addBody(o, "memberContactId", memberContactId); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask organizationName_service_exchangeService_mailingList_mailingListAddress_member_contact_POST(String organizationName, String exchangeService, String mailingListAddress, Long memberAccountId, Long memberContactId) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress}/member/contact"; StringBuilder sb = path(qPath, organizationName, exchangeService, mailingListAddress); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "memberAccountId", memberAccountId); addBody(o, "memberContactId", memberContactId); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "organizationName_service_exchangeService_mailingList_mailingListAddress_member_contact_POST", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "String", "mailingListAddress", ",", "Long", "memberAccountId", ",", "Long", "memberContactI...
Add new mailing list member REST: POST /email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress}/member/contact @param memberAccountId [required] Member account id @param memberContactId [required] Member contact id @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service @param mailingListAddress [required] The mailing list address
[ "Add", "new", "mailing", "list", "member" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L1176-L1184
OnyxDevTools/onyx-database-parent
onyx-database-examples/webservice-client/java-client/src/main/java/io/swagger/client/ApiClient.java
ApiClient.buildUrl
public String buildUrl(String path, List<Pair> queryParams) { final StringBuilder url = new StringBuilder(); url.append(basePath).append(path); if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" String prefix = path.contains("?") ? "&" : "?"; for (Pair param : queryParams) { if (param.getValue() != null) { if (prefix != null) { url.append(prefix); prefix = null; } else { url.append("&"); } String value = parameterToString(param.getValue()); url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } } return url.toString(); }
java
public String buildUrl(String path, List<Pair> queryParams) { final StringBuilder url = new StringBuilder(); url.append(basePath).append(path); if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" String prefix = path.contains("?") ? "&" : "?"; for (Pair param : queryParams) { if (param.getValue() != null) { if (prefix != null) { url.append(prefix); prefix = null; } else { url.append("&"); } String value = parameterToString(param.getValue()); url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } } return url.toString(); }
[ "public", "String", "buildUrl", "(", "String", "path", ",", "List", "<", "Pair", ">", "queryParams", ")", "{", "final", "StringBuilder", "url", "=", "new", "StringBuilder", "(", ")", ";", "url", ".", "append", "(", "basePath", ")", ".", "append", "(", ...
Build full URL by concatenating base path, the given sub path and query parameters. @param path The sub path @param queryParams The query parameters @return The full URL
[ "Build", "full", "URL", "by", "concatenating", "base", "path", "the", "given", "sub", "path", "and", "query", "parameters", "." ]
train
https://github.com/OnyxDevTools/onyx-database-parent/blob/474dfc273a094dbc2ca08fcc08a2858cd538c920/onyx-database-examples/webservice-client/java-client/src/main/java/io/swagger/client/ApiClient.java#L1165-L1187
wiibaker/robotframework-rest-java
src/main/java/org/wuokko/robot/restlib/JsonPathLibrary.java
JsonPathLibrary.findJsonElement
@RobotKeyword public Object findJsonElement(String source, String jsonPath, String method, String data, String contentType) throws Exception { System.out.println("*DEBUG* Reading jsonPath: " + jsonPath); String json = requestUtil.readSource(source, method, data, contentType); Object value; try { value = JsonPath.read(json, jsonPath); } catch (PathNotFoundException e) { throw new JsonElementNotFoundException("Path '" + jsonPath + "' was not found in JSON"); } return value; }
java
@RobotKeyword public Object findJsonElement(String source, String jsonPath, String method, String data, String contentType) throws Exception { System.out.println("*DEBUG* Reading jsonPath: " + jsonPath); String json = requestUtil.readSource(source, method, data, contentType); Object value; try { value = JsonPath.read(json, jsonPath); } catch (PathNotFoundException e) { throw new JsonElementNotFoundException("Path '" + jsonPath + "' was not found in JSON"); } return value; }
[ "@", "RobotKeyword", "public", "Object", "findJsonElement", "(", "String", "source", ",", "String", "jsonPath", ",", "String", "method", ",", "String", "data", ",", "String", "contentType", ")", "throws", "Exception", "{", "System", ".", "out", ".", "println",...
Find JSON element by `jsonPath` from the `source` and return its value if found. `source` can be either URI or the actual JSON content. You can add optional method (ie GET, POST, PUT), data or content type as parameters. Method defaults to GET. Example: | Find Json Element | http://example.com/test.json | $.foo.bar | | Find Json Element | {element: { param:hello, foo:bar } } | $.element.foo | | Find Json Element | {element: { param:hello, foo:bar } } | $.element.foo | POST | {hello: world} | application/json |
[ "Find", "JSON", "element", "by", "jsonPath", "from", "the", "source", "and", "return", "its", "value", "if", "found", "." ]
train
https://github.com/wiibaker/robotframework-rest-java/blob/e30a7e494c143b644ee4282137a5a38e75d9d97b/src/main/java/org/wuokko/robot/restlib/JsonPathLibrary.java#L243-L258
mgm-tp/jfunk
jfunk-common/src/main/java/com/mgmtp/jfunk/common/cli/CliUtils.java
CliUtils.executeCommandLine
public static CliOutput executeCommandLine(final Commandline cli, final String loggerName, final String logMessagePrefix) { try { String cliString = CommandLineUtils.toString(cli.getShellCommandline()); LOGGER.info("Executing command-line: {}", cliString); LoggingStreamConsumer out = new LoggingStreamConsumer(loggerName, logMessagePrefix, false); LoggingStreamConsumer err = new LoggingStreamConsumer(loggerName, logMessagePrefix, true); int exitCode = CommandLineUtils.executeCommandLine(cli, out, err); return new CliOutput(out.getOutput(), err.getOutput(), exitCode); } catch (CommandLineException ex) { throw new CliException("Error executing command-line process.", ex); } }
java
public static CliOutput executeCommandLine(final Commandline cli, final String loggerName, final String logMessagePrefix) { try { String cliString = CommandLineUtils.toString(cli.getShellCommandline()); LOGGER.info("Executing command-line: {}", cliString); LoggingStreamConsumer out = new LoggingStreamConsumer(loggerName, logMessagePrefix, false); LoggingStreamConsumer err = new LoggingStreamConsumer(loggerName, logMessagePrefix, true); int exitCode = CommandLineUtils.executeCommandLine(cli, out, err); return new CliOutput(out.getOutput(), err.getOutput(), exitCode); } catch (CommandLineException ex) { throw new CliException("Error executing command-line process.", ex); } }
[ "public", "static", "CliOutput", "executeCommandLine", "(", "final", "Commandline", "cli", ",", "final", "String", "loggerName", ",", "final", "String", "logMessagePrefix", ")", "{", "try", "{", "String", "cliString", "=", "CommandLineUtils", ".", "toString", "(",...
Executes the specified command line and blocks until the process has finished. The output of the process is captured, returned, as well as logged with info (stdout) and error (stderr) level, respectively. @param cli the command line @param loggerName the name of the logger to use (passed to {@link LoggerFactory#getLogger(String)}); if {@code null} this class' name is used @param logMessagePrefix if non-{@code null} consumed lines are prefix with this string @return the process' output
[ "Executes", "the", "specified", "command", "line", "and", "blocks", "until", "the", "process", "has", "finished", ".", "The", "output", "of", "the", "process", "is", "captured", "returned", "as", "well", "as", "logged", "with", "info", "(", "stdout", ")", ...
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/cli/CliUtils.java#L80-L92
rythmengine/rythmengine
src/main/java/org/rythmengine/toString/ToStringStyle.java
ToStringStyle.appendStart
public void appendStart(StringBuilder buffer, Object object) { if (object != null) { appendClassName(buffer, object); appendIdentityHashCode(buffer, object); appendContentStart(buffer); if (fieldSeparatorAtStart) { appendFieldSeparator(buffer); } } }
java
public void appendStart(StringBuilder buffer, Object object) { if (object != null) { appendClassName(buffer, object); appendIdentityHashCode(buffer, object); appendContentStart(buffer); if (fieldSeparatorAtStart) { appendFieldSeparator(buffer); } } }
[ "public", "void", "appendStart", "(", "StringBuilder", "buffer", ",", "Object", "object", ")", "{", "if", "(", "object", "!=", "null", ")", "{", "appendClassName", "(", "buffer", ",", "object", ")", ";", "appendIdentityHashCode", "(", "buffer", ",", "object"...
<p>Append to the <code>toString</code> the start of data indicator.</p> @param buffer the <code>StringBuilder</code> to populate @param object the <code>Object</code> to build a <code>toString</code> for
[ "<p", ">", "Append", "to", "the", "<code", ">", "toString<", "/", "code", ">", "the", "start", "of", "data", "indicator", ".", "<", "/", "p", ">" ]
train
https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/toString/ToStringStyle.java#L369-L378
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java
TheMovieDbApi.getCreditInfo
public CreditInfo getCreditInfo(String creditId, String language) throws MovieDbException { return tmdbCredits.getCreditInfo(creditId, language); }
java
public CreditInfo getCreditInfo(String creditId, String language) throws MovieDbException { return tmdbCredits.getCreditInfo(creditId, language); }
[ "public", "CreditInfo", "getCreditInfo", "(", "String", "creditId", ",", "String", "language", ")", "throws", "MovieDbException", "{", "return", "tmdbCredits", ".", "getCreditInfo", "(", "creditId", ",", "language", ")", ";", "}" ]
Get the detailed information about a particular credit record. <p> This is currently only supported with the new credit model found in TV. These IDs can be found from any TV credit response as well as the TV_credits and combined_credits methods for people.<br> The episodes object returns a list of episodes and are generally going to be guest stars. <br> The season array will return a list of season numbers. <br> Season credits are credits that were marked with the "add to every season" option in the editing interface and are assumed to be "season regulars". @param creditId creditId @param language language @return @throws MovieDbException exception
[ "Get", "the", "detailed", "information", "about", "a", "particular", "credit", "record", ".", "<p", ">", "This", "is", "currently", "only", "supported", "with", "the", "new", "credit", "model", "found", "in", "TV", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L623-L625
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/data/clock/Day.java
Day.getFirstOfMonth
public static Day getFirstOfMonth(int dayOfWeek, int month, int year) { return Day.getNthOfMonth(1, dayOfWeek, month, year); }
java
public static Day getFirstOfMonth(int dayOfWeek, int month, int year) { return Day.getNthOfMonth(1, dayOfWeek, month, year); }
[ "public", "static", "Day", "getFirstOfMonth", "(", "int", "dayOfWeek", ",", "int", "month", ",", "int", "year", ")", "{", "return", "Day", ".", "getNthOfMonth", "(", "1", ",", "dayOfWeek", ",", "month", ",", "year", ")", ";", "}" ]
Find the first of a specific day in a given month. For instance first Tuesday of May: getFirstOfMonth(Calendar.TUESDAY, Calendar.MAY, 2005); @param dayOfWeek Weekday to get. @param month Month of day to get. @param year Year of day to get. @return The requested day.
[ "Find", "the", "first", "of", "a", "specific", "day", "in", "a", "given", "month", ".", "For", "instance", "first", "Tuesday", "of", "May", ":", "getFirstOfMonth", "(", "Calendar", ".", "TUESDAY", "Calendar", ".", "MAY", "2005", ")", ";" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/data/clock/Day.java#L588-L591
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/config/ConfigValueHelper.java
ConfigValueHelper.checkNormalWithComma
protected static void checkNormalWithComma(String configKey, String configValue) throws SofaRpcRuntimeException { checkPattern(configKey, configValue, NORMAL_COMMA, "only allow a-zA-Z0-9 '-' '_' '.' ','"); }
java
protected static void checkNormalWithComma(String configKey, String configValue) throws SofaRpcRuntimeException { checkPattern(configKey, configValue, NORMAL_COMMA, "only allow a-zA-Z0-9 '-' '_' '.' ','"); }
[ "protected", "static", "void", "checkNormalWithComma", "(", "String", "configKey", ",", "String", "configValue", ")", "throws", "SofaRpcRuntimeException", "{", "checkPattern", "(", "configKey", ",", "configValue", ",", "NORMAL_COMMA", ",", "\"only allow a-zA-Z0-9 '-' '_' ...
检查字符串是否是正常值(含逗号),不是则抛出异常 @param configKey 配置项 @param configValue 配置值 @throws SofaRpcRuntimeException 非法异常
[ "检查字符串是否是正常值(含逗号),不是则抛出异常" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/config/ConfigValueHelper.java#L108-L110
jenkinsci/jenkins
core/src/main/java/hudson/ExtensionListView.java
ExtensionListView.createList
public static <T> List<T> createList(final Class<T> type) { return new AbstractList<T>() { private ExtensionList<T> storage() { return Jenkins.getInstance().getExtensionList(type); } @Override public Iterator<T> iterator() { return storage().iterator(); } public T get(int index) { return storage().get(index); } public int size() { return storage().size(); } @Override public boolean add(T t) { return storage().add(t); } @Override public void add(int index, T t) { // index ignored storage().add(t); } @Override public T remove(int index) { return storage().remove(index); } @Override public boolean remove(Object o) { return storage().remove(o); } }; }
java
public static <T> List<T> createList(final Class<T> type) { return new AbstractList<T>() { private ExtensionList<T> storage() { return Jenkins.getInstance().getExtensionList(type); } @Override public Iterator<T> iterator() { return storage().iterator(); } public T get(int index) { return storage().get(index); } public int size() { return storage().size(); } @Override public boolean add(T t) { return storage().add(t); } @Override public void add(int index, T t) { // index ignored storage().add(t); } @Override public T remove(int index) { return storage().remove(index); } @Override public boolean remove(Object o) { return storage().remove(o); } }; }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "createList", "(", "final", "Class", "<", "T", ">", "type", ")", "{", "return", "new", "AbstractList", "<", "T", ">", "(", ")", "{", "private", "ExtensionList", "<", "T", ">", "storage", "("...
Creates a plain {@link List} backed by the current {@link ExtensionList}.
[ "Creates", "a", "plain", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/ExtensionListView.java#L58-L98
duracloud/duracloud
durastore/src/main/java/org/duracloud/durastore/rest/SpaceResource.java
SpaceResource.getSpaceContents
public String getSpaceContents(String spaceID, String storeID, String prefix, long maxResults, String marker) throws ResourceException { Element spaceElem = new Element("space"); spaceElem.setAttribute("id", spaceID); try { StorageProvider storage = storageProviderFactory.getStorageProvider(storeID); List<String> contents = storage.getSpaceContentsChunked(spaceID, prefix, maxResults, marker); if (contents != null) { for (String contentItem : contents) { Element contentElem = new Element("item"); contentElem.setText(contentItem); spaceElem.addContent(contentElem); } } } catch (NotFoundException e) { throw new ResourceNotFoundException("build space XML for", spaceID, e); } catch (Exception e) { storageProviderFactory.expireStorageProvider(storeID); throw new ResourceException("build space XML for", spaceID, e); } Document doc = new Document(spaceElem); XMLOutputter xmlConverter = new XMLOutputter(); return xmlConverter.outputString(doc); }
java
public String getSpaceContents(String spaceID, String storeID, String prefix, long maxResults, String marker) throws ResourceException { Element spaceElem = new Element("space"); spaceElem.setAttribute("id", spaceID); try { StorageProvider storage = storageProviderFactory.getStorageProvider(storeID); List<String> contents = storage.getSpaceContentsChunked(spaceID, prefix, maxResults, marker); if (contents != null) { for (String contentItem : contents) { Element contentElem = new Element("item"); contentElem.setText(contentItem); spaceElem.addContent(contentElem); } } } catch (NotFoundException e) { throw new ResourceNotFoundException("build space XML for", spaceID, e); } catch (Exception e) { storageProviderFactory.expireStorageProvider(storeID); throw new ResourceException("build space XML for", spaceID, e); } Document doc = new Document(spaceElem); XMLOutputter xmlConverter = new XMLOutputter(); return xmlConverter.outputString(doc); }
[ "public", "String", "getSpaceContents", "(", "String", "spaceID", ",", "String", "storeID", ",", "String", "prefix", ",", "long", "maxResults", ",", "String", "marker", ")", "throws", "ResourceException", "{", "Element", "spaceElem", "=", "new", "Element", "(", ...
Gets a listing of the contents of a space. @param spaceID @param storeID @param prefix @param maxResults @param marker @return XML listing of space contents
[ "Gets", "a", "listing", "of", "the", "contents", "of", "a", "space", "." ]
train
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/durastore/src/main/java/org/duracloud/durastore/rest/SpaceResource.java#L126-L158
UrielCh/ovh-java-sdk
ovh-java-sdk-saascsp2/src/main/java/net/minidev/ovh/api/ApiOvhSaascsp2.java
ApiOvhSaascsp2.serviceName_subscription_POST
public OvhOfficeTask serviceName_subscription_POST(String serviceName, Long licenseId, Long quantity) throws IOException { String qPath = "/saas/csp2/{serviceName}/subscription"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "licenseId", licenseId); addBody(o, "quantity", quantity); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOfficeTask.class); }
java
public OvhOfficeTask serviceName_subscription_POST(String serviceName, Long licenseId, Long quantity) throws IOException { String qPath = "/saas/csp2/{serviceName}/subscription"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "licenseId", licenseId); addBody(o, "quantity", quantity); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOfficeTask.class); }
[ "public", "OvhOfficeTask", "serviceName_subscription_POST", "(", "String", "serviceName", ",", "Long", "licenseId", ",", "Long", "quantity", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/saas/csp2/{serviceName}/subscription\"", ";", "StringBuilder", "sb",...
Add a subscription to this tenant REST: POST /saas/csp2/{serviceName}/subscription @param licenseId [required] License's type unique identifier @param quantity [required] Quantity of licenses to order @param serviceName [required] The unique identifier of your Office service API beta
[ "Add", "a", "subscription", "to", "this", "tenant" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-saascsp2/src/main/java/net/minidev/ovh/api/ApiOvhSaascsp2.java#L70-L78
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java
TransformedRenditionHandler.rotateMapHeight
private long rotateMapHeight(long width, long height) { if (rotation != null && (rotation == ROTATE_90 || rotation == ROTATE_270)) { return width; } else { return height; } }
java
private long rotateMapHeight(long width, long height) { if (rotation != null && (rotation == ROTATE_90 || rotation == ROTATE_270)) { return width; } else { return height; } }
[ "private", "long", "rotateMapHeight", "(", "long", "width", ",", "long", "height", ")", "{", "if", "(", "rotation", "!=", "null", "&&", "(", "rotation", "==", "ROTATE_90", "||", "rotation", "==", "ROTATE_270", ")", ")", "{", "return", "width", ";", "}", ...
Swaps height with width if rotated 90° clock-wise or counter clock-wise @param width Rendition width @param height Rendition height @return Height
[ "Swaps", "height", "with", "width", "if", "rotated", "90°", "clock", "-", "wise", "or", "counter", "clock", "-", "wise" ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java#L149-L156
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/dataflow/PlainChangesLogImpl.java
PlainChangesLogImpl.getItemState
public ItemState getItemState(NodeData parentData, QPathEntry name, ItemType itemType) throws IllegalPathException { if (itemType != ItemType.UNKNOWN) { return index.get(new ParentIDQPathBasedKey(parentData.getIdentifier(), name, itemType)); } else { ItemState state = index.get(new ParentIDQPathBasedKey(parentData.getIdentifier(), name, ItemType.NODE)); if (state == null) { state = index.get(new ParentIDQPathBasedKey(parentData.getIdentifier(), name, ItemType.PROPERTY)); } return state; } }
java
public ItemState getItemState(NodeData parentData, QPathEntry name, ItemType itemType) throws IllegalPathException { if (itemType != ItemType.UNKNOWN) { return index.get(new ParentIDQPathBasedKey(parentData.getIdentifier(), name, itemType)); } else { ItemState state = index.get(new ParentIDQPathBasedKey(parentData.getIdentifier(), name, ItemType.NODE)); if (state == null) { state = index.get(new ParentIDQPathBasedKey(parentData.getIdentifier(), name, ItemType.PROPERTY)); } return state; } }
[ "public", "ItemState", "getItemState", "(", "NodeData", "parentData", ",", "QPathEntry", "name", ",", "ItemType", "itemType", ")", "throws", "IllegalPathException", "{", "if", "(", "itemType", "!=", "ItemType", ".", "UNKNOWN", ")", "{", "return", "index", ".", ...
Get ItemState by parent and item name. @param parentData parent @param name item name @param itemType item type @return @throws IllegalPathException
[ "Get", "ItemState", "by", "parent", "and", "item", "name", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/dataflow/PlainChangesLogImpl.java#L716-L731
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201808/placementservice/GetAllPlacements.java
GetAllPlacements.runExample
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the PlacementService. PlacementServiceInterface placementService = adManagerServices.get(session, PlacementServiceInterface.class); // Create a statement to get all placements. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get placements by statement. PlacementPage page = placementService.getPlacementsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (Placement placement : page.getResults()) { System.out.printf( "%d) Placement with ID %d and name '%s' was found.%n", i++, placement.getId(), placement.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the PlacementService. PlacementServiceInterface placementService = adManagerServices.get(session, PlacementServiceInterface.class); // Create a statement to get all placements. StatementBuilder statementBuilder = new StatementBuilder() .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Default for total result set size. int totalResultSetSize = 0; do { // Get placements by statement. PlacementPage page = placementService.getPlacementsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (Placement placement : page.getResults()) { System.out.printf( "%d) Placement with ID %d and name '%s' was found.%n", i++, placement.getId(), placement.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
[ "public", "static", "void", "runExample", "(", "AdManagerServices", "adManagerServices", ",", "AdManagerSession", "session", ")", "throws", "RemoteException", "{", "// Get the PlacementService.", "PlacementServiceInterface", "placementService", "=", "adManagerServices", ".", ...
Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors.
[ "Runs", "the", "example", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/placementservice/GetAllPlacements.java#L52-L85
lucee/Lucee
core/src/main/java/lucee/runtime/net/ldap/LDAPClient.java
LDAPClient.modifydn
public void modifydn(String dn, String attributes) throws NamingException { DirContext ctx = new InitialDirContext(env); ctx.rename(dn, attributes); ctx.close(); }
java
public void modifydn(String dn, String attributes) throws NamingException { DirContext ctx = new InitialDirContext(env); ctx.rename(dn, attributes); ctx.close(); }
[ "public", "void", "modifydn", "(", "String", "dn", ",", "String", "attributes", ")", "throws", "NamingException", "{", "DirContext", "ctx", "=", "new", "InitialDirContext", "(", "env", ")", ";", "ctx", ".", "rename", "(", "dn", ",", "attributes", ")", ";",...
modifies distinguished name attribute for LDAP entries on LDAP server @param dn @param attributes @throws NamingException
[ "modifies", "distinguished", "name", "attribute", "for", "LDAP", "entries", "on", "LDAP", "server" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/net/ldap/LDAPClient.java#L203-L207
hibernate/hibernate-ogm
infinispan-remote/src/main/java/org/hibernate/ogm/datastore/infinispanremote/impl/protobuf/schema/SchemaDefinitions.java
SchemaDefinitions.deploySchema
public void deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService, URL schemaOverrideResource) { // user defined schema if ( schemaOverrideService != null || schemaOverrideResource != null ) { cachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema(); } // or generate them generateProtoschema(); try { protobufCache.put( generatedProtobufName, cachedSchema ); String errors = protobufCache.get( generatedProtobufName + ".errors" ); if ( errors != null ) { throw LOG.errorAtSchemaDeploy( generatedProtobufName, errors ); } LOG.successfulSchemaDeploy( generatedProtobufName ); } catch (HotRodClientException hrce) { throw LOG.errorAtSchemaDeploy( generatedProtobufName, hrce ); } if ( schemaCapture != null ) { schemaCapture.put( generatedProtobufName, cachedSchema ); } }
java
public void deploySchema(String generatedProtobufName, RemoteCache<String, String> protobufCache, SchemaCapture schemaCapture, SchemaOverride schemaOverrideService, URL schemaOverrideResource) { // user defined schema if ( schemaOverrideService != null || schemaOverrideResource != null ) { cachedSchema = new SchemaValidator( this, schemaOverrideService, schemaOverrideResource, generatedProtobufName ).provideSchema(); } // or generate them generateProtoschema(); try { protobufCache.put( generatedProtobufName, cachedSchema ); String errors = protobufCache.get( generatedProtobufName + ".errors" ); if ( errors != null ) { throw LOG.errorAtSchemaDeploy( generatedProtobufName, errors ); } LOG.successfulSchemaDeploy( generatedProtobufName ); } catch (HotRodClientException hrce) { throw LOG.errorAtSchemaDeploy( generatedProtobufName, hrce ); } if ( schemaCapture != null ) { schemaCapture.put( generatedProtobufName, cachedSchema ); } }
[ "public", "void", "deploySchema", "(", "String", "generatedProtobufName", ",", "RemoteCache", "<", "String", ",", "String", ">", "protobufCache", ",", "SchemaCapture", "schemaCapture", ",", "SchemaOverride", "schemaOverrideService", ",", "URL", "schemaOverrideResource", ...
Typically this is transparently handled by using the Protostream codecs but be aware of it when bypassing Protostream.
[ "Typically", "this", "is", "transparently", "handled", "by", "using", "the", "Protostream", "codecs", "but", "be", "aware", "of", "it", "when", "bypassing", "Protostream", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/infinispan-remote/src/main/java/org/hibernate/ogm/datastore/infinispanremote/impl/protobuf/schema/SchemaDefinitions.java#L54-L78
Alexey1Gavrilov/ExpectIt
expectit-core/src/main/java/net/sf/expectit/filter/Filters.java
Filters.replaceInBuffer
public static Filter replaceInBuffer(final Pattern regexp, final String replacement) { return new FilterAdapter() { @Override protected boolean doAfterAppend(StringBuilder buffer) { Matcher matcher = regexp.matcher(buffer); String str = matcher.replaceAll(replacement); buffer.replace(0, buffer.length(), str); return false; } }; }
java
public static Filter replaceInBuffer(final Pattern regexp, final String replacement) { return new FilterAdapter() { @Override protected boolean doAfterAppend(StringBuilder buffer) { Matcher matcher = regexp.matcher(buffer); String str = matcher.replaceAll(replacement); buffer.replace(0, buffer.length(), str); return false; } }; }
[ "public", "static", "Filter", "replaceInBuffer", "(", "final", "Pattern", "regexp", ",", "final", "String", "replacement", ")", "{", "return", "new", "FilterAdapter", "(", ")", "{", "@", "Override", "protected", "boolean", "doAfterAppend", "(", "StringBuilder", ...
Creates a filter which replaces every substring in the input buffer that matches the given regular expression and replaces it with given replacement. <p/> The method just calls {@link String#replaceAll(String, String)} for the entire buffer contents every time new data arrives, @param regexp the regular expression @param replacement the string to be substituted for each match @return the filter
[ "Creates", "a", "filter", "which", "replaces", "every", "substring", "in", "the", "input", "buffer", "that", "matches", "the", "given", "regular", "expression", "and", "replaces", "it", "with", "given", "replacement", ".", "<p", "/", ">", "The", "method", "j...
train
https://github.com/Alexey1Gavrilov/ExpectIt/blob/5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3/expectit-core/src/main/java/net/sf/expectit/filter/Filters.java#L168-L178
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/ant/RepositoryVerifierHandler.java
RepositoryVerifierHandler.getLiteralId
private int getLiteralId(String literal) throws PersistenceBrokerException { ////logger.debug("lookup: " + literal); try { return tags.getIdByTag(literal); } catch (NullPointerException t) { throw new MetadataException("unknown literal: '" + literal + "'",t); } }
java
private int getLiteralId(String literal) throws PersistenceBrokerException { ////logger.debug("lookup: " + literal); try { return tags.getIdByTag(literal); } catch (NullPointerException t) { throw new MetadataException("unknown literal: '" + literal + "'",t); } }
[ "private", "int", "getLiteralId", "(", "String", "literal", ")", "throws", "PersistenceBrokerException", "{", "////logger.debug(\"lookup: \" + literal);\r", "try", "{", "return", "tags", ".", "getIdByTag", "(", "literal", ")", ";", "}", "catch", "(", "NullPointerExcep...
returns the XmlCapable id associated with the literal. OJB maintains a RepositoryTags table that provides a mapping from xml-tags to XmlCapable ids. @param literal the literal to lookup @return the int value representing the XmlCapable @throws MetadataException if no literal was found in tags mapping
[ "returns", "the", "XmlCapable", "id", "associated", "with", "the", "literal", ".", "OJB", "maintains", "a", "RepositoryTags", "table", "that", "provides", "a", "mapping", "from", "xml", "-", "tags", "to", "XmlCapable", "ids", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/ant/RepositoryVerifierHandler.java#L108-L120
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/utils/FastDateFormat.java
FastDateFormat.getDateInstance
public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale == null) { locale = Locale.getDefault(); } key = new Pair(key, locale); FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key); if (format == null) { try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; }
java
public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale == null) { locale = Locale.getDefault(); } key = new Pair(key, locale); FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key); if (format == null) { try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; }
[ "public", "static", "synchronized", "FastDateFormat", "getDateInstance", "(", "int", "style", ",", "TimeZone", "timeZone", ",", "Locale", "locale", ")", "{", "Object", "key", "=", "new", "Integer", "(", "style", ")", ";", "if", "(", "timeZone", "!=", "null",...
<p>Gets a date formatter instance using the specified style, time zone and locale.</p> @param style date style: FULL, LONG, MEDIUM, or SHORT @param timeZone optional time zone, overrides time zone of formatted date @param locale optional locale, overrides system locale @return a localized standard date formatter @throws IllegalArgumentException if the Locale has no date pattern defined
[ "<p", ">", "Gets", "a", "date", "formatter", "instance", "using", "the", "specified", "style", "time", "zone", "and", "locale", ".", "<", "/", "p", ">" ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/utils/FastDateFormat.java#L281-L306
NICTA/nicta-ner
conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java
Util.positionClassificationMap
public static Map<Integer, NerClassification> positionClassificationMap(final NerResultSet nerResultSet) { final Map<Integer, NerClassification> m = new HashMap<>(); for (final List<Phrase> sentence : nerResultSet.phrases) { for (final Phrase p : sentence) { final int phraseStartIndex = p.phrase.get(0).startIndex; for (final Token t : p.phrase) { final NerClassification clas = new NerClassification(t.text, p.phraseType, phraseStartIndex, p.score); final NerClassification replaced = m.put(t.startIndex, clas); if (replaced != null) { // since modifying the contents of the map this error should now never happen System.err.println("########### Error start"); System.err.print(nerResultSet); throw new IllegalStateException("Tried to add a Token to the position classification map " + "with startIndex " + t.startIndex + " that is already there!"); } } } } return m; }
java
public static Map<Integer, NerClassification> positionClassificationMap(final NerResultSet nerResultSet) { final Map<Integer, NerClassification> m = new HashMap<>(); for (final List<Phrase> sentence : nerResultSet.phrases) { for (final Phrase p : sentence) { final int phraseStartIndex = p.phrase.get(0).startIndex; for (final Token t : p.phrase) { final NerClassification clas = new NerClassification(t.text, p.phraseType, phraseStartIndex, p.score); final NerClassification replaced = m.put(t.startIndex, clas); if (replaced != null) { // since modifying the contents of the map this error should now never happen System.err.println("########### Error start"); System.err.print(nerResultSet); throw new IllegalStateException("Tried to add a Token to the position classification map " + "with startIndex " + t.startIndex + " that is already there!"); } } } } return m; }
[ "public", "static", "Map", "<", "Integer", ",", "NerClassification", ">", "positionClassificationMap", "(", "final", "NerResultSet", "nerResultSet", ")", "{", "final", "Map", "<", "Integer", ",", "NerClassification", ">", "m", "=", "new", "HashMap", "<>", "(", ...
Return a Map of Token startIndex to classification of the Phrase that Token is a part of.
[ "Return", "a", "Map", "of", "Token", "startIndex", "to", "classification", "of", "the", "Phrase", "that", "Token", "is", "a", "part", "of", "." ]
train
https://github.com/NICTA/nicta-ner/blob/c2156a0e299004e586926777a995b7795f35ff1c/conll2003-evaluation/src/main/java/org/t3as/ner/conll2003/Util.java#L39-L61
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkTapsInner.java
VirtualNetworkTapsInner.beginUpdateTags
public VirtualNetworkTapInner beginUpdateTags(String resourceGroupName, String tapName) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, tapName).toBlocking().single().body(); }
java
public VirtualNetworkTapInner beginUpdateTags(String resourceGroupName, String tapName) { return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, tapName).toBlocking().single().body(); }
[ "public", "VirtualNetworkTapInner", "beginUpdateTags", "(", "String", "resourceGroupName", ",", "String", "tapName", ")", "{", "return", "beginUpdateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "tapName", ")", ".", "toBlocking", "(", ")", ".", "single",...
Updates an VirtualNetworkTap tags. @param resourceGroupName The name of the resource group. @param tapName The name of the tap. @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 VirtualNetworkTapInner object if successful.
[ "Updates", "an", "VirtualNetworkTap", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VirtualNetworkTapsInner.java#L672-L674
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowControllerFactory.java
FlowControllerFactory.getPageFlowForURI
public static PageFlowController getPageFlowForURI( HttpServletRequest request, HttpServletResponse response, String uri, ServletContext servletContext ) { return getPageFlowForRelativeURI( request, response, PageFlowUtils.getRelativeURI( request, uri, null ), servletContext ); }
java
public static PageFlowController getPageFlowForURI( HttpServletRequest request, HttpServletResponse response, String uri, ServletContext servletContext ) { return getPageFlowForRelativeURI( request, response, PageFlowUtils.getRelativeURI( request, uri, null ), servletContext ); }
[ "public", "static", "PageFlowController", "getPageFlowForURI", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "String", "uri", ",", "ServletContext", "servletContext", ")", "{", "return", "getPageFlowForRelativeURI", "(", "request", ","...
Get the page flow instance that should be associated with the given URI. If it doesn't exist, create it. If one is created, the page flow stack (for nesting) will be cleared or pushed, and the new instance will be stored as the current page flow. @deprecated Use {@link #getPageFlowForPath(RequestContext, String)} instead. The URI must be stripped of the webapp context path before being passed. @param request the current HttpServletRequest. @param response the current HttpServletResponse. @param uri a server-relative URI. The URI should contain the webapp context path. @param servletContext the current ServletContext. @return the {@link PageFlowController} for the given URI, or <code>null</code> if none was found.
[ "Get", "the", "page", "flow", "instance", "that", "should", "be", "associated", "with", "the", "given", "URI", ".", "If", "it", "doesn", "t", "exist", "create", "it", ".", "If", "one", "is", "created", "the", "page", "flow", "stack", "(", "for", "nesti...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowControllerFactory.java#L587-L594
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.typeTextInWebElement
public void typeTextInWebElement(By by, String text){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "typeTextInWebElement("+by+", \""+text+"\")"); } typeTextInWebElement(by, text, 0); }
java
public void typeTextInWebElement(By by, String text){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "typeTextInWebElement("+by+", \""+text+"\")"); } typeTextInWebElement(by, text, 0); }
[ "public", "void", "typeTextInWebElement", "(", "By", "by", ",", "String", "text", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"typeTextInWebElement(\"", "+", "by", "+", "\...
Types text in a WebElement matching the specified By object. @param by the By object. Examples are: {@code By.id("id")} and {@code By.name("name")} @param text the text to enter in the {@link WebElement} field
[ "Types", "text", "in", "a", "WebElement", "matching", "the", "specified", "By", "object", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L2744-L2750
code4everything/util
src/main/java/com/zhazhapan/util/DateUtils.java
DateUtils.addYear
public static Date addYear(String date, int amount) throws ParseException { return add(date, Calendar.YEAR, amount); }
java
public static Date addYear(String date, int amount) throws ParseException { return add(date, Calendar.YEAR, amount); }
[ "public", "static", "Date", "addYear", "(", "String", "date", ",", "int", "amount", ")", "throws", "ParseException", "{", "return", "add", "(", "date", ",", "Calendar", ".", "YEAR", ",", "amount", ")", ";", "}" ]
添加年份 @param date 日期 @param amount 数量 @return 添加后的日期 @throws ParseException 异常
[ "添加年份" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/DateUtils.java#L397-L399
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java
Collections.everyWithin
public static SatisfiesBuilder everyWithin(String variable, Expression expression) { return new SatisfiesBuilder(x("EVERY"), variable, expression, false); }
java
public static SatisfiesBuilder everyWithin(String variable, Expression expression) { return new SatisfiesBuilder(x("EVERY"), variable, expression, false); }
[ "public", "static", "SatisfiesBuilder", "everyWithin", "(", "String", "variable", ",", "Expression", "expression", ")", "{", "return", "new", "SatisfiesBuilder", "(", "x", "(", "\"EVERY\"", ")", ",", "variable", ",", "expression", ",", "false", ")", ";", "}" ]
Create an EVERY comprehension with a first WITHIN range. EVERY is a range predicate that allows you to test a Boolean condition over the elements or attributes of a collection, object, or objects. It uses the IN and WITHIN operators to range through the collection. IN ranges in the direct elements of its array expression, WITHIN also ranges in its descendants. If every array element satisfies the EVERY expression, it returns TRUE. Otherwise it returns FALSE. If the array is empty, it returns TRUE.
[ "Create", "an", "EVERY", "comprehension", "with", "a", "first", "WITHIN", "range", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java#L214-L216
sarl/sarl
sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/spawn/StandardSpawnService.java
StandardSpawnService.fireAgentSpawnedOutsideAgent
protected void fireAgentSpawnedOutsideAgent(UUID spawningAgent, AgentContext context, Class<? extends Agent> agentClazz, List<Agent> agents, Object... initializationParameters) { // Notify the listeners on the spawn events (not restricted to a single agent) for (final SpawnServiceListener l : this.globalListeners.getListeners(SpawnServiceListener.class)) { l.agentSpawned(spawningAgent, context, agents, initializationParameters); } // Send the event in the default space. final EventSpace defSpace = context.getDefaultSpace(); assert defSpace != null : "A context does not contain a default space"; //$NON-NLS-1$ final UUID spawner = spawningAgent == null ? context.getID() : spawningAgent; final Address source = new Address(defSpace.getSpaceID(), spawner); assert source != null; final Collection<UUID> spawnedAgentIds = Collections3.serializableCollection( Collections2.transform(agents, it -> it.getID())); final AgentSpawned event = new AgentSpawned(source, agentClazz.getName(), spawnedAgentIds); final Scope<Address> scope = address -> { final UUID receiver = address.getUUID(); return !spawnedAgentIds.parallelStream().anyMatch(it -> it.equals(receiver)); }; // Event must not be received by the spawned agent. defSpace.emit( // No need to give an event source because it is explicitly set above. null, event, scope); }
java
protected void fireAgentSpawnedOutsideAgent(UUID spawningAgent, AgentContext context, Class<? extends Agent> agentClazz, List<Agent> agents, Object... initializationParameters) { // Notify the listeners on the spawn events (not restricted to a single agent) for (final SpawnServiceListener l : this.globalListeners.getListeners(SpawnServiceListener.class)) { l.agentSpawned(spawningAgent, context, agents, initializationParameters); } // Send the event in the default space. final EventSpace defSpace = context.getDefaultSpace(); assert defSpace != null : "A context does not contain a default space"; //$NON-NLS-1$ final UUID spawner = spawningAgent == null ? context.getID() : spawningAgent; final Address source = new Address(defSpace.getSpaceID(), spawner); assert source != null; final Collection<UUID> spawnedAgentIds = Collections3.serializableCollection( Collections2.transform(agents, it -> it.getID())); final AgentSpawned event = new AgentSpawned(source, agentClazz.getName(), spawnedAgentIds); final Scope<Address> scope = address -> { final UUID receiver = address.getUUID(); return !spawnedAgentIds.parallelStream().anyMatch(it -> it.equals(receiver)); }; // Event must not be received by the spawned agent. defSpace.emit( // No need to give an event source because it is explicitly set above. null, event, scope); }
[ "protected", "void", "fireAgentSpawnedOutsideAgent", "(", "UUID", "spawningAgent", ",", "AgentContext", "context", ",", "Class", "<", "?", "extends", "Agent", ">", "agentClazz", ",", "List", "<", "Agent", ">", "agents", ",", "Object", "...", "initializationParamet...
Notify the listeners about the agents' spawning. @param spawningAgent the spawning agent. @param context the context in which the agents were spawned. @param agentClazz the type of the spwnaed agents. @param agents the spawned agents. @param initializationParameters the initialization parameters.
[ "Notify", "the", "listeners", "about", "the", "agents", "spawning", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.plugin/src/io/janusproject/kernel/services/jdk/spawn/StandardSpawnService.java#L213-L239
Stratio/stratio-connector-commons
connector-commons/src/main/java/com/stratio/connector/commons/util/SelectorHelper.java
SelectorHelper.getRestrictedValue
public static Object getRestrictedValue(Selector selector, SelectorType type) throws ExecutionException { Object field = null; if (type != null && selector.getType() != type) { throw new ExecutionException("The selector type expected is: " + type + " but received: " + selector.getType()); } switch (selector.getType()) { case COLUMN: field = ((ColumnSelector) selector).getName().getName(); break; case BOOLEAN: field = ((BooleanSelector) selector).getValue(); break; case STRING: field = ((StringSelector) selector).getValue(); break; case INTEGER: field = ((IntegerSelector) selector).getValue(); break; case FLOATING_POINT: field = ((FloatingPointSelector) selector).getValue(); break; case GROUP: field = getRestrictedValue(((GroupSelector) selector).getFirstValue(), null); break; case LIST: if (((ListSelector) selector).getSelectorsList().isEmpty()){ throw new ExecutionException("Selector " + selector.getType() + " not supported get value operation."); } field = getRestrictedValue(((ListSelector)selector).getSelectorsList().get(0), null); break; default: throw new ExecutionException("Selector " + selector.getType() + " not supported get value operation."); } return field; }
java
public static Object getRestrictedValue(Selector selector, SelectorType type) throws ExecutionException { Object field = null; if (type != null && selector.getType() != type) { throw new ExecutionException("The selector type expected is: " + type + " but received: " + selector.getType()); } switch (selector.getType()) { case COLUMN: field = ((ColumnSelector) selector).getName().getName(); break; case BOOLEAN: field = ((BooleanSelector) selector).getValue(); break; case STRING: field = ((StringSelector) selector).getValue(); break; case INTEGER: field = ((IntegerSelector) selector).getValue(); break; case FLOATING_POINT: field = ((FloatingPointSelector) selector).getValue(); break; case GROUP: field = getRestrictedValue(((GroupSelector) selector).getFirstValue(), null); break; case LIST: if (((ListSelector) selector).getSelectorsList().isEmpty()){ throw new ExecutionException("Selector " + selector.getType() + " not supported get value operation."); } field = getRestrictedValue(((ListSelector)selector).getSelectorsList().get(0), null); break; default: throw new ExecutionException("Selector " + selector.getType() + " not supported get value operation."); } return field; }
[ "public", "static", "Object", "getRestrictedValue", "(", "Selector", "selector", ",", "SelectorType", "type", ")", "throws", "ExecutionException", "{", "Object", "field", "=", "null", ";", "if", "(", "type", "!=", "null", "&&", "selector", ".", "getType", "(",...
Return the selector value only if the type matches with the specified value. @param selector the selector. @param type the type of the expected selector @return the corresponding value or null if the selector type does not match. @throws ExecutionException if an error happens.
[ "Return", "the", "selector", "value", "only", "if", "the", "type", "matches", "with", "the", "specified", "value", "." ]
train
https://github.com/Stratio/stratio-connector-commons/blob/d7cc66cb9591344a13055962e87a91f01c3707d1/connector-commons/src/main/java/com/stratio/connector/commons/util/SelectorHelper.java#L78-L118
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/DdosProtectionPlansInner.java
DdosProtectionPlansInner.createOrUpdate
public DdosProtectionPlanInner createOrUpdate(String resourceGroupName, String ddosProtectionPlanName, DdosProtectionPlanInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, ddosProtectionPlanName, parameters).toBlocking().last().body(); }
java
public DdosProtectionPlanInner createOrUpdate(String resourceGroupName, String ddosProtectionPlanName, DdosProtectionPlanInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, ddosProtectionPlanName, parameters).toBlocking().last().body(); }
[ "public", "DdosProtectionPlanInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "ddosProtectionPlanName", ",", "DdosProtectionPlanInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "ddosPr...
Creates or updates a DDoS protection plan. @param resourceGroupName The name of the resource group. @param ddosProtectionPlanName The name of the DDoS protection plan. @param parameters Parameters supplied to the create or update operation. @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 DdosProtectionPlanInner object if successful.
[ "Creates", "or", "updates", "a", "DDoS", "protection", "plan", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/DdosProtectionPlansInner.java#L351-L353
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/RectifyImageOps.java
RectifyImageOps.rectifyImage
public static <T extends ImageGray<T>> ImageDistort<T,T> rectifyImage( FMatrixRMaj rectify , BorderType borderType, Class<T> imageType) { boolean skip = borderType == BorderType.SKIP; if( skip ) { borderType = BorderType.EXTENDED; } InterpolatePixelS<T> interp = FactoryInterpolation.bilinearPixelS(imageType, borderType); FMatrixRMaj rectifyInv = new FMatrixRMaj(3,3); CommonOps_FDRM.invert(rectify,rectifyInv); PointTransformHomography_F32 rectifyTran = new PointTransformHomography_F32(rectifyInv); // don't bother caching the results since it is likely to only be applied once and is cheap to compute ImageDistort<T,T> ret = FactoryDistort.distortSB(false, interp, imageType); ret.setRenderAll(!skip); ret.setModel(new PointToPixelTransform_F32(rectifyTran)); return ret; }
java
public static <T extends ImageGray<T>> ImageDistort<T,T> rectifyImage( FMatrixRMaj rectify , BorderType borderType, Class<T> imageType) { boolean skip = borderType == BorderType.SKIP; if( skip ) { borderType = BorderType.EXTENDED; } InterpolatePixelS<T> interp = FactoryInterpolation.bilinearPixelS(imageType, borderType); FMatrixRMaj rectifyInv = new FMatrixRMaj(3,3); CommonOps_FDRM.invert(rectify,rectifyInv); PointTransformHomography_F32 rectifyTran = new PointTransformHomography_F32(rectifyInv); // don't bother caching the results since it is likely to only be applied once and is cheap to compute ImageDistort<T,T> ret = FactoryDistort.distortSB(false, interp, imageType); ret.setRenderAll(!skip); ret.setModel(new PointToPixelTransform_F32(rectifyTran)); return ret; }
[ "public", "static", "<", "T", "extends", "ImageGray", "<", "T", ">", ">", "ImageDistort", "<", "T", ",", "T", ">", "rectifyImage", "(", "FMatrixRMaj", "rectify", ",", "BorderType", "borderType", ",", "Class", "<", "T", ">", "imageType", ")", "{", "boolea...
Creates an {@link ImageDistort} for rectifying an image given its rectification matrix. Lens distortion is assumed to have been previously removed. @param rectify Transform for rectifying the image. @param imageType Type of single band image the transform is to be applied to. @return ImageDistort for rectifying the image.
[ "Creates", "an", "{", "@link", "ImageDistort", "}", "for", "rectifying", "an", "image", "given", "its", "rectification", "matrix", ".", "Lens", "distortion", "is", "assumed", "to", "have", "been", "previously", "removed", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/RectifyImageOps.java#L376-L396
xiancloud/xian
xian-message/src/main/java/info/xiancloud/message/short_msg/yunpian/JavaSmsApi.java
JavaSmsApi.sendVoice
public static Single<String> sendVoice(String apikey, String mobile, String code) { Map<String, String> params = new HashMap<>(); params.put("apikey", apikey); params.put("mobile", mobile); params.put("code", code); return post(URI_SEND_VOICE, params); }
java
public static Single<String> sendVoice(String apikey, String mobile, String code) { Map<String, String> params = new HashMap<>(); params.put("apikey", apikey); params.put("mobile", mobile); params.put("code", code); return post(URI_SEND_VOICE, params); }
[ "public", "static", "Single", "<", "String", ">", "sendVoice", "(", "String", "apikey", ",", "String", "mobile", ",", "String", "code", ")", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "params", ...
通过接口发送语音验证码 @param apikey apikey @param mobile 接收的手机号 @param code 验证码 @return the http result
[ "通过接口发送语音验证码" ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-message/src/main/java/info/xiancloud/message/short_msg/yunpian/JavaSmsApi.java#L126-L132
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java
ElementMatchers.takesArgument
public static <T extends MethodDescription> ElementMatcher.Junction<T> takesArgument(int index, Class<?> type) { return takesArgument(index, TypeDescription.ForLoadedType.of(type)); }
java
public static <T extends MethodDescription> ElementMatcher.Junction<T> takesArgument(int index, Class<?> type) { return takesArgument(index, TypeDescription.ForLoadedType.of(type)); }
[ "public", "static", "<", "T", "extends", "MethodDescription", ">", "ElementMatcher", ".", "Junction", "<", "T", ">", "takesArgument", "(", "int", "index", ",", "Class", "<", "?", ">", "type", ")", "{", "return", "takesArgument", "(", "index", ",", "TypeDes...
Matches {@link MethodDescription}s that define a given generic type as a parameter at the given index. @param index The index of the parameter. @param type The erasure of the type the matched method is expected to define as a parameter type. @param <T> The type of the matched object. @return An element matcher that matches a given argument type for a method description.
[ "Matches", "{", "@link", "MethodDescription", "}", "s", "that", "define", "a", "given", "generic", "type", "as", "a", "parameter", "at", "the", "given", "index", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java#L1242-L1244
googleapis/google-cloud-java
google-cloud-clients/google-cloud-talent/src/main/java/com/google/cloud/talent/v4beta1/JobServiceClient.java
JobServiceClient.batchDeleteJobs
public final void batchDeleteJobs(String parent, String filter) { BatchDeleteJobsRequest request = BatchDeleteJobsRequest.newBuilder().setParent(parent).setFilter(filter).build(); batchDeleteJobs(request); }
java
public final void batchDeleteJobs(String parent, String filter) { BatchDeleteJobsRequest request = BatchDeleteJobsRequest.newBuilder().setParent(parent).setFilter(filter).build(); batchDeleteJobs(request); }
[ "public", "final", "void", "batchDeleteJobs", "(", "String", "parent", ",", "String", "filter", ")", "{", "BatchDeleteJobsRequest", "request", "=", "BatchDeleteJobsRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", ")", ".", "setFilter", "("...
Deletes a list of [Job][google.cloud.talent.v4beta1.Job]s by filter. <p>Sample code: <pre><code> try (JobServiceClient jobServiceClient = JobServiceClient.create()) { TenantOrProjectName parent = TenantName.of("[PROJECT]", "[TENANT]"); String filter = ""; jobServiceClient.batchDeleteJobs(parent.toString(), filter); } </code></pre> @param parent Required. <p>The resource name of the tenant under which the job is created. <p>The format is "projects/{project_id}/tenants/{tenant_id}", for example, "projects/api-test-project/tenant/foo". <p>Tenant id is optional and the default tenant is used if unspecified, for example, "projects/api-test-project". @param filter Required. <p>The filter string specifies the jobs to be deleted. <p>Supported operator: =, AND <p>The fields eligible for filtering are: <p>&#42; `companyName` (Required) &#42; `requisitionId` (Required) <p>Sample Query: companyName = "projects/api-test-project/companies/123" AND requisitionId = "req-1" @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Deletes", "a", "list", "of", "[", "Job", "]", "[", "google", ".", "cloud", ".", "talent", ".", "v4beta1", ".", "Job", "]", "s", "by", "filter", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-talent/src/main/java/com/google/cloud/talent/v4beta1/JobServiceClient.java#L802-L807
alkacon/opencms-core
src/org/opencms/ade/contenteditor/A_CmsXmlContentEditorChangeHandler.java
A_CmsXmlContentEditorChangeHandler.resolveRelativePath
public String resolveRelativePath(String source, String target) { String result = null; if (target.startsWith(".")) { if (target.startsWith("./")) { target = target.substring(2); } while (target.startsWith("../")) { source = CmsResource.getParentFolder(source); target = target.substring(3); } result = CmsStringUtil.joinPaths(source, target); } else { result = target; } return result; }
java
public String resolveRelativePath(String source, String target) { String result = null; if (target.startsWith(".")) { if (target.startsWith("./")) { target = target.substring(2); } while (target.startsWith("../")) { source = CmsResource.getParentFolder(source); target = target.substring(3); } result = CmsStringUtil.joinPaths(source, target); } else { result = target; } return result; }
[ "public", "String", "resolveRelativePath", "(", "String", "source", ",", "String", "target", ")", "{", "String", "result", "=", "null", ";", "if", "(", "target", ".", "startsWith", "(", "\".\"", ")", ")", "{", "if", "(", "target", ".", "startsWith", "(",...
Resolves a relative content value path to an absolute one.<p> @param source the source path @param target the target path @return the resolved path
[ "Resolves", "a", "relative", "content", "value", "path", "to", "an", "absolute", "one", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/contenteditor/A_CmsXmlContentEditorChangeHandler.java#L69-L85
Axway/Grapes
commons/src/main/java/org/axway/grapes/commons/datamodel/DataModelFactory.java
DataModelFactory.createArtifact
public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){ final Artifact artifact = new Artifact(); artifact.setGroupId(groupId); artifact.setArtifactId(artifactId); artifact.setVersion(version); if(classifier != null){ artifact.setClassifier(classifier); } if(type != null){ artifact.setType(type); } if(extension != null){ artifact.setExtension(extension); } artifact.setOrigin(origin == null ? "maven" : origin); return artifact; }
java
public static Artifact createArtifact(final String groupId, final String artifactId, final String version, final String classifier, final String type, final String extension, final String origin){ final Artifact artifact = new Artifact(); artifact.setGroupId(groupId); artifact.setArtifactId(artifactId); artifact.setVersion(version); if(classifier != null){ artifact.setClassifier(classifier); } if(type != null){ artifact.setType(type); } if(extension != null){ artifact.setExtension(extension); } artifact.setOrigin(origin == null ? "maven" : origin); return artifact; }
[ "public", "static", "Artifact", "createArtifact", "(", "final", "String", "groupId", ",", "final", "String", "artifactId", ",", "final", "String", "version", ",", "final", "String", "classifier", ",", "final", "String", "type", ",", "final", "String", "extension...
Generates an artifact regarding the parameters. <P> <b>WARNING:</b> The parameters grId/arId/version should be filled!!! Only classifier and type are not mandatory. @param groupId String @param artifactId String @param version String @param classifier String @param type String @param extension String @return Artifact
[ "Generates", "an", "artifact", "regarding", "the", "parameters", "." ]
train
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/commons/src/main/java/org/axway/grapes/commons/datamodel/DataModelFactory.java#L90-L112
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRadioButtonSelectExample.java
WRadioButtonSelectExample.addInsideAFieldLayoutExample
private void addInsideAFieldLayoutExample() { add(new WHeading(HeadingLevel.H3, "WRadioButtonSelect inside a WFieldLayout")); add(new ExplanatoryText( "When a WRadioButtonSelect is inside a WField its label is exposed in a way which appears and behaves like a regular HTML label." + " This allows WRadioButtonSelects to be used in a layout with simple form controls (such as WTextField) and produce a consistent" + " and predicatable interface.\n" + "The third example in this set uses a null label and a toolTip to hide the labelling element. This can lead to user confusion and" + " is not recommended.")); // Note: the wrapper WPanel here is to work around a bug in validation. See https://github.com/BorderTech/wcomponents/issues/1370 final WPanel wrapper = new WPanel(); add(wrapper); final WMessages messages = new WMessages(); wrapper.add(messages); WFieldLayout layout = new WFieldLayout(); layout.setLabelWidth(25); wrapper.add(layout); WButton resetThisBit = new WButton("Reset this bit"); resetThisBit.setCancel(true); resetThisBit.setAjaxTarget(wrapper); resetThisBit.setAction(new Action() { @Override public void execute(final ActionEvent event) { wrapper.reset(); } }); layout.addField(resetThisBit); String[] options = new String[]{"Dog", "Cat", "Bird", "Turtle"}; WRadioButtonSelect select = new WRadioButtonSelect(options); layout.addField("Select an animal", select); String[] options2 = new String[]{"Parrot", "Galah", "Cockatoo", "Lyre"}; select = new WRadioButtonSelect(options2); select.setMandatory(true); layout.addField("You must select a bird", select); select.setFrameless(true); //a tooltip can be used as a label stand-in even in a WField String[] options3 = new String[]{"Carrot", "Beet", "Brocolli", "Bacon - the perfect vegetable"}; select = new WRadioButtonSelect(options3); //if you absolutely do not want a WLabel in a WField then it has to be added using null cast to a WLabel. layout.addField((WLabel) null, select); select.setToolTip("Veggies"); WButton btnValidate = new WButton("validate"); btnValidate.setAction(new ValidatingAction(messages.getValidationErrors(), layout) { @Override public void executeOnValid(final ActionEvent event) { // do nothing } }); layout.addField(btnValidate); wrapper.add(new WAjaxControl(btnValidate, wrapper)); }
java
private void addInsideAFieldLayoutExample() { add(new WHeading(HeadingLevel.H3, "WRadioButtonSelect inside a WFieldLayout")); add(new ExplanatoryText( "When a WRadioButtonSelect is inside a WField its label is exposed in a way which appears and behaves like a regular HTML label." + " This allows WRadioButtonSelects to be used in a layout with simple form controls (such as WTextField) and produce a consistent" + " and predicatable interface.\n" + "The third example in this set uses a null label and a toolTip to hide the labelling element. This can lead to user confusion and" + " is not recommended.")); // Note: the wrapper WPanel here is to work around a bug in validation. See https://github.com/BorderTech/wcomponents/issues/1370 final WPanel wrapper = new WPanel(); add(wrapper); final WMessages messages = new WMessages(); wrapper.add(messages); WFieldLayout layout = new WFieldLayout(); layout.setLabelWidth(25); wrapper.add(layout); WButton resetThisBit = new WButton("Reset this bit"); resetThisBit.setCancel(true); resetThisBit.setAjaxTarget(wrapper); resetThisBit.setAction(new Action() { @Override public void execute(final ActionEvent event) { wrapper.reset(); } }); layout.addField(resetThisBit); String[] options = new String[]{"Dog", "Cat", "Bird", "Turtle"}; WRadioButtonSelect select = new WRadioButtonSelect(options); layout.addField("Select an animal", select); String[] options2 = new String[]{"Parrot", "Galah", "Cockatoo", "Lyre"}; select = new WRadioButtonSelect(options2); select.setMandatory(true); layout.addField("You must select a bird", select); select.setFrameless(true); //a tooltip can be used as a label stand-in even in a WField String[] options3 = new String[]{"Carrot", "Beet", "Brocolli", "Bacon - the perfect vegetable"}; select = new WRadioButtonSelect(options3); //if you absolutely do not want a WLabel in a WField then it has to be added using null cast to a WLabel. layout.addField((WLabel) null, select); select.setToolTip("Veggies"); WButton btnValidate = new WButton("validate"); btnValidate.setAction(new ValidatingAction(messages.getValidationErrors(), layout) { @Override public void executeOnValid(final ActionEvent event) { // do nothing } }); layout.addField(btnValidate); wrapper.add(new WAjaxControl(btnValidate, wrapper)); }
[ "private", "void", "addInsideAFieldLayoutExample", "(", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H3", ",", "\"WRadioButtonSelect inside a WFieldLayout\"", ")", ")", ";", "add", "(", "new", "ExplanatoryText", "(", "\"When a WRadioButtonSelect...
When a WRadioButtonSelect is added to a WFieldLayout the legend is moved. The first CheckBoxSelect has a frame, the second doesn't
[ "When", "a", "WRadioButtonSelect", "is", "added", "to", "a", "WFieldLayout", "the", "legend", "is", "moved", ".", "The", "first", "CheckBoxSelect", "has", "a", "frame", "the", "second", "doesn", "t" ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WRadioButtonSelectExample.java#L123-L173
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java
Check.instanceOf
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class }) @SuppressWarnings("unchecked") public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj) { return (T) instanceOf(type, obj, EMPTY_ARGUMENT_NAME); }
java
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalInstanceOfArgumentException.class }) @SuppressWarnings("unchecked") public static <T> T instanceOf(@Nonnull final Class<?> type, @Nonnull final Object obj) { return (T) instanceOf(type, obj, EMPTY_ARGUMENT_NAME); }
[ "@", "ArgumentsChecked", "@", "Throws", "(", "{", "IllegalNullArgumentException", ".", "class", ",", "IllegalInstanceOfArgumentException", ".", "class", "}", ")", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "instance...
Ensures that a passed argument is a member of a specific type. @param type class that the given object is a member of @param obj the object reference that should be a member of a specific {@code type} @return the given object cast to type @throws IllegalInstanceOfArgumentException if the given argument {@code obj} is not a member of {@code type}
[ "Ensures", "that", "a", "passed", "argument", "is", "a", "member", "of", "a", "specific", "type", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L1141-L1146
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.getTroubleshootingResultAsync
public Observable<TroubleshootingResultInner> getTroubleshootingResultAsync(String resourceGroupName, String networkWatcherName, String targetResourceId) { return getTroubleshootingResultWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).map(new Func1<ServiceResponse<TroubleshootingResultInner>, TroubleshootingResultInner>() { @Override public TroubleshootingResultInner call(ServiceResponse<TroubleshootingResultInner> response) { return response.body(); } }); }
java
public Observable<TroubleshootingResultInner> getTroubleshootingResultAsync(String resourceGroupName, String networkWatcherName, String targetResourceId) { return getTroubleshootingResultWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).map(new Func1<ServiceResponse<TroubleshootingResultInner>, TroubleshootingResultInner>() { @Override public TroubleshootingResultInner call(ServiceResponse<TroubleshootingResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "TroubleshootingResultInner", ">", "getTroubleshootingResultAsync", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "targetResourceId", ")", "{", "return", "getTroubleshootingResultWithServiceResponseAsync", "...
Get the last completed troubleshooting result on a specified resource. @param resourceGroupName The name of the resource group. @param networkWatcherName The name of the network watcher resource. @param targetResourceId The target resource ID to query the troubleshooting result. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Get", "the", "last", "completed", "troubleshooting", "result", "on", "a", "specified", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L1659-L1666
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/logging/Redwood.java
Redwood.appendHandler
protected static void appendHandler(Class<? extends LogRecordHandler> parent, LogRecordHandler child){ List<LogRecordHandler> toAdd = new LinkedList<LogRecordHandler>(); //--Find Parents for(LogRecordHandler term : handlers){ if(parent.isAssignableFrom(term.getClass())){ toAdd.add(term); } } //--Add Handler for(LogRecordHandler p : toAdd){ appendHandler(p, child); } }
java
protected static void appendHandler(Class<? extends LogRecordHandler> parent, LogRecordHandler child){ List<LogRecordHandler> toAdd = new LinkedList<LogRecordHandler>(); //--Find Parents for(LogRecordHandler term : handlers){ if(parent.isAssignableFrom(term.getClass())){ toAdd.add(term); } } //--Add Handler for(LogRecordHandler p : toAdd){ appendHandler(p, child); } }
[ "protected", "static", "void", "appendHandler", "(", "Class", "<", "?", "extends", "LogRecordHandler", ">", "parent", ",", "LogRecordHandler", "child", ")", "{", "List", "<", "LogRecordHandler", ">", "toAdd", "=", "new", "LinkedList", "<", "LogRecordHandler", ">...
Append a Handler to every parent of the given class @param parent The class of the parents to add the child to @param child The Handler to add.
[ "Append", "a", "Handler", "to", "every", "parent", "of", "the", "given", "class" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/logging/Redwood.java#L327-L339
joniles/mpxj
src/main/java/net/sf/mpxj/mpd/MPD9AbstractReader.java
MPD9AbstractReader.processField
protected void processField(Row row, String fieldIDColumn, String entityIDColumn, Object value) { processField(row, fieldIDColumn, row.getInteger(entityIDColumn), value); }
java
protected void processField(Row row, String fieldIDColumn, String entityIDColumn, Object value) { processField(row, fieldIDColumn, row.getInteger(entityIDColumn), value); }
[ "protected", "void", "processField", "(", "Row", "row", ",", "String", "fieldIDColumn", ",", "String", "entityIDColumn", ",", "Object", "value", ")", "{", "processField", "(", "row", ",", "fieldIDColumn", ",", "row", ".", "getInteger", "(", "entityIDColumn", "...
Generic method to process an extended attribute field. @param row extended attribute data @param fieldIDColumn column containing the field ID @param entityIDColumn column containing the entity ID @param value field value
[ "Generic", "method", "to", "process", "an", "extended", "attribute", "field", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpd/MPD9AbstractReader.java#L716-L719
apache/incubator-shardingsphere
sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResultUnit.java
InsertOptimizeResultUnit.setColumnValue
public final void setColumnValue(final String columnName, final Object columnValue) { SQLExpression sqlExpression = values[getColumnIndex(columnName)]; if (sqlExpression instanceof SQLParameterMarkerExpression) { parameters[getParameterIndex(sqlExpression)] = columnValue; } else { SQLExpression columnExpression = String.class == columnValue.getClass() ? new SQLTextExpression(String.valueOf(columnValue)) : new SQLNumberExpression((Number) columnValue); values[getColumnIndex(columnName)] = columnExpression; } }
java
public final void setColumnValue(final String columnName, final Object columnValue) { SQLExpression sqlExpression = values[getColumnIndex(columnName)]; if (sqlExpression instanceof SQLParameterMarkerExpression) { parameters[getParameterIndex(sqlExpression)] = columnValue; } else { SQLExpression columnExpression = String.class == columnValue.getClass() ? new SQLTextExpression(String.valueOf(columnValue)) : new SQLNumberExpression((Number) columnValue); values[getColumnIndex(columnName)] = columnExpression; } }
[ "public", "final", "void", "setColumnValue", "(", "final", "String", "columnName", ",", "final", "Object", "columnValue", ")", "{", "SQLExpression", "sqlExpression", "=", "values", "[", "getColumnIndex", "(", "columnName", ")", "]", ";", "if", "(", "sqlExpressio...
Set column value. @param columnName column name @param columnValue column value
[ "Set", "column", "value", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResultUnit.java#L87-L95
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/AssertUtil.java
AssertUtil.assertTrue
static void assertTrue(boolean condition, String internalErrorMesg) throws SFException { if (!condition) { throw new SFException(ErrorCode.INTERNAL_ERROR, internalErrorMesg); } }
java
static void assertTrue(boolean condition, String internalErrorMesg) throws SFException { if (!condition) { throw new SFException(ErrorCode.INTERNAL_ERROR, internalErrorMesg); } }
[ "static", "void", "assertTrue", "(", "boolean", "condition", ",", "String", "internalErrorMesg", ")", "throws", "SFException", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "SFException", "(", "ErrorCode", ".", "INTERNAL_ERROR", ",", "internalError...
Assert the condition is true, otherwise throw an internal error exception with the given message. @param condition @param internalErrorMesg @throws SFException
[ "Assert", "the", "condition", "is", "true", "otherwise", "throw", "an", "internal", "error", "exception", "with", "the", "given", "message", "." ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/AssertUtil.java#L22-L29
Azure/azure-sdk-for-java
datamigration/resource-manager/v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/implementation/TasksInner.java
TasksInner.getAsync
public Observable<ProjectTaskInner> getAsync(String groupName, String serviceName, String projectName, String taskName) { return getWithServiceResponseAsync(groupName, serviceName, projectName, taskName).map(new Func1<ServiceResponse<ProjectTaskInner>, ProjectTaskInner>() { @Override public ProjectTaskInner call(ServiceResponse<ProjectTaskInner> response) { return response.body(); } }); }
java
public Observable<ProjectTaskInner> getAsync(String groupName, String serviceName, String projectName, String taskName) { return getWithServiceResponseAsync(groupName, serviceName, projectName, taskName).map(new Func1<ServiceResponse<ProjectTaskInner>, ProjectTaskInner>() { @Override public ProjectTaskInner call(ServiceResponse<ProjectTaskInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ProjectTaskInner", ">", "getAsync", "(", "String", "groupName", ",", "String", "serviceName", ",", "String", "projectName", ",", "String", "taskName", ")", "{", "return", "getWithServiceResponseAsync", "(", "groupName", ",", "serviceNam...
Get task information. The tasks resource is a nested, proxy-only resource representing work performed by a DMS instance. The GET method retrieves information about a task. @param groupName Name of the resource group @param serviceName Name of the service @param projectName Name of the project @param taskName Name of the Task @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ProjectTaskInner object
[ "Get", "task", "information", ".", "The", "tasks", "resource", "is", "a", "nested", "proxy", "-", "only", "resource", "representing", "work", "performed", "by", "a", "DMS", "instance", ".", "The", "GET", "method", "retrieves", "information", "about", "a", "t...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/implementation/TasksInner.java#L524-L531
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/AccountFiltersInner.java
AccountFiltersInner.listAsync
public Observable<Page<AccountFilterInner>> listAsync(final String resourceGroupName, final String accountName) { return listWithServiceResponseAsync(resourceGroupName, accountName) .map(new Func1<ServiceResponse<Page<AccountFilterInner>>, Page<AccountFilterInner>>() { @Override public Page<AccountFilterInner> call(ServiceResponse<Page<AccountFilterInner>> response) { return response.body(); } }); }
java
public Observable<Page<AccountFilterInner>> listAsync(final String resourceGroupName, final String accountName) { return listWithServiceResponseAsync(resourceGroupName, accountName) .map(new Func1<ServiceResponse<Page<AccountFilterInner>>, Page<AccountFilterInner>>() { @Override public Page<AccountFilterInner> call(ServiceResponse<Page<AccountFilterInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "AccountFilterInner", ">", ">", "listAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "accountName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName",...
List Account Filters. List Account Filters in the Media Services account. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;AccountFilterInner&gt; object
[ "List", "Account", "Filters", ".", "List", "Account", "Filters", "in", "the", "Media", "Services", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/AccountFiltersInner.java#L143-L151
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataComplementOfImpl_CustomFieldSerializer.java
OWLDataComplementOfImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLDataComplementOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLDataComplementOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLDataComplementOfImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", "}" ]
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataComplementOfImpl_CustomFieldSerializer.java#L89-L92
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/input/CmsMultiSelectCell.java
CmsMultiSelectCell.getGridLayout
private Grid getGridLayout(int count) { Grid grid = new Grid(); int x, y, z, modolo = 0; x = count % 3; y = count % 5; z = count % 7; if ((z <= y) && (z <= x)) { modolo = 7; } else if ((y <= z) && (y <= x)) { modolo = 5; } else if ((x <= z) && (x <= y)) { modolo = 3; } if (count < modolo) { grid = new Grid(count, 1); } else if ((count % modolo) == 0) { grid = new Grid(count / modolo, modolo); } else { grid = new Grid((count / modolo) + 1, modolo); } return grid; }
java
private Grid getGridLayout(int count) { Grid grid = new Grid(); int x, y, z, modolo = 0; x = count % 3; y = count % 5; z = count % 7; if ((z <= y) && (z <= x)) { modolo = 7; } else if ((y <= z) && (y <= x)) { modolo = 5; } else if ((x <= z) && (x <= y)) { modolo = 3; } if (count < modolo) { grid = new Grid(count, 1); } else if ((count % modolo) == 0) { grid = new Grid(count / modolo, modolo); } else { grid = new Grid((count / modolo) + 1, modolo); } return grid; }
[ "private", "Grid", "getGridLayout", "(", "int", "count", ")", "{", "Grid", "grid", "=", "new", "Grid", "(", ")", ";", "int", "x", ",", "y", ",", "z", ",", "modolo", "=", "0", ";", "x", "=", "count", "%", "3", ";", "y", "=", "count", "%", "5",...
Helper function to generate the grid layout.<p> @param count @return the new grid
[ "Helper", "function", "to", "generate", "the", "grid", "layout", ".", "<p", ">", "@param", "count" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/CmsMultiSelectCell.java#L174-L197
Cornutum/tcases
tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java
SystemInputJson.toJson
private static JsonStructure toJson( FunctionInputDef functionInput, String varType) { JsonObjectBuilder builder = Json.createObjectBuilder(); toStream( functionInput.getVarDefs()) .filter( varDef -> varDef.getType().equals( varType)) .sorted() .forEach( varDef -> builder.add( varDef.getName(), toJson( varDef))); return builder.build(); }
java
private static JsonStructure toJson( FunctionInputDef functionInput, String varType) { JsonObjectBuilder builder = Json.createObjectBuilder(); toStream( functionInput.getVarDefs()) .filter( varDef -> varDef.getType().equals( varType)) .sorted() .forEach( varDef -> builder.add( varDef.getName(), toJson( varDef))); return builder.build(); }
[ "private", "static", "JsonStructure", "toJson", "(", "FunctionInputDef", "functionInput", ",", "String", "varType", ")", "{", "JsonObjectBuilder", "builder", "=", "Json", ".", "createObjectBuilder", "(", ")", ";", "toStream", "(", "functionInput", ".", "getVarDefs",...
Returns the JSON object that represents the function variables of the given type.
[ "Returns", "the", "JSON", "object", "that", "represents", "the", "function", "variables", "of", "the", "given", "type", "." ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java#L76-L85
the-fascinator/plugin-subscriber-solrEventLog
src/main/java/com/googlecode/fascinator/subscriber/solrEventLog/SolrEventLogSubscriber.java
SolrEventLogSubscriber.onEvent
@Override public void onEvent(Map<String, String> param) throws SubscriberException { try { addToIndex(param); } catch (Exception e) { throw new SubscriberException("Fail to add log to solr" + e.getMessage()); } }
java
@Override public void onEvent(Map<String, String> param) throws SubscriberException { try { addToIndex(param); } catch (Exception e) { throw new SubscriberException("Fail to add log to solr" + e.getMessage()); } }
[ "@", "Override", "public", "void", "onEvent", "(", "Map", "<", "String", ",", "String", ">", "param", ")", "throws", "SubscriberException", "{", "try", "{", "addToIndex", "(", "param", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "...
Method to fire for incoming events @param param : Map of key/value pairs to add to the index @throws SubscriberException if there was an error
[ "Method", "to", "fire", "for", "incoming", "events" ]
train
https://github.com/the-fascinator/plugin-subscriber-solrEventLog/blob/2c9da188887a622a6d43d33ea9099aff53a0516d/src/main/java/com/googlecode/fascinator/subscriber/solrEventLog/SolrEventLogSubscriber.java#L464-L472
edwardcapriolo/teknek-core
src/main/java/io/teknek/datalayer/WorkerDao.java
WorkerDao.registerWorkerStatus
public void registerWorkerStatus(ZooKeeper zk, Plan plan, WorkerStatus s) throws WorkerDaoException{ String writeToPath = PLAN_WORKERS_ZK + "/" + plan.getName() + "/" + s.getWorkerUuid(); try { Stat planBase = zk.exists(PLAN_WORKERS_ZK + "/" + plan.getName(), false); if (planBase == null){ try { zk.create(PLAN_WORKERS_ZK + "/" + plan.getName(), new byte [0] , Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (Exception ignore){} } zk.create(writeToPath, MAPPER.writeValueAsBytes(s), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); LOGGER.debug("Registered as ephemeral " + writeToPath); zk.exists(PLANS_ZK + "/" + plan.getName(), true); //watch job for events } catch (KeeperException | InterruptedException | IOException e) { LOGGER.warn(e); throw new WorkerDaoException(e); } }
java
public void registerWorkerStatus(ZooKeeper zk, Plan plan, WorkerStatus s) throws WorkerDaoException{ String writeToPath = PLAN_WORKERS_ZK + "/" + plan.getName() + "/" + s.getWorkerUuid(); try { Stat planBase = zk.exists(PLAN_WORKERS_ZK + "/" + plan.getName(), false); if (planBase == null){ try { zk.create(PLAN_WORKERS_ZK + "/" + plan.getName(), new byte [0] , Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (Exception ignore){} } zk.create(writeToPath, MAPPER.writeValueAsBytes(s), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); LOGGER.debug("Registered as ephemeral " + writeToPath); zk.exists(PLANS_ZK + "/" + plan.getName(), true); //watch job for events } catch (KeeperException | InterruptedException | IOException e) { LOGGER.warn(e); throw new WorkerDaoException(e); } }
[ "public", "void", "registerWorkerStatus", "(", "ZooKeeper", "zk", ",", "Plan", "plan", ",", "WorkerStatus", "s", ")", "throws", "WorkerDaoException", "{", "String", "writeToPath", "=", "PLAN_WORKERS_ZK", "+", "\"/\"", "+", "plan", ".", "getName", "(", ")", "+"...
Registers an ephemeral node representing ownership of a feed partition. Note we do not use curator here because we want a standard watch not from the main thread! @param zk @param plan @param s @throws WorkerDaoException
[ "Registers", "an", "ephemeral", "node", "representing", "ownership", "of", "a", "feed", "partition", ".", "Note", "we", "do", "not", "use", "curator", "here", "because", "we", "want", "a", "standard", "watch", "not", "from", "the", "main", "thread!" ]
train
https://github.com/edwardcapriolo/teknek-core/blob/4fa972d11044dee2954c0cc5e1b53b18fba319b9/src/main/java/io/teknek/datalayer/WorkerDao.java#L308-L324
anotheria/configureme
src/main/java/org/configureme/util/StringUtils.java
StringUtils.getStringAfter
public static String getStringAfter(final String src, final String toSearch, final int start) { final int ind = src.indexOf(toSearch, start); if (ind == -1) return ""; return src.substring(ind + toSearch.length()); }
java
public static String getStringAfter(final String src, final String toSearch, final int start) { final int ind = src.indexOf(toSearch, start); if (ind == -1) return ""; return src.substring(ind + toSearch.length()); }
[ "public", "static", "String", "getStringAfter", "(", "final", "String", "src", ",", "final", "String", "toSearch", ",", "final", "int", "start", ")", "{", "final", "int", "ind", "=", "src", ".", "indexOf", "(", "toSearch", ",", "start", ")", ";", "if", ...
Get {@link java.lang.String} after given search {@link java.lang.String} from given start search index. @param src source string @param toSearch search string @param start start search index @return {@link java.lang.String}
[ "Get", "{", "@link", "java", ".", "lang", ".", "String", "}", "after", "given", "search", "{", "@link", "java", ".", "lang", ".", "String", "}", "from", "given", "start", "search", "index", "." ]
train
https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/util/StringUtils.java#L139-L144
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/TimeRestrictedAccessPolicy.java
TimeRestrictedAccessPolicy.matchesDay
private boolean matchesDay(DateTime currentTime, TimeRestrictedAccess filter) { Integer dayStart = filter.getDayStart(); Integer dayEnd = filter.getDayEnd(); int dayNow = currentTime.getDayOfWeek(); if (dayStart >= dayEnd) { return dayNow >= dayStart && dayNow <= dayEnd; } else { return dayNow <= dayEnd && dayNow >= dayStart; } }
java
private boolean matchesDay(DateTime currentTime, TimeRestrictedAccess filter) { Integer dayStart = filter.getDayStart(); Integer dayEnd = filter.getDayEnd(); int dayNow = currentTime.getDayOfWeek(); if (dayStart >= dayEnd) { return dayNow >= dayStart && dayNow <= dayEnd; } else { return dayNow <= dayEnd && dayNow >= dayStart; } }
[ "private", "boolean", "matchesDay", "(", "DateTime", "currentTime", ",", "TimeRestrictedAccess", "filter", ")", "{", "Integer", "dayStart", "=", "filter", ".", "getDayStart", "(", ")", ";", "Integer", "dayEnd", "=", "filter", ".", "getDayEnd", "(", ")", ";", ...
Returns true if the given time matches the day-of-week restrictions specified by the included filter/rule. @param currentTime @param filter
[ "Returns", "true", "if", "the", "given", "time", "matches", "the", "day", "-", "of", "-", "week", "restrictions", "specified", "by", "the", "included", "filter", "/", "rule", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/TimeRestrictedAccessPolicy.java#L154-L163
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DomainsInner.java
DomainsInner.listOwnershipIdentifiersWithServiceResponseAsync
public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> listOwnershipIdentifiersWithServiceResponseAsync(final String resourceGroupName, final String domainName) { return listOwnershipIdentifiersSinglePageAsync(resourceGroupName, domainName) .concatMap(new Func1<ServiceResponse<Page<DomainOwnershipIdentifierInner>>, Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>>>() { @Override public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> call(ServiceResponse<Page<DomainOwnershipIdentifierInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listOwnershipIdentifiersNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> listOwnershipIdentifiersWithServiceResponseAsync(final String resourceGroupName, final String domainName) { return listOwnershipIdentifiersSinglePageAsync(resourceGroupName, domainName) .concatMap(new Func1<ServiceResponse<Page<DomainOwnershipIdentifierInner>>, Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>>>() { @Override public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> call(ServiceResponse<Page<DomainOwnershipIdentifierInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listOwnershipIdentifiersNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "DomainOwnershipIdentifierInner", ">", ">", ">", "listOwnershipIdentifiersWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "domainName", ")", "{", "return", ...
Lists domain ownership identifiers. Lists domain ownership identifiers. @param resourceGroupName Name of the resource group to which the resource belongs. @param domainName Name of domain. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;DomainOwnershipIdentifierInner&gt; object
[ "Lists", "domain", "ownership", "identifiers", ".", "Lists", "domain", "ownership", "identifiers", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DomainsInner.java#L1354-L1366
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ListCrawlersRequest.java
ListCrawlersRequest.withTags
public ListCrawlersRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public ListCrawlersRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "ListCrawlersRequest", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> Specifies to return only these tagged resources. </p> @param tags Specifies to return only these tagged resources. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Specifies", "to", "return", "only", "these", "tagged", "resources", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/ListCrawlersRequest.java#L162-L165
apache/flink
flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/statemachine/generator/EventsGenerator.java
EventsGenerator.nextInvalid
@Nullable public Event nextInvalid() { final Iterator<Entry<Integer, State>> iter = states.entrySet().iterator(); if (iter.hasNext()) { final Entry<Integer, State> entry = iter.next(); State currentState = entry.getValue(); int address = entry.getKey(); iter.remove(); EventType event = currentState.randomInvalidTransition(rnd); return new Event(event, address); } else { return null; } }
java
@Nullable public Event nextInvalid() { final Iterator<Entry<Integer, State>> iter = states.entrySet().iterator(); if (iter.hasNext()) { final Entry<Integer, State> entry = iter.next(); State currentState = entry.getValue(); int address = entry.getKey(); iter.remove(); EventType event = currentState.randomInvalidTransition(rnd); return new Event(event, address); } else { return null; } }
[ "@", "Nullable", "public", "Event", "nextInvalid", "(", ")", "{", "final", "Iterator", "<", "Entry", "<", "Integer", ",", "State", ">", ">", "iter", "=", "states", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "if", "(", "iter", ".", "...
Creates an event for an illegal state transition of one of the internal state machines. If the generator has not yet started any state machines (for example, because no call to {@link #next(int, int)} was made, yet), this will return null. @return An event for a illegal state transition, or null, if not possible.
[ "Creates", "an", "event", "for", "an", "illegal", "state", "transition", "of", "one", "of", "the", "internal", "state", "machines", ".", "If", "the", "generator", "has", "not", "yet", "started", "any", "state", "machines", "(", "for", "example", "because", ...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/statemachine/generator/EventsGenerator.java#L143-L159
cdk/cdk
tool/sdg/src/main/java/org/openscience/cdk/layout/StructureDiagramGenerator.java
StructureDiagramGenerator.placeFirstBond
private IAtomContainer placeFirstBond(IBond bond, Vector2d bondVector) { IAtomContainer sharedAtoms = null; bondVector.normalize(); logger.debug("placeFirstBondOfFirstRing->bondVector.length():" + bondVector.length()); bondVector.scale(bondLength); logger.debug("placeFirstBondOfFirstRing->bondVector.length() after scaling:" + bondVector.length()); IAtom atom; Point2d point = new Point2d(0, 0); atom = bond.getBegin(); logger.debug("Atom 1 of first Bond: " + (molecule.indexOf(atom) + 1)); atom.setPoint2d(point); atom.setFlag(CDKConstants.ISPLACED, true); point = new Point2d(0, 0); atom = bond.getEnd(); logger.debug("Atom 2 of first Bond: " + (molecule.indexOf(atom) + 1)); point.add(bondVector); atom.setPoint2d(point); atom.setFlag(CDKConstants.ISPLACED, true); /* * The new ring is layed out relativ to some shared atoms that have * already been placed. Usually this is another ring, that has * already been draw and to which the new ring is somehow connected, * or some other system of atoms in an aliphatic chain. In this * case, it's the first bond that we layout by hand. */ sharedAtoms = atom.getBuilder().newInstance(IAtomContainer.class); sharedAtoms.addAtom(bond.getBegin()); sharedAtoms.addAtom(bond.getEnd()); sharedAtoms.addBond(bond); return sharedAtoms; }
java
private IAtomContainer placeFirstBond(IBond bond, Vector2d bondVector) { IAtomContainer sharedAtoms = null; bondVector.normalize(); logger.debug("placeFirstBondOfFirstRing->bondVector.length():" + bondVector.length()); bondVector.scale(bondLength); logger.debug("placeFirstBondOfFirstRing->bondVector.length() after scaling:" + bondVector.length()); IAtom atom; Point2d point = new Point2d(0, 0); atom = bond.getBegin(); logger.debug("Atom 1 of first Bond: " + (molecule.indexOf(atom) + 1)); atom.setPoint2d(point); atom.setFlag(CDKConstants.ISPLACED, true); point = new Point2d(0, 0); atom = bond.getEnd(); logger.debug("Atom 2 of first Bond: " + (molecule.indexOf(atom) + 1)); point.add(bondVector); atom.setPoint2d(point); atom.setFlag(CDKConstants.ISPLACED, true); /* * The new ring is layed out relativ to some shared atoms that have * already been placed. Usually this is another ring, that has * already been draw and to which the new ring is somehow connected, * or some other system of atoms in an aliphatic chain. In this * case, it's the first bond that we layout by hand. */ sharedAtoms = atom.getBuilder().newInstance(IAtomContainer.class); sharedAtoms.addAtom(bond.getBegin()); sharedAtoms.addAtom(bond.getEnd()); sharedAtoms.addBond(bond); return sharedAtoms; }
[ "private", "IAtomContainer", "placeFirstBond", "(", "IBond", "bond", ",", "Vector2d", "bondVector", ")", "{", "IAtomContainer", "sharedAtoms", "=", "null", ";", "bondVector", ".", "normalize", "(", ")", ";", "logger", ".", "debug", "(", "\"placeFirstBondOfFirstRin...
Places the first bond of the first ring such that one atom is at (0,0) and the other one at the position given by bondVector @param bondVector A 2D vector to point to the position of the second bond atom @param bond the bond to lay out @return an IAtomContainer with the atoms of the bond and the bond itself
[ "Places", "the", "first", "bond", "of", "the", "first", "ring", "such", "that", "one", "atom", "is", "at", "(", "0", "0", ")", "and", "the", "other", "one", "at", "the", "position", "given", "by", "bondVector" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/sdg/src/main/java/org/openscience/cdk/layout/StructureDiagramGenerator.java#L2029-L2060
vvakame/JsonPullParser
jsonpullparser-apt/src/main/java/net/vvakame/util/jsonpullparser/factory/template/Template.java
Template.writeJsonMeta
public static void writeJsonMeta(JavaFileObject fileObject, JsonModelModel model) throws IOException { MvelTemplate.writeJsonMeta(fileObject, model); }
java
public static void writeJsonMeta(JavaFileObject fileObject, JsonModelModel model) throws IOException { MvelTemplate.writeJsonMeta(fileObject, model); }
[ "public", "static", "void", "writeJsonMeta", "(", "JavaFileObject", "fileObject", ",", "JsonModelModel", "model", ")", "throws", "IOException", "{", "MvelTemplate", ".", "writeJsonMeta", "(", "fileObject", ",", "model", ")", ";", "}" ]
Generates source code into the given file object from the given data model, utilizing the templating engine. @param fileObject Target file object @param model Data model for source code generation @throws IOException @author vvakame
[ "Generates", "source", "code", "into", "the", "given", "file", "object", "from", "the", "given", "data", "model", "utilizing", "the", "templating", "engine", "." ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-apt/src/main/java/net/vvakame/util/jsonpullparser/factory/template/Template.java#L53-L56
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/h/HomographyTotalLeastSquares.java
HomographyTotalLeastSquares.backsubstitution0134
static void backsubstitution0134(DMatrixRMaj P_plus, DMatrixRMaj P , DMatrixRMaj X , double H[] ) { final int N = P.numRows; DMatrixRMaj tmp = new DMatrixRMaj(N*2, 1); double H6 = H[6]; double H7 = H[7]; double H8 = H[8]; for (int i = 0, index = 0; i < N; i++) { double x = -X.data[index],y = -X.data[index+1]; double sum = P.data[index++] * H6 + P.data[index++] * H7 + H8; tmp.data[i] = x * sum; tmp.data[i+N] = y * sum; } double h0=0,h1=0,h3=0,h4=0; for (int i = 0; i < N; i++) { double P_pls_0 = P_plus.data[i]; double P_pls_1 = P_plus.data[i+N]; double tmp_i = tmp.data[i]; double tmp_j = tmp.data[i+N]; h0 += P_pls_0*tmp_i; h1 += P_pls_1*tmp_i; h3 += P_pls_0*tmp_j; h4 += P_pls_1*tmp_j; } H[0] = -h0; H[1] = -h1; H[3] = -h3; H[4] = -h4; }
java
static void backsubstitution0134(DMatrixRMaj P_plus, DMatrixRMaj P , DMatrixRMaj X , double H[] ) { final int N = P.numRows; DMatrixRMaj tmp = new DMatrixRMaj(N*2, 1); double H6 = H[6]; double H7 = H[7]; double H8 = H[8]; for (int i = 0, index = 0; i < N; i++) { double x = -X.data[index],y = -X.data[index+1]; double sum = P.data[index++] * H6 + P.data[index++] * H7 + H8; tmp.data[i] = x * sum; tmp.data[i+N] = y * sum; } double h0=0,h1=0,h3=0,h4=0; for (int i = 0; i < N; i++) { double P_pls_0 = P_plus.data[i]; double P_pls_1 = P_plus.data[i+N]; double tmp_i = tmp.data[i]; double tmp_j = tmp.data[i+N]; h0 += P_pls_0*tmp_i; h1 += P_pls_1*tmp_i; h3 += P_pls_0*tmp_j; h4 += P_pls_1*tmp_j; } H[0] = -h0; H[1] = -h1; H[3] = -h3; H[4] = -h4; }
[ "static", "void", "backsubstitution0134", "(", "DMatrixRMaj", "P_plus", ",", "DMatrixRMaj", "P", ",", "DMatrixRMaj", "X", ",", "double", "H", "[", "]", ")", "{", "final", "int", "N", "=", "P", ".", "numRows", ";", "DMatrixRMaj", "tmp", "=", "new", "DMatr...
Backsubstitution for solving for 0,1 and 3,4 using solution for 6,7,8
[ "Backsubstitution", "for", "solving", "for", "0", "1", "and", "3", "4", "using", "solution", "for", "6", "7", "8" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/h/HomographyTotalLeastSquares.java#L114-L148
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
DebugUtil.printTimeDifference
public static void printTimeDifference(final Calendar pStartCalendar, final Calendar pEndCalendar) { printTimeDifference(pStartCalendar, pEndCalendar, System.out); }
java
public static void printTimeDifference(final Calendar pStartCalendar, final Calendar pEndCalendar) { printTimeDifference(pStartCalendar, pEndCalendar, System.out); }
[ "public", "static", "void", "printTimeDifference", "(", "final", "Calendar", "pStartCalendar", ",", "final", "Calendar", "pEndCalendar", ")", "{", "printTimeDifference", "(", "pStartCalendar", ",", "pEndCalendar", ",", "System", ".", "out", ")", ";", "}" ]
Prints out the difference between to calendar times two {@code System.out}. The first calendar object is subtracted from the second one. <p> @param pStartCalendar the first {@code java.util.Calendar}. @param pEndCalendar the second {@code java.util.Calendar}. @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/util/Calendar.html">{@code java.util.Calendar}</a>
[ "Prints", "out", "the", "difference", "between", "to", "calendar", "times", "two", "{" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L1046-L1048
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.getMinimumCacheSize
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static int getMinimumCacheSize(Context c, int tileSize, double overdrawFactor, float screenRatio) { WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int height; int width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Point p = new Point(); display.getSize(p); height = p.y; width = p.x; } else { // deprecated since Android 13 height = display.getHeight(); width = display.getWidth(); } // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // Multiplying by screenRatio adjusts this somewhat inaccurately for MapViews on only part // of a screen (the result can be too low if a MapView is very narrow). // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return (int) Math.max(4, screenRatio * (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
java
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static int getMinimumCacheSize(Context c, int tileSize, double overdrawFactor, float screenRatio) { WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int height; int width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Point p = new Point(); display.getSize(p); height = p.y; width = p.x; } else { // deprecated since Android 13 height = display.getHeight(); width = display.getWidth(); } // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // Multiplying by screenRatio adjusts this somewhat inaccurately for MapViews on only part // of a screen (the result can be too low if a MapView is very narrow). // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return (int) Math.max(4, screenRatio * (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "HONEYCOMB_MR2", ")", "public", "static", "int", "getMinimumCacheSize", "(", "Context", "c", ",", "int", "tileSize", ",", "double", "overdrawFactor", ...
Compute the minimum cache size for a view. When the cache is created we do not actually know the size of the mapview, so the screenRatio is an approximation of the required size. For the view size we use the frame buffer calculated dimension. @param c the context @param tileSize the tile size @param overdrawFactor the overdraw factor applied to the mapview @param screenRatio the part of the screen the view covers @return the minimum cache size for the view
[ "Compute", "the", "minimum", "cache", "size", "for", "a", "view", ".", "When", "the", "cache", "is", "created", "we", "do", "not", "actually", "know", "the", "size", "of", "the", "mapview", "so", "the", "screenRatio", "is", "an", "approximation", "of", "...
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L350-L379
micrometer-metrics/micrometer
micrometer-spring-legacy/src/main/java/io/micrometer/spring/async/ThreadPoolTaskExecutorMetrics.java
ThreadPoolTaskExecutorMetrics.monitor
public static ThreadPoolTaskExecutor monitor(MeterRegistry registry, String name, Iterable<Tag> tags) { return new TimedThreadPoolTaskExecutor(registry, name, tags); }
java
public static ThreadPoolTaskExecutor monitor(MeterRegistry registry, String name, Iterable<Tag> tags) { return new TimedThreadPoolTaskExecutor(registry, name, tags); }
[ "public", "static", "ThreadPoolTaskExecutor", "monitor", "(", "MeterRegistry", "registry", ",", "String", "name", ",", "Iterable", "<", "Tag", ">", "tags", ")", "{", "return", "new", "TimedThreadPoolTaskExecutor", "(", "registry", ",", "name", ",", "tags", ")", ...
Returns a new {@link ThreadPoolTaskExecutor} with recorded metrics. @param registry The registry to bind metrics to. @param name The name prefix of the metrics. @param tags Tags to apply to all recorded metrics. @return The instrumented executor, proxied.
[ "Returns", "a", "new", "{", "@link", "ThreadPoolTaskExecutor", "}", "with", "recorded", "metrics", "." ]
train
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-spring-legacy/src/main/java/io/micrometer/spring/async/ThreadPoolTaskExecutorMetrics.java#L64-L66
cverges/expect4j
src/main/java/expect4j/ExpectUtils.java
ExpectUtils.SSH
public static Expect4j SSH(String hostname, String username, String password) throws Exception { return SSH(hostname, username, password, 22); }
java
public static Expect4j SSH(String hostname, String username, String password) throws Exception { return SSH(hostname, username, password, 22); }
[ "public", "static", "Expect4j", "SSH", "(", "String", "hostname", ",", "String", "username", ",", "String", "password", ")", "throws", "Exception", "{", "return", "SSH", "(", "hostname", ",", "username", ",", "password", ",", "22", ")", ";", "}" ]
Creates an SSH session to the given server on TCP port 22 using the provided credentials. This is equivalent to Expect's <code>spawn ssh $hostname</code>. @param hostname the DNS or IP address of the remote server @param username the account name to use when authenticating @param password the account password to use when authenticating @return the controlling Expect4j instance @throws Exception on a variety of errors
[ "Creates", "an", "SSH", "session", "to", "the", "given", "server", "on", "TCP", "port", "22", "using", "the", "provided", "credentials", ".", "This", "is", "equivalent", "to", "Expect", "s", "<code", ">", "spawn", "ssh", "$hostname<", "/", "code", ">", "...
train
https://github.com/cverges/expect4j/blob/97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6/src/main/java/expect4j/ExpectUtils.java#L164-L166
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java
SARLOperationHelper._hasSideEffects
protected boolean _hasSideEffects(XAbstractWhileExpression expression, ISideEffectContext context) { context.open(); if (hasSideEffects(expression.getPredicate(), context)) { return true; } if (hasSideEffects(expression.getBody(), context.branch())) { return true; } context.close(); return false; }
java
protected boolean _hasSideEffects(XAbstractWhileExpression expression, ISideEffectContext context) { context.open(); if (hasSideEffects(expression.getPredicate(), context)) { return true; } if (hasSideEffects(expression.getBody(), context.branch())) { return true; } context.close(); return false; }
[ "protected", "boolean", "_hasSideEffects", "(", "XAbstractWhileExpression", "expression", ",", "ISideEffectContext", "context", ")", "{", "context", ".", "open", "(", ")", ";", "if", "(", "hasSideEffects", "(", "expression", ".", "getPredicate", "(", ")", ",", "...
Test if the given expression has side effects. @param expression the expression. @param context the list of context expressions. @return {@code true} if the expression has side effects.
[ "Test", "if", "the", "given", "expression", "has", "side", "effects", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java#L284-L294
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/PickupUrl.java
PickupUrl.getPickupUrl
public static MozuUrl getPickupUrl(String orderId, String pickupId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/pickups/{pickupId}?responseFields={responseFields}"); formatter.formatUrl("orderId", orderId); formatter.formatUrl("pickupId", pickupId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getPickupUrl(String orderId, String pickupId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/pickups/{pickupId}?responseFields={responseFields}"); formatter.formatUrl("orderId", orderId); formatter.formatUrl("pickupId", pickupId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getPickupUrl", "(", "String", "orderId", ",", "String", "pickupId", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/orders/{orderId}/pickups/{pickupId}?responseFields={...
Get Resource Url for GetPickup @param orderId Unique identifier of the order. @param pickupId Unique identifier of the pickup to remove. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetPickup" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/PickupUrl.java#L37-L44
grails/grails-core
grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java
GroovyPagesUriSupport.getDeployedAbsoluteViewURI
public String getDeployedAbsoluteViewURI(String viewName) { FastStringWriter buf = new FastStringWriter(PATH_TO_VIEWS); return getAbsoluteViewURIInternal(viewName, buf, true); }
java
public String getDeployedAbsoluteViewURI(String viewName) { FastStringWriter buf = new FastStringWriter(PATH_TO_VIEWS); return getAbsoluteViewURIInternal(viewName, buf, true); }
[ "public", "String", "getDeployedAbsoluteViewURI", "(", "String", "viewName", ")", "{", "FastStringWriter", "buf", "=", "new", "FastStringWriter", "(", "PATH_TO_VIEWS", ")", ";", "return", "getAbsoluteViewURIInternal", "(", "viewName", ",", "buf", ",", "true", ")", ...
Obtains a view URI when deployed within the /WEB-INF/grails-app/views context @param viewName The name of the view @return The view URI
[ "Obtains", "a", "view", "URI", "when", "deployed", "within", "the", "/", "WEB", "-", "INF", "/", "grails", "-", "app", "/", "views", "context" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java#L231-L234
socialsensor/geo-util
src/main/java/eu/socialsensor/geo/ReverseGeocoder.java
ReverseGeocoder.loadCitiesFileToTree
protected void loadCitiesFileToTree(String gnObjectsFilename, Map<String, String> countryCodes){ EasyBufferedReader reader = new EasyBufferedReader(gnObjectsFilename); String line = null; int count = 0; long t0 = System.currentTimeMillis(); logger.info("loading of objects started"); while ((line = reader.readLine()) != null){ if (line.trim().length() < 1) continue; count++; GeoObject city = new GeoObject(line); double[] coords = new double[2]; coords[0] = city.getLat(); coords[1] = city.getLon(); try { tree.insert(coords, new LightweightGeoObject(city)); } catch (KeySizeException e) { logger.error(e.getMessage()); } catch (KeyDuplicateException e) { logger.error(e.getMessage()); } } logger.info(count + " objects loaded in " + (System.currentTimeMillis()-t0)/1000.0 + "secs"); reader.close(); logger.info("file " + gnObjectsFilename + " closed"); }
java
protected void loadCitiesFileToTree(String gnObjectsFilename, Map<String, String> countryCodes){ EasyBufferedReader reader = new EasyBufferedReader(gnObjectsFilename); String line = null; int count = 0; long t0 = System.currentTimeMillis(); logger.info("loading of objects started"); while ((line = reader.readLine()) != null){ if (line.trim().length() < 1) continue; count++; GeoObject city = new GeoObject(line); double[] coords = new double[2]; coords[0] = city.getLat(); coords[1] = city.getLon(); try { tree.insert(coords, new LightweightGeoObject(city)); } catch (KeySizeException e) { logger.error(e.getMessage()); } catch (KeyDuplicateException e) { logger.error(e.getMessage()); } } logger.info(count + " objects loaded in " + (System.currentTimeMillis()-t0)/1000.0 + "secs"); reader.close(); logger.info("file " + gnObjectsFilename + " closed"); }
[ "protected", "void", "loadCitiesFileToTree", "(", "String", "gnObjectsFilename", ",", "Map", "<", "String", ",", "String", ">", "countryCodes", ")", "{", "EasyBufferedReader", "reader", "=", "new", "EasyBufferedReader", "(", "gnObjectsFilename", ")", ";", "String", ...
A kd-tree is loaded with the set of geographical objects. The key for each entry corresponds to its lat/lon coordinates, while the value is a LightweightGeoObject @param gnObjectsFilename @param countryCodes
[ "A", "kd", "-", "tree", "is", "loaded", "with", "the", "set", "of", "geographical", "objects", ".", "The", "key", "for", "each", "entry", "corresponds", "to", "its", "lat", "/", "lon", "coordinates", "while", "the", "value", "is", "a", "LightweightGeoObjec...
train
https://github.com/socialsensor/geo-util/blob/ffe729896187dc589f4a362d6e6819fc155ced1d/src/main/java/eu/socialsensor/geo/ReverseGeocoder.java#L62-L88
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/BadComparable.java
BadComparable.getTypeOfSubtract
private static Type getTypeOfSubtract(BinaryTree expression, VisitorState state) { Type expressionType = ASTHelpers.getType(expression.getLeftOperand()); if (!ASTHelpers.isSameType( expressionType, ASTHelpers.getType(expression.getRightOperand()), state)) { return ASTHelpers.getType(expression); } return expressionType; }
java
private static Type getTypeOfSubtract(BinaryTree expression, VisitorState state) { Type expressionType = ASTHelpers.getType(expression.getLeftOperand()); if (!ASTHelpers.isSameType( expressionType, ASTHelpers.getType(expression.getRightOperand()), state)) { return ASTHelpers.getType(expression); } return expressionType; }
[ "private", "static", "Type", "getTypeOfSubtract", "(", "BinaryTree", "expression", ",", "VisitorState", "state", ")", "{", "Type", "expressionType", "=", "ASTHelpers", ".", "getType", "(", "expression", ".", "getLeftOperand", "(", ")", ")", ";", "if", "(", "!"...
Compute the type of the subtract BinaryTree. We use the type of the left/right operand except when they're not the same, in which case we prefer the type of the expression. This ensures that a byte/short subtracted from another byte/short isn't regarded as an int.
[ "Compute", "the", "type", "of", "the", "subtract", "BinaryTree", ".", "We", "use", "the", "type", "of", "the", "left", "/", "right", "operand", "except", "when", "they", "re", "not", "the", "same", "in", "which", "case", "we", "prefer", "the", "type", ...
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/BadComparable.java#L83-L90
spring-cloud/spring-cloud-netflix
spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java
SpringClientFactory.getClient
public <C extends IClient<?, ?>> C getClient(String name, Class<C> clientClass) { return getInstance(name, clientClass); }
java
public <C extends IClient<?, ?>> C getClient(String name, Class<C> clientClass) { return getInstance(name, clientClass); }
[ "public", "<", "C", "extends", "IClient", "<", "?", ",", "?", ">", ">", "C", "getClient", "(", "String", "name", ",", "Class", "<", "C", ">", "clientClass", ")", "{", "return", "getInstance", "(", "name", ",", "clientClass", ")", ";", "}" ]
Get the rest client associated with the name. @param name name to search by @param clientClass the class of the client bean @param <C> {@link IClient} subtype @return {@link IClient} instance @throws RuntimeException if any error occurs
[ "Get", "the", "rest", "client", "associated", "with", "the", "name", "." ]
train
https://github.com/spring-cloud/spring-cloud-netflix/blob/03b1e326ce5971c41239890dc71cae616366cff8/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java#L54-L56
Red5/red5-server-common
src/main/java/org/red5/server/net/remoting/RemotingClient.java
RemotingClient.setCredentials
public void setCredentials(String userid, String password) { Map<String, String> data = new HashMap<String, String>(); data.put("userid", userid); data.put("password", password); RemotingHeader header = new RemotingHeader(RemotingHeader.CREDENTIALS, true, data); headers.put(RemotingHeader.CREDENTIALS, header); }
java
public void setCredentials(String userid, String password) { Map<String, String> data = new HashMap<String, String>(); data.put("userid", userid); data.put("password", password); RemotingHeader header = new RemotingHeader(RemotingHeader.CREDENTIALS, true, data); headers.put(RemotingHeader.CREDENTIALS, header); }
[ "public", "void", "setCredentials", "(", "String", "userid", ",", "String", "password", ")", "{", "Map", "<", "String", ",", "String", ">", "data", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "data", ".", "put", "(", "\"u...
Send authentication data with each remoting request. @param userid User identifier @param password Password
[ "Send", "authentication", "data", "with", "each", "remoting", "request", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/remoting/RemotingClient.java#L265-L271
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java
SparseCpuLevel1.dscal
@Override protected void dscal(long N, double a, INDArray X, int incx) { cblas_dscal((int) N, a, (DoublePointer) X.data().addressPointer(), incx); }
java
@Override protected void dscal(long N, double a, INDArray X, int incx) { cblas_dscal((int) N, a, (DoublePointer) X.data().addressPointer(), incx); }
[ "@", "Override", "protected", "void", "dscal", "(", "long", "N", ",", "double", "a", ",", "INDArray", "X", ",", "int", "incx", ")", "{", "cblas_dscal", "(", "(", "int", ")", "N", ",", "a", ",", "(", "DoublePointer", ")", "X", ".", "data", "(", ")...
Computes the product of a double vector by a scalar. @param N The number of elements of the vector X @param a a scalar @param X a vector @param incx the increment of the vector X
[ "Computes", "the", "product", "of", "a", "double", "vector", "by", "a", "scalar", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java#L267-L270
google/error-prone-javac
src/jdk.jdeps/share/classes/com/sun/tools/jdeps/DependencyFinder.java
DependencyFinder.parseExportedAPIs
public Set<Location> parseExportedAPIs(Archive archive, String name) { try { return parse(archive, API_FINDER, name); } catch (IOException e) { throw new UncheckedIOException(e); } }
java
public Set<Location> parseExportedAPIs(Archive archive, String name) { try { return parse(archive, API_FINDER, name); } catch (IOException e) { throw new UncheckedIOException(e); } }
[ "public", "Set", "<", "Location", ">", "parseExportedAPIs", "(", "Archive", "archive", ",", "String", "name", ")", "{", "try", "{", "return", "parse", "(", "archive", ",", "API_FINDER", ",", "name", ")", ";", "}", "catch", "(", "IOException", "e", ")", ...
Parses the exported API of the named class from the given archive and returns all target locations the named class references.
[ "Parses", "the", "exported", "API", "of", "the", "named", "class", "from", "the", "given", "archive", "and", "returns", "all", "target", "locations", "the", "named", "class", "references", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/DependencyFinder.java#L160-L167
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optSerializable
@Nullable @SuppressWarnings("unchecked") // Bundle#getSerializable(String) returns Serializable object so it is safe to cast to a type which extends Serializable. public static <T extends Serializable> T optSerializable(@Nullable Bundle bundle, @Nullable String key, @Nullable T fallback) { if (bundle == null) { return fallback; } return (T) bundle.getSerializable(key); }
java
@Nullable @SuppressWarnings("unchecked") // Bundle#getSerializable(String) returns Serializable object so it is safe to cast to a type which extends Serializable. public static <T extends Serializable> T optSerializable(@Nullable Bundle bundle, @Nullable String key, @Nullable T fallback) { if (bundle == null) { return fallback; } return (T) bundle.getSerializable(key); }
[ "@", "Nullable", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// Bundle#getSerializable(String) returns Serializable object so it is safe to cast to a type which extends Serializable.", "public", "static", "<", "T", "extends", "Serializable", ">", "T", "optSerializable", "(...
Returns a optional {@link java.io.Serializable}. In other words, returns the value mapped by key if it exists and is a {@link java.io.Serializable}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @param fallback fallback value. @return a {@link java.io.Serializable} {@link java.util.ArrayList} value if exists, null otherwise. @see android.os.Bundle#getSerializable(String)
[ "Returns", "a", "optional", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L796-L803
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TranscriptManager.java
TranscriptManager.getTranscript
public Transcript getTranscript(EntityBareJid workgroupJID, String sessionID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { Transcript request = new Transcript(sessionID); request.setTo(workgroupJID); Transcript response = connection.createStanzaCollectorAndSend(request).nextResultOrThrow(); return response; }
java
public Transcript getTranscript(EntityBareJid workgroupJID, String sessionID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { Transcript request = new Transcript(sessionID); request.setTo(workgroupJID); Transcript response = connection.createStanzaCollectorAndSend(request).nextResultOrThrow(); return response; }
[ "public", "Transcript", "getTranscript", "(", "EntityBareJid", "workgroupJID", ",", "String", "sessionID", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "Transcript", "request", "=", "new",...
Returns the full conversation transcript of a given session. @param sessionID the id of the session to get the full transcript. @param workgroupJID the JID of the workgroup that will process the request. @return the full conversation transcript of a given session. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Returns", "the", "full", "conversation", "transcript", "of", "a", "given", "session", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TranscriptManager.java#L56-L61
h2oai/h2o-2
src/main/java/water/ga/GoogleAnalyticsRequest.java
GoogleAnalyticsRequest.customDimension
public T customDimension(int index, String value) { customDimentions.put("cd" + index, value); return (T) this; }
java
public T customDimension(int index, String value) { customDimentions.put("cd" + index, value); return (T) this; }
[ "public", "T", "customDimension", "(", "int", "index", ",", "String", "value", ")", "{", "customDimentions", ".", "put", "(", "\"cd\"", "+", "index", ",", "value", ")", ";", "return", "(", "T", ")", "this", ";", "}" ]
<div class="ind"> <p> Optional. </p> <p>Each custom dimension has an associated index. There is a maximum of 20 custom dimensions (200 for Premium accounts). The name suffix must be a positive integer between 1 and 200, inclusive.</p> <table border="1"> <tbody> <tr> <th>Parameter</th> <th>Value Type</th> <th>Default Value</th> <th>Max Length</th> <th>Supported Hit Types</th> </tr> <tr> <td><code>cd[1-9][0-9]*</code></td> <td>text</td> <td><span class="none">None</span> </td> <td>150 Bytes </td> <td>all</td> </tr> </tbody> </table> <div> Example value: <code>Sports</code><br> Example usage: <code>cd[1-9][0-9]*=Sports</code> </div> </div>
[ "<div", "class", "=", "ind", ">", "<p", ">", "Optional", ".", "<", "/", "p", ">", "<p", ">", "Each", "custom", "dimension", "has", "an", "associated", "index", ".", "There", "is", "a", "maximum", "of", "20", "custom", "dimensions", "(", "200", "for",...
train
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/ga/GoogleAnalyticsRequest.java#L227-L230
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java
VMath.transposeTimesTimes
public static double transposeTimesTimes(final double[] v1, final double[][] m2, final double[] v3) { final int rowdim = m2.length, coldim = getColumnDimensionality(m2); assert rowdim == v1.length : ERR_MATRIX_INNERDIM; assert coldim == v3.length : ERR_MATRIX_INNERDIM; double sum = 0.0; for(int k = 0; k < rowdim; k++) { final double[] B_k = m2[k]; double s = 0; for(int j = 0; j < coldim; j++) { s += v3[j] * B_k[j]; } sum += s * v1[k]; } return sum; }
java
public static double transposeTimesTimes(final double[] v1, final double[][] m2, final double[] v3) { final int rowdim = m2.length, coldim = getColumnDimensionality(m2); assert rowdim == v1.length : ERR_MATRIX_INNERDIM; assert coldim == v3.length : ERR_MATRIX_INNERDIM; double sum = 0.0; for(int k = 0; k < rowdim; k++) { final double[] B_k = m2[k]; double s = 0; for(int j = 0; j < coldim; j++) { s += v3[j] * B_k[j]; } sum += s * v1[k]; } return sum; }
[ "public", "static", "double", "transposeTimesTimes", "(", "final", "double", "[", "]", "v1", ",", "final", "double", "[", "]", "[", "]", "m2", ",", "final", "double", "[", "]", "v3", ")", "{", "final", "int", "rowdim", "=", "m2", ".", "length", ",", ...
Matrix multiplication, v1<sup>T</sup> * m2 * v3 @param v1 vector on the left @param m2 matrix @param v3 vector on the right @return Matrix product, v1<sup>T</sup> * m2 * v3
[ "Matrix", "multiplication", "v1<sup", ">", "T<", "/", "sup", ">", "*", "m2", "*", "v3" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java#L1405-L1419
structurizr/java
structurizr-core/src/com/structurizr/model/ModelItem.java
ModelItem.addProperty
public void addProperty(String name, String value) { if (name == null || name.trim().length() == 0) { throw new IllegalArgumentException("A property name must be specified."); } if (value == null || value.trim().length() == 0) { throw new IllegalArgumentException("A property value must be specified."); } properties.put(name, value); }
java
public void addProperty(String name, String value) { if (name == null || name.trim().length() == 0) { throw new IllegalArgumentException("A property name must be specified."); } if (value == null || value.trim().length() == 0) { throw new IllegalArgumentException("A property value must be specified."); } properties.put(name, value); }
[ "public", "void", "addProperty", "(", "String", "name", ",", "String", "value", ")", "{", "if", "(", "name", "==", "null", "||", "name", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", ...
Adds a name-value pair property to this element. @param name the name of the property @param value the value of the property
[ "Adds", "a", "name", "-", "value", "pair", "property", "to", "this", "element", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/model/ModelItem.java#L111-L121
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/GitLabApi.java
GitLabApi.enableRequestResponseLogging
public void enableRequestResponseLogging(Level level, int maxEntitySize, List<String> maskedHeaderNames) { apiClient.enableRequestResponseLogging(LOGGER, level, maxEntitySize, maskedHeaderNames); }
java
public void enableRequestResponseLogging(Level level, int maxEntitySize, List<String> maskedHeaderNames) { apiClient.enableRequestResponseLogging(LOGGER, level, maxEntitySize, maskedHeaderNames); }
[ "public", "void", "enableRequestResponseLogging", "(", "Level", "level", ",", "int", "maxEntitySize", ",", "List", "<", "String", ">", "maskedHeaderNames", ")", "{", "apiClient", ".", "enableRequestResponseLogging", "(", "LOGGER", ",", "level", ",", "maxEntitySize",...
Enable the logging of the requests to and the responses from the GitLab server API using the GitLab4J shared Logger instance. @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST) @param maxEntitySize maximum number of entity bytes to be logged. When logging if the maxEntitySize is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at the end of the log entry. If maxEntitySize is &lt;= 0, entity logging will be disabled @param maskedHeaderNames a list of header names that should have the values masked
[ "Enable", "the", "logging", "of", "the", "requests", "to", "and", "the", "responses", "from", "the", "GitLab", "server", "API", "using", "the", "GitLab4J", "shared", "Logger", "instance", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/GitLabApi.java#L704-L706
line/armeria
examples/grpc-service/src/main/java/example/armeria/grpc/HelloServiceImpl.java
HelloServiceImpl.blockingHello
@Override public void blockingHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { // Unlike upstream gRPC-Java, Armeria does not run service logic in a separate thread pool by default. // Therefore, this method will run in the event loop, which means that you can suffer the performance // degradation if you call a blocking API in this method. In this case, you have the following options: // // 1. Call a blocking API in the blockingTaskExecutor provided by Armeria. // 2. Set GrpcServiceBuilder.useBlockingTaskExecutor(true) when building your GrpcService. // 3. Call a blocking API in the separate thread pool you manage. // // In this example, we chose the option 1: final ServiceRequestContext ctx = RequestContext.current(); ctx.blockingTaskExecutor().submit(() -> { try { // Simulate a blocking API call. Thread.sleep(3000); } catch (Exception ignored) { // Do nothing. } responseObserver.onNext(buildReply(toMessage(request.getName()))); responseObserver.onCompleted(); }); }
java
@Override public void blockingHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { // Unlike upstream gRPC-Java, Armeria does not run service logic in a separate thread pool by default. // Therefore, this method will run in the event loop, which means that you can suffer the performance // degradation if you call a blocking API in this method. In this case, you have the following options: // // 1. Call a blocking API in the blockingTaskExecutor provided by Armeria. // 2. Set GrpcServiceBuilder.useBlockingTaskExecutor(true) when building your GrpcService. // 3. Call a blocking API in the separate thread pool you manage. // // In this example, we chose the option 1: final ServiceRequestContext ctx = RequestContext.current(); ctx.blockingTaskExecutor().submit(() -> { try { // Simulate a blocking API call. Thread.sleep(3000); } catch (Exception ignored) { // Do nothing. } responseObserver.onNext(buildReply(toMessage(request.getName()))); responseObserver.onCompleted(); }); }
[ "@", "Override", "public", "void", "blockingHello", "(", "HelloRequest", "request", ",", "StreamObserver", "<", "HelloReply", ">", "responseObserver", ")", "{", "// Unlike upstream gRPC-Java, Armeria does not run service logic in a separate thread pool by default.", "// Therefore, ...
Sends a {@link HelloReply} using {@code blockingTaskExecutor}. @see <a href="https://line.github.io/armeria/server-grpc.html#blocking-service-implementation">Blocking service implementation</a>
[ "Sends", "a", "{", "@link", "HelloReply", "}", "using", "{", "@code", "blockingTaskExecutor", "}", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/examples/grpc-service/src/main/java/example/armeria/grpc/HelloServiceImpl.java#L46-L68