repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
adyliu/jafka
src/main/java/io/jafka/log/LogManager.java
LogManager.cleanupSegmentsToMaintainSize
private int cleanupSegmentsToMaintainSize(final Log log) throws IOException { if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0; List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() { long diff = log.size() - logRetentionSize; public boolean filter(LogSegment segment) { diff -= segment.size(); return diff >= 0; } }); return deleteSegments(log, toBeDeleted); }
java
private int cleanupSegmentsToMaintainSize(final Log log) throws IOException { if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0; List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() { long diff = log.size() - logRetentionSize; public boolean filter(LogSegment segment) { diff -= segment.size(); return diff >= 0; } }); return deleteSegments(log, toBeDeleted); }
[ "private", "int", "cleanupSegmentsToMaintainSize", "(", "final", "Log", "log", ")", "throws", "IOException", "{", "if", "(", "logRetentionSize", "<", "0", "||", "log", ".", "size", "(", ")", "<", "logRetentionSize", ")", "return", "0", ";", "List", "<", "L...
Runs through the log removing segments until the size of the log is at least logRetentionSize bytes in size @throws IOException
[ "Runs", "through", "the", "log", "removing", "segments", "until", "the", "size", "of", "the", "log", "is", "at", "least", "logRetentionSize", "bytes", "in", "size" ]
train
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/log/LogManager.java#L274-L287
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newSearchException
public static SearchException newSearchException(String message, Object... args) { return newSearchException(null, message, args); }
java
public static SearchException newSearchException(String message, Object... args) { return newSearchException(null, message, args); }
[ "public", "static", "SearchException", "newSearchException", "(", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "newSearchException", "(", "null", ",", "message", ",", "args", ")", ";", "}" ]
Constructs and initializes a new {@link SearchException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link SearchException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link SearchException} with the given {@link String message}. @see #newSearchException(Throwable, String, Object...) @see org.cp.elements.util.search.SearchException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "SearchException", "}", "with", "the", "given", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L873-L875
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java
Expressions.numberTemplate
public static <T extends Number & Comparable<?>> NumberTemplate<T> numberTemplate(Class<? extends T> cl, String template, List<?> args) { return numberTemplate(cl, createTemplate(template), args); }
java
public static <T extends Number & Comparable<?>> NumberTemplate<T> numberTemplate(Class<? extends T> cl, String template, List<?> args) { return numberTemplate(cl, createTemplate(template), args); }
[ "public", "static", "<", "T", "extends", "Number", "&", "Comparable", "<", "?", ">", ">", "NumberTemplate", "<", "T", ">", "numberTemplate", "(", "Class", "<", "?", "extends", "T", ">", "cl", ",", "String", "template", ",", "List", "<", "?", ">", "ar...
Create a new Template expression @param cl type of expression @param template template @param args template parameters @return template expression
[ "Create", "a", "new", "Template", "expression" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L836-L838
osglworks/java-tool
src/main/java/org/osgl/util/E.java
E.illegalStateIf
public static void illegalStateIf(boolean tester, String msg, Object... args) { if (tester) { throw new IllegalStateException(S.fmt(msg, args)); } }
java
public static void illegalStateIf(boolean tester, String msg, Object... args) { if (tester) { throw new IllegalStateException(S.fmt(msg, args)); } }
[ "public", "static", "void", "illegalStateIf", "(", "boolean", "tester", ",", "String", "msg", ",", "Object", "...", "args", ")", "{", "if", "(", "tester", ")", "{", "throw", "new", "IllegalStateException", "(", "S", ".", "fmt", "(", "msg", ",", "args", ...
Throws out an {@link IllegalStateException} with error message specified if `tester` is `true`. @param tester when `true` then throw out the exception. @param msg the error message format pattern. @param args the error message format arguments.
[ "Throws", "out", "an", "{", "@link", "IllegalStateException", "}", "with", "error", "message", "specified", "if", "tester", "is", "true", "." ]
train
https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/util/E.java#L783-L787
OpenLiberty/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/renderkit/_SharedRendererUtils.java
_SharedRendererUtils.log
private static void log(FacesContext context, String msg, Exception e) { log.log(Level.SEVERE, msg, e); }
java
private static void log(FacesContext context, String msg, Exception e) { log.log(Level.SEVERE, msg, e); }
[ "private", "static", "void", "log", "(", "FacesContext", "context", ",", "String", "msg", ",", "Exception", "e", ")", "{", "log", ".", "log", "(", "Level", ".", "SEVERE", ",", "msg", ",", "e", ")", ";", "}" ]
This method is different in the two versions of _SharedRendererUtils.
[ "This", "method", "is", "different", "in", "the", "two", "versions", "of", "_SharedRendererUtils", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/renderkit/_SharedRendererUtils.java#L499-L502
JM-Lab/utils-elasticsearch
src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchBulk.java
JMElasticsearchBulk.buildBulkProcessor
public BulkProcessor buildBulkProcessor(Listener bulkProcessorListener, int bulkActions, long bulkSizeKB, int flushIntervalSeconds, Integer concurrentRequests, BackoffPolicy backoffPolicy) { return getBulkProcessorBuilder(bulkProcessorListener, bulkActions, new ByteSizeValue(bulkSizeKB, ByteSizeUnit.KB), TimeValue.timeValueSeconds(flushIntervalSeconds), concurrentRequests, backoffPolicy).build(); }
java
public BulkProcessor buildBulkProcessor(Listener bulkProcessorListener, int bulkActions, long bulkSizeKB, int flushIntervalSeconds, Integer concurrentRequests, BackoffPolicy backoffPolicy) { return getBulkProcessorBuilder(bulkProcessorListener, bulkActions, new ByteSizeValue(bulkSizeKB, ByteSizeUnit.KB), TimeValue.timeValueSeconds(flushIntervalSeconds), concurrentRequests, backoffPolicy).build(); }
[ "public", "BulkProcessor", "buildBulkProcessor", "(", "Listener", "bulkProcessorListener", ",", "int", "bulkActions", ",", "long", "bulkSizeKB", ",", "int", "flushIntervalSeconds", ",", "Integer", "concurrentRequests", ",", "BackoffPolicy", "backoffPolicy", ")", "{", "r...
Build bulk processor bulk processor. @param bulkProcessorListener the bulk processor listener @param bulkActions the bulk actions @param bulkSizeKB the bulk size kb @param flushIntervalSeconds the flush interval seconds @param concurrentRequests the concurrent requests @param backoffPolicy the backoff policy @return the bulk processor
[ "Build", "bulk", "processor", "bulk", "processor", "." ]
train
https://github.com/JM-Lab/utils-elasticsearch/blob/6ccec90e1e51d65d2af5efbb6d7b9f9bad90e638/src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchBulk.java#L162-L169
amzn/ion-java
src/com/amazon/ion/util/IonStreamUtils.java
IonStreamUtils.writeStringList
public static void writeStringList(IonWriter writer, String[] values) throws IOException { if (writer instanceof _Private_ListWriter) { ((_Private_ListWriter)writer).writeStringList(values); return; } writer.stepIn(IonType.LIST); for (int ii=0; ii<values.length; ii++) { writer.writeString(values[ii]); } writer.stepOut(); }
java
public static void writeStringList(IonWriter writer, String[] values) throws IOException { if (writer instanceof _Private_ListWriter) { ((_Private_ListWriter)writer).writeStringList(values); return; } writer.stepIn(IonType.LIST); for (int ii=0; ii<values.length; ii++) { writer.writeString(values[ii]); } writer.stepOut(); }
[ "public", "static", "void", "writeStringList", "(", "IonWriter", "writer", ",", "String", "[", "]", "values", ")", "throws", "IOException", "{", "if", "(", "writer", "instanceof", "_Private_ListWriter", ")", "{", "(", "(", "_Private_ListWriter", ")", "writer", ...
writes an IonList with a series of IonString values. This starts a List, writes the values (without any annoations) and closes the list. For text and tree writers this is just a convienience, but for the binary writer it can be optimized internally. @param values Java String to populate the lists IonString's from
[ "writes", "an", "IonList", "with", "a", "series", "of", "IonString", "values", ".", "This", "starts", "a", "List", "writes", "the", "values", "(", "without", "any", "annoations", ")", "and", "closes", "the", "list", ".", "For", "text", "and", "tree", "wr...
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonStreamUtils.java#L303-L316
logic-ng/LogicNG
src/main/java/org/logicng/solvers/sat/MiniSatStyleSolver.java
MiniSatStyleSolver.addName
public void addName(final String name, int id) { this.name2idx.put(name, id); this.idx2name.put(id, name); }
java
public void addName(final String name, int id) { this.name2idx.put(name, id); this.idx2name.put(id, name); }
[ "public", "void", "addName", "(", "final", "String", "name", ",", "int", "id", ")", "{", "this", ".", "name2idx", ".", "put", "(", "name", ",", "id", ")", ";", "this", ".", "idx2name", ".", "put", "(", "id", ",", "name", ")", ";", "}" ]
Adds a new variable name with a given variable index to this solver. @param name the variable name @param id the variable index
[ "Adds", "a", "new", "variable", "name", "with", "a", "given", "variable", "index", "to", "this", "solver", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/sat/MiniSatStyleSolver.java#L294-L297
elki-project/elki
elki-index-preprocessed/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/knn/MaterializeKNNPreprocessor.java
MaterializeKNNPreprocessor.fireKNNsRemoved
protected void fireKNNsRemoved(DBIDs removals, DBIDs updates) { KNNChangeEvent e = new KNNChangeEvent(this, KNNChangeEvent.Type.DELETE, removals, updates); Object[] listeners = listenerList.getListenerList(); for(int i = listeners.length - 2; i >= 0; i -= 2) { if(listeners[i] == KNNListener.class) { ((KNNListener) listeners[i + 1]).kNNsChanged(e); } } }
java
protected void fireKNNsRemoved(DBIDs removals, DBIDs updates) { KNNChangeEvent e = new KNNChangeEvent(this, KNNChangeEvent.Type.DELETE, removals, updates); Object[] listeners = listenerList.getListenerList(); for(int i = listeners.length - 2; i >= 0; i -= 2) { if(listeners[i] == KNNListener.class) { ((KNNListener) listeners[i + 1]).kNNsChanged(e); } } }
[ "protected", "void", "fireKNNsRemoved", "(", "DBIDs", "removals", ",", "DBIDs", "updates", ")", "{", "KNNChangeEvent", "e", "=", "new", "KNNChangeEvent", "(", "this", ",", "KNNChangeEvent", ".", "Type", ".", "DELETE", ",", "removals", ",", "updates", ")", ";...
Informs all registered KNNListener that existing kNNs have been removed and as a result some kNNs have been changed. @param removals the ids of the removed kNNs @param updates the ids of kNNs which have been changed due to the removals @see KNNListener
[ "Informs", "all", "registered", "KNNListener", "that", "existing", "kNNs", "have", "been", "removed", "and", "as", "a", "result", "some", "kNNs", "have", "been", "changed", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-preprocessed/src/main/java/de/lmu/ifi/dbs/elki/index/preprocessed/knn/MaterializeKNNPreprocessor.java#L327-L335
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Flowable.java
Flowable.ambWith
@SuppressWarnings("unchecked") @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> ambWith(Publisher<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return ambArray(this, other); }
java
@SuppressWarnings("unchecked") @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final Flowable<T> ambWith(Publisher<? extends T> other) { ObjectHelper.requireNonNull(other, "other is null"); return ambArray(this, other); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "CheckReturnValue", "@", "BackpressureSupport", "(", "BackpressureKind", ".", "FULL", ")", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "final", "Flowable", "<", "T", ">", ...
Mirrors the Publisher (current or provided) that first either emits an item or sends a termination notification. <p> <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> <dl> <dt><b>Backpressure:</b></dt> <dd>The operator itself doesn't interfere with backpressure which is determined by the winning {@code Publisher}'s backpressure behavior.</dd> <dt><b>Scheduler:</b></dt> <dd>{@code ambWith} does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param other a Publisher competing to react first. A subscription to this provided Publisher will occur after subscribing to the current Publisher. @return a Flowable that emits the same sequence as whichever of the source Publishers first emitted an item or sent a termination notification @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a>
[ "Mirrors", "the", "Publisher", "(", "current", "or", "provided", ")", "that", "first", "either", "emits", "an", "item", "or", "sends", "a", "termination", "notification", ".", "<p", ">", "<img", "width", "=", "640", "height", "=", "385", "src", "=", "htt...
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L5418-L5425
apereo/cas
core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/actions/RedirectToServiceAction.java
RedirectToServiceAction.getFinalResponseEventId
protected String getFinalResponseEventId(final WebApplicationService service, final Response response, final RequestContext requestContext) { val eventId = response.getResponseType().name().toLowerCase(); LOGGER.debug("Signaling flow to redirect to service [{}] via event [{}]", service, eventId); return eventId; }
java
protected String getFinalResponseEventId(final WebApplicationService service, final Response response, final RequestContext requestContext) { val eventId = response.getResponseType().name().toLowerCase(); LOGGER.debug("Signaling flow to redirect to service [{}] via event [{}]", service, eventId); return eventId; }
[ "protected", "String", "getFinalResponseEventId", "(", "final", "WebApplicationService", "service", ",", "final", "Response", "response", ",", "final", "RequestContext", "requestContext", ")", "{", "val", "eventId", "=", "response", ".", "getResponseType", "(", ")", ...
Gets final response event id. @param service the service @param response the response @param requestContext the request context @return the final response event id
[ "Gets", "final", "response", "event", "id", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/actions/RedirectToServiceAction.java#L70-L74
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/Launcher.java
Launcher.findLocations
protected void findLocations(BootstrapConfig bootProps, String processName) { // Check for environment variables... String userDirStr = getEnv(BootstrapConstants.ENV_WLP_USER_DIR); String serversDirStr = getEnv(bootProps.getOutputDirectoryEnvName()); // Check for the variable calculated by the shell script first (X_LOG_DIR) // If that wasn't found, check for LOG_DIR set for java -jar invocation String logDirStr = getEnv(BootstrapConstants.ENV_X_LOG_DIR); if (logDirStr == null) logDirStr = getEnv(BootstrapConstants.ENV_LOG_DIR); // Likewise for X_LOG_FILE and LOG_FILE. String consoleLogFileStr = getEnv(BootstrapConstants.ENV_X_LOG_FILE); if (consoleLogFileStr == null) consoleLogFileStr = getEnv(BootstrapConstants.ENV_LOG_FILE); // Do enough processing to know where the directories should be.. // this should not cause any directories to be created bootProps.findLocations(processName, userDirStr, serversDirStr, logDirStr, consoleLogFileStr); }
java
protected void findLocations(BootstrapConfig bootProps, String processName) { // Check for environment variables... String userDirStr = getEnv(BootstrapConstants.ENV_WLP_USER_DIR); String serversDirStr = getEnv(bootProps.getOutputDirectoryEnvName()); // Check for the variable calculated by the shell script first (X_LOG_DIR) // If that wasn't found, check for LOG_DIR set for java -jar invocation String logDirStr = getEnv(BootstrapConstants.ENV_X_LOG_DIR); if (logDirStr == null) logDirStr = getEnv(BootstrapConstants.ENV_LOG_DIR); // Likewise for X_LOG_FILE and LOG_FILE. String consoleLogFileStr = getEnv(BootstrapConstants.ENV_X_LOG_FILE); if (consoleLogFileStr == null) consoleLogFileStr = getEnv(BootstrapConstants.ENV_LOG_FILE); // Do enough processing to know where the directories should be.. // this should not cause any directories to be created bootProps.findLocations(processName, userDirStr, serversDirStr, logDirStr, consoleLogFileStr); }
[ "protected", "void", "findLocations", "(", "BootstrapConfig", "bootProps", ",", "String", "processName", ")", "{", "// Check for environment variables...", "String", "userDirStr", "=", "getEnv", "(", "BootstrapConstants", ".", "ENV_WLP_USER_DIR", ")", ";", "String", "se...
Find main locations @param bootProps An instance of BootstrapConfig @param processName Process name to be used
[ "Find", "main", "locations" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/Launcher.java#L307-L326
apache/incubator-druid
extensions-core/parquet-extensions/src/main/java/org/apache/druid/data/input/parquet/simple/ParquetGroupConverter.java
ParquetGroupConverter.unwrapListPrimitive
Object unwrapListPrimitive(Object o) { assert isWrappedListPrimitive(o); Group g = (Group) o; return convertPrimitiveField(g, 0, binaryAsString); }
java
Object unwrapListPrimitive(Object o) { assert isWrappedListPrimitive(o); Group g = (Group) o; return convertPrimitiveField(g, 0, binaryAsString); }
[ "Object", "unwrapListPrimitive", "(", "Object", "o", ")", "{", "assert", "isWrappedListPrimitive", "(", "o", ")", ";", "Group", "g", "=", "(", "Group", ")", "o", ";", "return", "convertPrimitiveField", "(", "g", ",", "0", ",", "binaryAsString", ")", ";", ...
Properly formed parquet lists when passed through {@link ParquetGroupConverter#convertField(Group, String)} can return lists which contain 'wrapped' primitives, that are a {@link Group} with a single, primitive field (see {@link ParquetGroupConverter#isWrappedListPrimitive(Object)})
[ "Properly", "formed", "parquet", "lists", "when", "passed", "through", "{" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/parquet-extensions/src/main/java/org/apache/druid/data/input/parquet/simple/ParquetGroupConverter.java#L495-L500
i-net-software/jlessc
src/com/inet/lib/less/ValueExpression.java
ValueExpression.eval
public static ValueExpression eval( CssFormatter formatter, Expression expr ) { expr = expr.unpack( formatter ); // unpack to increase the chance to find a ValueExpression if( expr.getClass() == ValueExpression.class ) { return (ValueExpression)expr; } ValueExpression valueEx = new ValueExpression( expr, expr.stringValue( formatter ) ); valueEx.type = expr.getDataType( formatter ); valueEx.unit = expr.unit( formatter ); switch( valueEx.type ) { case STRING: case BOOLEAN: break; //string is already set case LIST: Operation op = valueEx.op = new Operation( expr, ' ' ); ArrayList<Expression> operants = expr.listValue( formatter ).getOperands(); for( int j = 0; j < operants.size(); j++ ) { op.addOperand( ValueExpression.eval( formatter, operants.get( j ) ) ); } break; default: valueEx.value = expr.doubleValue( formatter ); } return valueEx; }
java
public static ValueExpression eval( CssFormatter formatter, Expression expr ) { expr = expr.unpack( formatter ); // unpack to increase the chance to find a ValueExpression if( expr.getClass() == ValueExpression.class ) { return (ValueExpression)expr; } ValueExpression valueEx = new ValueExpression( expr, expr.stringValue( formatter ) ); valueEx.type = expr.getDataType( formatter ); valueEx.unit = expr.unit( formatter ); switch( valueEx.type ) { case STRING: case BOOLEAN: break; //string is already set case LIST: Operation op = valueEx.op = new Operation( expr, ' ' ); ArrayList<Expression> operants = expr.listValue( formatter ).getOperands(); for( int j = 0; j < operants.size(); j++ ) { op.addOperand( ValueExpression.eval( formatter, operants.get( j ) ) ); } break; default: valueEx.value = expr.doubleValue( formatter ); } return valueEx; }
[ "public", "static", "ValueExpression", "eval", "(", "CssFormatter", "formatter", ",", "Expression", "expr", ")", "{", "expr", "=", "expr", ".", "unpack", "(", "formatter", ")", ";", "// unpack to increase the chance to find a ValueExpression", "if", "(", "expr", "."...
Create a value expression as parameter for a mixin which not change it value in a different context. @param formatter current formatter @param expr current expression @return a ValueExpression
[ "Create", "a", "value", "expression", "as", "parameter", "for", "a", "mixin", "which", "not", "change", "it", "value", "in", "a", "different", "context", "." ]
train
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/ValueExpression.java#L99-L122
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/EntityUtils.java
EntityUtils.isEquipped
public static boolean isEquipped(EntityPlayer player, Item item, EnumHand hand) { return player != null && player.getHeldItem(hand) != null && player.getHeldItem(hand).getItem() == item; }
java
public static boolean isEquipped(EntityPlayer player, Item item, EnumHand hand) { return player != null && player.getHeldItem(hand) != null && player.getHeldItem(hand).getItem() == item; }
[ "public", "static", "boolean", "isEquipped", "(", "EntityPlayer", "player", ",", "Item", "item", ",", "EnumHand", "hand", ")", "{", "return", "player", "!=", "null", "&&", "player", ".", "getHeldItem", "(", "hand", ")", "!=", "null", "&&", "player", ".", ...
Checks if is the {@link Item} is equipped for the player. @param player the player @param item the item @return true, if is equipped
[ "Checks", "if", "is", "the", "{", "@link", "Item", "}", "is", "equipped", "for", "the", "player", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/EntityUtils.java#L201-L204
twilio/twilio-java
src/main/java/com/twilio/rest/autopilot/v1/AssistantReader.java
AssistantReader.nextPage
@Override public Page<Assistant> nextPage(final Page<Assistant> page, final TwilioRestClient client) { Request request = new Request( HttpMethod.GET, page.getNextPageUrl( Domains.AUTOPILOT.toString(), client.getRegion() ) ); return pageForRequest(client, request); }
java
@Override public Page<Assistant> nextPage(final Page<Assistant> page, final TwilioRestClient client) { Request request = new Request( HttpMethod.GET, page.getNextPageUrl( Domains.AUTOPILOT.toString(), client.getRegion() ) ); return pageForRequest(client, request); }
[ "@", "Override", "public", "Page", "<", "Assistant", ">", "nextPage", "(", "final", "Page", "<", "Assistant", ">", "page", ",", "final", "TwilioRestClient", "client", ")", "{", "Request", "request", "=", "new", "Request", "(", "HttpMethod", ".", "GET", ","...
Retrieve the next page from the Twilio API. @param page current page @param client TwilioRestClient with which to make the request @return Next Page
[ "Retrieve", "the", "next", "page", "from", "the", "Twilio", "API", "." ]
train
https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/autopilot/v1/AssistantReader.java#L84-L95
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AbstractAddStepHandler.java
AbstractAddStepHandler.rollbackRuntime
@Deprecated protected void rollbackRuntime(OperationContext context, final ModelNode operation, final ModelNode model, List<ServiceController<?>> controllers) { // no-op }
java
@Deprecated protected void rollbackRuntime(OperationContext context, final ModelNode operation, final ModelNode model, List<ServiceController<?>> controllers) { // no-op }
[ "@", "Deprecated", "protected", "void", "rollbackRuntime", "(", "OperationContext", "context", ",", "final", "ModelNode", "operation", ",", "final", "ModelNode", "model", ",", "List", "<", "ServiceController", "<", "?", ">", ">", "controllers", ")", "{", "// no-...
<strong>Deprecated</strong>. Subclasses wishing for custom rollback behavior should instead override {@link #rollbackRuntime(OperationContext, org.jboss.dmr.ModelNode, org.jboss.as.controller.registry.Resource)}. <p> This default implementation does nothing. <strong>Subclasses that override this method should not call {@code super.performRuntime(...)}.</strong> </p> </p> @param context the operation context @param operation the operation being executed @param model persistent configuration model node that corresponds to the address of {@code operation} @param controllers will always be an empty list @deprecated instead override {@link #rollbackRuntime(OperationContext, org.jboss.dmr.ModelNode, org.jboss.as.controller.registry.Resource)}
[ "<strong", ">", "Deprecated<", "/", "strong", ">", ".", "Subclasses", "wishing", "for", "custom", "rollback", "behavior", "should", "instead", "override", "{", "@link", "#rollbackRuntime", "(", "OperationContext", "org", ".", "jboss", ".", "dmr", ".", "ModelNode...
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractAddStepHandler.java#L394-L397
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Authentication.java
Authentication.validSecondFactor
public boolean validSecondFactor(String secret, String number) { Objects.requireNonNull(secret, Required.SECRET.toString()); Objects.requireNonNull(number, Required.TOTP.toString()); return TotpUtils.verifiedTotp(secret, number); }
java
public boolean validSecondFactor(String secret, String number) { Objects.requireNonNull(secret, Required.SECRET.toString()); Objects.requireNonNull(number, Required.TOTP.toString()); return TotpUtils.verifiedTotp(secret, number); }
[ "public", "boolean", "validSecondFactor", "(", "String", "secret", ",", "String", "number", ")", "{", "Objects", ".", "requireNonNull", "(", "secret", ",", "Required", ".", "SECRET", ".", "toString", "(", ")", ")", ";", "Objects", ".", "requireNonNull", "(",...
Checks if a given number for 2FA is valid for the given secret @param secret The plaintext secret to use for checking @param number The number entered by the user @return True if number is valid, false otherwise
[ "Checks", "if", "a", "given", "number", "for", "2FA", "is", "valid", "for", "the", "given", "secret" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Authentication.java#L195-L200
daimajia/AndroidImageSlider
library/src/main/java/com/daimajia/slider/library/Tricks/ViewPagerEx.java
ViewPagerEx.setPageTransformer
public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) { final boolean hasTransformer = transformer != null; final boolean needsPopulate = hasTransformer != (mPageTransformer != null); mPageTransformer = transformer; setChildrenDrawingOrderEnabledCompat(hasTransformer); if (hasTransformer) { mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD; } else { mDrawingOrder = DRAW_ORDER_DEFAULT; } if (needsPopulate) populate(); }
java
public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) { final boolean hasTransformer = transformer != null; final boolean needsPopulate = hasTransformer != (mPageTransformer != null); mPageTransformer = transformer; setChildrenDrawingOrderEnabledCompat(hasTransformer); if (hasTransformer) { mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD; } else { mDrawingOrder = DRAW_ORDER_DEFAULT; } if (needsPopulate) populate(); }
[ "public", "void", "setPageTransformer", "(", "boolean", "reverseDrawingOrder", ",", "PageTransformer", "transformer", ")", "{", "final", "boolean", "hasTransformer", "=", "transformer", "!=", "null", ";", "final", "boolean", "needsPopulate", "=", "hasTransformer", "!=...
Set a {@link PageTransformer} that will be called for each attached page whenever the scroll position is changed. This allows the application to apply custom property transformations to each page, overriding the default sliding look and feel. <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist. As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.</p> @param reverseDrawingOrder true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last. @param transformer PageTransformer that will modify each page's animation properties
[ "Set", "a", "{", "@link", "PageTransformer", "}", "that", "will", "be", "called", "for", "each", "attached", "page", "whenever", "the", "scroll", "position", "is", "changed", ".", "This", "allows", "the", "application", "to", "apply", "custom", "property", "...
train
https://github.com/daimajia/AndroidImageSlider/blob/e318cabdef668de985efdcc45ca304e2ac6f58b5/library/src/main/java/com/daimajia/slider/library/Tricks/ViewPagerEx.java#L625-L636
exoplatform/jcr
exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipTypeHandlerImpl.java
MembershipTypeHandlerImpl.postSave
private void postSave(MembershipType type, boolean isNew) throws Exception { for (MembershipTypeEventListener listener : listeners) { listener.postSave(type, isNew); } }
java
private void postSave(MembershipType type, boolean isNew) throws Exception { for (MembershipTypeEventListener listener : listeners) { listener.postSave(type, isNew); } }
[ "private", "void", "postSave", "(", "MembershipType", "type", ",", "boolean", "isNew", ")", "throws", "Exception", "{", "for", "(", "MembershipTypeEventListener", "listener", ":", "listeners", ")", "{", "listener", ".", "postSave", "(", "type", ",", "isNew", "...
Notifying listeners after membership type creation. @param type the membership which is used in create operation @param isNew true, if we have a deal with new membership type, otherwise it is false which mean update operation is in progress @throws Exception if any listener failed to handle the event
[ "Notifying", "listeners", "after", "membership", "type", "creation", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/MembershipTypeHandlerImpl.java#L484-L490
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementPlugin.java
ElementPlugin.updateVisibility
@Override protected void updateVisibility(boolean visible, boolean activated) { super.updateVisibility(visible, activated); if (registeredComponents != null) { for (BaseUIComponent component : registeredComponents) { if (!visible) { component.setAttribute(Constants.ATTR_VISIBLE, component.isVisible()); component.setVisible(false); } else { component.setVisible((Boolean) component.getAttribute(Constants.ATTR_VISIBLE)); } } } if (visible) { checkBusy(); } }
java
@Override protected void updateVisibility(boolean visible, boolean activated) { super.updateVisibility(visible, activated); if (registeredComponents != null) { for (BaseUIComponent component : registeredComponents) { if (!visible) { component.setAttribute(Constants.ATTR_VISIBLE, component.isVisible()); component.setVisible(false); } else { component.setVisible((Boolean) component.getAttribute(Constants.ATTR_VISIBLE)); } } } if (visible) { checkBusy(); } }
[ "@", "Override", "protected", "void", "updateVisibility", "(", "boolean", "visible", ",", "boolean", "activated", ")", "{", "super", ".", "updateVisibility", "(", "visible", ",", "activated", ")", ";", "if", "(", "registeredComponents", "!=", "null", ")", "{",...
Sets the visibility of the contained resource and any registered components. @param visible Visibility state to set
[ "Sets", "the", "visibility", "of", "the", "contained", "resource", "and", "any", "registered", "components", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementPlugin.java#L292-L311
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/IOUtils.java
IOUtils.copy
public static void copy(InputStream input, OutputStream output) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int num = 0; while ((num = input.read(buf, 0, buf.length)) != -1) { output.write(buf, 0, num); } }
java
public static void copy(InputStream input, OutputStream output) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int num = 0; while ((num = input.read(buf, 0, buf.length)) != -1) { output.write(buf, 0, num); } }
[ "public", "static", "void", "copy", "(", "InputStream", "input", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "byte", "[", "]", "buf", "=", "new", "byte", "[", "BUFFER_SIZE", "]", ";", "int", "num", "=", "0", ";", "while", "(", "("...
Writes all the contents of a Reader to a Writer. @param input the input to read from @param output the output to write to @throws java.io.IOException if an IOExcption occurs
[ "Writes", "all", "the", "contents", "of", "a", "Reader", "to", "a", "Writer", "." ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/IOUtils.java#L85-L92
lucee/Lucee
core/src/main/java/lucee/runtime/op/Caster.java
Caster.toDecimal
public static String toDecimal(Object value, String defaultValue) { double res = toDoubleValue(value, true, Double.NaN); if (Double.isNaN(res)) return defaultValue; return toDecimal(res); }
java
public static String toDecimal(Object value, String defaultValue) { double res = toDoubleValue(value, true, Double.NaN); if (Double.isNaN(res)) return defaultValue; return toDecimal(res); }
[ "public", "static", "String", "toDecimal", "(", "Object", "value", ",", "String", "defaultValue", ")", "{", "double", "res", "=", "toDoubleValue", "(", "value", ",", "true", ",", "Double", ".", "NaN", ")", ";", "if", "(", "Double", ".", "isNaN", "(", "...
cast a double to a decimal value (String:xx.xx) @param value Object to cast @param defaultValue @return casted decimal value
[ "cast", "a", "double", "to", "a", "decimal", "value", "(", "String", ":", "xx", ".", "xx", ")" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L849-L853
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/ExceptionFactory.java
ExceptionFactory.createExecutionException
public static RedisCommandExecutionException createExecutionException(String message, Throwable cause) { if (message != null) { if (message.startsWith("BUSY")) { return cause != null ? new RedisBusyException(message, cause) : new RedisBusyException(message); } if (message.startsWith("NOSCRIPT")) { return cause != null ? new RedisNoScriptException(message, cause) : new RedisNoScriptException(message); } if (message.startsWith("LOADING")) { return cause != null ? new RedisLoadingException(message, cause) : new RedisLoadingException(message); } return cause != null ? new RedisCommandExecutionException(message, cause) : new RedisCommandExecutionException( message); } return new RedisCommandExecutionException(cause); }
java
public static RedisCommandExecutionException createExecutionException(String message, Throwable cause) { if (message != null) { if (message.startsWith("BUSY")) { return cause != null ? new RedisBusyException(message, cause) : new RedisBusyException(message); } if (message.startsWith("NOSCRIPT")) { return cause != null ? new RedisNoScriptException(message, cause) : new RedisNoScriptException(message); } if (message.startsWith("LOADING")) { return cause != null ? new RedisLoadingException(message, cause) : new RedisLoadingException(message); } return cause != null ? new RedisCommandExecutionException(message, cause) : new RedisCommandExecutionException( message); } return new RedisCommandExecutionException(cause); }
[ "public", "static", "RedisCommandExecutionException", "createExecutionException", "(", "String", "message", ",", "Throwable", "cause", ")", "{", "if", "(", "message", "!=", "null", ")", "{", "if", "(", "message", ".", "startsWith", "(", "\"BUSY\"", ")", ")", "...
Create a {@link RedisCommandExecutionException} with a detail message and optionally a {@link Throwable cause}. Specific Redis error messages may create subtypes of {@link RedisCommandExecutionException}. @param message the detail message. @param cause the nested exception, may be {@literal null}. @return the {@link RedisCommandExecutionException}.
[ "Create", "a", "{", "@link", "RedisCommandExecutionException", "}", "with", "a", "detail", "message", "and", "optionally", "a", "{", "@link", "Throwable", "cause", "}", ".", "Specific", "Redis", "error", "messages", "may", "create", "subtypes", "of", "{", "@li...
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/ExceptionFactory.java#L119-L140
TGIO/RNCryptorNative
rncryptor-native/src/main/java/tgio/rncryptor/RNCryptorNative.java
RNCryptorNative.encryptFile
public static void encryptFile(File raw, File encryptedFile, String password) throws IOException { byte[] b = readBytes(raw); String encodedImage = Base64.encodeToString(b, Base64.DEFAULT); byte[] encryptedBytes = new RNCryptorNative().encrypt(encodedImage, password); writeBytes(encryptedFile, encryptedBytes); }
java
public static void encryptFile(File raw, File encryptedFile, String password) throws IOException { byte[] b = readBytes(raw); String encodedImage = Base64.encodeToString(b, Base64.DEFAULT); byte[] encryptedBytes = new RNCryptorNative().encrypt(encodedImage, password); writeBytes(encryptedFile, encryptedBytes); }
[ "public", "static", "void", "encryptFile", "(", "File", "raw", ",", "File", "encryptedFile", ",", "String", "password", ")", "throws", "IOException", "{", "byte", "[", "]", "b", "=", "readBytes", "(", "raw", ")", ";", "String", "encodedImage", "=", "Base64...
Encrypts file using password @param raw the original file to be encrypted @param encryptedFile the result file @param password strong generated password @throws IOException
[ "Encrypts", "file", "using", "password" ]
train
https://github.com/TGIO/RNCryptorNative/blob/5209f10b988e4033c0b769a40b0d6cc99ea16af7/rncryptor-native/src/main/java/tgio/rncryptor/RNCryptorNative.java#L98-L103
morfologik/morfologik-stemming
morfologik-stemming/src/main/java/morfologik/stemming/BufferUtils.java
BufferUtils.clearAndEnsureCapacity
public static CharBuffer clearAndEnsureCapacity(CharBuffer buffer, int elements) { if (buffer == null || buffer.capacity() < elements) { buffer = CharBuffer.allocate(elements); } else { buffer.clear(); } return buffer; }
java
public static CharBuffer clearAndEnsureCapacity(CharBuffer buffer, int elements) { if (buffer == null || buffer.capacity() < elements) { buffer = CharBuffer.allocate(elements); } else { buffer.clear(); } return buffer; }
[ "public", "static", "CharBuffer", "clearAndEnsureCapacity", "(", "CharBuffer", "buffer", ",", "int", "elements", ")", "{", "if", "(", "buffer", "==", "null", "||", "buffer", ".", "capacity", "(", ")", "<", "elements", ")", "{", "buffer", "=", "CharBuffer", ...
Ensure the buffer's capacity is large enough to hold a given number of elements. If the input buffer is not large enough, a new buffer is allocated and returned. @param elements The required number of elements to be appended to the buffer. @param buffer The buffer to check or <code>null</code> if a new buffer should be allocated. @return Returns the same buffer or a new buffer with the given capacity.
[ "Ensure", "the", "buffer", "s", "capacity", "is", "large", "enough", "to", "hold", "a", "given", "number", "of", "elements", ".", "If", "the", "input", "buffer", "is", "not", "large", "enough", "a", "new", "buffer", "is", "allocated", "and", "returned", ...
train
https://github.com/morfologik/morfologik-stemming/blob/9d9099cc5ec4155a0eb8dfecdc23d01cbd734f6e/morfologik-stemming/src/main/java/morfologik/stemming/BufferUtils.java#L56-L63
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/SampleableConcurrentHashMap.java
SampleableConcurrentHashMap.fetchKeys
public int fetchKeys(int tableIndex, int size, List<K> keys) { final long now = Clock.currentTimeMillis(); final Segment<K, V> segment = segments[0]; final HashEntry<K, V>[] currentTable = segment.table; int nextTableIndex; if (tableIndex >= 0 && tableIndex < segment.table.length) { nextTableIndex = tableIndex; } else { nextTableIndex = currentTable.length - 1; } int counter = 0; while (nextTableIndex >= 0 && counter < size) { HashEntry<K, V> nextEntry = currentTable[nextTableIndex--]; while (nextEntry != null) { if (nextEntry.key() != null) { final V value = nextEntry.value(); if (isValidForFetching(value, now)) { keys.add(nextEntry.key()); counter++; } } nextEntry = nextEntry.next; } } return nextTableIndex; }
java
public int fetchKeys(int tableIndex, int size, List<K> keys) { final long now = Clock.currentTimeMillis(); final Segment<K, V> segment = segments[0]; final HashEntry<K, V>[] currentTable = segment.table; int nextTableIndex; if (tableIndex >= 0 && tableIndex < segment.table.length) { nextTableIndex = tableIndex; } else { nextTableIndex = currentTable.length - 1; } int counter = 0; while (nextTableIndex >= 0 && counter < size) { HashEntry<K, V> nextEntry = currentTable[nextTableIndex--]; while (nextEntry != null) { if (nextEntry.key() != null) { final V value = nextEntry.value(); if (isValidForFetching(value, now)) { keys.add(nextEntry.key()); counter++; } } nextEntry = nextEntry.next; } } return nextTableIndex; }
[ "public", "int", "fetchKeys", "(", "int", "tableIndex", ",", "int", "size", ",", "List", "<", "K", ">", "keys", ")", "{", "final", "long", "now", "=", "Clock", ".", "currentTimeMillis", "(", ")", ";", "final", "Segment", "<", "K", ",", "V", ">", "s...
Fetches keys from given <code>tableIndex</code> as <code>size</code> and puts them into <code>keys</code> list. @param tableIndex Index (checkpoint) for starting point of fetch operation @param size Count of how many keys will be fetched @param keys List that fetched keys will be put into @return the next index (checkpoint) for later fetches
[ "Fetches", "keys", "from", "given", "<code", ">", "tableIndex<", "/", "code", ">", "as", "<code", ">", "size<", "/", "code", ">", "and", "puts", "them", "into", "<code", ">", "keys<", "/", "code", ">", "list", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/SampleableConcurrentHashMap.java#L66-L91
kuali/ojb-1.0.4
src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java
OjbTagsHandler.forAllCollectionDefinitions
public void forAllCollectionDefinitions(String template, Properties attributes) throws XDocletException { for (Iterator it = _curClassDef.getCollections(); it.hasNext(); ) { _curCollectionDef = (CollectionDescriptorDef)it.next(); if (!isFeatureIgnored(LEVEL_COLLECTION) && !_curCollectionDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false)) { generate(template); } } _curCollectionDef = null; }
java
public void forAllCollectionDefinitions(String template, Properties attributes) throws XDocletException { for (Iterator it = _curClassDef.getCollections(); it.hasNext(); ) { _curCollectionDef = (CollectionDescriptorDef)it.next(); if (!isFeatureIgnored(LEVEL_COLLECTION) && !_curCollectionDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false)) { generate(template); } } _curCollectionDef = null; }
[ "public", "void", "forAllCollectionDefinitions", "(", "String", "template", ",", "Properties", "attributes", ")", "throws", "XDocletException", "{", "for", "(", "Iterator", "it", "=", "_curClassDef", ".", "getCollections", "(", ")", ";", "it", ".", "hasNext", "(...
Processes the template for all collection definitions of the current class definition. @param template The template @param attributes The attributes of the tag @exception XDocletException if an error occurs @doc.tag type="block"
[ "Processes", "the", "template", "for", "all", "collection", "definitions", "of", "the", "current", "class", "definition", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L1062-L1074
buschmais/jqa-core-framework
report/src/main/java/com/buschmais/jqassistant/core/report/api/LanguageHelper.java
LanguageHelper.getLanguageElement
public static LanguageElement getLanguageElement(CompositeObject descriptor) { Queue<Class<?>> queue = new LinkedList<>(); Class<?>[] descriptorTypes = descriptor.getClass().getInterfaces(); do { queue.addAll(Arrays.asList(descriptorTypes)); Class<?> descriptorType = queue.poll(); AnnotatedType annotatedType = new AnnotatedType(descriptorType); Annotation languageAnnotation = annotatedType.getByMetaAnnotation(Language.class); if (languageAnnotation != null) { return getAnnotationValue(languageAnnotation, "value", LanguageElement.class); } descriptorTypes = descriptorType.getInterfaces(); } while (!queue.isEmpty()); return null; }
java
public static LanguageElement getLanguageElement(CompositeObject descriptor) { Queue<Class<?>> queue = new LinkedList<>(); Class<?>[] descriptorTypes = descriptor.getClass().getInterfaces(); do { queue.addAll(Arrays.asList(descriptorTypes)); Class<?> descriptorType = queue.poll(); AnnotatedType annotatedType = new AnnotatedType(descriptorType); Annotation languageAnnotation = annotatedType.getByMetaAnnotation(Language.class); if (languageAnnotation != null) { return getAnnotationValue(languageAnnotation, "value", LanguageElement.class); } descriptorTypes = descriptorType.getInterfaces(); } while (!queue.isEmpty()); return null; }
[ "public", "static", "LanguageElement", "getLanguageElement", "(", "CompositeObject", "descriptor", ")", "{", "Queue", "<", "Class", "<", "?", ">", ">", "queue", "=", "new", "LinkedList", "<>", "(", ")", ";", "Class", "<", "?", ">", "[", "]", "descriptorTyp...
Return the {@link LanguageElement} associated with a {@link CompositeObject}. The method uses a breadth-first-search to identify a descriptor type annotated with {@link LanguageElement}. @param descriptor The descriptor. @return The resolved {@link LanguageElement}
[ "Return", "the", "{", "@link", "LanguageElement", "}", "associated", "with", "a", "{", "@link", "CompositeObject", "}", "." ]
train
https://github.com/buschmais/jqa-core-framework/blob/0e63ff509cfe52f9063539a23d5f9f183b2ea4a5/report/src/main/java/com/buschmais/jqassistant/core/report/api/LanguageHelper.java#L26-L41
BotMill/fb-botmill
src/main/java/co/aurasphere/botmill/fb/support/FbBotMillMockMediator.java
FbBotMillMockMediator.sendQuickReplyPayload
public void sendQuickReplyPayload(String payload) { MessageEnvelope envelope = new MessageEnvelope(); QuickReply quickReply = new QuickReply("Sample", payload); ReceivedMessage message = new ReceivedMessage(); message.setQuickReply(quickReply); envelope.setMessage(message); envelope.setSender(new User(facebookMockId)); System.out.println("Sending quick reply: [" + message + "] as user : [" + facebookMockId + "]."); forward(envelope); System.out.println("Sent!"); }
java
public void sendQuickReplyPayload(String payload) { MessageEnvelope envelope = new MessageEnvelope(); QuickReply quickReply = new QuickReply("Sample", payload); ReceivedMessage message = new ReceivedMessage(); message.setQuickReply(quickReply); envelope.setMessage(message); envelope.setSender(new User(facebookMockId)); System.out.println("Sending quick reply: [" + message + "] as user : [" + facebookMockId + "]."); forward(envelope); System.out.println("Sent!"); }
[ "public", "void", "sendQuickReplyPayload", "(", "String", "payload", ")", "{", "MessageEnvelope", "envelope", "=", "new", "MessageEnvelope", "(", ")", ";", "QuickReply", "quickReply", "=", "new", "QuickReply", "(", "\"Sample\"", ",", "payload", ")", ";", "Receiv...
Sends a quickreply to all the registered bots. Used to simulate a user interacting with buttons. @param payload the payload to send.
[ "Sends", "a", "quickreply", "to", "all", "the", "registered", "bots", ".", "Used", "to", "simulate", "a", "user", "interacting", "with", "buttons", "." ]
train
https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/support/FbBotMillMockMediator.java#L183-L196
alipay/sofa-rpc
extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/server/http/HttpServerHandler.java
HttpServerHandler.handleHttp1Request
public void handleHttp1Request(SofaRequest request, ChannelHandlerContext ctx, boolean keepAlive) { Http1ServerTask task = new Http1ServerTask(this, request, ctx, keepAlive); processingCount.incrementAndGet(); try { task.run(); } catch (RejectedExecutionException e) { processingCount.decrementAndGet(); throw e; } }
java
public void handleHttp1Request(SofaRequest request, ChannelHandlerContext ctx, boolean keepAlive) { Http1ServerTask task = new Http1ServerTask(this, request, ctx, keepAlive); processingCount.incrementAndGet(); try { task.run(); } catch (RejectedExecutionException e) { processingCount.decrementAndGet(); throw e; } }
[ "public", "void", "handleHttp1Request", "(", "SofaRequest", "request", ",", "ChannelHandlerContext", "ctx", ",", "boolean", "keepAlive", ")", "{", "Http1ServerTask", "task", "=", "new", "Http1ServerTask", "(", "this", ",", "request", ",", "ctx", ",", "keepAlive", ...
Handle request from HTTP/1.1 @param request SofaRequest @param ctx ChannelHandlerContext @param keepAlive keepAlive
[ "Handle", "request", "from", "HTTP", "/", "1", ".", "1" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/server/http/HttpServerHandler.java#L81-L92
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java
ServerParams.updateMap
@SuppressWarnings("unchecked") private void updateMap(Map<String, Object> parentMap, String paramName, Object paramValue) { Object currentValue = parentMap.get(paramName); if (currentValue == null || !(currentValue instanceof Map)) { if (paramValue instanceof Map) { parentMap.put(paramName, paramValue); } else { parentMap.put(paramName, paramValue.toString()); } } else { Utils.require(paramValue instanceof Map, "Parameter '%s' must be a map: %s", paramName, paramValue.toString()); Map<String, Object> currentMap = (Map<String, Object>)currentValue; Map<String, Object> updateMap = (Map<String, Object>)paramValue; for (String subParam : updateMap.keySet()) { updateMap(currentMap, subParam, updateMap.get(subParam)); } } }
java
@SuppressWarnings("unchecked") private void updateMap(Map<String, Object> parentMap, String paramName, Object paramValue) { Object currentValue = parentMap.get(paramName); if (currentValue == null || !(currentValue instanceof Map)) { if (paramValue instanceof Map) { parentMap.put(paramName, paramValue); } else { parentMap.put(paramName, paramValue.toString()); } } else { Utils.require(paramValue instanceof Map, "Parameter '%s' must be a map: %s", paramName, paramValue.toString()); Map<String, Object> currentMap = (Map<String, Object>)currentValue; Map<String, Object> updateMap = (Map<String, Object>)paramValue; for (String subParam : updateMap.keySet()) { updateMap(currentMap, subParam, updateMap.get(subParam)); } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "updateMap", "(", "Map", "<", "String", ",", "Object", ">", "parentMap", ",", "String", "paramName", ",", "Object", "paramValue", ")", "{", "Object", "currentValue", "=", "parentMap", ".", ...
Replace or add the given parameter name and value to the given map.
[ "Replace", "or", "add", "the", "given", "parameter", "name", "and", "value", "to", "the", "given", "map", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L501-L519
dadoonet/fscrawler
framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java
FsCrawlerUtil.copyResourceFile
public static void copyResourceFile(String source, Path target) throws IOException { InputStream resource = FsCrawlerUtil.class.getResourceAsStream(source); FileUtils.copyInputStreamToFile(resource, target.toFile()); }
java
public static void copyResourceFile(String source, Path target) throws IOException { InputStream resource = FsCrawlerUtil.class.getResourceAsStream(source); FileUtils.copyInputStreamToFile(resource, target.toFile()); }
[ "public", "static", "void", "copyResourceFile", "(", "String", "source", ",", "Path", "target", ")", "throws", "IOException", "{", "InputStream", "resource", "=", "FsCrawlerUtil", ".", "class", ".", "getResourceAsStream", "(", "source", ")", ";", "FileUtils", "....
Copy a single resource file from the classpath or from a JAR. @param target The target @throws IOException If copying does not work
[ "Copy", "a", "single", "resource", "file", "from", "the", "classpath", "or", "from", "a", "JAR", "." ]
train
https://github.com/dadoonet/fscrawler/blob/cca00a14e21ef9986aa30e19b160463aed6bf921/framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java#L460-L463
mapbox/mapbox-navigation-android
libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/instruction/maneuver/ManeuverView.java
ManeuverView.setManeuverTypeAndModifier
public void setManeuverTypeAndModifier(@NonNull String maneuverType, @Nullable String maneuverModifier) { if (isNewTypeOrModifier(maneuverType, maneuverModifier)) { this.maneuverType = maneuverType; this.maneuverModifier = maneuverModifier; if (checkManeuverTypeWithNullModifier(maneuverType)) { return; } maneuverType = checkManeuverModifier(maneuverType, maneuverModifier); maneuverTypeAndModifier = new Pair<>(maneuverType, maneuverModifier); invalidate(); } }
java
public void setManeuverTypeAndModifier(@NonNull String maneuverType, @Nullable String maneuverModifier) { if (isNewTypeOrModifier(maneuverType, maneuverModifier)) { this.maneuverType = maneuverType; this.maneuverModifier = maneuverModifier; if (checkManeuverTypeWithNullModifier(maneuverType)) { return; } maneuverType = checkManeuverModifier(maneuverType, maneuverModifier); maneuverTypeAndModifier = new Pair<>(maneuverType, maneuverModifier); invalidate(); } }
[ "public", "void", "setManeuverTypeAndModifier", "(", "@", "NonNull", "String", "maneuverType", ",", "@", "Nullable", "String", "maneuverModifier", ")", "{", "if", "(", "isNewTypeOrModifier", "(", "maneuverType", ",", "maneuverModifier", ")", ")", "{", "this", ".",...
Updates the maneuver type and modifier which determine how this view will render itself. <p> If determined the provided maneuver type and modifier will render a new image, the view will invalidate and redraw itself with the new data. @param maneuverType to determine the maneuver icon to render @param maneuverModifier to determine the maneuver icon to render
[ "Updates", "the", "maneuver", "type", "and", "modifier", "which", "determine", "how", "this", "view", "will", "render", "itself", ".", "<p", ">", "If", "determined", "the", "provided", "maneuver", "type", "and", "modifier", "will", "render", "a", "new", "ima...
train
https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/instruction/maneuver/ManeuverView.java#L142-L153
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java
RepositoryApplicationConfiguration.autoAssignScheduler
@Bean @ConditionalOnMissingBean // don't active the auto assign scheduler in test, otherwise it is hard to // test @Profile("!test") @ConditionalOnProperty(prefix = "hawkbit.autoassign.scheduler", name = "enabled", matchIfMissing = true) AutoAssignScheduler autoAssignScheduler(final TenantAware tenantAware, final SystemManagement systemManagement, final SystemSecurityContext systemSecurityContext, final AutoAssignChecker autoAssignChecker, final LockRegistry lockRegistry) { return new AutoAssignScheduler(systemManagement, systemSecurityContext, autoAssignChecker, lockRegistry); }
java
@Bean @ConditionalOnMissingBean // don't active the auto assign scheduler in test, otherwise it is hard to // test @Profile("!test") @ConditionalOnProperty(prefix = "hawkbit.autoassign.scheduler", name = "enabled", matchIfMissing = true) AutoAssignScheduler autoAssignScheduler(final TenantAware tenantAware, final SystemManagement systemManagement, final SystemSecurityContext systemSecurityContext, final AutoAssignChecker autoAssignChecker, final LockRegistry lockRegistry) { return new AutoAssignScheduler(systemManagement, systemSecurityContext, autoAssignChecker, lockRegistry); }
[ "@", "Bean", "@", "ConditionalOnMissingBean", "// don't active the auto assign scheduler in test, otherwise it is hard to", "// test", "@", "Profile", "(", "\"!test\"", ")", "@", "ConditionalOnProperty", "(", "prefix", "=", "\"hawkbit.autoassign.scheduler\"", ",", "name", "=", ...
{@link AutoAssignScheduler} bean. Note: does not activate in test profile, otherwise it is hard to test the auto assign functionality. @param tenantAware to run as specific tenant @param systemManagement to find all tenants @param systemSecurityContext to run as system @param autoAssignChecker to run a check as tenant @param lockRegistry to lock the tenant for auto assignment @return a new {@link AutoAssignChecker}
[ "{", "@link", "AutoAssignScheduler", "}", "bean", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java#L783-L793
opengeospatial/teamengine
teamengine-spi/src/main/java/com/occamlab/te/spi/util/HtmlReport.java
HtmlReport.addDir
private static void addDir(File dirObj, ZipOutputStream out) throws IOException { File[] dirList = dirObj.listFiles(); byte[] tmpBuf = new byte[1024]; for (int i = 0; i < dirList.length; i++) { if (dirList[i].isDirectory()) { addDir(dirList[i], out); continue; } FileInputStream in = new FileInputStream( dirList[i].getAbsolutePath()); System.out.println(" Adding: " + dirList[i].getAbsolutePath()); out.putNextEntry(new ZipEntry(dirList[i].getAbsolutePath())); // Transfer from the file to the ZIP file int len; while ((len = in.read(tmpBuf)) > 0) { out.write(tmpBuf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } }
java
private static void addDir(File dirObj, ZipOutputStream out) throws IOException { File[] dirList = dirObj.listFiles(); byte[] tmpBuf = new byte[1024]; for (int i = 0; i < dirList.length; i++) { if (dirList[i].isDirectory()) { addDir(dirList[i], out); continue; } FileInputStream in = new FileInputStream( dirList[i].getAbsolutePath()); System.out.println(" Adding: " + dirList[i].getAbsolutePath()); out.putNextEntry(new ZipEntry(dirList[i].getAbsolutePath())); // Transfer from the file to the ZIP file int len; while ((len = in.read(tmpBuf)) > 0) { out.write(tmpBuf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } }
[ "private", "static", "void", "addDir", "(", "File", "dirObj", ",", "ZipOutputStream", "out", ")", "throws", "IOException", "{", "File", "[", "]", "dirList", "=", "dirObj", ".", "listFiles", "(", ")", ";", "byte", "[", "]", "tmpBuf", "=", "new", "byte", ...
Add directory to zip file @param dirObj @param out @throws IOException
[ "Add", "directory", "to", "zip", "file" ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-spi/src/main/java/com/occamlab/te/spi/util/HtmlReport.java#L149-L176
atomix/catalyst
serializer/src/main/java/io/atomix/catalyst/serializer/SerializerRegistry.java
SerializerRegistry.registerAbstract
public SerializerRegistry registerAbstract(Class<?> abstractType, TypeSerializerFactory factory) { return registerAbstract(abstractType, calculateTypeId(abstractType), factory); }
java
public SerializerRegistry registerAbstract(Class<?> abstractType, TypeSerializerFactory factory) { return registerAbstract(abstractType, calculateTypeId(abstractType), factory); }
[ "public", "SerializerRegistry", "registerAbstract", "(", "Class", "<", "?", ">", "abstractType", ",", "TypeSerializerFactory", "factory", ")", "{", "return", "registerAbstract", "(", "abstractType", ",", "calculateTypeId", "(", "abstractType", ")", ",", "factory", "...
Registers the given class as an abstract serializer for the given abstract type. @param abstractType The abstract type for which to register the serializer. @param factory The serializer factory. @return The serializer registry.
[ "Registers", "the", "given", "class", "as", "an", "abstract", "serializer", "for", "the", "given", "abstract", "type", "." ]
train
https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/SerializerRegistry.java#L219-L221
structr/structr
structr-ui/src/main/java/org/structr/web/common/FileHelper.java
FileHelper.getFileByAbsolutePath
public static AbstractFile getFileByAbsolutePath(final SecurityContext securityContext, final String absolutePath) { try { return StructrApp.getInstance(securityContext).nodeQuery(AbstractFile.class).and(StructrApp.key(AbstractFile.class, "path"), absolutePath).getFirst(); } catch (FrameworkException ex) { ex.printStackTrace(); logger.warn("File not found: {}", absolutePath); } return null; }
java
public static AbstractFile getFileByAbsolutePath(final SecurityContext securityContext, final String absolutePath) { try { return StructrApp.getInstance(securityContext).nodeQuery(AbstractFile.class).and(StructrApp.key(AbstractFile.class, "path"), absolutePath).getFirst(); } catch (FrameworkException ex) { ex.printStackTrace(); logger.warn("File not found: {}", absolutePath); } return null; }
[ "public", "static", "AbstractFile", "getFileByAbsolutePath", "(", "final", "SecurityContext", "securityContext", ",", "final", "String", "absolutePath", ")", "{", "try", "{", "return", "StructrApp", ".", "getInstance", "(", "securityContext", ")", ".", "nodeQuery", ...
Find a file by its absolute ancestor path. File may not be hidden or deleted. @param securityContext @param absolutePath @return file
[ "Find", "a", "file", "by", "its", "absolute", "ancestor", "path", "." ]
train
https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-ui/src/main/java/org/structr/web/common/FileHelper.java#L635-L647
biojava/biojava
biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java
FastaWriterHelper.writeNucleotideSequence
public static void writeNucleotideSequence(OutputStream outputStream, Collection<DNASequence> dnaSequences) throws Exception { FastaWriter<DNASequence, NucleotideCompound> fastaWriter = new FastaWriter<DNASequence, NucleotideCompound>( outputStream, dnaSequences, new GenericFastaHeaderFormat<DNASequence, NucleotideCompound>()); fastaWriter.process(); }
java
public static void writeNucleotideSequence(OutputStream outputStream, Collection<DNASequence> dnaSequences) throws Exception { FastaWriter<DNASequence, NucleotideCompound> fastaWriter = new FastaWriter<DNASequence, NucleotideCompound>( outputStream, dnaSequences, new GenericFastaHeaderFormat<DNASequence, NucleotideCompound>()); fastaWriter.process(); }
[ "public", "static", "void", "writeNucleotideSequence", "(", "OutputStream", "outputStream", ",", "Collection", "<", "DNASequence", ">", "dnaSequences", ")", "throws", "Exception", "{", "FastaWriter", "<", "DNASequence", ",", "NucleotideCompound", ">", "fastaWriter", "...
Write a collection of NucleotideSequences to a file @param outputStream @param dnaSequences @throws Exception
[ "Write", "a", "collection", "of", "NucleotideSequences", "to", "a", "file" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java#L134-L140
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/Metric.java
Metric.distanceWithDivisionSquared
public static double distanceWithDivisionSquared(double[] pointA, double dA) { double distance = 0.0; for (int i = 0; i < pointA.length; i++) { double d = pointA[i] / dA; distance += d * d; } return distance; }
java
public static double distanceWithDivisionSquared(double[] pointA, double dA) { double distance = 0.0; for (int i = 0; i < pointA.length; i++) { double d = pointA[i] / dA; distance += d * d; } return distance; }
[ "public", "static", "double", "distanceWithDivisionSquared", "(", "double", "[", "]", "pointA", ",", "double", "dA", ")", "{", "double", "distance", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pointA", ".", "length", ";", "i", ...
Calculates the squared Euclidean length of a point divided by a scalar. @param pointA point @param dA scalar @return the squared Euclidean length
[ "Calculates", "the", "squared", "Euclidean", "length", "of", "a", "point", "divided", "by", "a", "scalar", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/Metric.java#L134-L141
igniterealtime/jbosh
src/main/java/org/igniterealtime/jbosh/BOSHClientConnEvent.java
BOSHClientConnEvent.createConnectionClosedOnErrorEvent
static BOSHClientConnEvent createConnectionClosedOnErrorEvent( final BOSHClient source, final List<ComposableBody> outstanding, final Throwable cause) { return new BOSHClientConnEvent(source, false, outstanding, cause); }
java
static BOSHClientConnEvent createConnectionClosedOnErrorEvent( final BOSHClient source, final List<ComposableBody> outstanding, final Throwable cause) { return new BOSHClientConnEvent(source, false, outstanding, cause); }
[ "static", "BOSHClientConnEvent", "createConnectionClosedOnErrorEvent", "(", "final", "BOSHClient", "source", ",", "final", "List", "<", "ComposableBody", ">", "outstanding", ",", "final", "Throwable", "cause", ")", "{", "return", "new", "BOSHClientConnEvent", "(", "so...
Creates a connection closed on error event. This represents an unexpected termination of the client session. @param source client which has been disconnected @param outstanding list of requests which may not have been received by the remote connection manager @param cause cause of termination @return event instance
[ "Creates", "a", "connection", "closed", "on", "error", "event", ".", "This", "represents", "an", "unexpected", "termination", "of", "the", "client", "session", "." ]
train
https://github.com/igniterealtime/jbosh/blob/b43378f27e19b753b552b1e9666abc0476cdceff/src/main/java/org/igniterealtime/jbosh/BOSHClientConnEvent.java#L127-L132
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.deleteIntent
public OperationStatus deleteIntent(UUID appId, String versionId, UUID intentId, DeleteIntentOptionalParameter deleteIntentOptionalParameter) { return deleteIntentWithServiceResponseAsync(appId, versionId, intentId, deleteIntentOptionalParameter).toBlocking().single().body(); }
java
public OperationStatus deleteIntent(UUID appId, String versionId, UUID intentId, DeleteIntentOptionalParameter deleteIntentOptionalParameter) { return deleteIntentWithServiceResponseAsync(appId, versionId, intentId, deleteIntentOptionalParameter).toBlocking().single().body(); }
[ "public", "OperationStatus", "deleteIntent", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "intentId", ",", "DeleteIntentOptionalParameter", "deleteIntentOptionalParameter", ")", "{", "return", "deleteIntentWithServiceResponseAsync", "(", "appId", ",", "v...
Deletes an intent classifier from the application. @param appId The application ID. @param versionId The version ID. @param intentId The intent classifier ID. @param deleteIntentOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatus object if successful.
[ "Deletes", "an", "intent", "classifier", "from", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L3100-L3102
openbase/jul
extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java
LabelProcessor.addLabel
public static Label.Builder addLabel(final Label.Builder labelBuilder, final String languageCode, final String label) { for (int i = 0; i < labelBuilder.getEntryCount(); i++) { // found labels for the entry key if (labelBuilder.getEntry(i).getKey().equals(languageCode)) { // check if the new value is not already contained for (String value : labelBuilder.getEntryBuilder(i).getValueList()) { if (value.equalsIgnoreCase(label)) { // return because label is already in there return labelBuilder; } } // add new label labelBuilder.getEntryBuilder(i).addValue(label); return labelBuilder; } } // language code not present yet labelBuilder.addEntryBuilder().setKey(languageCode).addValue(label); return labelBuilder; }
java
public static Label.Builder addLabel(final Label.Builder labelBuilder, final String languageCode, final String label) { for (int i = 0; i < labelBuilder.getEntryCount(); i++) { // found labels for the entry key if (labelBuilder.getEntry(i).getKey().equals(languageCode)) { // check if the new value is not already contained for (String value : labelBuilder.getEntryBuilder(i).getValueList()) { if (value.equalsIgnoreCase(label)) { // return because label is already in there return labelBuilder; } } // add new label labelBuilder.getEntryBuilder(i).addValue(label); return labelBuilder; } } // language code not present yet labelBuilder.addEntryBuilder().setKey(languageCode).addValue(label); return labelBuilder; }
[ "public", "static", "Label", ".", "Builder", "addLabel", "(", "final", "Label", ".", "Builder", "labelBuilder", ",", "final", "String", "languageCode", ",", "final", "String", "label", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "labelBuil...
Add a label to a labelBuilder by languageCode. If the label is already contained for the language code nothing will be done. If the languageCode already exists and the label is not contained it will be added to the end of the label list by this language code. If no entry for the languageCode exists a new entry will be added and the label added as its first value. @param labelBuilder the label builder to be updated @param languageCode the languageCode for which the label is added @param label the label to be added @return the updated label builder
[ "Add", "a", "label", "to", "a", "labelBuilder", "by", "languageCode", ".", "If", "the", "label", "is", "already", "contained", "for", "the", "language", "code", "nothing", "will", "be", "done", ".", "If", "the", "languageCode", "already", "exists", "and", ...
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java#L162-L183
pedrovgs/Renderers
renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java
RVRendererAdapter.onCreateViewHolder
@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { rendererBuilder.withParent(viewGroup); rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext())); rendererBuilder.withViewType(viewType); RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder(); if (viewHolder == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null viewHolder"); } return viewHolder; }
java
@Override public RendererViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { rendererBuilder.withParent(viewGroup); rendererBuilder.withLayoutInflater(LayoutInflater.from(viewGroup.getContext())); rendererBuilder.withViewType(viewType); RendererViewHolder viewHolder = rendererBuilder.buildRendererViewHolder(); if (viewHolder == null) { throw new NullRendererBuiltException("RendererBuilder have to return a not null viewHolder"); } return viewHolder; }
[ "@", "Override", "public", "RendererViewHolder", "onCreateViewHolder", "(", "ViewGroup", "viewGroup", ",", "int", "viewType", ")", "{", "rendererBuilder", ".", "withParent", "(", "viewGroup", ")", ";", "rendererBuilder", ".", "withLayoutInflater", "(", "LayoutInflater...
One of the two main methods in this class. Creates a RendererViewHolder instance with a Renderer inside ready to be used. The RendererBuilder to create a RendererViewHolder using the information given as parameter. @param viewGroup used to create the ViewHolder. @param viewType associated to the renderer. @return ViewHolder extension with the Renderer it has to use inside.
[ "One", "of", "the", "two", "main", "methods", "in", "this", "class", ".", "Creates", "a", "RendererViewHolder", "instance", "with", "a", "Renderer", "inside", "ready", "to", "be", "used", ".", "The", "RendererBuilder", "to", "create", "a", "RendererViewHolder"...
train
https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/RVRendererAdapter.java#L95-L104
srikalyc/Sql4D
Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/sql/MysqlAccessor.java
MysqlAccessor.execute
public boolean execute(Map<String, String> params, String query) { final AtomicBoolean result = new AtomicBoolean(false); Tuple2<DataSource, Connection> conn = null; try { conn = getConnection(); NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1()); jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() { @Override public Void doInPreparedStatement(PreparedStatement ps) { try { result.set(ps.execute()); } catch(SQLException e) { result.set(false); } return null; } }); } catch (Exception ex) { Logger.getLogger(MysqlAccessor.class.getName()).log(Level.SEVERE, null, ex); result.set(false); } finally { returnConnection(conn); } return result.get(); }
java
public boolean execute(Map<String, String> params, String query) { final AtomicBoolean result = new AtomicBoolean(false); Tuple2<DataSource, Connection> conn = null; try { conn = getConnection(); NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1()); jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() { @Override public Void doInPreparedStatement(PreparedStatement ps) { try { result.set(ps.execute()); } catch(SQLException e) { result.set(false); } return null; } }); } catch (Exception ex) { Logger.getLogger(MysqlAccessor.class.getName()).log(Level.SEVERE, null, ex); result.set(false); } finally { returnConnection(conn); } return result.get(); }
[ "public", "boolean", "execute", "(", "Map", "<", "String", ",", "String", ">", "params", ",", "String", "query", ")", "{", "final", "AtomicBoolean", "result", "=", "new", "AtomicBoolean", "(", "false", ")", ";", "Tuple2", "<", "DataSource", ",", "Connectio...
Suitable for CRUD operations where no result set is expected. @param params @param query @return
[ "Suitable", "for", "CRUD", "operations", "where", "no", "result", "set", "is", "expected", "." ]
train
https://github.com/srikalyc/Sql4D/blob/2c052fe60ead5a16277c798a3440de7d4f6f24f6/Sql4Ddriver/src/main/java/com/yahoo/sql4d/sql4ddriver/sql/MysqlAccessor.java#L164-L188
alipay/sofa-rpc
core/common/src/main/java/com/alipay/sofa/rpc/common/utils/ExceptionUtils.java
ExceptionUtils.toShortString
public static String toShortString(Throwable e, int stackLevel) { StackTraceElement[] traces = e.getStackTrace(); StringBuilder sb = new StringBuilder(1024); sb.append(e.toString()).append("\t"); if (traces != null) { for (int i = 0; i < traces.length; i++) { if (i < stackLevel) { sb.append("\tat ").append(traces[i]).append("\t"); } else { break; } } } return sb.toString(); }
java
public static String toShortString(Throwable e, int stackLevel) { StackTraceElement[] traces = e.getStackTrace(); StringBuilder sb = new StringBuilder(1024); sb.append(e.toString()).append("\t"); if (traces != null) { for (int i = 0; i < traces.length; i++) { if (i < stackLevel) { sb.append("\tat ").append(traces[i]).append("\t"); } else { break; } } } return sb.toString(); }
[ "public", "static", "String", "toShortString", "(", "Throwable", "e", ",", "int", "stackLevel", ")", "{", "StackTraceElement", "[", "]", "traces", "=", "e", ".", "getStackTrace", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "1024",...
返回消息+简短堆栈信息(e.printStackTrace()的内容) @param e Throwable @param stackLevel 堆栈层级 @return 异常堆栈信息
[ "返回消息", "+", "简短堆栈信息(e", ".", "printStackTrace", "()", "的内容)" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/utils/ExceptionUtils.java#L74-L88
pmlopes/yoke
framework/src/main/java/com/jetdrone/vertx/yoke/MimeType.java
MimeType.getCharset
public static String getCharset(@NotNull String mime, String fallback) { // TODO: exceptions json and which other should also be marked as text if (mime.startsWith("text")) { return defaultContentEncoding; } return fallback; }
java
public static String getCharset(@NotNull String mime, String fallback) { // TODO: exceptions json and which other should also be marked as text if (mime.startsWith("text")) { return defaultContentEncoding; } return fallback; }
[ "public", "static", "String", "getCharset", "(", "@", "NotNull", "String", "mime", ",", "String", "fallback", ")", "{", "// TODO: exceptions json and which other should also be marked as text", "if", "(", "mime", ".", "startsWith", "(", "\"text\"", ")", ")", "{", "r...
Gets the default charset for a file. for now all mime types that start with text returns UTF-8 otherwise the fallback. @param mime the mime type to query @param fallback if not found returns fallback @return charset string
[ "Gets", "the", "default", "charset", "for", "a", "file", ".", "for", "now", "all", "mime", "types", "that", "start", "with", "text", "returns", "UTF", "-", "8", "otherwise", "the", "fallback", "." ]
train
https://github.com/pmlopes/yoke/blob/fe8a64036f09fb745f0644faddd46162d64faf3c/framework/src/main/java/com/jetdrone/vertx/yoke/MimeType.java#L109-L116
strator-dev/greenpepper
greenpepper/core/src/main/java/com/greenpepper/systemunderdevelopment/DefaultSystemUnderDevelopment.java
DefaultSystemUnderDevelopment.loadType
protected Type<?> loadType( String name ) { Type<?> type = typeLoader.loadType( name ); if (type == null) throw new TypeNotFoundException( name , this.getClass()); return type; }
java
protected Type<?> loadType( String name ) { Type<?> type = typeLoader.loadType( name ); if (type == null) throw new TypeNotFoundException( name , this.getClass()); return type; }
[ "protected", "Type", "<", "?", ">", "loadType", "(", "String", "name", ")", "{", "Type", "<", "?", ">", "type", "=", "typeLoader", ".", "loadType", "(", "name", ")", ";", "if", "(", "type", "==", "null", ")", "throw", "new", "TypeNotFoundException", ...
<p>loadType.</p> @param name a {@link java.lang.String} object. @return a {@link com.greenpepper.reflect.Type} object.
[ "<p", ">", "loadType", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/systemunderdevelopment/DefaultSystemUnderDevelopment.java#L90-L95
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java
ElementMatchers.nameEndsWithIgnoreCase
public static <T extends NamedElement> ElementMatcher.Junction<T> nameEndsWithIgnoreCase(String suffix) { return new NameMatcher<T>(new StringMatcher(suffix, StringMatcher.Mode.ENDS_WITH_IGNORE_CASE)); }
java
public static <T extends NamedElement> ElementMatcher.Junction<T> nameEndsWithIgnoreCase(String suffix) { return new NameMatcher<T>(new StringMatcher(suffix, StringMatcher.Mode.ENDS_WITH_IGNORE_CASE)); }
[ "public", "static", "<", "T", "extends", "NamedElement", ">", "ElementMatcher", ".", "Junction", "<", "T", ">", "nameEndsWithIgnoreCase", "(", "String", "suffix", ")", "{", "return", "new", "NameMatcher", "<", "T", ">", "(", "new", "StringMatcher", "(", "suf...
Matches a {@link NamedElement} for its name's suffix. The name's capitalization is ignored. @param suffix The expected name's suffix. @param <T> The type of the matched object. @return An element matcher for a named element's name's suffix.
[ "Matches", "a", "{", "@link", "NamedElement", "}", "for", "its", "name", "s", "suffix", ".", "The", "name", "s", "capitalization", "is", "ignored", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java#L712-L714
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/event/SetUserIDHandler.java
SetUserIDHandler.doRecordChange
public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Write/Update a record int iErrorCode = DBConstants.NORMAL_RETURN; switch (iChangeType) { case DBConstants.REFRESH_TYPE: case DBConstants.UPDATE_TYPE: if (m_bFirstTimeOnly) break; case DBConstants.ADD_TYPE: iErrorCode = this.setUserID(iChangeType, bDisplayOption); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; break; case DBConstants.FIELD_CHANGED_TYPE: if ((this.getOwner().getEditMode() == DBConstants.EDIT_ADD) && (this.getOwner().getField(userIdFieldName).getValue() == -1)) { // Special case - Init Record did not have record owner, but I probably do now. iErrorCode = this.setUserID(iChangeType, bDisplayOption); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; } } return super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record }
java
public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Write/Update a record int iErrorCode = DBConstants.NORMAL_RETURN; switch (iChangeType) { case DBConstants.REFRESH_TYPE: case DBConstants.UPDATE_TYPE: if (m_bFirstTimeOnly) break; case DBConstants.ADD_TYPE: iErrorCode = this.setUserID(iChangeType, bDisplayOption); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; break; case DBConstants.FIELD_CHANGED_TYPE: if ((this.getOwner().getEditMode() == DBConstants.EDIT_ADD) && (this.getOwner().getField(userIdFieldName).getValue() == -1)) { // Special case - Init Record did not have record owner, but I probably do now. iErrorCode = this.setUserID(iChangeType, bDisplayOption); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; } } return super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record }
[ "public", "int", "doRecordChange", "(", "FieldInfo", "field", ",", "int", "iChangeType", ",", "boolean", "bDisplayOption", ")", "{", "// Write/Update a record", "int", "iErrorCode", "=", "DBConstants", ".", "NORMAL_RETURN", ";", "switch", "(", "iChangeType", ")", ...
Called when a change is the record status is about to happen/has happened. @param field If this file change is due to a field, this is the field. @param iChangeType The type of change that occurred. @param bDisplayOption If true, display any changes. @return an error code.
[ "Called", "when", "a", "change", "is", "the", "record", "status", "is", "about", "to", "happen", "/", "has", "happened", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/event/SetUserIDHandler.java#L88-L112
VoltDB/voltdb
third_party/java/src/com/google_voltpatches/common/collect/Maps.java
Maps.safeContainsKey
static boolean safeContainsKey(Map<?, ?> map, Object key) { checkNotNull(map); try { return map.containsKey(key); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } }
java
static boolean safeContainsKey(Map<?, ?> map, Object key) { checkNotNull(map); try { return map.containsKey(key); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } }
[ "static", "boolean", "safeContainsKey", "(", "Map", "<", "?", ",", "?", ">", "map", ",", "Object", "key", ")", "{", "checkNotNull", "(", "map", ")", ";", "try", "{", "return", "map", ".", "containsKey", "(", "key", ")", ";", "}", "catch", "(", "Cla...
Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and {@code NullPointerException}.
[ "Delegates", "to", "{" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/collect/Maps.java#L3506-L3515
GwtMaterialDesign/gwt-material-themes
src/main/java/gwt/material/design/themes/client/ThemeLoader.java
ThemeLoader.loadAsync
public static void loadAsync(final ThemeBundle bundle, final ThemeAsyncCallback callback) { GWT.runAsync(new RunAsyncCallback() { @Override public void onSuccess() { if(bundle != null) { if(elements == null) { elements = new ArrayList<>(); } else { unload(); } // More resources might be loaded in the future. elements.add(StyleInjector.injectStylesheet(bundle.style().getText())); elements.add(StyleInjector.injectStylesheet(bundle.overrides().getText())); } if(callback != null) { callback.onSuccess(elements.size()); } } @Override public void onFailure(Throwable reason) { if(callback != null) { callback.onFailure(reason); } } }); }
java
public static void loadAsync(final ThemeBundle bundle, final ThemeAsyncCallback callback) { GWT.runAsync(new RunAsyncCallback() { @Override public void onSuccess() { if(bundle != null) { if(elements == null) { elements = new ArrayList<>(); } else { unload(); } // More resources might be loaded in the future. elements.add(StyleInjector.injectStylesheet(bundle.style().getText())); elements.add(StyleInjector.injectStylesheet(bundle.overrides().getText())); } if(callback != null) { callback.onSuccess(elements.size()); } } @Override public void onFailure(Throwable reason) { if(callback != null) { callback.onFailure(reason); } } }); }
[ "public", "static", "void", "loadAsync", "(", "final", "ThemeBundle", "bundle", ",", "final", "ThemeAsyncCallback", "callback", ")", "{", "GWT", ".", "runAsync", "(", "new", "RunAsyncCallback", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "("...
Load a provided {@link ThemeBundle} asynchronously. @param bundle The required theme bundle. @param callback The async callback.
[ "Load", "a", "provided", "{", "@link", "ThemeBundle", "}", "asynchronously", "." ]
train
https://github.com/GwtMaterialDesign/gwt-material-themes/blob/318beb635e69b24bf3840b20f8611cf061576592/src/main/java/gwt/material/design/themes/client/ThemeLoader.java#L65-L92
rhuss/jolokia
agent/core/src/main/java/org/jolokia/config/Configuration.java
Configuration.getProcessingParameters
public ProcessingParameters getProcessingParameters(Map<String,String> pParams) { Map<ConfigKey,String> procParams = ProcessingParameters.convertToConfigMap(pParams); for (Map.Entry<ConfigKey,String> entry : globalConfig.entrySet()) { ConfigKey key = entry.getKey(); if (key.isRequestConfig() && !procParams.containsKey(key)) { procParams.put(key,entry.getValue()); } } return new ProcessingParameters(procParams,pParams.get(PATH_QUERY_PARAM)); }
java
public ProcessingParameters getProcessingParameters(Map<String,String> pParams) { Map<ConfigKey,String> procParams = ProcessingParameters.convertToConfigMap(pParams); for (Map.Entry<ConfigKey,String> entry : globalConfig.entrySet()) { ConfigKey key = entry.getKey(); if (key.isRequestConfig() && !procParams.containsKey(key)) { procParams.put(key,entry.getValue()); } } return new ProcessingParameters(procParams,pParams.get(PATH_QUERY_PARAM)); }
[ "public", "ProcessingParameters", "getProcessingParameters", "(", "Map", "<", "String", ",", "String", ">", "pParams", ")", "{", "Map", "<", "ConfigKey", ",", "String", ">", "procParams", "=", "ProcessingParameters", ".", "convertToConfigMap", "(", "pParams", ")",...
Get processing parameters from a string-string map @param pParams params to extra. A parameter "p" is used as extra path info @return the processing parameters
[ "Get", "processing", "parameters", "from", "a", "string", "-", "string", "map" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/config/Configuration.java#L119-L128
Netflix/servo
servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java
Monitors.isObjectRegistered
public static boolean isObjectRegistered(String id, Object obj) { return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj)); }
java
public static boolean isObjectRegistered(String id, Object obj) { return DefaultMonitorRegistry.getInstance().isRegistered(newObjectMonitor(id, obj)); }
[ "public", "static", "boolean", "isObjectRegistered", "(", "String", "id", ",", "Object", "obj", ")", "{", "return", "DefaultMonitorRegistry", ".", "getInstance", "(", ")", ".", "isRegistered", "(", "newObjectMonitor", "(", "id", ",", "obj", ")", ")", ";", "}...
Check whether an object is currently registered with the default registry.
[ "Check", "whether", "an", "object", "is", "currently", "registered", "with", "the", "default", "registry", "." ]
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L229-L231
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java
WebSocketServerHandshakerFactory.newHandshaker
public WebSocketServerHandshaker newHandshaker(HttpRequest req) { CharSequence version = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION); if (version != null) { if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) { // Version 13 of the wire protocol - RFC 6455 (version 17 of the draft hybi specification). return new WebSocketServerHandshaker13( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V08.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 10 of the draft hybi specification. return new WebSocketServerHandshaker08( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 07 of the draft hybi specification. return new WebSocketServerHandshaker07( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else { return null; } } else { // Assume version 00 where version header was not specified return new WebSocketServerHandshaker00(webSocketURL, subprotocols, maxFramePayloadLength); } }
java
public WebSocketServerHandshaker newHandshaker(HttpRequest req) { CharSequence version = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION); if (version != null) { if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) { // Version 13 of the wire protocol - RFC 6455 (version 17 of the draft hybi specification). return new WebSocketServerHandshaker13( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V08.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 10 of the draft hybi specification. return new WebSocketServerHandshaker08( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 07 of the draft hybi specification. return new WebSocketServerHandshaker07( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else { return null; } } else { // Assume version 00 where version header was not specified return new WebSocketServerHandshaker00(webSocketURL, subprotocols, maxFramePayloadLength); } }
[ "public", "WebSocketServerHandshaker", "newHandshaker", "(", "HttpRequest", "req", ")", "{", "CharSequence", "version", "=", "req", ".", "headers", "(", ")", ".", "get", "(", "HttpHeaderNames", ".", "SEC_WEBSOCKET_VERSION", ")", ";", "if", "(", "version", "!=", ...
Instances a new handshaker @return A new WebSocketServerHandshaker for the requested web socket version. Null if web socket version is not supported.
[ "Instances", "a", "new", "handshaker" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshakerFactory.java#L114-L137
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ResourceCopy.java
ResourceCopy.copyTemplates
public static void copyTemplates(AbstractWisdomMojo mojo, MavenResourcesFiltering filtering) throws IOException { File in = new File(mojo.basedir, Constants.TEMPLATES_SRC_DIR); if (!in.exists()) { return; } File out = new File(mojo.getWisdomRootDirectory(), Constants.TEMPLATES_DIR); filterAndCopy(mojo, filtering, in, out); }
java
public static void copyTemplates(AbstractWisdomMojo mojo, MavenResourcesFiltering filtering) throws IOException { File in = new File(mojo.basedir, Constants.TEMPLATES_SRC_DIR); if (!in.exists()) { return; } File out = new File(mojo.getWisdomRootDirectory(), Constants.TEMPLATES_DIR); filterAndCopy(mojo, filtering, in, out); }
[ "public", "static", "void", "copyTemplates", "(", "AbstractWisdomMojo", "mojo", ",", "MavenResourcesFiltering", "filtering", ")", "throws", "IOException", "{", "File", "in", "=", "new", "File", "(", "mojo", ".", "basedir", ",", "Constants", ".", "TEMPLATES_SRC_DIR...
Copies the external templates from "src/main/templates" to "wisdom/templates". Copied resources are filtered. @param mojo the mojo @param filtering the component required to filter resources @throws IOException if a file cannot be copied
[ "Copies", "the", "external", "templates", "from", "src", "/", "main", "/", "templates", "to", "wisdom", "/", "templates", ".", "Copied", "resources", "are", "filtered", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/ResourceCopy.java#L230-L238
SourcePond/fileobserver
fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/DirectoryFactory.java
DirectoryFactory.newKey
DispatchKey newKey(final Object pDirectoryKey, final Path pRelativePath) { return fileKeyFactory.newKey(pDirectoryKey, pRelativePath); }
java
DispatchKey newKey(final Object pDirectoryKey, final Path pRelativePath) { return fileKeyFactory.newKey(pDirectoryKey, pRelativePath); }
[ "DispatchKey", "newKey", "(", "final", "Object", "pDirectoryKey", ",", "final", "Path", "pRelativePath", ")", "{", "return", "fileKeyFactory", ".", "newKey", "(", "pDirectoryKey", ",", "pRelativePath", ")", ";", "}" ]
<p><em>INTERNAL API, only ot be used in class hierarchy</em></p> <p> Creates a new {@link DispatchKey} based on the directory-key and relative path specified, see {@link Directory#addWatchedDirectory(WatchedDirectory)} for further information. @param pDirectoryKey Directory-key, must not be {@code null} @param pRelativePath Relative path, must not be {@code null} @return New file-key, never {@code null}
[ "<p", ">", "<em", ">", "INTERNAL", "API", "only", "ot", "be", "used", "in", "class", "hierarchy<", "/", "em", ">", "<", "/", "p", ">", "<p", ">", "Creates", "a", "new", "{", "@link", "DispatchKey", "}", "based", "on", "the", "directory", "-", "key"...
train
https://github.com/SourcePond/fileobserver/blob/dfb3055ed35759a47f52f6cfdea49879c415fd6b/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/DirectoryFactory.java#L89-L91
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java
AppServicePlansInner.listRoutesForVnet
public List<VnetRouteInner> listRoutesForVnet(String resourceGroupName, String name, String vnetName) { return listRoutesForVnetWithServiceResponseAsync(resourceGroupName, name, vnetName).toBlocking().single().body(); }
java
public List<VnetRouteInner> listRoutesForVnet(String resourceGroupName, String name, String vnetName) { return listRoutesForVnetWithServiceResponseAsync(resourceGroupName, name, vnetName).toBlocking().single().body(); }
[ "public", "List", "<", "VnetRouteInner", ">", "listRoutesForVnet", "(", "String", "resourceGroupName", ",", "String", "name", ",", "String", "vnetName", ")", "{", "return", "listRoutesForVnetWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "vnetN...
Get all routes that are associated with a Virtual Network in an App Service plan. Get all routes that are associated with a Virtual Network in an App Service plan. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service plan. @param vnetName Name of the Virtual Network. @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 List&lt;VnetRouteInner&gt; object if successful.
[ "Get", "all", "routes", "that", "are", "associated", "with", "a", "Virtual", "Network", "in", "an", "App", "Service", "plan", ".", "Get", "all", "routes", "that", "are", "associated", "with", "a", "Virtual", "Network", "in", "an", "App", "Service", "plan",...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L3389-L3391
pac4j/pac4j
pac4j-core/src/main/java/org/pac4j/core/profile/BasicUserProfile.java
BasicUserProfile.addAuthenticationAttributes
public void addAuthenticationAttributes(Map<String, Object> attributeMap) { if (attributeMap != null) { for (final Map.Entry<String, Object> entry : attributeMap.entrySet()) { addAuthenticationAttribute(entry.getKey(), entry.getValue()); } } }
java
public void addAuthenticationAttributes(Map<String, Object> attributeMap) { if (attributeMap != null) { for (final Map.Entry<String, Object> entry : attributeMap.entrySet()) { addAuthenticationAttribute(entry.getKey(), entry.getValue()); } } }
[ "public", "void", "addAuthenticationAttributes", "(", "Map", "<", "String", ",", "Object", ">", "attributeMap", ")", "{", "if", "(", "attributeMap", "!=", "null", ")", "{", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "ent...
Add authentication attributes. @param attributeMap the authentication attributes
[ "Add", "authentication", "attributes", "." ]
train
https://github.com/pac4j/pac4j/blob/d9cd029f8783792b31dd48bf1e32f80628f2c4a3/pac4j-core/src/main/java/org/pac4j/core/profile/BasicUserProfile.java#L188-L194
Impetus/Kundera
src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBObjectMapper.java
CouchDBObjectMapper.getJsonObject
private static JsonObject getJsonObject(Set<Attribute> columns, Object object) { JsonObject jsonObject = new JsonObject(); for (Attribute column : columns) { if (!column.isAssociation()) { Object valueObject = PropertyAccessorHelper.getObject(object, (Field) column.getJavaMember()); jsonObject.add(((AbstractAttribute) column).getJPAColumnName(), getJsonPrimitive(valueObject, column.getJavaType())); } } return jsonObject; }
java
private static JsonObject getJsonObject(Set<Attribute> columns, Object object) { JsonObject jsonObject = new JsonObject(); for (Attribute column : columns) { if (!column.isAssociation()) { Object valueObject = PropertyAccessorHelper.getObject(object, (Field) column.getJavaMember()); jsonObject.add(((AbstractAttribute) column).getJPAColumnName(), getJsonPrimitive(valueObject, column.getJavaType())); } } return jsonObject; }
[ "private", "static", "JsonObject", "getJsonObject", "(", "Set", "<", "Attribute", ">", "columns", ",", "Object", "object", ")", "{", "JsonObject", "jsonObject", "=", "new", "JsonObject", "(", ")", ";", "for", "(", "Attribute", "column", ":", "columns", ")", ...
Gets the json object. @param columns the columns @param object the object @return the json object
[ "Gets", "the", "json", "object", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBObjectMapper.java#L190-L203
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.deleteHistoricalVersions
public void deleteHistoricalVersions(int versionsToKeep, int versionsDeleted, long timeDeleted, I_CmsReport report) throws CmsException { m_securityManager.deleteHistoricalVersions(m_context, versionsToKeep, versionsDeleted, timeDeleted, report); }
java
public void deleteHistoricalVersions(int versionsToKeep, int versionsDeleted, long timeDeleted, I_CmsReport report) throws CmsException { m_securityManager.deleteHistoricalVersions(m_context, versionsToKeep, versionsDeleted, timeDeleted, report); }
[ "public", "void", "deleteHistoricalVersions", "(", "int", "versionsToKeep", ",", "int", "versionsDeleted", ",", "long", "timeDeleted", ",", "I_CmsReport", "report", ")", "throws", "CmsException", "{", "m_securityManager", ".", "deleteHistoricalVersions", "(", "m_context...
Deletes the versions from the history tables, keeping the given number of versions per resource.<p> @param versionsToKeep number of versions to keep, is ignored if negative @param versionsDeleted number of versions to keep for deleted resources, is ignored if negative @param timeDeleted deleted resources older than this will also be deleted, is ignored if negative @param report the report for output logging @throws CmsException if operation was not successful
[ "Deletes", "the", "versions", "from", "the", "history", "tables", "keeping", "the", "given", "number", "of", "versions", "per", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L952-L956
Tourenathan-G5organisation/SiliCompressor
silicompressor/src/main/java/com/iceteck/silicompressorr/SiliCompressor.java
SiliCompressor.getFilename
private String getFilename(String filename, File file) { if (!file.exists()) { file.mkdirs(); } String ext = ".jpg"; //get extension /*if (Pattern.matches("^[.][p][n][g]", filename)){ ext = ".png"; }*/ return (file.getAbsolutePath() + "/IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ext); }
java
private String getFilename(String filename, File file) { if (!file.exists()) { file.mkdirs(); } String ext = ".jpg"; //get extension /*if (Pattern.matches("^[.][p][n][g]", filename)){ ext = ".png"; }*/ return (file.getAbsolutePath() + "/IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ext); }
[ "private", "String", "getFilename", "(", "String", "filename", ",", "File", "file", ")", "{", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "file", ".", "mkdirs", "(", ")", ";", "}", "String", "ext", "=", "\".jpg\"", ";", "//get extensio...
Get the file path of the compressed file @param filename @param file Destination directory @return
[ "Get", "the", "file", "path", "of", "the", "compressed", "file" ]
train
https://github.com/Tourenathan-G5organisation/SiliCompressor/blob/546f6cd7b2a7a783e1122df46c1e237f8938fe72/silicompressor/src/main/java/com/iceteck/silicompressorr/SiliCompressor.java#L371-L383
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/LocationInventoryUrl.java
LocationInventoryUrl.deleteLocationInventoryUrl
public static MozuUrl deleteLocationInventoryUrl(String locationCode, String productCode) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/locationinventory/{locationCode}/{productCode}"); formatter.formatUrl("locationCode", locationCode); formatter.formatUrl("productCode", productCode); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deleteLocationInventoryUrl(String locationCode, String productCode) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/locationinventory/{locationCode}/{productCode}"); formatter.formatUrl("locationCode", locationCode); formatter.formatUrl("productCode", productCode); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "deleteLocationInventoryUrl", "(", "String", "locationCode", ",", "String", "productCode", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/catalog/admin/locationinventory/{locationCode}/{productCode}\"", ")...
Get Resource Url for DeleteLocationInventory @param locationCode The unique, user-defined code that identifies a location. @param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product. @return String Resource Url
[ "Get", "Resource", "Url", "for", "DeleteLocationInventory" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/LocationInventoryUrl.java#L88-L94
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/AbstractWFieldIndicatorRenderer.java
AbstractWFieldIndicatorRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { AbstractWFieldIndicator fieldIndicator = (AbstractWFieldIndicator) component; XmlStringBuilder xml = renderContext.getWriter(); WComponent validationTarget = fieldIndicator.getTargetComponent(); // no need to render an indicator for nothing. // Diagnosables takes care of thieir own messaging. if (validationTarget == null || (validationTarget instanceof Diagnosable && !(validationTarget instanceof Input))) { return; } if (validationTarget instanceof Input && !((Input) validationTarget).isReadOnly()) { return; } List<Diagnostic> diags = fieldIndicator.getDiagnostics(); if (diags != null && !diags.isEmpty()) { xml.appendTagOpen("ui:fieldindicator"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); switch (fieldIndicator.getFieldIndicatorType()) { case INFO: xml.appendAttribute("type", "info"); break; case WARN: xml.appendAttribute("type", "warn"); break; case ERROR: xml.appendAttribute("type", "error"); break; default: throw new SystemException("Cannot paint field indicator due to an invalid field indicator type: " + fieldIndicator.getFieldIndicatorType()); } xml.appendAttribute("for", fieldIndicator.getRelatedFieldId()); xml.appendClose(); for (Diagnostic diag : diags) { xml.appendTag("ui:message"); xml.appendEscaped(diag.getDescription()); xml.appendEndTag("ui:message"); } xml.appendEndTag("ui:fieldindicator"); } }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { AbstractWFieldIndicator fieldIndicator = (AbstractWFieldIndicator) component; XmlStringBuilder xml = renderContext.getWriter(); WComponent validationTarget = fieldIndicator.getTargetComponent(); // no need to render an indicator for nothing. // Diagnosables takes care of thieir own messaging. if (validationTarget == null || (validationTarget instanceof Diagnosable && !(validationTarget instanceof Input))) { return; } if (validationTarget instanceof Input && !((Input) validationTarget).isReadOnly()) { return; } List<Diagnostic> diags = fieldIndicator.getDiagnostics(); if (diags != null && !diags.isEmpty()) { xml.appendTagOpen("ui:fieldindicator"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); switch (fieldIndicator.getFieldIndicatorType()) { case INFO: xml.appendAttribute("type", "info"); break; case WARN: xml.appendAttribute("type", "warn"); break; case ERROR: xml.appendAttribute("type", "error"); break; default: throw new SystemException("Cannot paint field indicator due to an invalid field indicator type: " + fieldIndicator.getFieldIndicatorType()); } xml.appendAttribute("for", fieldIndicator.getRelatedFieldId()); xml.appendClose(); for (Diagnostic diag : diags) { xml.appendTag("ui:message"); xml.appendEscaped(diag.getDescription()); xml.appendEndTag("ui:message"); } xml.appendEndTag("ui:fieldindicator"); } }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "AbstractWFieldIndicator", "fieldIndicator", "=", "(", "AbstractWFieldIndicator", ")", "component", ";", "XmlStringBui...
Paints the given AbstractWFieldIndicator. @param component the WFieldErrorIndicator to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "AbstractWFieldIndicator", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/AbstractWFieldIndicatorRenderer.java#L28-L81
jenkinsci/jenkins
core/src/main/java/hudson/model/queue/WorkUnitContext.java
WorkUnitContext.createWorkUnit
public WorkUnit createWorkUnit(SubTask execUnit) { WorkUnit wu = new WorkUnit(this, execUnit); workUnits.add(wu); return wu; }
java
public WorkUnit createWorkUnit(SubTask execUnit) { WorkUnit wu = new WorkUnit(this, execUnit); workUnits.add(wu); return wu; }
[ "public", "WorkUnit", "createWorkUnit", "(", "SubTask", "execUnit", ")", "{", "WorkUnit", "wu", "=", "new", "WorkUnit", "(", "this", ",", "execUnit", ")", ";", "workUnits", ".", "add", "(", "wu", ")", ";", "return", "wu", ";", "}" ]
Called within the queue maintenance process to create a {@link WorkUnit} for the given {@link SubTask}
[ "Called", "within", "the", "queue", "maintenance", "process", "to", "create", "a", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/queue/WorkUnitContext.java#L93-L97
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java
SftpClient.chmod
public void chmod(int permissions, String path) throws SftpStatusException, SshException { String actual = resolveRemotePath(path); sftp.changePermissions(actual, permissions); }
java
public void chmod(int permissions, String path) throws SftpStatusException, SshException { String actual = resolveRemotePath(path); sftp.changePermissions(actual, permissions); }
[ "public", "void", "chmod", "(", "int", "permissions", ",", "String", "path", ")", "throws", "SftpStatusException", ",", "SshException", "{", "String", "actual", "=", "resolveRemotePath", "(", "path", ")", ";", "sftp", ".", "changePermissions", "(", "actual", "...
<p> Changes the access permissions or modes of the specified file or directory. </p> <p> Modes determine who can read, change or execute a file. </p> <blockquote> <pre> Absolute modes are octal numbers specifying the complete list of attributes for the files; you specify attributes by OR'ing together these bits. 0400 Individual read 0200 Individual write 0100 Individual execute (or list directory) 0040 Group read 0020 Group write 0010 Group execute 0004 Other read 0002 Other write 0001 Other execute </pre> </blockquote> @param permissions the absolute mode of the file/directory @param path the path to the file/directory on the remote server @throws SftpStatusException @throws SshException
[ "<p", ">", "Changes", "the", "access", "permissions", "or", "modes", "of", "the", "specified", "file", "or", "directory", ".", "<", "/", "p", ">" ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L2071-L2075
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/reflect/TypeReflector.java
TypeReflector.createInstance
public static Object createInstance(String name, Object... args) throws Exception { return createInstance(name, (String) null, args); }
java
public static Object createInstance(String name, Object... args) throws Exception { return createInstance(name, (String) null, args); }
[ "public", "static", "Object", "createInstance", "(", "String", "name", ",", "Object", "...", "args", ")", "throws", "Exception", "{", "return", "createInstance", "(", "name", ",", "(", "String", ")", "null", ",", "args", ")", ";", "}" ]
Creates an instance of an object type specified by its name. @param name an object type name. @param args arguments for the object constructor. @return the created object instance. @throws Exception when type of instance not found @see #getType(String, String) @see #createInstanceByType(Class, Object...)
[ "Creates", "an", "instance", "of", "an", "object", "type", "specified", "by", "its", "name", "." ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/reflect/TypeReflector.java#L133-L135
infinispan/infinispan
core/src/main/java/org/infinispan/configuration/parsing/ParseUtils.java
ParseUtils.readStringAttributeElement
public static String readStringAttributeElement(final XMLStreamReader reader, final String attributeName) throws XMLStreamException { final String value = requireSingleAttribute(reader, attributeName); requireNoContent(reader); return value; }
java
public static String readStringAttributeElement(final XMLStreamReader reader, final String attributeName) throws XMLStreamException { final String value = requireSingleAttribute(reader, attributeName); requireNoContent(reader); return value; }
[ "public", "static", "String", "readStringAttributeElement", "(", "final", "XMLStreamReader", "reader", ",", "final", "String", "attributeName", ")", "throws", "XMLStreamException", "{", "final", "String", "value", "=", "requireSingleAttribute", "(", "reader", ",", "at...
Read an element which contains only a single string attribute. @param reader the reader @param attributeName the attribute name, usually "value" or "name" @return the string value @throws javax.xml.stream.XMLStreamException if an error occurs or if the element does not contain the specified attribute, contains other attributes, or contains child elements.
[ "Read", "an", "element", "which", "contains", "only", "a", "single", "string", "attribute", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/configuration/parsing/ParseUtils.java#L196-L201
peholmst/vaadin4spring
addons/i18n/src/main/java/org/vaadin/spring/i18n/I18N.java
I18N.getWithDefault
public String getWithDefault(String code, Locale locale, String defaultMessage, Object... arguments) { if (locale == null) { throw new IllegalArgumentException("Locale must not be null"); } try { return getMessage(code, locale, arguments); } catch (NoSuchMessageException ex) { return defaultMessage; } }
java
public String getWithDefault(String code, Locale locale, String defaultMessage, Object... arguments) { if (locale == null) { throw new IllegalArgumentException("Locale must not be null"); } try { return getMessage(code, locale, arguments); } catch (NoSuchMessageException ex) { return defaultMessage; } }
[ "public", "String", "getWithDefault", "(", "String", "code", ",", "Locale", "locale", ",", "String", "defaultMessage", ",", "Object", "...", "arguments", ")", "{", "if", "(", "locale", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", ...
Tries to resolve the specified message for the given locale. @param code the code to lookup up, such as 'calculator.noRateSet', never {@code null}. @param locale The Locale for which it is tried to look up the code. Must not be null @param defaultMessage string to return if the lookup fails, never {@code null}. @param arguments Array of arguments that will be filled in for params within the message (params look like "{0}", "{1,date}", "{2,time}"), or {@code null} if none. @return the resolved message, or the {@code defaultMessage} if the lookup fails.
[ "Tries", "to", "resolve", "the", "specified", "message", "for", "the", "given", "locale", "." ]
train
https://github.com/peholmst/vaadin4spring/blob/ea896012f15d6abea6e6391def9a0001113a1f7a/addons/i18n/src/main/java/org/vaadin/spring/i18n/I18N.java#L171-L180
lotaris/rox-client-java
rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java
Configuration.getUid
public String getUid(String category, String projectName, String projectVersion) { return getUid(category, projectName, projectVersion, false); }
java
public String getUid(String category, String projectName, String projectVersion) { return getUid(category, projectName, projectVersion, false); }
[ "public", "String", "getUid", "(", "String", "category", ",", "String", "projectName", ",", "String", "projectVersion", ")", "{", "return", "getUid", "(", "category", ",", "projectName", ",", "projectVersion", ",", "false", ")", ";", "}" ]
Shortcut method to {@link Configuration#getUid(java.lang.String, java.lang.String, java.lang.String, boolean) } @param category The category @param projectName The project name @param projectVersion The project version @return The UID generated
[ "Shortcut", "method", "to", "{", "@link", "Configuration#getUid", "(", "java", ".", "lang", ".", "String", "java", ".", "lang", ".", "String", "java", ".", "lang", ".", "String", "boolean", ")", "}" ]
train
https://github.com/lotaris/rox-client-java/blob/1b33f7560347c382c59a40c4037d175ab8127fde/rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java#L408-L410
brunocvcunha/inutils4j
src/main/java/org/brunocvcunha/inutils4j/thirdparty/DateUtils.java
DateUtils.isTimeInRange
@SuppressWarnings("deprecation") public static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) { d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds()); if (start == null || end == null) { return false; } if (start.before(end) && (!(d.after(start) && d.before(end)))) { return false; } if (end.before(start) && (!(d.after(end) || d.before(start)))) { return false; } return true; }
java
@SuppressWarnings("deprecation") public static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) { d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds()); if (start == null || end == null) { return false; } if (start.before(end) && (!(d.after(start) && d.before(end)))) { return false; } if (end.before(start) && (!(d.after(end) || d.before(start)))) { return false; } return true; }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "static", "boolean", "isTimeInRange", "(", "java", ".", "sql", ".", "Time", "start", ",", "java", ".", "sql", ".", "Time", "end", ",", "java", ".", "util", ".", "Date", "d", ")", "{", "d",...
Tells you if the date part of a datetime is in a certain time range.
[ "Tells", "you", "if", "the", "date", "part", "of", "a", "datetime", "is", "in", "a", "certain", "time", "range", "." ]
train
https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/thirdparty/DateUtils.java#L410-L426
ontop/ontop
mapping/sql/owlapi/src/main/java/it/unibz/inf/ontop/spec/mapping/bootstrap/impl/DirectMappingEngine.java
DirectMappingEngine.bootstrapMappings
private SQLPPMapping bootstrapMappings(SQLPPMapping ppMapping) throws SQLException, DuplicateMappingException { if (ppMapping == null) { throw new IllegalArgumentException("Model should not be null"); } try (Connection conn = LocalJDBCConnectionUtils.createConnection(settings)) { RDBMetadata metadata = RDBMetadataExtractionTools.createMetadata(conn, typeFactory, jdbcTypeMapper); // this operation is EXPENSIVE RDBMetadataExtractionTools.loadMetadata(metadata, conn, null); return bootstrapMappings(metadata, ppMapping); } }
java
private SQLPPMapping bootstrapMappings(SQLPPMapping ppMapping) throws SQLException, DuplicateMappingException { if (ppMapping == null) { throw new IllegalArgumentException("Model should not be null"); } try (Connection conn = LocalJDBCConnectionUtils.createConnection(settings)) { RDBMetadata metadata = RDBMetadataExtractionTools.createMetadata(conn, typeFactory, jdbcTypeMapper); // this operation is EXPENSIVE RDBMetadataExtractionTools.loadMetadata(metadata, conn, null); return bootstrapMappings(metadata, ppMapping); } }
[ "private", "SQLPPMapping", "bootstrapMappings", "(", "SQLPPMapping", "ppMapping", ")", "throws", "SQLException", ",", "DuplicateMappingException", "{", "if", "(", "ppMapping", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Model should not b...
* extract mappings from given datasource, and insert them into the pre-processed mapping Duplicate Exception may happen, since mapping id is generated randomly and same id may occur
[ "*", "extract", "mappings", "from", "given", "datasource", "and", "insert", "them", "into", "the", "pre", "-", "processed", "mapping" ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/mapping/sql/owlapi/src/main/java/it/unibz/inf/ontop/spec/mapping/bootstrap/impl/DirectMappingEngine.java#L238-L249
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java
CmsSitemapController.disableModelPage
public void disableModelPage(final CmsUUID id, final boolean disable) { CmsRpcAction<Void> action = new CmsRpcAction<Void>() { @Override public void execute() { start(200, true); getService().disableModelPage(getEntryPoint(), id, disable, this); } @Override protected void onResponse(Void result) { stop(false); CmsSitemapView.getInstance().updateModelPageDisabledState(id, disable); } }; action.execute(); }
java
public void disableModelPage(final CmsUUID id, final boolean disable) { CmsRpcAction<Void> action = new CmsRpcAction<Void>() { @Override public void execute() { start(200, true); getService().disableModelPage(getEntryPoint(), id, disable, this); } @Override protected void onResponse(Void result) { stop(false); CmsSitemapView.getInstance().updateModelPageDisabledState(id, disable); } }; action.execute(); }
[ "public", "void", "disableModelPage", "(", "final", "CmsUUID", "id", ",", "final", "boolean", "disable", ")", "{", "CmsRpcAction", "<", "Void", ">", "action", "=", "new", "CmsRpcAction", "<", "Void", ">", "(", ")", "{", "@", "Override", "public", "void", ...
Disables the given model page entry within the configuration.<p> @param id the entry id @param disable <code>true</code> to disable the entry
[ "Disables", "the", "given", "model", "page", "entry", "within", "the", "configuration", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java#L783-L804
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/Step.java
Step.switchFrame
protected void switchFrame(PageElement element, Object... args) throws FailureException, TechnicalException { try { Context.waitUntil(ExpectedConditions.frameToBeAvailableAndSwitchToIt(Utilities.getLocator(element, args))); } catch (final Exception e) { new Result.Failure<>(element, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_FRAME), element, element.getPage().getApplication()), true, element.getPage().getCallBack()); } }
java
protected void switchFrame(PageElement element, Object... args) throws FailureException, TechnicalException { try { Context.waitUntil(ExpectedConditions.frameToBeAvailableAndSwitchToIt(Utilities.getLocator(element, args))); } catch (final Exception e) { new Result.Failure<>(element, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_FRAME), element, element.getPage().getApplication()), true, element.getPage().getCallBack()); } }
[ "protected", "void", "switchFrame", "(", "PageElement", "element", ",", "Object", "...", "args", ")", "throws", "FailureException", ",", "TechnicalException", "{", "try", "{", "Context", ".", "waitUntil", "(", "ExpectedConditions", ".", "frameToBeAvailableAndSwitchToI...
Switches to the given frame. @param element The PageElement representing a frame. @param args list of arguments to format the found selector with @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_SWITCH_FRAME} message (with screenshot, with exception) @throws FailureException if the scenario encounters a functional error
[ "Switches", "to", "the", "given", "frame", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L769-L776
samskivert/pythagoras
src/main/java/pythagoras/i/Points.java
Points.manhattanDistance
public static int manhattanDistance (int x1, int y1, int x2, int y2) { return Math.abs(x2 - x1) + Math.abs(y2 - y1); }
java
public static int manhattanDistance (int x1, int y1, int x2, int y2) { return Math.abs(x2 - x1) + Math.abs(y2 - y1); }
[ "public", "static", "int", "manhattanDistance", "(", "int", "x1", ",", "int", "y1", ",", "int", "x2", ",", "int", "y2", ")", "{", "return", "Math", ".", "abs", "(", "x2", "-", "x1", ")", "+", "Math", ".", "abs", "(", "y2", "-", "y1", ")", ";", ...
Returns the Manhattan distance between the specified two points.
[ "Returns", "the", "Manhattan", "distance", "between", "the", "specified", "two", "points", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/i/Points.java#L32-L35
apache/groovy
src/main/java/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.java
InnerClassCompletionVisitor.addCompilationErrorOnCustomMethodNode
private void addCompilationErrorOnCustomMethodNode(InnerClassNode node, String methodName, Parameter[] parameters) { MethodNode existingMethodNode = node.getMethod(methodName, parameters); // if there is a user-defined methodNode, add compiler error msg and continue if (existingMethodNode != null && !isSynthetic(existingMethodNode)) { addError("\"" +methodName + "\" implementations are not supported on static inner classes as " + "a synthetic version of \"" + methodName + "\" is added during compilation for the purpose " + "of outer class delegation.", existingMethodNode); } }
java
private void addCompilationErrorOnCustomMethodNode(InnerClassNode node, String methodName, Parameter[] parameters) { MethodNode existingMethodNode = node.getMethod(methodName, parameters); // if there is a user-defined methodNode, add compiler error msg and continue if (existingMethodNode != null && !isSynthetic(existingMethodNode)) { addError("\"" +methodName + "\" implementations are not supported on static inner classes as " + "a synthetic version of \"" + methodName + "\" is added during compilation for the purpose " + "of outer class delegation.", existingMethodNode); } }
[ "private", "void", "addCompilationErrorOnCustomMethodNode", "(", "InnerClassNode", "node", ",", "String", "methodName", ",", "Parameter", "[", "]", "parameters", ")", "{", "MethodNode", "existingMethodNode", "=", "node", ".", "getMethod", "(", "methodName", ",", "pa...
Adds a compilation error if a {@link MethodNode} with the given <tt>methodName</tt> and <tt>parameters</tt> exists in the {@link InnerClassNode}.
[ "Adds", "a", "compilation", "error", "if", "a", "{" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/InnerClassCompletionVisitor.java#L349-L358
sangupta/jerry-web
src/main/java/com/sangupta/jerry/web/filters/JavascriptReorderingFilter.java
JavascriptReorderingFilter.doFilter
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // try and see if this request is for an HTML page HttpServletRequest request = (HttpServletRequest) servletRequest; String uri = request.getRequestURI(); final boolean htmlPage = isHtmlPage(uri); // if this is an HTML page, get the entire contents of the page // in a byte-stream if (!htmlPage) { LOGGER.debug("Not an HTML page for javascript reordering: {}", uri); filterChain.doFilter(servletRequest, servletResponse); return; } // run through a wrapper response object HttpServletResponseWrapperImpl wrapper = new HttpServletResponseWrapperImpl((HttpServletResponse) servletResponse); filterChain.doFilter(servletRequest, wrapper); // check if this is an HTML output if (!"text/html".equals(wrapper.getContentType())) { LOGGER.debug("Response content not HTML for javascript reordering: {}", uri); // just write the plain response // this is not HTML response wrapper.copyToResponse(servletResponse); return; } final long startTime = System.currentTimeMillis(); LOGGER.debug("Javascript reordering candidate found: {}", uri); writeReorderedHtml(wrapper, servletResponse); final long endTime = System.currentTimeMillis(); LOGGER.debug("Reordering javascript for url: {} took: {}ms", uri, (endTime - startTime)); }
java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // try and see if this request is for an HTML page HttpServletRequest request = (HttpServletRequest) servletRequest; String uri = request.getRequestURI(); final boolean htmlPage = isHtmlPage(uri); // if this is an HTML page, get the entire contents of the page // in a byte-stream if (!htmlPage) { LOGGER.debug("Not an HTML page for javascript reordering: {}", uri); filterChain.doFilter(servletRequest, servletResponse); return; } // run through a wrapper response object HttpServletResponseWrapperImpl wrapper = new HttpServletResponseWrapperImpl((HttpServletResponse) servletResponse); filterChain.doFilter(servletRequest, wrapper); // check if this is an HTML output if (!"text/html".equals(wrapper.getContentType())) { LOGGER.debug("Response content not HTML for javascript reordering: {}", uri); // just write the plain response // this is not HTML response wrapper.copyToResponse(servletResponse); return; } final long startTime = System.currentTimeMillis(); LOGGER.debug("Javascript reordering candidate found: {}", uri); writeReorderedHtml(wrapper, servletResponse); final long endTime = System.currentTimeMillis(); LOGGER.debug("Reordering javascript for url: {} took: {}ms", uri, (endTime - startTime)); }
[ "@", "Override", "public", "void", "doFilter", "(", "ServletRequest", "servletRequest", ",", "ServletResponse", "servletResponse", ",", "FilterChain", "filterChain", ")", "throws", "IOException", ",", "ServletException", "{", "// try and see if this request is for an HTML pag...
Move all included JavaScript files to the end of <code>BODY</code> tag in the same order that they appeared in the original HTML response. @param servletRequest the incoming {@link ServletRequest} instance @param servletResponse the outgoing {@link ServletResponse} instance @param filterChain the {@link FilterChain} being executed @throws IOException if something fails @throws ServletException if something fails @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
[ "Move", "all", "included", "JavaScript", "files", "to", "the", "end", "of", "<code", ">", "BODY<", "/", "code", ">", "tag", "in", "the", "same", "order", "that", "they", "appeared", "in", "the", "original", "HTML", "response", "." ]
train
https://github.com/sangupta/jerry-web/blob/f0d02a5d6e7d1c15292509ce588caf52a4ddb895/src/main/java/com/sangupta/jerry/web/filters/JavascriptReorderingFilter.java#L93-L130
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java
CoverageUtilities.buildDummyCoverage
public static GridCoverage2D buildDummyCoverage() { HashMap<String, Double> envelopeParams = new HashMap<String, Double>(); envelopeParams.put(NORTH, 1.0); envelopeParams.put(SOUTH, 0.0); envelopeParams.put(WEST, 0.0); envelopeParams.put(EAST, 1.0); envelopeParams.put(XRES, 1.0); envelopeParams.put(YRES, 1.0); envelopeParams.put(ROWS, 1.0); envelopeParams.put(COLS, 1.0); double[][] dataMatrix = new double[1][1]; dataMatrix[0][0] = 0; WritableRaster writableRaster = createWritableRasterFromMatrix(dataMatrix, true); return buildCoverage("dummy", writableRaster, envelopeParams, DefaultGeographicCRS.WGS84); //$NON-NLS-1$ }
java
public static GridCoverage2D buildDummyCoverage() { HashMap<String, Double> envelopeParams = new HashMap<String, Double>(); envelopeParams.put(NORTH, 1.0); envelopeParams.put(SOUTH, 0.0); envelopeParams.put(WEST, 0.0); envelopeParams.put(EAST, 1.0); envelopeParams.put(XRES, 1.0); envelopeParams.put(YRES, 1.0); envelopeParams.put(ROWS, 1.0); envelopeParams.put(COLS, 1.0); double[][] dataMatrix = new double[1][1]; dataMatrix[0][0] = 0; WritableRaster writableRaster = createWritableRasterFromMatrix(dataMatrix, true); return buildCoverage("dummy", writableRaster, envelopeParams, DefaultGeographicCRS.WGS84); //$NON-NLS-1$ }
[ "public", "static", "GridCoverage2D", "buildDummyCoverage", "(", ")", "{", "HashMap", "<", "String", ",", "Double", ">", "envelopeParams", "=", "new", "HashMap", "<", "String", ",", "Double", ">", "(", ")", ";", "envelopeParams", ".", "put", "(", "NORTH", ...
Creates a useless {@link GridCoverage2D} that might be usefull as placeholder. @return the dummy grod coverage.
[ "Creates", "a", "useless", "{", "@link", "GridCoverage2D", "}", "that", "might", "be", "usefull", "as", "placeholder", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java#L916-L930
lessthanoptimal/ejml
main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java
CommonOps_ZDRM.extractDiag
public static void extractDiag(ZMatrixRMaj src, ZMatrixRMaj dst ) { int N = Math.min(src.numRows, src.numCols); // reshape if it's not the right size if( !MatrixFeatures_ZDRM.isVector(dst) || dst.numCols*dst.numCols != N ) { dst.reshape(N,1); } for( int i = 0; i < N; i++ ) { int index = src.getIndex(i,i); dst.data[i*2] = src.data[index]; dst.data[i*2+1] = src.data[index+1]; } }
java
public static void extractDiag(ZMatrixRMaj src, ZMatrixRMaj dst ) { int N = Math.min(src.numRows, src.numCols); // reshape if it's not the right size if( !MatrixFeatures_ZDRM.isVector(dst) || dst.numCols*dst.numCols != N ) { dst.reshape(N,1); } for( int i = 0; i < N; i++ ) { int index = src.getIndex(i,i); dst.data[i*2] = src.data[index]; dst.data[i*2+1] = src.data[index+1]; } }
[ "public", "static", "void", "extractDiag", "(", "ZMatrixRMaj", "src", ",", "ZMatrixRMaj", "dst", ")", "{", "int", "N", "=", "Math", ".", "min", "(", "src", ".", "numRows", ",", "src", ".", "numCols", ")", ";", "// reshape if it's not the right size", "if", ...
<p> Extracts the diagonal elements 'src' write it to the 'dst' vector. 'dst' can either be a row or column vector. <p> @param src Matrix whose diagonal elements are being extracted. Not modified. @param dst A vector the results will be written into. Modified.
[ "<p", ">", "Extracts", "the", "diagonal", "elements", "src", "write", "it", "to", "the", "dst", "vector", ".", "dst", "can", "either", "be", "a", "row", "or", "column", "vector", ".", "<p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/CommonOps_ZDRM.java#L122-L136
logic-ng/LogicNG
src/main/java/org/logicng/solvers/maxsat/algorithms/MaxSAT.java
MaxSAT.computeCostModel
public int computeCostModel(final LNGBooleanVector currentModel, int weight) { assert currentModel.size() != 0; int currentCost = 0; for (int i = 0; i < nSoft(); i++) { boolean unsatisfied = true; for (int j = 0; j < softClauses.get(i).clause().size(); j++) { if (weight != Integer.MAX_VALUE && softClauses.get(i).weight() != weight) { unsatisfied = false; continue; } assert var(softClauses.get(i).clause().get(j)) < currentModel.size(); if ((sign(softClauses.get(i).clause().get(j)) && !currentModel.get(var(softClauses.get(i).clause().get(j)))) || (!sign(softClauses.get(i).clause().get(j)) && currentModel.get(var(softClauses.get(i).clause().get(j))))) { unsatisfied = false; break; } } if (unsatisfied) currentCost += softClauses.get(i).weight(); } return currentCost; }
java
public int computeCostModel(final LNGBooleanVector currentModel, int weight) { assert currentModel.size() != 0; int currentCost = 0; for (int i = 0; i < nSoft(); i++) { boolean unsatisfied = true; for (int j = 0; j < softClauses.get(i).clause().size(); j++) { if (weight != Integer.MAX_VALUE && softClauses.get(i).weight() != weight) { unsatisfied = false; continue; } assert var(softClauses.get(i).clause().get(j)) < currentModel.size(); if ((sign(softClauses.get(i).clause().get(j)) && !currentModel.get(var(softClauses.get(i).clause().get(j)))) || (!sign(softClauses.get(i).clause().get(j)) && currentModel.get(var(softClauses.get(i).clause().get(j))))) { unsatisfied = false; break; } } if (unsatisfied) currentCost += softClauses.get(i).weight(); } return currentCost; }
[ "public", "int", "computeCostModel", "(", "final", "LNGBooleanVector", "currentModel", ",", "int", "weight", ")", "{", "assert", "currentModel", ".", "size", "(", ")", "!=", "0", ";", "int", "currentCost", "=", "0", ";", "for", "(", "int", "i", "=", "0",...
Computes the cost of a given model. The cost of a model is the sum of the weights of the unsatisfied soft clauses. If a weight is specified, then it only considers the sum of the weights of the unsatisfied soft clauses with the specified weight. @param currentModel the model @param weight the weight @return the cost of the given model
[ "Computes", "the", "cost", "of", "a", "given", "model", ".", "The", "cost", "of", "a", "model", "is", "the", "sum", "of", "the", "weights", "of", "the", "unsatisfied", "soft", "clauses", ".", "If", "a", "weight", "is", "specified", "then", "it", "only"...
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/algorithms/MaxSAT.java#L345-L366
EdwardRaff/JSAT
JSAT/src/jsat/utils/IndexTable.java
IndexTable.apply
public void apply(int[] target) { //use DoubleList view b/d we are only using set ops, so we wont run into an issue of re-allocating the array apply(IntList.view(target, target.length), new IntList(target.length)); }
java
public void apply(int[] target) { //use DoubleList view b/d we are only using set ops, so we wont run into an issue of re-allocating the array apply(IntList.view(target, target.length), new IntList(target.length)); }
[ "public", "void", "apply", "(", "int", "[", "]", "target", ")", "{", "//use DoubleList view b/d we are only using set ops, so we wont run into an issue of re-allocating the array", "apply", "(", "IntList", ".", "view", "(", "target", ",", "target", ".", "length", ")", "...
Applies this index table to the specified target, putting {@code target} into the same ordering as this IndexTable. @param target the array to re-order into the sorted order defined by this index table @throws RuntimeException if the length of the target array is not the same as the index table
[ "Applies", "this", "index", "table", "to", "the", "specified", "target", "putting", "{", "@code", "target", "}", "into", "the", "same", "ordering", "as", "this", "IndexTable", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/utils/IndexTable.java#L281-L285
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/segmentation/ImageSegmentationOps.java
ImageSegmentationOps.countRegionPixels
public static void countRegionPixels(GrayS32 labeled , int totalRegions , int counts[] ) { Arrays.fill(counts,0,totalRegions,0); for( int y = 0; y < labeled.height; y++ ) { int index = labeled.startIndex + y*labeled.stride; for( int x = 0; x < labeled.width; x++ ) { counts[labeled.data[index++]]++; } } }
java
public static void countRegionPixels(GrayS32 labeled , int totalRegions , int counts[] ) { Arrays.fill(counts,0,totalRegions,0); for( int y = 0; y < labeled.height; y++ ) { int index = labeled.startIndex + y*labeled.stride; for( int x = 0; x < labeled.width; x++ ) { counts[labeled.data[index++]]++; } } }
[ "public", "static", "void", "countRegionPixels", "(", "GrayS32", "labeled", ",", "int", "totalRegions", ",", "int", "counts", "[", "]", ")", "{", "Arrays", ".", "fill", "(", "counts", ",", "0", ",", "totalRegions", ",", "0", ")", ";", "for", "(", "int"...
Counts the number of pixels in all regions. Regions must be have labels from 0 to totalRegions-1. @param labeled (Input) labeled image @param totalRegions Total number of regions @param counts Storage for pixel counts
[ "Counts", "the", "number", "of", "pixels", "in", "all", "regions", ".", "Regions", "must", "be", "have", "labels", "from", "0", "to", "totalRegions", "-", "1", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/segmentation/ImageSegmentationOps.java#L64-L74
grpc/grpc-java
protobuf/src/main/java/io/grpc/protobuf/StatusProto.java
StatusProto.fromStatusAndTrailers
@Nullable public static com.google.rpc.Status fromStatusAndTrailers(Status status, Metadata trailers) { if (trailers != null) { com.google.rpc.Status statusProto = trailers.get(STATUS_DETAILS_KEY); if (statusProto != null) { checkArgument( status.getCode().value() == statusProto.getCode(), "com.google.rpc.Status code must match gRPC status code"); return statusProto; } } return null; }
java
@Nullable public static com.google.rpc.Status fromStatusAndTrailers(Status status, Metadata trailers) { if (trailers != null) { com.google.rpc.Status statusProto = trailers.get(STATUS_DETAILS_KEY); if (statusProto != null) { checkArgument( status.getCode().value() == statusProto.getCode(), "com.google.rpc.Status code must match gRPC status code"); return statusProto; } } return null; }
[ "@", "Nullable", "public", "static", "com", ".", "google", ".", "rpc", ".", "Status", "fromStatusAndTrailers", "(", "Status", "status", ",", "Metadata", "trailers", ")", "{", "if", "(", "trailers", "!=", "null", ")", "{", "com", ".", "google", ".", "rpc"...
Extracts the google.rpc.Status from trailers, and makes sure they match the gRPC {@code status}. @return the embedded google.rpc.Status or {@code null} if it is not present. @since 1.11.0
[ "Extracts", "the", "google", ".", "rpc", ".", "Status", "from", "trailers", "and", "makes", "sure", "they", "match", "the", "gRPC", "{", "@code", "status", "}", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/protobuf/src/main/java/io/grpc/protobuf/StatusProto.java#L156-L168
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.createImagesFromFilesAsync
public Observable<ImageCreateSummary> createImagesFromFilesAsync(UUID projectId, ImageFileCreateBatch batch) { return createImagesFromFilesWithServiceResponseAsync(projectId, batch).map(new Func1<ServiceResponse<ImageCreateSummary>, ImageCreateSummary>() { @Override public ImageCreateSummary call(ServiceResponse<ImageCreateSummary> response) { return response.body(); } }); }
java
public Observable<ImageCreateSummary> createImagesFromFilesAsync(UUID projectId, ImageFileCreateBatch batch) { return createImagesFromFilesWithServiceResponseAsync(projectId, batch).map(new Func1<ServiceResponse<ImageCreateSummary>, ImageCreateSummary>() { @Override public ImageCreateSummary call(ServiceResponse<ImageCreateSummary> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ImageCreateSummary", ">", "createImagesFromFilesAsync", "(", "UUID", "projectId", ",", "ImageFileCreateBatch", "batch", ")", "{", "return", "createImagesFromFilesWithServiceResponseAsync", "(", "projectId", ",", "batch", ")", ".", "map", "(...
Add the provided batch of images to the set of training images. This API accepts a batch of files, and optionally tags, to create images. There is a limit of 64 images and 20 tags. @param projectId The project id @param batch The batch of image files to add. Limited to 64 images and 20 tags per batch @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ImageCreateSummary object
[ "Add", "the", "provided", "batch", "of", "images", "to", "the", "set", "of", "training", "images", ".", "This", "API", "accepts", "a", "batch", "of", "files", "and", "optionally", "tags", "to", "create", "images", ".", "There", "is", "a", "limit", "of", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L3955-L3962
knightliao/disconf
disconf-web/src/main/java/com/baidu/disconf/web/service/roleres/service/RoleResourceAspectMock.java
RoleResourceAspectMock.decideAccess
@Around("anyPublicMethod() && @annotation(requestMapping)") public Object decideAccess(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable { Object rtnOb = null; try { // 执行方法 rtnOb = pjp.proceed(); } catch (Throwable t) { LOG.info(t.getMessage()); throw t; } return rtnOb; }
java
@Around("anyPublicMethod() && @annotation(requestMapping)") public Object decideAccess(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable { Object rtnOb = null; try { // 执行方法 rtnOb = pjp.proceed(); } catch (Throwable t) { LOG.info(t.getMessage()); throw t; } return rtnOb; }
[ "@", "Around", "(", "\"anyPublicMethod() && @annotation(requestMapping)\"", ")", "public", "Object", "decideAccess", "(", "ProceedingJoinPoint", "pjp", ",", "RequestMapping", "requestMapping", ")", "throws", "Throwable", "{", "Object", "rtnOb", "=", "null", ";", "try", ...
判断当前用户对访问的方法是否有权限 @param pjp 方法 @param requestMapping 方法上的annotation @return @throws Throwable
[ "判断当前用户对访问的方法是否有权限" ]
train
https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-web/src/main/java/com/baidu/disconf/web/service/roleres/service/RoleResourceAspectMock.java#L37-L51
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/LoggerFactory.java
LoggerFactory.getLogger
public static Logger getLogger(final String aName, final String aBundleName) { final ILoggerFactory factory = org.slf4j.LoggerFactory.getILoggerFactory(); final Logger logger; if (aBundleName != null) { logger = new Logger(factory.getLogger(aName), aBundleName); } else { logger = new Logger(factory.getLogger(aName)); } return logger; }
java
public static Logger getLogger(final String aName, final String aBundleName) { final ILoggerFactory factory = org.slf4j.LoggerFactory.getILoggerFactory(); final Logger logger; if (aBundleName != null) { logger = new Logger(factory.getLogger(aName), aBundleName); } else { logger = new Logger(factory.getLogger(aName)); } return logger; }
[ "public", "static", "Logger", "getLogger", "(", "final", "String", "aName", ",", "final", "String", "aBundleName", ")", "{", "final", "ILoggerFactory", "factory", "=", "org", ".", "slf4j", ".", "LoggerFactory", ".", "getILoggerFactory", "(", ")", ";", "final",...
Gets an {@link XMLResourceBundle} wrapped SLF4J {@link org.slf4j.Logger}. @param aName A class to use for the logger name @param aBundleName The name of the resource bundle to use @return A resource bundle aware logger
[ "Gets", "an", "{", "@link", "XMLResourceBundle", "}", "wrapped", "SLF4J", "{", "@link", "org", ".", "slf4j", ".", "Logger", "}", "." ]
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/LoggerFactory.java#L54-L65
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/util/locale/InternalLocaleBuilder.java
InternalLocaleBuilder.checkVariants
private int checkVariants(String variants, String sep) { StringTokenIterator itr = new StringTokenIterator(variants, sep); while (!itr.isDone()) { String s = itr.current(); if (!LanguageTag.isVariant(s)) { return itr.currentStart(); } itr.next(); } return -1; }
java
private int checkVariants(String variants, String sep) { StringTokenIterator itr = new StringTokenIterator(variants, sep); while (!itr.isDone()) { String s = itr.current(); if (!LanguageTag.isVariant(s)) { return itr.currentStart(); } itr.next(); } return -1; }
[ "private", "int", "checkVariants", "(", "String", "variants", ",", "String", "sep", ")", "{", "StringTokenIterator", "itr", "=", "new", "StringTokenIterator", "(", "variants", ",", "sep", ")", ";", "while", "(", "!", "itr", ".", "isDone", "(", ")", ")", ...
/* Check if the given variant subtags separated by the given separator(s) are valid
[ "/", "*", "Check", "if", "the", "given", "variant", "subtags", "separated", "by", "the", "given", "separator", "(", "s", ")", "are", "valid" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/util/locale/InternalLocaleBuilder.java#L575-L585
Axway/Grapes
server/src/main/java/org/axway/grapes/server/db/mongo/JongoUtils.java
JongoUtils.generateQuery
public static String generateQuery(final String key, final Object value) { final Map<String, Object> params = new HashMap<>(); params.put(key, value); return generateQuery(params); }
java
public static String generateQuery(final String key, final Object value) { final Map<String, Object> params = new HashMap<>(); params.put(key, value); return generateQuery(params); }
[ "public", "static", "String", "generateQuery", "(", "final", "String", "key", ",", "final", "Object", "value", ")", "{", "final", "Map", "<", "String", ",", "Object", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "params", ".", "put", "(",...
Generate a Jongo query with provided the parameter. @param key @param value @return String
[ "Generate", "a", "Jongo", "query", "with", "provided", "the", "parameter", "." ]
train
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/server/src/main/java/org/axway/grapes/server/db/mongo/JongoUtils.java#L55-L59
alkacon/opencms-core
src/org/opencms/ui/dialogs/history/CmsHistoryDialog.java
CmsHistoryDialog.openChildDialog
public static void openChildDialog(Component currentComponent, Component newView, String newCaption) { final Window window = CmsVaadinUtils.getWindow(currentComponent); final String oldCaption = window.getCaption(); CmsBasicDialog dialog = new CmsBasicDialog(); VerticalLayout vl = new VerticalLayout(); dialog.setContent(vl); Button backButton = new Button(CmsVaadinUtils.getMessageText(Messages.GUI_CHILD_DIALOG_GO_BACK_0)); HorizontalLayout buttonBar = new HorizontalLayout(); buttonBar.addComponent(backButton); buttonBar.setMargin(true); vl.addComponent(buttonBar); vl.addComponent(newView); final Component oldContent = window.getContent(); if (oldContent instanceof CmsBasicDialog) { List<CmsResource> infoResources = ((CmsBasicDialog)oldContent).getInfoResources(); dialog.displayResourceInfo(infoResources); if (oldContent instanceof CmsHistoryDialog) { dialog.addButton(((CmsHistoryDialog)oldContent).createCloseButton()); } } backButton.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { window.setContent(oldContent); window.setCaption(oldCaption); window.center(); } }); window.setContent(dialog); window.setCaption(newCaption); window.center(); }
java
public static void openChildDialog(Component currentComponent, Component newView, String newCaption) { final Window window = CmsVaadinUtils.getWindow(currentComponent); final String oldCaption = window.getCaption(); CmsBasicDialog dialog = new CmsBasicDialog(); VerticalLayout vl = new VerticalLayout(); dialog.setContent(vl); Button backButton = new Button(CmsVaadinUtils.getMessageText(Messages.GUI_CHILD_DIALOG_GO_BACK_0)); HorizontalLayout buttonBar = new HorizontalLayout(); buttonBar.addComponent(backButton); buttonBar.setMargin(true); vl.addComponent(buttonBar); vl.addComponent(newView); final Component oldContent = window.getContent(); if (oldContent instanceof CmsBasicDialog) { List<CmsResource> infoResources = ((CmsBasicDialog)oldContent).getInfoResources(); dialog.displayResourceInfo(infoResources); if (oldContent instanceof CmsHistoryDialog) { dialog.addButton(((CmsHistoryDialog)oldContent).createCloseButton()); } } backButton.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { window.setContent(oldContent); window.setCaption(oldCaption); window.center(); } }); window.setContent(dialog); window.setCaption(newCaption); window.center(); }
[ "public", "static", "void", "openChildDialog", "(", "Component", "currentComponent", ",", "Component", "newView", ",", "String", "newCaption", ")", "{", "final", "Window", "window", "=", "CmsVaadinUtils", ".", "getWindow", "(", "currentComponent", ")", ";", "final...
Replaces the contents of the window containing a given component with a basic dialog consisting of a back button to restore the previous window state and another user provided widget.<p> @param currentComponent the component whose parent window's content should be replaced @param newView the user supplied part of the new window content @param newCaption the caption for the child dialog
[ "Replaces", "the", "contents", "of", "the", "window", "containing", "a", "given", "component", "with", "a", "basic", "dialog", "consisting", "of", "a", "back", "button", "to", "restore", "the", "previous", "window", "state", "and", "another", "user", "provided...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/dialogs/history/CmsHistoryDialog.java#L206-L245
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fsadmin/FileSystemAdminShellUtils.java
FileSystemAdminShellUtils.compareTierNames
public static int compareTierNames(String a, String b) { int aValue = getTierRankValue(a); int bValue = getTierRankValue(b); if (aValue == bValue) { return a.compareTo(b); } return aValue - bValue; }
java
public static int compareTierNames(String a, String b) { int aValue = getTierRankValue(a); int bValue = getTierRankValue(b); if (aValue == bValue) { return a.compareTo(b); } return aValue - bValue; }
[ "public", "static", "int", "compareTierNames", "(", "String", "a", ",", "String", "b", ")", "{", "int", "aValue", "=", "getTierRankValue", "(", "a", ")", ";", "int", "bValue", "=", "getTierRankValue", "(", "b", ")", ";", "if", "(", "aValue", "==", "bVa...
Compares two tier names according to their rank values. @param a one tier name @param b another tier name @return compared result
[ "Compares", "two", "tier", "names", "according", "to", "their", "rank", "values", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fsadmin/FileSystemAdminShellUtils.java#L43-L50
apache/flink
flink-core/src/main/java/org/apache/flink/configuration/Configuration.java
Configuration.getInteger
public int getInteger(String key, int defaultValue) { Object o = getRawValue(key); if (o == null) { return defaultValue; } return convertToInt(o, defaultValue); }
java
public int getInteger(String key, int defaultValue) { Object o = getRawValue(key); if (o == null) { return defaultValue; } return convertToInt(o, defaultValue); }
[ "public", "int", "getInteger", "(", "String", "key", ",", "int", "defaultValue", ")", "{", "Object", "o", "=", "getRawValue", "(", "key", ")", ";", "if", "(", "o", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "return", "convertToInt", "(...
Returns the value associated with the given key as an integer. @param key the key pointing to the associated value @param defaultValue the default value which is returned in case there is no value associated with the given key @return the (default) value associated with the given key
[ "Returns", "the", "value", "associated", "with", "the", "given", "key", "as", "an", "integer", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/configuration/Configuration.java#L204-L211
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java
OADProfile.needsUpdate
private boolean needsUpdate(Long bundleVersion, String beanVersion) { if (beanVersion.contains("OAD")) { Log.i(TAG, "Bundle version: " + bundleVersion); Log.i(TAG, "Bean version: " + beanVersion); return true; } else { try { long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]); Log.i(TAG, "Bundle version: " + bundleVersion); Log.i(TAG, "Bean version: " + parsedVersion); if (bundleVersion > parsedVersion) { return true; } else { Log.i(TAG, "No update required!"); } } catch (NumberFormatException e) { Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion); fail(BeanError.UNPARSABLE_FW_VERSION); } } return false; }
java
private boolean needsUpdate(Long bundleVersion, String beanVersion) { if (beanVersion.contains("OAD")) { Log.i(TAG, "Bundle version: " + bundleVersion); Log.i(TAG, "Bean version: " + beanVersion); return true; } else { try { long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]); Log.i(TAG, "Bundle version: " + bundleVersion); Log.i(TAG, "Bean version: " + parsedVersion); if (bundleVersion > parsedVersion) { return true; } else { Log.i(TAG, "No update required!"); } } catch (NumberFormatException e) { Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion); fail(BeanError.UNPARSABLE_FW_VERSION); } } return false; }
[ "private", "boolean", "needsUpdate", "(", "Long", "bundleVersion", ",", "String", "beanVersion", ")", "{", "if", "(", "beanVersion", ".", "contains", "(", "\"OAD\"", ")", ")", "{", "Log", ".", "i", "(", "TAG", ",", "\"Bundle version: \"", "+", "bundleVersion...
Helper function to determine whether a Bean needs a FW update given a specific Bundle version @param bundleVersion the version string from the provided firmware bundle @param beanVersion the version string provided from the Bean Device Information Service @return boolean value stating whether the Bean needs an update
[ "Helper", "function", "to", "determine", "whether", "a", "Bean", "needs", "a", "FW", "update", "given", "a", "specific", "Bundle", "version" ]
train
https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L337-L358
hibernate/hibernate-ogm
neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jAssociationQueries.java
EmbeddedNeo4jAssociationQueries.removeAssociationRow
@Override public void removeAssociationRow(GraphDatabaseService executionEngine, AssociationKey associationKey, RowKey rowKey) { Object[] queryValues = relationshipValues( associationKey, rowKey ); executionEngine.execute( removeAssociationRowQuery, params( queryValues ) ); }
java
@Override public void removeAssociationRow(GraphDatabaseService executionEngine, AssociationKey associationKey, RowKey rowKey) { Object[] queryValues = relationshipValues( associationKey, rowKey ); executionEngine.execute( removeAssociationRowQuery, params( queryValues ) ); }
[ "@", "Override", "public", "void", "removeAssociationRow", "(", "GraphDatabaseService", "executionEngine", ",", "AssociationKey", "associationKey", ",", "RowKey", "rowKey", ")", "{", "Object", "[", "]", "queryValues", "=", "relationshipValues", "(", "associationKey", ...
Remove an association row @param executionEngine the {@link GraphDatabaseService} used to run the query @param associationKey represents the association @param rowKey represents a row in an association
[ "Remove", "an", "association", "row" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jAssociationQueries.java#L100-L104
kenyee/android-ddp-client
src/com/keysolutions/ddpclient/android/MeteorAuthCommands.java
MeteorAuthCommands.login
public void login(String username, String password) { Object[] methodArgs = new Object[1]; if (username != null && username.indexOf('@') > 1) { EmailAuth emailpass = new EmailAuth(username, password); methodArgs[0] = emailpass; } else { UsernameAuth userpass = new UsernameAuth(username, password); methodArgs[0] = userpass; } getDDP().call("login", methodArgs, new DDPListener() { @Override public void onResult(Map<String, Object> jsonFields) { handleLoginResult(jsonFields); } }); }
java
public void login(String username, String password) { Object[] methodArgs = new Object[1]; if (username != null && username.indexOf('@') > 1) { EmailAuth emailpass = new EmailAuth(username, password); methodArgs[0] = emailpass; } else { UsernameAuth userpass = new UsernameAuth(username, password); methodArgs[0] = userpass; } getDDP().call("login", methodArgs, new DDPListener() { @Override public void onResult(Map<String, Object> jsonFields) { handleLoginResult(jsonFields); } }); }
[ "public", "void", "login", "(", "String", "username", ",", "String", "password", ")", "{", "Object", "[", "]", "methodArgs", "=", "new", "Object", "[", "1", "]", ";", "if", "(", "username", "!=", "null", "&&", "username", ".", "indexOf", "(", "'", "'...
Logs in using username/password @param username username/email @param password password
[ "Logs", "in", "using", "username", "/", "password" ]
train
https://github.com/kenyee/android-ddp-client/blob/6ab416e415570a03f96c383497144dd742de3f08/src/com/keysolutions/ddpclient/android/MeteorAuthCommands.java#L55-L71
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.verifyAsync
public Observable<KeyVerifyResult> verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).map(new Func1<ServiceResponse<KeyVerifyResult>, KeyVerifyResult>() { @Override public KeyVerifyResult call(ServiceResponse<KeyVerifyResult> response) { return response.body(); } }); }
java
public Observable<KeyVerifyResult> verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).map(new Func1<ServiceResponse<KeyVerifyResult>, KeyVerifyResult>() { @Override public KeyVerifyResult call(ServiceResponse<KeyVerifyResult> response) { return response.body(); } }); }
[ "public", "Observable", "<", "KeyVerifyResult", ">", "verifyAsync", "(", "String", "vaultBaseUrl", ",", "String", "keyName", ",", "String", "keyVersion", ",", "JsonWebKeySignatureAlgorithm", "algorithm", ",", "byte", "[", "]", "digest", ",", "byte", "[", "]", "s...
Verifies a signature using a specified key. The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public portion of the key but this operation is supported as a convenience for callers that only have a key-reference and not the public portion of the key. This operation requires the keys/verify permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param keyName The name of the key. @param keyVersion The version of the key. @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'RSNULL', 'ES256', 'ES384', 'ES512', 'ES256K' @param digest The digest used for signing. @param signature The signature to be verified. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the KeyVerifyResult object
[ "Verifies", "a", "signature", "using", "a", "specified", "key", ".", "The", "VERIFY", "operation", "is", "applicable", "to", "symmetric", "keys", "stored", "in", "Azure", "Key", "Vault", ".", "VERIFY", "is", "not", "strictly", "necessary", "for", "asymmetric",...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L2518-L2525
cdk/cdk
tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java
ModelBuilder3D.setForceField
private void setForceField(String ffname, IChemObjectBuilder builder) throws CDKException { if (ffname == null) { ffname = "mm2"; } try { forceFieldName = ffname; ffc.setForceFieldConfigurator(ffname, builder); parameterSet = ffc.getParameterSet(); } catch (CDKException ex1) { logger.error("Problem with ForceField configuration due to>" + ex1.getMessage()); logger.debug(ex1); throw new CDKException("Problem with ForceField configuration due to>" + ex1.getMessage(), ex1); } }
java
private void setForceField(String ffname, IChemObjectBuilder builder) throws CDKException { if (ffname == null) { ffname = "mm2"; } try { forceFieldName = ffname; ffc.setForceFieldConfigurator(ffname, builder); parameterSet = ffc.getParameterSet(); } catch (CDKException ex1) { logger.error("Problem with ForceField configuration due to>" + ex1.getMessage()); logger.debug(ex1); throw new CDKException("Problem with ForceField configuration due to>" + ex1.getMessage(), ex1); } }
[ "private", "void", "setForceField", "(", "String", "ffname", ",", "IChemObjectBuilder", "builder", ")", "throws", "CDKException", "{", "if", "(", "ffname", "==", "null", ")", "{", "ffname", "=", "\"mm2\"", ";", "}", "try", "{", "forceFieldName", "=", "ffname...
Sets the forceField attribute of the ModelBuilder3D object. @param ffname forceField name
[ "Sets", "the", "forceField", "attribute", "of", "the", "ModelBuilder3D", "object", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java#L134-L147
cdk/cdk
tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java
AtomPlacer3D.getBondLengthValue
public double getBondLengthValue(String id1, String id2) { String dkey = ""; if (pSet.containsKey(("bond" + id1 + ";" + id2))) { dkey = "bond" + id1 + ";" + id2; } else if (pSet.containsKey(("bond" + id2 + ";" + id1))) { dkey = "bond" + id2 + ";" + id1; } else { logger.warn("KEYError: Unknown distance key in pSet: " + id2 + ";" + id1 + " take default bond length: " + DEFAULT_BOND_LENGTH); return DEFAULT_BOND_LENGTH; } return ((Double) (pSet.get(dkey).get(0))).doubleValue(); }
java
public double getBondLengthValue(String id1, String id2) { String dkey = ""; if (pSet.containsKey(("bond" + id1 + ";" + id2))) { dkey = "bond" + id1 + ";" + id2; } else if (pSet.containsKey(("bond" + id2 + ";" + id1))) { dkey = "bond" + id2 + ";" + id1; } else { logger.warn("KEYError: Unknown distance key in pSet: " + id2 + ";" + id1 + " take default bond length: " + DEFAULT_BOND_LENGTH); return DEFAULT_BOND_LENGTH; } return ((Double) (pSet.get(dkey).get(0))).doubleValue(); }
[ "public", "double", "getBondLengthValue", "(", "String", "id1", ",", "String", "id2", ")", "{", "String", "dkey", "=", "\"\"", ";", "if", "(", "pSet", ".", "containsKey", "(", "(", "\"bond\"", "+", "id1", "+", "\";\"", "+", "id2", ")", ")", ")", "{",...
Gets the distanceValue attribute of the parameter set. @param id1 atom1 id @param id2 atom2 id @return The distanceValue value from the force field parameter set
[ "Gets", "the", "distanceValue", "attribute", "of", "the", "parameter", "set", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java#L327-L339
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/workspace/LayerWorkspaceMgr.java
LayerWorkspaceMgr.setHelperWorkspace
public void setHelperWorkspace(@NonNull String key, Pointer value){ if(helperWorkspacePointers == null){ helperWorkspacePointers = new HashMap<>(); } helperWorkspacePointers.put(key, value); }
java
public void setHelperWorkspace(@NonNull String key, Pointer value){ if(helperWorkspacePointers == null){ helperWorkspacePointers = new HashMap<>(); } helperWorkspacePointers.put(key, value); }
[ "public", "void", "setHelperWorkspace", "(", "@", "NonNull", "String", "key", ",", "Pointer", "value", ")", "{", "if", "(", "helperWorkspacePointers", "==", "null", ")", "{", "helperWorkspacePointers", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "helper...
Set the pointer to the helper memory. Usually used for CuDNN workspace memory sharing. NOTE: Don't use this method unless you are fully aware of how it is used to manage CuDNN memory! Will (by design) throw a NPE if the underlying map (set from MultiLayerNetwork or ComputationGraph) is not set. @param key Key for the helper workspace pointer @param value Pointer
[ "Set", "the", "pointer", "to", "the", "helper", "memory", ".", "Usually", "used", "for", "CuDNN", "workspace", "memory", "sharing", ".", "NOTE", ":", "Don", "t", "use", "this", "method", "unless", "you", "are", "fully", "aware", "of", "how", "it", "is", ...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/workspace/LayerWorkspaceMgr.java#L110-L115
aws/aws-sdk-java
aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java
StepFunctionBuilder.gte
public static StringGreaterThanOrEqualCondition.Builder gte(String variable, String expectedValue) { return StringGreaterThanOrEqualCondition.builder().variable(variable).expectedValue(expectedValue); }
java
public static StringGreaterThanOrEqualCondition.Builder gte(String variable, String expectedValue) { return StringGreaterThanOrEqualCondition.builder().variable(variable).expectedValue(expectedValue); }
[ "public", "static", "StringGreaterThanOrEqualCondition", ".", "Builder", "gte", "(", "String", "variable", ",", "String", "expectedValue", ")", "{", "return", "StringGreaterThanOrEqualCondition", ".", "builder", "(", ")", ".", "variable", "(", "variable", ")", ".", ...
Binary condition for String greater than or equal to comparison. @param variable The JSONPath expression that determines which piece of the input document is used for the comparison. @param expectedValue The expected value for this condition. @see <a href="https://states-language.net/spec.html#choice-state">https://states-language.net/spec.html#choice-state</a> @see com.amazonaws.services.stepfunctions.builder.states.Choice
[ "Binary", "condition", "for", "String", "greater", "than", "or", "equal", "to", "comparison", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java#L320-L322
hltcoe/annotated-nyt
src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java
NYTCorpusDocumentParser.getDOMObject
private Document getDOMObject(String filename, boolean validating) throws SAXException, IOException, ParserConfigurationException { // Create a builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (!validating) { factory.setValidating(validating); factory.setSchema(null); factory.setNamespaceAware(false); } DocumentBuilder builder = factory.newDocumentBuilder(); // Create the builder and parse the file Document doc = builder.parse(new File(filename)); return doc; }
java
private Document getDOMObject(String filename, boolean validating) throws SAXException, IOException, ParserConfigurationException { // Create a builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (!validating) { factory.setValidating(validating); factory.setSchema(null); factory.setNamespaceAware(false); } DocumentBuilder builder = factory.newDocumentBuilder(); // Create the builder and parse the file Document doc = builder.parse(new File(filename)); return doc; }
[ "private", "Document", "getDOMObject", "(", "String", "filename", ",", "boolean", "validating", ")", "throws", "SAXException", ",", "IOException", ",", "ParserConfigurationException", "{", "// Create a builder factory", "DocumentBuilderFactory", "factory", "=", "DocumentBui...
Parse a file containing an XML document, into a DOM object. @param filename A path to a valid file. @param validating True iff validating should be turned on. @return A DOM Object containing a parsed XML document or a null value if there is an error in parsing. @throws ParserConfigurationException @throws IOException @throws SAXException
[ "Parse", "a", "file", "containing", "an", "XML", "document", "into", "a", "DOM", "object", "." ]
train
https://github.com/hltcoe/annotated-nyt/blob/0a4daa97705591cefea9de61614770ae2665a48e/src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java#L942-L958