repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/compiler/CommandLineCompiler.java
CommandLineCompiler.getTotalArgumentLengthForInputFile
protected int getTotalArgumentLengthForInputFile(final File outputDir, final String inputFile) { final int argumentCountPerInputFile = getArgumentCountPerInputFile(); int len=0; for (int k = 0; k < argumentCountPerInputFile; k++) { len+=getInputFileArgument(outputDir, inputFile, k).length(); } return len + argumentCountPerInputFile; // argumentCountPerInputFile added for spaces }
java
protected int getTotalArgumentLengthForInputFile(final File outputDir, final String inputFile) { final int argumentCountPerInputFile = getArgumentCountPerInputFile(); int len=0; for (int k = 0; k < argumentCountPerInputFile; k++) { len+=getInputFileArgument(outputDir, inputFile, k).length(); } return len + argumentCountPerInputFile; // argumentCountPerInputFile added for spaces }
[ "protected", "int", "getTotalArgumentLengthForInputFile", "(", "final", "File", "outputDir", ",", "final", "String", "inputFile", ")", "{", "final", "int", "argumentCountPerInputFile", "=", "getArgumentCountPerInputFile", "(", ")", ";", "int", "len", "=", "0", ";", ...
Get total command line length due to the input file. @param outputDir File output directory @param inputFile String input file @return int characters added to command line for the input file.
[ "Get", "total", "command", "line", "length", "due", "to", "the", "input", "file", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/compiler/CommandLineCompiler.java#L552-L559
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java
UndertowServletWebServerFactory.getUndertowWebServer
protected UndertowServletWebServer getUndertowWebServer(Builder builder, DeploymentManager manager, int port) { return new UndertowServletWebServer(builder, manager, getContextPath(), isUseForwardHeaders(), port >= 0, getCompression(), getServerHeader()); }
java
protected UndertowServletWebServer getUndertowWebServer(Builder builder, DeploymentManager manager, int port) { return new UndertowServletWebServer(builder, manager, getContextPath(), isUseForwardHeaders(), port >= 0, getCompression(), getServerHeader()); }
[ "protected", "UndertowServletWebServer", "getUndertowWebServer", "(", "Builder", "builder", ",", "DeploymentManager", "manager", ",", "int", "port", ")", "{", "return", "new", "UndertowServletWebServer", "(", "builder", ",", "manager", ",", "getContextPath", "(", ")",...
Factory method called to create the {@link UndertowServletWebServer}. Subclasses can override this method to return a different {@link UndertowServletWebServer} or apply additional processing to the {@link Builder} and {@link DeploymentManager} used to bootstrap Undertow @param builder the builder @param manager the deployment manager @param port the port that Undertow should listen on @return a new {@link UndertowServletWebServer} instance
[ "Factory", "method", "called", "to", "create", "the", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java#L445-L449
facebook/nailgun
nailgun-server/src/main/java/com/facebook/nailgun/NGCommunicator.java
NGCommunicator.readCommandContext
CommandContext readCommandContext() throws IOException { // client info - command line arguments and environment List<String> remoteArgs = new ArrayList(); Properties remoteEnv = new Properties(); String cwd = null; // working directory String command = null; // alias or class name // read everything from the client up to and including the command while (command == null) { int bytesToRead = in.readInt(); byte chunkType = in.readByte(); byte[] b = new byte[bytesToRead]; in.readFully(b); String line = new String(b, "UTF-8"); switch (chunkType) { case NGConstants.CHUNKTYPE_ARGUMENT: // command line argument remoteArgs.add(line); break; case NGConstants.CHUNKTYPE_ENVIRONMENT: // parse environment into property int equalsIndex = line.indexOf('='); if (equalsIndex > 0) { remoteEnv.setProperty(line.substring(0, equalsIndex), line.substring(equalsIndex + 1)); } break; case NGConstants.CHUNKTYPE_COMMAND: // command (alias or classname) command = line; break; case NGConstants.CHUNKTYPE_WORKINGDIRECTORY: // client working directory cwd = line; break; default: // freakout? } } // Command and environment is read. Move other communication with client, which is heartbeats // and // stdin, to background thread startBackgroundReceive(); return new CommandContext(command, cwd, remoteEnv, remoteArgs); }
java
CommandContext readCommandContext() throws IOException { // client info - command line arguments and environment List<String> remoteArgs = new ArrayList(); Properties remoteEnv = new Properties(); String cwd = null; // working directory String command = null; // alias or class name // read everything from the client up to and including the command while (command == null) { int bytesToRead = in.readInt(); byte chunkType = in.readByte(); byte[] b = new byte[bytesToRead]; in.readFully(b); String line = new String(b, "UTF-8"); switch (chunkType) { case NGConstants.CHUNKTYPE_ARGUMENT: // command line argument remoteArgs.add(line); break; case NGConstants.CHUNKTYPE_ENVIRONMENT: // parse environment into property int equalsIndex = line.indexOf('='); if (equalsIndex > 0) { remoteEnv.setProperty(line.substring(0, equalsIndex), line.substring(equalsIndex + 1)); } break; case NGConstants.CHUNKTYPE_COMMAND: // command (alias or classname) command = line; break; case NGConstants.CHUNKTYPE_WORKINGDIRECTORY: // client working directory cwd = line; break; default: // freakout? } } // Command and environment is read. Move other communication with client, which is heartbeats // and // stdin, to background thread startBackgroundReceive(); return new CommandContext(command, cwd, remoteEnv, remoteArgs); }
[ "CommandContext", "readCommandContext", "(", ")", "throws", "IOException", "{", "// client info - command line arguments and environment", "List", "<", "String", ">", "remoteArgs", "=", "new", "ArrayList", "(", ")", ";", "Properties", "remoteEnv", "=", "new", "Propertie...
Get nail command context from the header and start reading for stdin and heartbeats
[ "Get", "nail", "command", "context", "from", "the", "header", "and", "start", "reading", "for", "stdin", "and", "heartbeats" ]
train
https://github.com/facebook/nailgun/blob/948c51c5fce138c65bb3df369c3f7b4d01440605/nailgun-server/src/main/java/com/facebook/nailgun/NGCommunicator.java#L129-L178
Netflix/ribbon
ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListSubsetFilter.java
ServerListSubsetFilter.compare
@Override public int compare(T server1, T server2) { LoadBalancerStats lbStats = getLoadBalancerStats(); ServerStats stats1 = lbStats.getSingleServerStat(server1); ServerStats stats2 = lbStats.getSingleServerStat(server2); int failuresDiff = (int) (stats2.getFailureCount() - stats1.getFailureCount()); if (failuresDiff != 0) { return failuresDiff; } else { return (stats2.getActiveRequestsCount() - stats1.getActiveRequestsCount()); } }
java
@Override public int compare(T server1, T server2) { LoadBalancerStats lbStats = getLoadBalancerStats(); ServerStats stats1 = lbStats.getSingleServerStat(server1); ServerStats stats2 = lbStats.getSingleServerStat(server2); int failuresDiff = (int) (stats2.getFailureCount() - stats1.getFailureCount()); if (failuresDiff != 0) { return failuresDiff; } else { return (stats2.getActiveRequestsCount() - stats1.getActiveRequestsCount()); } }
[ "@", "Override", "public", "int", "compare", "(", "T", "server1", ",", "T", "server2", ")", "{", "LoadBalancerStats", "lbStats", "=", "getLoadBalancerStats", "(", ")", ";", "ServerStats", "stats1", "=", "lbStats", ".", "getSingleServerStat", "(", "server1", ")...
Function to sort the list by server health condition, with unhealthy servers before healthy servers. The servers are first sorted by failures count, and then concurrent connection count.
[ "Function", "to", "sort", "the", "list", "by", "server", "health", "condition", "with", "unhealthy", "servers", "before", "healthy", "servers", ".", "The", "servers", "are", "first", "sorted", "by", "failures", "count", "and", "then", "concurrent", "connection",...
train
https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListSubsetFilter.java#L193-L204
facebookarchive/hadoop-20
src/core/org/apache/hadoop/filecache/DistributedCache.java
DistributedCache.addCacheArchive
public static void addCacheArchive(URI uri, Configuration conf) { String archives = conf.get("mapred.cache.archives"); conf.set("mapred.cache.archives", archives == null ? uri.toString() : archives + "," + uri.toString()); }
java
public static void addCacheArchive(URI uri, Configuration conf) { String archives = conf.get("mapred.cache.archives"); conf.set("mapred.cache.archives", archives == null ? uri.toString() : archives + "," + uri.toString()); }
[ "public", "static", "void", "addCacheArchive", "(", "URI", "uri", ",", "Configuration", "conf", ")", "{", "String", "archives", "=", "conf", ".", "get", "(", "\"mapred.cache.archives\"", ")", ";", "conf", ".", "set", "(", "\"mapred.cache.archives\"", ",", "arc...
Add a archives to be localized to the conf @param uri The uri of the cache to be localized @param conf Configuration to add the cache to
[ "Add", "a", "archives", "to", "be", "localized", "to", "the", "conf" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/filecache/DistributedCache.java#L923-L927
trustathsh/ifmapj
src/main/java/de/hshannover/f4/trust/ifmapj/IfmapJ.java
IfmapJ.createClockSkewDetector
public static ClockSkewDetector createClockSkewDetector(SSRC ssrc, Device dev) { return ClockSkewDetector.newInstance(ssrc, dev); }
java
public static ClockSkewDetector createClockSkewDetector(SSRC ssrc, Device dev) { return ClockSkewDetector.newInstance(ssrc, dev); }
[ "public", "static", "ClockSkewDetector", "createClockSkewDetector", "(", "SSRC", "ssrc", ",", "Device", "dev", ")", "{", "return", "ClockSkewDetector", ".", "newInstance", "(", "ssrc", ",", "dev", ")", ";", "}" ]
Create a {@link ClockSkewDetector} instance which can be used to synchronize the time with the MAPS. @param ssrc the {@link SSRC} instance to be used for synchronization @param dev the {@link Device} used for time synchronization @return
[ "Create", "a", "{", "@link", "ClockSkewDetector", "}", "instance", "which", "can", "be", "used", "to", "synchronize", "the", "time", "with", "the", "MAPS", "." ]
train
https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/de/hshannover/f4/trust/ifmapj/IfmapJ.java#L246-L248
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Single.java
Single.takeUntil
@BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <E> Single<T> takeUntil(final Publisher<E> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new SingleTakeUntil<T, E>(this, other)); }
java
@BackpressureSupport(BackpressureKind.FULL) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) public final <E> Single<T> takeUntil(final Publisher<E> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new SingleTakeUntil<T, E>(this, other)); }
[ "@", "BackpressureSupport", "(", "BackpressureKind", ".", "FULL", ")", "@", "CheckReturnValue", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "final", "<", "E", ">", "Single", "<", "T", ">", "takeUntil", "(", "final", "Publisher...
Returns a Single that emits the item emitted by the source Single until a Publisher emits an item. Upon emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to {@link SingleObserver#onSuccess(Object)}. <p> <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt=""> <dl> <dt><b>Backpressure:</b></dt> <dd>The {@code other} publisher is consumed in an unbounded fashion but will be cancelled after the first item it produced.</dd> <dt><b>Scheduler:</b></dt> <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param other the Publisher whose first emitted item will cause {@code takeUntil} to emit the item from the source Single @param <E> the type of items emitted by {@code other} @return a Single that emits the item emitted by the source Single until such time as {@code other} emits its first item @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a>
[ "Returns", "a", "Single", "that", "emits", "the", "item", "emitted", "by", "the", "source", "Single", "until", "a", "Publisher", "emits", "an", "item", ".", "Upon", "emission", "of", "an", "item", "from", "{", "@code", "other", "}", "this", "will", "emit...
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Single.java#L3559-L3565
apache/flink
flink-core/src/main/java/org/apache/flink/core/memory/MemorySegment.java
MemorySegment.putShortLittleEndian
public final void putShortLittleEndian(int index, short value) { if (LITTLE_ENDIAN) { putShort(index, value); } else { putShort(index, Short.reverseBytes(value)); } }
java
public final void putShortLittleEndian(int index, short value) { if (LITTLE_ENDIAN) { putShort(index, value); } else { putShort(index, Short.reverseBytes(value)); } }
[ "public", "final", "void", "putShortLittleEndian", "(", "int", "index", ",", "short", "value", ")", "{", "if", "(", "LITTLE_ENDIAN", ")", "{", "putShort", "(", "index", ",", "value", ")", ";", "}", "else", "{", "putShort", "(", "index", ",", "Short", "...
Writes the given short integer value (16 bit, 2 bytes) to the given position in little-endian byte order. This method's speed depends on the system's native byte order, and it is possibly slower than {@link #putShort(int, short)}. For most cases (such as transient storage in memory or serialization for I/O and network), it suffices to know that the byte order in which the value is written is the same as the one in which it is read, and {@link #putShort(int, short)} is the preferable choice. @param index The position at which the value will be written. @param value The short value to be written. @throws IndexOutOfBoundsException Thrown, if the index is negative, or larger than the segment size minus 2.
[ "Writes", "the", "given", "short", "integer", "value", "(", "16", "bit", "2", "bytes", ")", "to", "the", "given", "position", "in", "little", "-", "endian", "byte", "order", ".", "This", "method", "s", "speed", "depends", "on", "the", "system", "s", "n...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/core/memory/MemorySegment.java#L647-L653
iipc/openwayback-access-control
access-control/src/main/java/org/archive/accesscontrol/AccessControlClient.java
AccessControlClient.getPolicy
public String getPolicy(String url, Date captureDate, Date retrievalDate, String who) throws RobotsUnavailableException, RuleOracleUnavailableException { return getPolicy(url, getRule(url, captureDate, retrievalDate, who)); }
java
public String getPolicy(String url, Date captureDate, Date retrievalDate, String who) throws RobotsUnavailableException, RuleOracleUnavailableException { return getPolicy(url, getRule(url, captureDate, retrievalDate, who)); }
[ "public", "String", "getPolicy", "(", "String", "url", ",", "Date", "captureDate", ",", "Date", "retrievalDate", ",", "String", "who", ")", "throws", "RobotsUnavailableException", ",", "RuleOracleUnavailableException", "{", "return", "getPolicy", "(", "url", ",", ...
Return the best-matching policy for the requested document. @param url URL of the requested document. @param captureDate Date the document was archived. @param retrievalDate Date of retrieval (usually now). @param who Group name of the user accessing the document. @return Access-control policy that should be enforced. eg "robots", "block" or "allow". @throws RobotsUnavailableException @throws RuleOracleUnavailableException
[ "Return", "the", "best", "-", "matching", "policy", "for", "the", "requested", "document", "." ]
train
https://github.com/iipc/openwayback-access-control/blob/4a0f70f200fd8d7b6e313624b7628656d834bf31/access-control/src/main/java/org/archive/accesscontrol/AccessControlClient.java#L89-L93
ocelotds/ocelot
ocelot-processor/src/main/java/org/ocelotds/frameworks/angularjs/FunctionWriter.java
FunctionWriter.writeInjectDependenciesOnObject
public void writeInjectDependenciesOnObject(Writer writer, String object, String... dependencies) throws IOException { if (dependencies != null && dependencies.length > 0) { writer.append(TAB).append(object).append(DOT).append("$inject").append(SPACEOPTIONAL).append(EQUALS).append(SPACEOPTIONAL).append(OPENBRACKET); writeDependencies(writer, "'", dependencies); writer.append(CLOSEBRACKET).append(SEMICOLON).append(CR); } }
java
public void writeInjectDependenciesOnObject(Writer writer, String object, String... dependencies) throws IOException { if (dependencies != null && dependencies.length > 0) { writer.append(TAB).append(object).append(DOT).append("$inject").append(SPACEOPTIONAL).append(EQUALS).append(SPACEOPTIONAL).append(OPENBRACKET); writeDependencies(writer, "'", dependencies); writer.append(CLOSEBRACKET).append(SEMICOLON).append(CR); } }
[ "public", "void", "writeInjectDependenciesOnObject", "(", "Writer", "writer", ",", "String", "object", ",", "String", "...", "dependencies", ")", "throws", "IOException", "{", "if", "(", "dependencies", "!=", "null", "&&", "dependencies", ".", "length", ">", "0"...
\tobject.$inject = ['dep1', 'dep2']; @param writer @param object @param dependencies @throws IOException
[ "\\", "tobject", ".", "$inject", "=", "[", "dep1", "dep2", "]", ";" ]
train
https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-processor/src/main/java/org/ocelotds/frameworks/angularjs/FunctionWriter.java#L23-L29
duracloud/duracloud
durastore/src/main/java/org/duracloud/durastore/rest/ContentRest.java
ContentRest.putContent
@PUT public Response putContent(@PathParam("spaceID") String spaceID, @PathParam("contentID") String contentID, @QueryParam("storeID") String storeID, @HeaderParam(COPY_SOURCE_HEADER) String copySource, @HeaderParam(COPY_SOURCE_STORE_HEADER) String sourceStoreID) { if (null != copySource) { return copyContent(spaceID, contentID, storeID, sourceStoreID, copySource); } else { return addContent(spaceID, contentID, storeID); } }
java
@PUT public Response putContent(@PathParam("spaceID") String spaceID, @PathParam("contentID") String contentID, @QueryParam("storeID") String storeID, @HeaderParam(COPY_SOURCE_HEADER) String copySource, @HeaderParam(COPY_SOURCE_STORE_HEADER) String sourceStoreID) { if (null != copySource) { return copyContent(spaceID, contentID, storeID, sourceStoreID, copySource); } else { return addContent(spaceID, contentID, storeID); } }
[ "@", "PUT", "public", "Response", "putContent", "(", "@", "PathParam", "(", "\"spaceID\"", ")", "String", "spaceID", ",", "@", "PathParam", "(", "\"contentID\"", ")", "String", "contentID", ",", "@", "QueryParam", "(", "\"storeID\"", ")", "String", "storeID", ...
see ContentResource.addContent() and ContentResource.copyContent(). @return 201 response indicating content added/copied successfully
[ "see", "ContentResource", ".", "addContent", "()", "and", "ContentResource", ".", "copyContent", "()", "." ]
train
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/durastore/src/main/java/org/duracloud/durastore/rest/ContentRest.java#L396-L408
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.getEntitySuggestionsAsync
public Observable<List<EntitiesSuggestionExample>> getEntitySuggestionsAsync(UUID appId, String versionId, UUID entityId, GetEntitySuggestionsOptionalParameter getEntitySuggestionsOptionalParameter) { return getEntitySuggestionsWithServiceResponseAsync(appId, versionId, entityId, getEntitySuggestionsOptionalParameter).map(new Func1<ServiceResponse<List<EntitiesSuggestionExample>>, List<EntitiesSuggestionExample>>() { @Override public List<EntitiesSuggestionExample> call(ServiceResponse<List<EntitiesSuggestionExample>> response) { return response.body(); } }); }
java
public Observable<List<EntitiesSuggestionExample>> getEntitySuggestionsAsync(UUID appId, String versionId, UUID entityId, GetEntitySuggestionsOptionalParameter getEntitySuggestionsOptionalParameter) { return getEntitySuggestionsWithServiceResponseAsync(appId, versionId, entityId, getEntitySuggestionsOptionalParameter).map(new Func1<ServiceResponse<List<EntitiesSuggestionExample>>, List<EntitiesSuggestionExample>>() { @Override public List<EntitiesSuggestionExample> call(ServiceResponse<List<EntitiesSuggestionExample>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "EntitiesSuggestionExample", ">", ">", "getEntitySuggestionsAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "GetEntitySuggestionsOptionalParameter", "getEntitySuggestionsOptionalParameter", ")...
Get suggestion examples that would improve the accuracy of the entity model. @param appId The application ID. @param versionId The version ID. @param entityId The target entity extractor model to enhance. @param getEntitySuggestionsOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;EntitiesSuggestionExample&gt; object
[ "Get", "suggestion", "examples", "that", "would", "improve", "the", "accuracy", "of", "the", "entity", "model", "." ]
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#L5287-L5294
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java
Util.copyFile
public static int copyFile(String from, String to) { InputStream inStream = null; FileOutputStream fs = null; try { int bytesum = 0; int byteread; File oldfile = new File(from); if (oldfile.exists()) { inStream = new FileInputStream(from); fs = new FileOutputStream(to); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } } return bytesum; } catch (Exception e) { return 0; } finally { Util.ensureClosed(inStream); Util.ensureClosed(fs); } }
java
public static int copyFile(String from, String to) { InputStream inStream = null; FileOutputStream fs = null; try { int bytesum = 0; int byteread; File oldfile = new File(from); if (oldfile.exists()) { inStream = new FileInputStream(from); fs = new FileOutputStream(to); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } } return bytesum; } catch (Exception e) { return 0; } finally { Util.ensureClosed(inStream); Util.ensureClosed(fs); } }
[ "public", "static", "int", "copyFile", "(", "String", "from", ",", "String", "to", ")", "{", "InputStream", "inStream", "=", "null", ";", "FileOutputStream", "fs", "=", "null", ";", "try", "{", "int", "bytesum", "=", "0", ";", "int", "byteread", ";", "...
This function copies file from one location to another @param from the full path to the source file @param to the full path to the destination file @return total bytes copied. 0 indicates
[ "This", "function", "copies", "file", "from", "one", "location", "to", "another" ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L705-L728
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java
CPMeasurementUnitPersistenceImpl.findAll
@Override public List<CPMeasurementUnit> findAll(int start, int end) { return findAll(start, end, null); }
java
@Override public List<CPMeasurementUnit> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CPMeasurementUnit", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the cp measurement units. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPMeasurementUnitModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of cp measurement units @param end the upper bound of the range of cp measurement units (not inclusive) @return the range of cp measurement units
[ "Returns", "a", "range", "of", "all", "the", "cp", "measurement", "units", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L4146-L4149
dottydingo/hyperion
core/src/main/java/com/dottydingo/hyperion/core/endpoint/pipeline/phase/CreatePhase.java
CreatePhase.processLegacyRequest
protected void processLegacyRequest(HyperionContext hyperionContext) { EndpointRequest request = hyperionContext.getEndpointRequest(); EndpointResponse response = hyperionContext.getEndpointResponse(); ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin(); EntityPlugin plugin = hyperionContext.getEntityPlugin(); ApiObject clientObject = null; try { clientObject = marshaller.unmarshall(request.getInputStream(),apiVersionPlugin.getApiClass()); } catch (MarshallingException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e); } clientObject.setId(null); PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext); Set<String> fieldSet = persistenceContext.getRequestedFields(); if(fieldSet != null) fieldSet.add("id"); ApiObject saved = (ApiObject) plugin.getPersistenceOperations().createOrUpdateItems( Collections.singletonList(clientObject), persistenceContext).get(0); processChangeEvents(hyperionContext, persistenceContext); response.setResponseCode(200); hyperionContext.setResult(saved); }
java
protected void processLegacyRequest(HyperionContext hyperionContext) { EndpointRequest request = hyperionContext.getEndpointRequest(); EndpointResponse response = hyperionContext.getEndpointResponse(); ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin(); EntityPlugin plugin = hyperionContext.getEntityPlugin(); ApiObject clientObject = null; try { clientObject = marshaller.unmarshall(request.getInputStream(),apiVersionPlugin.getApiClass()); } catch (MarshallingException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e); } clientObject.setId(null); PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext); Set<String> fieldSet = persistenceContext.getRequestedFields(); if(fieldSet != null) fieldSet.add("id"); ApiObject saved = (ApiObject) plugin.getPersistenceOperations().createOrUpdateItems( Collections.singletonList(clientObject), persistenceContext).get(0); processChangeEvents(hyperionContext, persistenceContext); response.setResponseCode(200); hyperionContext.setResult(saved); }
[ "protected", "void", "processLegacyRequest", "(", "HyperionContext", "hyperionContext", ")", "{", "EndpointRequest", "request", "=", "hyperionContext", ".", "getEndpointRequest", "(", ")", ";", "EndpointResponse", "response", "=", "hyperionContext", ".", "getEndpointRespo...
Process a legacy V1 request (single item) @param hyperionContext The context
[ "Process", "a", "legacy", "V1", "request", "(", "single", "item", ")" ]
train
https://github.com/dottydingo/hyperion/blob/c4d119c90024a88c0335d7d318e9ccdb70149764/core/src/main/java/com/dottydingo/hyperion/core/endpoint/pipeline/phase/CreatePhase.java#L48-L79
networknt/light-4j
client/src/main/java/org/apache/hc/core5/util/copied/CharArrayBuffer.java
CharArrayBuffer.substringTrimmed
public String substringTrimmed(final int beginIndex, final int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); } int beginIndex0 = beginIndex; int endIndex0 = endIndex; while (beginIndex0 < endIndex && isWhitespace(this.array[beginIndex0])) { beginIndex0++; } while (endIndex0 > beginIndex0 && isWhitespace(this.array[endIndex0 - 1])) { endIndex0--; } return new String(this.array, beginIndex0, endIndex0 - beginIndex0); }
java
public String substringTrimmed(final int beginIndex, final int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: " + beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: " + endIndex + " > length: " + this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: " + beginIndex + " > endIndex: " + endIndex); } int beginIndex0 = beginIndex; int endIndex0 = endIndex; while (beginIndex0 < endIndex && isWhitespace(this.array[beginIndex0])) { beginIndex0++; } while (endIndex0 > beginIndex0 && isWhitespace(this.array[endIndex0 - 1])) { endIndex0--; } return new String(this.array, beginIndex0, endIndex0 - beginIndex0); }
[ "public", "String", "substringTrimmed", "(", "final", "int", "beginIndex", ",", "final", "int", "endIndex", ")", "{", "if", "(", "beginIndex", "<", "0", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "\"Negative beginIndex: \"", "+", "beginIndex", "...
Returns a substring of this buffer with leading and trailing whitespace omitted. The substring begins with the first non-whitespace character from {@code beginIndex} and extends to the last non-whitespace character with the index lesser than {@code endIndex}. @param beginIndex the beginning index, inclusive. @param endIndex the ending index, exclusive. @return the specified substring. @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or {@code endIndex} is larger than the length of this buffer, or {@code beginIndex} is larger than {@code endIndex}.
[ "Returns", "a", "substring", "of", "this", "buffer", "with", "leading", "and", "trailing", "whitespace", "omitted", ".", "The", "substring", "begins", "with", "the", "first", "non", "-", "whitespace", "character", "from", "{", "@code", "beginIndex", "}", "and"...
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/client/src/main/java/org/apache/hc/core5/util/copied/CharArrayBuffer.java#L452-L471
jbundle/jbundle
thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/memory/MemoryRemoteTable.java
MemoryRemoteTable.doSetHandle
public Object doSetHandle(Object bookmark, int iOpenMode, String strFields, int iHandleType) throws DBException, RemoteException { return this.seek(null, 0, null, strFields, bookmark); }
java
public Object doSetHandle(Object bookmark, int iOpenMode, String strFields, int iHandleType) throws DBException, RemoteException { return this.seek(null, 0, null, strFields, bookmark); }
[ "public", "Object", "doSetHandle", "(", "Object", "bookmark", ",", "int", "iOpenMode", ",", "String", "strFields", ",", "int", "iHandleType", ")", "throws", "DBException", ",", "RemoteException", "{", "return", "this", ".", "seek", "(", "null", ",", "0", ","...
Reposition to this record using this bookmark. <p />In the thin implementation, you can only read using the primary key as the bookmark. JiniTables can't access the datasource on the server, so they must use the bookmark.
[ "Reposition", "to", "this", "record", "using", "this", "bookmark", ".", "<p", "/", ">", "In", "the", "thin", "implementation", "you", "can", "only", "read", "using", "the", "primary", "key", "as", "the", "bookmark", ".", "JiniTables", "can", "t", "access",...
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/misc/src/main/java/org/jbundle/thin/base/db/client/memory/MemoryRemoteTable.java#L226-L229
bozaro/git-lfs-java
gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java
Client.putObject
public boolean putObject(@NotNull final StreamProvider streamProvider, @NotNull final Meta meta) throws IOException { return doWork(auth -> { final ObjectRes links = doRequest(auth, new MetaPost(meta), AuthHelper.join(auth.getHref(), PATH_OBJECTS)); return links != null && putObject(streamProvider, meta, links); }, Operation.Upload); }
java
public boolean putObject(@NotNull final StreamProvider streamProvider, @NotNull final Meta meta) throws IOException { return doWork(auth -> { final ObjectRes links = doRequest(auth, new MetaPost(meta), AuthHelper.join(auth.getHref(), PATH_OBJECTS)); return links != null && putObject(streamProvider, meta, links); }, Operation.Upload); }
[ "public", "boolean", "putObject", "(", "@", "NotNull", "final", "StreamProvider", "streamProvider", ",", "@", "NotNull", "final", "Meta", "meta", ")", "throws", "IOException", "{", "return", "doWork", "(", "auth", "->", "{", "final", "ObjectRes", "links", "=",...
Upload object with specified hash and size. @param streamProvider Object stream provider. @param meta Object metadata. @return Return true is object is uploaded successfully and false if object is already uploaded. @throws IOException On some errors.
[ "Upload", "object", "with", "specified", "hash", "and", "size", "." ]
train
https://github.com/bozaro/git-lfs-java/blob/ee05bf0472ee61bf362cf93d283e5ee5d44ef685/gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java#L214-L219
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternToken.java
PatternToken.compile
public PatternToken compile(AnalyzedTokenReadings token, Synthesizer synth) throws IOException { PatternToken compiledPatternToken; try { compiledPatternToken = (PatternToken) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Could not clone element", e); } compiledPatternToken.doCompile(token, synth); return compiledPatternToken; }
java
public PatternToken compile(AnalyzedTokenReadings token, Synthesizer synth) throws IOException { PatternToken compiledPatternToken; try { compiledPatternToken = (PatternToken) clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Could not clone element", e); } compiledPatternToken.doCompile(token, synth); return compiledPatternToken; }
[ "public", "PatternToken", "compile", "(", "AnalyzedTokenReadings", "token", ",", "Synthesizer", "synth", ")", "throws", "IOException", "{", "PatternToken", "compiledPatternToken", ";", "try", "{", "compiledPatternToken", "=", "(", "PatternToken", ")", "clone", "(", ...
Prepare PatternToken for matching by formatting its string token and POS (if the Element is supposed to refer to some other token). @param token the token specified as {@link AnalyzedTokenReadings} @param synth the language synthesizer ({@link Synthesizer})
[ "Prepare", "PatternToken", "for", "matching", "by", "formatting", "its", "string", "token", "and", "POS", "(", "if", "the", "Element", "is", "supposed", "to", "refer", "to", "some", "other", "token", ")", "." ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/PatternToken.java#L526-L535
davidcarboni/cryptolite-java
src/main/java/com/github/davidcarboni/cryptolite/DigitalSignature.java
DigitalSignature.verify
public boolean verify(String content, PublicKey publicKey, String signature) { byte[] bytes = content.getBytes(StandardCharsets.UTF_8); InputStream input = new ByteArrayInputStream(bytes); return verify(input, publicKey, signature); // ByteArrayInputStream does not need to be closed. }
java
public boolean verify(String content, PublicKey publicKey, String signature) { byte[] bytes = content.getBytes(StandardCharsets.UTF_8); InputStream input = new ByteArrayInputStream(bytes); return verify(input, publicKey, signature); // ByteArrayInputStream does not need to be closed. }
[ "public", "boolean", "verify", "(", "String", "content", ",", "PublicKey", "publicKey", ",", "String", "signature", ")", "{", "byte", "[", "]", "bytes", "=", "content", ".", "getBytes", "(", "StandardCharsets", ".", "UTF_8", ")", ";", "InputStream", "input",...
Verifies whether the given content matches the given signature. @param content The content to be verified. @param publicKey The public key to use in the verification process. @param signature The signature with which the content is to be verified. This can be obtained via {@link Keys#newKeyPair()}. @return If the content matches the given signature, using the given key, true.
[ "Verifies", "whether", "the", "given", "content", "matches", "the", "given", "signature", "." ]
train
https://github.com/davidcarboni/cryptolite-java/blob/e67954181a04ffc9beb1d9abca1421195fcf9764/src/main/java/com/github/davidcarboni/cryptolite/DigitalSignature.java#L113-L120
maxirosson/jdroid-android
jdroid-android-core/src/main/java/com/jdroid/android/activity/ActivityLauncher.java
ActivityLauncher.startActivity
public static void startActivity(@Nullable Activity activity, Class<? extends Activity> targetActivityClass) { if (activity != null) { if (activity.getClass() != targetActivityClass) { Intent intent = new Intent(activity, targetActivityClass); activity.startActivity(intent); } } else { LOGGER.warn("Null activity. Ignoring launch of " + targetActivityClass.getSimpleName()); } }
java
public static void startActivity(@Nullable Activity activity, Class<? extends Activity> targetActivityClass) { if (activity != null) { if (activity.getClass() != targetActivityClass) { Intent intent = new Intent(activity, targetActivityClass); activity.startActivity(intent); } } else { LOGGER.warn("Null activity. Ignoring launch of " + targetActivityClass.getSimpleName()); } }
[ "public", "static", "void", "startActivity", "(", "@", "Nullable", "Activity", "activity", ",", "Class", "<", "?", "extends", "Activity", ">", "targetActivityClass", ")", "{", "if", "(", "activity", "!=", "null", ")", "{", "if", "(", "activity", ".", "getC...
Launches a new {@link Activity} @param targetActivityClass The target {@link Activity} class to launch
[ "Launches", "a", "new", "{", "@link", "Activity", "}" ]
train
https://github.com/maxirosson/jdroid-android/blob/1ba9cae56a16fa36bdb2c9c04379853f0300707f/jdroid-android-core/src/main/java/com/jdroid/android/activity/ActivityLauncher.java#L84-L93
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectStreamClass.java
ObjectStreamClass.findMethod
static Method findMethod(Class<?> cl, String methodName) { Class<?> search = cl; Method method = null; while (search != null) { try { method = search.getDeclaredMethod(methodName, (Class[]) null); if (search == cl || (method.getModifiers() & Modifier.PRIVATE) == 0) { method.setAccessible(true); return method; } } catch (NoSuchMethodException nsm) { } search = search.getSuperclass(); } return null; }
java
static Method findMethod(Class<?> cl, String methodName) { Class<?> search = cl; Method method = null; while (search != null) { try { method = search.getDeclaredMethod(methodName, (Class[]) null); if (search == cl || (method.getModifiers() & Modifier.PRIVATE) == 0) { method.setAccessible(true); return method; } } catch (NoSuchMethodException nsm) { } search = search.getSuperclass(); } return null; }
[ "static", "Method", "findMethod", "(", "Class", "<", "?", ">", "cl", ",", "String", "methodName", ")", "{", "Class", "<", "?", ">", "search", "=", "cl", ";", "Method", "method", "=", "null", ";", "while", "(", "search", "!=", "null", ")", "{", "try...
Return the java.lang.reflect.Method if class <code>cl</code> implements <code>methodName</code> . Return null otherwise. @param cl a java.lang.Class which to test @return <code>java.lang.reflect.Method</code> if the class implements writeReplace <code>null</code> if the class does not implement writeReplace
[ "Return", "the", "java", ".", "lang", ".", "reflect", ".", "Method", "if", "class", "<code", ">", "cl<", "/", "code", ">", "implements", "<code", ">", "methodName<", "/", "code", ">", ".", "Return", "null", "otherwise", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/ObjectStreamClass.java#L1145-L1161
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/mathematics/regularization/L2Regularizer.java
L2Regularizer.updateWeights
public static <K> void updateWeights(double l2, double learningRate, Map<K, Double> weights, Map<K, Double> newWeights) { if(l2 > 0.0) { for(Map.Entry<K, Double> e : weights.entrySet()) { K column = e.getKey(); newWeights.put(column, newWeights.get(column) + l2*e.getValue()*(-learningRate)); } } }
java
public static <K> void updateWeights(double l2, double learningRate, Map<K, Double> weights, Map<K, Double> newWeights) { if(l2 > 0.0) { for(Map.Entry<K, Double> e : weights.entrySet()) { K column = e.getKey(); newWeights.put(column, newWeights.get(column) + l2*e.getValue()*(-learningRate)); } } }
[ "public", "static", "<", "K", ">", "void", "updateWeights", "(", "double", "l2", ",", "double", "learningRate", ",", "Map", "<", "K", ",", "Double", ">", "weights", ",", "Map", "<", "K", ",", "Double", ">", "newWeights", ")", "{", "if", "(", "l2", ...
Updates the weights by applying the L2 regularization. @param l2 @param learningRate @param weights @param newWeights @param <K>
[ "Updates", "the", "weights", "by", "applying", "the", "L2", "regularization", "." ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/mathematics/regularization/L2Regularizer.java#L36-L43
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/tracker/circulant/CirculantTracker.java
CirculantTracker.updateTrackLocation
protected void updateTrackLocation(T image) { get_subwindow(image, templateNew); // calculate response of the classifier at all locations // matlab: k = dense_gauss_kernel(sigma, x, z); dense_gauss_kernel(sigma, templateNew, template,k); fft.forward(k,kf); // response = real(ifft2(alphaf .* fft2(k))); %(Eq. 9) DiscreteFourierTransformOps.multiplyComplex(alphaf, kf, tmpFourier0); fft.inverse(tmpFourier0, response); // find the pixel with the largest response int N = response.width*response.height; int indexBest = -1; double valueBest = -1; for( int i = 0; i < N; i++ ) { double v = response.data[i]; if( v > valueBest ) { valueBest = v; indexBest = i; } } int peakX = indexBest % response.width; int peakY = indexBest / response.width; // sub-pixel peak estimation subpixelPeak(peakX, peakY); // peak in region's coordinate system float deltaX = (peakX+offX) - templateNew.width/2; float deltaY = (peakY+offY) - templateNew.height/2; // convert peak location into image coordinate system regionTrack.x0 = regionTrack.x0 + deltaX*stepX; regionTrack.y0 = regionTrack.y0 + deltaY*stepY; updateRegionOut(); }
java
protected void updateTrackLocation(T image) { get_subwindow(image, templateNew); // calculate response of the classifier at all locations // matlab: k = dense_gauss_kernel(sigma, x, z); dense_gauss_kernel(sigma, templateNew, template,k); fft.forward(k,kf); // response = real(ifft2(alphaf .* fft2(k))); %(Eq. 9) DiscreteFourierTransformOps.multiplyComplex(alphaf, kf, tmpFourier0); fft.inverse(tmpFourier0, response); // find the pixel with the largest response int N = response.width*response.height; int indexBest = -1; double valueBest = -1; for( int i = 0; i < N; i++ ) { double v = response.data[i]; if( v > valueBest ) { valueBest = v; indexBest = i; } } int peakX = indexBest % response.width; int peakY = indexBest / response.width; // sub-pixel peak estimation subpixelPeak(peakX, peakY); // peak in region's coordinate system float deltaX = (peakX+offX) - templateNew.width/2; float deltaY = (peakY+offY) - templateNew.height/2; // convert peak location into image coordinate system regionTrack.x0 = regionTrack.x0 + deltaX*stepX; regionTrack.y0 = regionTrack.y0 + deltaY*stepY; updateRegionOut(); }
[ "protected", "void", "updateTrackLocation", "(", "T", "image", ")", "{", "get_subwindow", "(", "image", ",", "templateNew", ")", ";", "// calculate response of the classifier at all locations", "// matlab: k = dense_gauss_kernel(sigma, x, z);", "dense_gauss_kernel", "(", "sigma...
Find the target inside the current image by searching around its last known location
[ "Find", "the", "target", "inside", "the", "current", "image", "by", "searching", "around", "its", "last", "known", "location" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/circulant/CirculantTracker.java#L332-L372
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_GoogleMapLink.java
ST_GoogleMapLink.generateGMLink
public static String generateGMLink(Geometry geom, String layerType, int zoom) { if (geom == null) { return null; } try { LayerType layer = LayerType.valueOf(layerType.toLowerCase()); Coordinate centre = geom.getEnvelopeInternal().centre(); StringBuilder sb = new StringBuilder("https://maps.google.com/maps?ll="); sb.append(centre.y); sb.append(","); sb.append(centre.x); sb.append("&z="); sb.append(zoom); sb.append("&t="); sb.append(layer.name()); return sb.toString(); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Layer type supported are m (normal map) , k (satellite), h (hybrid), p (terrain)", ex); } }
java
public static String generateGMLink(Geometry geom, String layerType, int zoom) { if (geom == null) { return null; } try { LayerType layer = LayerType.valueOf(layerType.toLowerCase()); Coordinate centre = geom.getEnvelopeInternal().centre(); StringBuilder sb = new StringBuilder("https://maps.google.com/maps?ll="); sb.append(centre.y); sb.append(","); sb.append(centre.x); sb.append("&z="); sb.append(zoom); sb.append("&t="); sb.append(layer.name()); return sb.toString(); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException("Layer type supported are m (normal map) , k (satellite), h (hybrid), p (terrain)", ex); } }
[ "public", "static", "String", "generateGMLink", "(", "Geometry", "geom", ",", "String", "layerType", ",", "int", "zoom", ")", "{", "if", "(", "geom", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "LayerType", "layer", "=", "LayerType", ...
Generate a Google Map link URL based on the center of the bounding box of the input geometry. Set the layer type and the zoom level. @param geom @param layerType @param zoom @return
[ "Generate", "a", "Google", "Map", "link", "URL", "based", "on", "the", "center", "of", "the", "bounding", "box", "of", "the", "input", "geometry", ".", "Set", "the", "layer", "type", "and", "the", "zoom", "level", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/convert/ST_GoogleMapLink.java#L78-L97
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/extension/related/RelatedTablesCoreExtension.java
RelatedTablesCoreExtension.addMediaRelationship
public ExtendedRelation addMediaRelationship(String baseTableName, MediaTable mediaTable, String mappingTableName) { return addRelationship(baseTableName, mediaTable, mappingTableName); }
java
public ExtendedRelation addMediaRelationship(String baseTableName, MediaTable mediaTable, String mappingTableName) { return addRelationship(baseTableName, mediaTable, mappingTableName); }
[ "public", "ExtendedRelation", "addMediaRelationship", "(", "String", "baseTableName", ",", "MediaTable", "mediaTable", ",", "String", "mappingTableName", ")", "{", "return", "addRelationship", "(", "baseTableName", ",", "mediaTable", ",", "mappingTableName", ")", ";", ...
Adds a media relationship between the base table and user media related table. Creates a default user mapping table and the media table if needed. @param baseTableName base table name @param mediaTable user media table @param mappingTableName user mapping table name @return The relationship that was added
[ "Adds", "a", "media", "relationship", "between", "the", "base", "table", "and", "user", "media", "related", "table", ".", "Creates", "a", "default", "user", "mapping", "table", "and", "the", "media", "table", "if", "needed", "." ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/related/RelatedTablesCoreExtension.java#L527-L530
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java
PhotosInterface.getImage
public BufferedImage getImage(Photo photo, int size) throws FlickrException { try { return ImageIO.read(getImageAsStream(photo, size)); } catch (IOException e) { throw new FlickrException(e.getMessage(), e.getCause()); } }
java
public BufferedImage getImage(Photo photo, int size) throws FlickrException { try { return ImageIO.read(getImageAsStream(photo, size)); } catch (IOException e) { throw new FlickrException(e.getMessage(), e.getCause()); } }
[ "public", "BufferedImage", "getImage", "(", "Photo", "photo", ",", "int", "size", ")", "throws", "FlickrException", "{", "try", "{", "return", "ImageIO", ".", "read", "(", "getImageAsStream", "(", "photo", ",", "size", ")", ")", ";", "}", "catch", "(", "...
Request an image from the Flickr-servers. <p> At {@link Size} you can find constants for the available sizes. @param photo A photo-object @param size The size @return An Image @throws FlickrException
[ "Request", "an", "image", "from", "the", "Flickr", "-", "servers", ".", "<p", ">" ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java#L1409-L1415
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/LocalDateTime.java
LocalDateTime.plusWeeks
public LocalDateTime plusWeeks(long weeks) { LocalDate newDate = date.plusWeeks(weeks); return with(newDate, time); }
java
public LocalDateTime plusWeeks(long weeks) { LocalDate newDate = date.plusWeeks(weeks); return with(newDate, time); }
[ "public", "LocalDateTime", "plusWeeks", "(", "long", "weeks", ")", "{", "LocalDate", "newDate", "=", "date", ".", "plusWeeks", "(", "weeks", ")", ";", "return", "with", "(", "newDate", ",", "time", ")", ";", "}" ]
Returns a copy of this {@code LocalDateTime} with the specified number of weeks added. <p> This method adds the specified amount in weeks to the days field incrementing the month and year fields as necessary to ensure the result remains valid. The result is only invalid if the maximum/minimum year is exceeded. <p> For example, 2008-12-31 plus one week would result in 2009-01-07. <p> This instance is immutable and unaffected by this method call. @param weeks the weeks to add, may be negative @return a {@code LocalDateTime} based on this date-time with the weeks added, not null @throws DateTimeException if the result exceeds the supported date range
[ "Returns", "a", "copy", "of", "this", "{", "@code", "LocalDateTime", "}", "with", "the", "specified", "number", "of", "weeks", "added", ".", "<p", ">", "This", "method", "adds", "the", "specified", "amount", "in", "weeks", "to", "the", "days", "field", "...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/LocalDateTime.java#L1259-L1262
janus-project/guava.janusproject.io
guava/src/com/google/common/base/Joiner.java
Joiner.appendTo
public final <A extends Appendable> A appendTo(A appendable, Object[] parts) throws IOException { return appendTo(appendable, Arrays.asList(parts)); }
java
public final <A extends Appendable> A appendTo(A appendable, Object[] parts) throws IOException { return appendTo(appendable, Arrays.asList(parts)); }
[ "public", "final", "<", "A", "extends", "Appendable", ">", "A", "appendTo", "(", "A", "appendable", ",", "Object", "[", "]", "parts", ")", "throws", "IOException", "{", "return", "appendTo", "(", "appendable", ",", "Arrays", ".", "asList", "(", "parts", ...
Appends the string representation of each of {@code parts}, using the previously configured separator between each, to {@code appendable}.
[ "Appends", "the", "string", "representation", "of", "each", "of", "{" ]
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/base/Joiner.java#L121-L123
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnsview_binding.java
dnsview_binding.get
public static dnsview_binding get(nitro_service service, String viewname) throws Exception{ dnsview_binding obj = new dnsview_binding(); obj.set_viewname(viewname); dnsview_binding response = (dnsview_binding) obj.get_resource(service); return response; }
java
public static dnsview_binding get(nitro_service service, String viewname) throws Exception{ dnsview_binding obj = new dnsview_binding(); obj.set_viewname(viewname); dnsview_binding response = (dnsview_binding) obj.get_resource(service); return response; }
[ "public", "static", "dnsview_binding", "get", "(", "nitro_service", "service", ",", "String", "viewname", ")", "throws", "Exception", "{", "dnsview_binding", "obj", "=", "new", "dnsview_binding", "(", ")", ";", "obj", ".", "set_viewname", "(", "viewname", ")", ...
Use this API to fetch dnsview_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "dnsview_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/dns/dnsview_binding.java#L114-L119
mboudreau/Alternator
src/main/java/com/amazonaws/services/dynamodb/model/DeleteItemResult.java
DeleteItemResult.withAttributes
public DeleteItemResult withAttributes(java.util.Map<String,AttributeValue> attributes) { setAttributes(attributes); return this; }
java
public DeleteItemResult withAttributes(java.util.Map<String,AttributeValue> attributes) { setAttributes(attributes); return this; }
[ "public", "DeleteItemResult", "withAttributes", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "AttributeValue", ">", "attributes", ")", "{", "setAttributes", "(", "attributes", ")", ";", "return", "this", ";", "}" ]
If the <code>ReturnValues</code> parameter is provided as <code>ALL_OLD</code> in the request, Amazon DynamoDB returns an array of attribute name-value pairs (essentially, the deleted item). Otherwise, the response contains an empty set. <p> Returns a reference to this object so that method calls can be chained together. @param attributes If the <code>ReturnValues</code> parameter is provided as <code>ALL_OLD</code> in the request, Amazon DynamoDB returns an array of attribute name-value pairs (essentially, the deleted item). Otherwise, the response contains an empty set. @return A reference to this updated object so that method calls can be chained together.
[ "If", "the", "<code", ">", "ReturnValues<", "/", "code", ">", "parameter", "is", "provided", "as", "<code", ">", "ALL_OLD<", "/", "code", ">", "in", "the", "request", "Amazon", "DynamoDB", "returns", "an", "array", "of", "attribute", "name", "-", "value", ...
train
https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/model/DeleteItemResult.java#L92-L95
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/config/UserPreferences.java
UserPreferences.setCustomPlugins
public void setCustomPlugins(Map<String, Boolean> customPlugins) { if (customPlugins == null) { throw new IllegalArgumentException("customPlugins may not be null."); } this.customPlugins = customPlugins; }
java
public void setCustomPlugins(Map<String, Boolean> customPlugins) { if (customPlugins == null) { throw new IllegalArgumentException("customPlugins may not be null."); } this.customPlugins = customPlugins; }
[ "public", "void", "setCustomPlugins", "(", "Map", "<", "String", ",", "Boolean", ">", "customPlugins", ")", "{", "if", "(", "customPlugins", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"customPlugins may not be null.\"", ")", ";", ...
Additional plugins which could be used by {@link IFindBugsEngine} (if enabled), or which shouldn't be used (if disabled). If a plugin is not included in the set, it's enablement depends on it's default settings. @param customPlugins map with additional third party plugin locations (as absolute paths), never null, but might be empty @see Plugin#isCorePlugin() @see Plugin#isGloballyEnabled()
[ "Additional", "plugins", "which", "could", "be", "used", "by", "{", "@link", "IFindBugsEngine", "}", "(", "if", "enabled", ")", "or", "which", "shouldn", "t", "be", "used", "(", "if", "disabled", ")", ".", "If", "a", "plugin", "is", "not", "included", ...
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/config/UserPreferences.java#L593-L598
eclipse/hawkbit
hawkbit-rest/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java
MgmtDownloadArtifactResource.downloadArtifact
@Override public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("artifactId") final Long artifactId) { final SoftwareModule module = softwareModuleManagement.get(softwareModuleId) .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId)); final Artifact artifact = module.getArtifact(artifactId) .orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId)); final AbstractDbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash()) .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash())); final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest(); final String ifMatch = request.getHeader(HttpHeaders.IF_MATCH); if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); } return FileStreamingUtil.writeFileResponse(file, artifact.getFilename(), artifact.getCreatedAt(), requestResponseContextHolder.getHttpServletResponse(), request, null); }
java
@Override public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("artifactId") final Long artifactId) { final SoftwareModule module = softwareModuleManagement.get(softwareModuleId) .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId)); final Artifact artifact = module.getArtifact(artifactId) .orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId)); final AbstractDbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash()) .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash())); final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest(); final String ifMatch = request.getHeader(HttpHeaders.IF_MATCH); if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); } return FileStreamingUtil.writeFileResponse(file, artifact.getFilename(), artifact.getCreatedAt(), requestResponseContextHolder.getHttpServletResponse(), request, null); }
[ "@", "Override", "public", "ResponseEntity", "<", "InputStream", ">", "downloadArtifact", "(", "@", "PathVariable", "(", "\"softwareModuleId\"", ")", "final", "Long", "softwareModuleId", ",", "@", "PathVariable", "(", "\"artifactId\"", ")", "final", "Long", "artifac...
Handles the GET request for downloading an artifact. @param softwareModuleId of the parent SoftwareModule @param artifactId of the related Artifact @return responseEntity with status ok if successful
[ "Handles", "the", "GET", "request", "for", "downloading", "an", "artifact", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-rest/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java#L60-L79
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_portability_id_cancel_POST
public void billingAccount_portability_id_cancel_POST(String billingAccount, Long id, String reason) throws IOException { String qPath = "/telephony/{billingAccount}/portability/{id}/cancel"; StringBuilder sb = path(qPath, billingAccount, id); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "reason", reason); exec(qPath, "POST", sb.toString(), o); }
java
public void billingAccount_portability_id_cancel_POST(String billingAccount, Long id, String reason) throws IOException { String qPath = "/telephony/{billingAccount}/portability/{id}/cancel"; StringBuilder sb = path(qPath, billingAccount, id); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "reason", reason); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "billingAccount_portability_id_cancel_POST", "(", "String", "billingAccount", ",", "Long", "id", ",", "String", "reason", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/portability/{id}/cancel\"", ";", "StringBuil...
Ask to cancel the portability REST: POST /telephony/{billingAccount}/portability/{id}/cancel @param reason [required] The cancellation reason @param billingAccount [required] The name of your billingAccount @param id [required] The ID of the portability
[ "Ask", "to", "cancel", "the", "portability" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L359-L365
threerings/nenya
tools/src/main/java/com/threerings/media/tile/tools/xml/XMLTileSetParser.java
XMLTileSetParser.loadTileSets
public void loadTileSets (File file, Map<String, TileSet> tilesets) throws IOException { // load up the tilesets loadTileSets(new FileInputStream(file), tilesets); }
java
public void loadTileSets (File file, Map<String, TileSet> tilesets) throws IOException { // load up the tilesets loadTileSets(new FileInputStream(file), tilesets); }
[ "public", "void", "loadTileSets", "(", "File", "file", ",", "Map", "<", "String", ",", "TileSet", ">", "tilesets", ")", "throws", "IOException", "{", "// load up the tilesets", "loadTileSets", "(", "new", "FileInputStream", "(", "file", ")", ",", "tilesets", "...
Loads all of the tilesets specified in the supplied XML tileset description file and places them into the supplied map indexed by tileset name. This method is not reentrant, so don't go calling it from multiple threads. @param file the file in which the tileset definition file can be found. @param tilesets the map into which the tilesets will be placed, indexed by tileset name.
[ "Loads", "all", "of", "the", "tilesets", "specified", "in", "the", "supplied", "XML", "tileset", "description", "file", "and", "places", "them", "into", "the", "supplied", "map", "indexed", "by", "tileset", "name", ".", "This", "method", "is", "not", "reentr...
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/tools/src/main/java/com/threerings/media/tile/tools/xml/XMLTileSetParser.java#L123-L128
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.writeUser
public void writeUser(CmsRequestContext context, CmsUser user) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(user.getName())); checkRoleForUserModification(dbc, user.getName(), role); m_driverManager.writeUser(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_USER_1, user.getName()), e); } finally { dbc.clear(); } }
java
public void writeUser(CmsRequestContext context, CmsUser user) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(user.getName())); checkRoleForUserModification(dbc, user.getName(), role); m_driverManager.writeUser(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_USER_1, user.getName()), e); } finally { dbc.clear(); } }
[ "public", "void", "writeUser", "(", "CmsRequestContext", "context", ",", "CmsUser", "user", ")", "throws", "CmsException", ",", "CmsRoleViolationException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "try", ...
Updates the user information. <p> The user id has to be a valid OpenCms user id.<br> The user with the given id will be completely overridden by the given data.<p> @param context the current request context @param user the user to be updated @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} for the current project @throws CmsException if operation was not successful
[ "Updates", "the", "user", "information", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6992-L7004
canoo/dolphin-platform
platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/Assert.java
Assert.requireNonNullEntries
public static <T, L extends List<T>> L requireNonNullEntries(final L collection, final String argumentName) { requireNonNull(collection, argumentName); final String msg = String.format(NOT_NULL_ENTRIES_MSG_FORMAT, argumentName); for (final Object value : collection) { requireState(value != null, msg); } return collection; }
java
public static <T, L extends List<T>> L requireNonNullEntries(final L collection, final String argumentName) { requireNonNull(collection, argumentName); final String msg = String.format(NOT_NULL_ENTRIES_MSG_FORMAT, argumentName); for (final Object value : collection) { requireState(value != null, msg); } return collection; }
[ "public", "static", "<", "T", ",", "L", "extends", "List", "<", "T", ">", ">", "L", "requireNonNullEntries", "(", "final", "L", "collection", ",", "final", "String", "argumentName", ")", "{", "requireNonNull", "(", "collection", ",", "argumentName", ")", "...
Checks whether the specified {@code collection} contains null values, throws {@link IllegalStateException} with a customized error message if it has. @param collection the collection to be checked. @param argumentName the name of the argument to be used in the error message. @return the {@code collection}. @throws java.lang.NullPointerException if {@code collection} is null. @throws java.lang.IllegalStateException if {@code collection} contains null values. @see #requireNonNull(Object, String)
[ "Checks", "whether", "the", "specified", "{", "@code", "collection", "}", "contains", "null", "values", "throws", "{", "@link", "IllegalStateException", "}", "with", "a", "customized", "error", "message", "if", "it", "has", "." ]
train
https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/Assert.java#L106-L113
lightblueseas/swing-components
src/main/java/de/alpharogroup/layout/ScreenSizeExtensions.java
ScreenSizeExtensions.getScreenDimension
public static Dimension getScreenDimension(Component component) { int screenID = getScreenID(component); Dimension dimension = new Dimension(0, 0); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsConfiguration defaultConfiguration = ge.getScreenDevices()[screenID] .getDefaultConfiguration(); Rectangle rectangle = defaultConfiguration.getBounds(); dimension.setSize(rectangle.getWidth(), rectangle.getHeight()); return dimension; }
java
public static Dimension getScreenDimension(Component component) { int screenID = getScreenID(component); Dimension dimension = new Dimension(0, 0); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsConfiguration defaultConfiguration = ge.getScreenDevices()[screenID] .getDefaultConfiguration(); Rectangle rectangle = defaultConfiguration.getBounds(); dimension.setSize(rectangle.getWidth(), rectangle.getHeight()); return dimension; }
[ "public", "static", "Dimension", "getScreenDimension", "(", "Component", "component", ")", "{", "int", "screenID", "=", "getScreenID", "(", "component", ")", ";", "Dimension", "dimension", "=", "new", "Dimension", "(", "0", ",", "0", ")", ";", "GraphicsEnviron...
Gets the screen dimension. @param component the component @return the screen dimension
[ "Gets", "the", "screen", "dimension", "." ]
train
https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/layout/ScreenSizeExtensions.java#L174-L185
mnlipp/jgrapes
org.jgrapes.io/src/org/jgrapes/io/FileStorage.java
FileStorage.onStreamFile
@Handler @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.AccessorClassGeneration", "PMD.AvoidDuplicateLiterals" }) public void onStreamFile(StreamFile event) throws InterruptedException { if (Arrays.asList(event.options()) .contains(StandardOpenOption.WRITE)) { throw new IllegalArgumentException( "Cannot stream file opened for writing."); } for (IOSubchannel channel : event.channels(IOSubchannel.class)) { if (inputWriters.containsKey(channel)) { channel.respond(new IOError(event, new IllegalStateException("File is already open."))); } else { new FileStreamer(event, channel); } } }
java
@Handler @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.AccessorClassGeneration", "PMD.AvoidDuplicateLiterals" }) public void onStreamFile(StreamFile event) throws InterruptedException { if (Arrays.asList(event.options()) .contains(StandardOpenOption.WRITE)) { throw new IllegalArgumentException( "Cannot stream file opened for writing."); } for (IOSubchannel channel : event.channels(IOSubchannel.class)) { if (inputWriters.containsKey(channel)) { channel.respond(new IOError(event, new IllegalStateException("File is already open."))); } else { new FileStreamer(event, channel); } } }
[ "@", "Handler", "@", "SuppressWarnings", "(", "{", "\"PMD.AvoidInstantiatingObjectsInLoops\"", ",", "\"PMD.AccessorClassGeneration\"", ",", "\"PMD.AvoidDuplicateLiterals\"", "}", ")", "public", "void", "onStreamFile", "(", "StreamFile", "event", ")", "throws", "InterruptedE...
Opens a file for reading using the properties of the event and streams its content as a sequence of {@link Output} events with the end of record flag set in the last event. All generated events are considered responses to this event and therefore fired using the event processor from the event's I/O subchannel. @param event the event @throws InterruptedException if the execution was interrupted
[ "Opens", "a", "file", "for", "reading", "using", "the", "properties", "of", "the", "event", "and", "streams", "its", "content", "as", "a", "sequence", "of", "{", "@link", "Output", "}", "events", "with", "the", "end", "of", "record", "flag", "set", "in",...
train
https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/io/FileStorage.java#L103-L121
phax/ph-schedule
ph-mini-quartz/src/main/java/com/helger/quartz/impl/StdScheduler.java
StdScheduler.rescheduleJob
public Date rescheduleJob (final TriggerKey triggerKey, final ITrigger newTrigger) throws SchedulerException { return m_aSched.rescheduleJob (triggerKey, newTrigger); }
java
public Date rescheduleJob (final TriggerKey triggerKey, final ITrigger newTrigger) throws SchedulerException { return m_aSched.rescheduleJob (triggerKey, newTrigger); }
[ "public", "Date", "rescheduleJob", "(", "final", "TriggerKey", "triggerKey", ",", "final", "ITrigger", "newTrigger", ")", "throws", "SchedulerException", "{", "return", "m_aSched", ".", "rescheduleJob", "(", "triggerKey", ",", "newTrigger", ")", ";", "}" ]
<p> Calls the equivalent method on the 'proxied' <code>QuartzScheduler</code>. </p>
[ "<p", ">", "Calls", "the", "equivalent", "method", "on", "the", "proxied", "<code", ">", "QuartzScheduler<", "/", "code", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/impl/StdScheduler.java#L329-L332
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLClassAssertionAxiomImpl_CustomFieldSerializer.java
OWLClassAssertionAxiomImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLClassAssertionAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLClassAssertionAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLClassAssertionAxiomImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", "}" ]
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLClassAssertionAxiomImpl_CustomFieldSerializer.java#L98-L101
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.toSorted
public static <K, V> Map<K, V> toSorted(Map<K, V> self) { return toSorted(self, new NumberAwareValueComparator<K, V>()); }
java
public static <K, V> Map<K, V> toSorted(Map<K, V> self) { return toSorted(self, new NumberAwareValueComparator<K, V>()); }
[ "public", "static", "<", "K", ",", "V", ">", "Map", "<", "K", ",", "V", ">", "toSorted", "(", "Map", "<", "K", ",", "V", ">", "self", ")", "{", "return", "toSorted", "(", "self", ",", "new", "NumberAwareValueComparator", "<", "K", ",", "V", ">", ...
Sorts the elements from the given map into a new ordered map using a {@link NumberAwareComparator} on map entry values to determine the resulting order. {@code NumberAwareComparator} has special treatment for numbers but otherwise uses the natural ordering of the Iterator elements. The original map is unchanged. <pre class="groovyTestCase"> def map = [a:5L, b:3, c:6, d:4.0].toSorted() assert map.toString() == '[b:3, d:4.0, a:5, c:6]' </pre> @param self the original unsorted map @return the sorted map @since 2.4.0
[ "Sorts", "the", "elements", "from", "the", "given", "map", "into", "a", "new", "ordered", "map", "using", "a", "{", "@link", "NumberAwareComparator", "}", "on", "map", "entry", "values", "to", "determine", "the", "resulting", "order", ".", "{", "@code", "N...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L9563-L9565
aol/cyclops
cyclops/src/main/java/cyclops/companion/Functions.java
Functions.limitInts
public static Function<? super ReactiveSeq<Integer>, ? extends ReactiveSeq<Integer>> limitInts(long maxSize){ return a->a.ints(i->i,s->s.limit(maxSize)); }
java
public static Function<? super ReactiveSeq<Integer>, ? extends ReactiveSeq<Integer>> limitInts(long maxSize){ return a->a.ints(i->i,s->s.limit(maxSize)); }
[ "public", "static", "Function", "<", "?", "super", "ReactiveSeq", "<", "Integer", ">", ",", "?", "extends", "ReactiveSeq", "<", "Integer", ">", ">", "limitInts", "(", "long", "maxSize", ")", "{", "return", "a", "->", "a", ".", "ints", "(", "i", "->", ...
/* Fluent limit operation using primitive types e.g. <pre> {@code import static cyclops.ReactiveSeq.limitInts; ReactiveSeq.ofInts(1,2,3) .to(limitInts(1)); //[1] } </pre>
[ "/", "*", "Fluent", "limit", "operation", "using", "primitive", "types", "e", ".", "g", ".", "<pre", ">", "{", "@code", "import", "static", "cyclops", ".", "ReactiveSeq", ".", "limitInts", ";" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Functions.java#L221-L224
ManfredTremmel/gwt-bean-validators
gwt-mt-widgets/src/main/java/de/knightsoftnet/mtwidgets/client/ui/widget/SortableIdAndNameRadioButton.java
SortableIdAndNameRadioButton.fillEntries
private void fillEntries(final Collection<T> pids) { this.entries.clear(); final Stream<IdAndNameBean<T>> stream = pids.stream().map(proEnum -> new IdAndNameBean<>(proEnum, this.messages.name(proEnum))); final Stream<IdAndNameBean<T>> sortedStream; if (this.sortOrder == null) { sortedStream = stream; } else { switch (this.sortOrder == null ? null : this.sortOrder) { case ID_ASC: sortedStream = stream.sorted(new IdAndNameIdComperator<T>()); break; case ID_DSC: sortedStream = stream.sorted(Collections.reverseOrder(new IdAndNameIdComperator<T>())); break; case NAME_ASC: sortedStream = stream.sorted(new IdAndNameNameComperator<T>()); break; case NAME_DSC: sortedStream = stream.sorted(Collections.reverseOrder(new IdAndNameNameComperator<T>())); break; default: sortedStream = stream; break; } } this.entries.addAll(sortedStream.collect(Collectors.toList())); this.flowPanel.clear(); this.entries.forEach(entry -> { final RadioButton radioButton = new RadioButton(this.widgetId, entry.getName()); radioButton.setFormValue(Objects.toString(entry.getId())); radioButton.setEnabled(this.enabled); this.flowPanel.add(radioButton); this.idToButtonMap.put(entry.getId(), radioButton); }); }
java
private void fillEntries(final Collection<T> pids) { this.entries.clear(); final Stream<IdAndNameBean<T>> stream = pids.stream().map(proEnum -> new IdAndNameBean<>(proEnum, this.messages.name(proEnum))); final Stream<IdAndNameBean<T>> sortedStream; if (this.sortOrder == null) { sortedStream = stream; } else { switch (this.sortOrder == null ? null : this.sortOrder) { case ID_ASC: sortedStream = stream.sorted(new IdAndNameIdComperator<T>()); break; case ID_DSC: sortedStream = stream.sorted(Collections.reverseOrder(new IdAndNameIdComperator<T>())); break; case NAME_ASC: sortedStream = stream.sorted(new IdAndNameNameComperator<T>()); break; case NAME_DSC: sortedStream = stream.sorted(Collections.reverseOrder(new IdAndNameNameComperator<T>())); break; default: sortedStream = stream; break; } } this.entries.addAll(sortedStream.collect(Collectors.toList())); this.flowPanel.clear(); this.entries.forEach(entry -> { final RadioButton radioButton = new RadioButton(this.widgetId, entry.getName()); radioButton.setFormValue(Objects.toString(entry.getId())); radioButton.setEnabled(this.enabled); this.flowPanel.add(radioButton); this.idToButtonMap.put(entry.getId(), radioButton); }); }
[ "private", "void", "fillEntries", "(", "final", "Collection", "<", "T", ">", "pids", ")", "{", "this", ".", "entries", ".", "clear", "(", ")", ";", "final", "Stream", "<", "IdAndNameBean", "<", "T", ">", ">", "stream", "=", "pids", ".", "stream", "("...
fill entries of the radio buttons. @param pids list of entries
[ "fill", "entries", "of", "the", "radio", "buttons", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwt-mt-widgets/src/main/java/de/knightsoftnet/mtwidgets/client/ui/widget/SortableIdAndNameRadioButton.java#L131-L169
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/pipeline/common/executors/MavenExecutor.java
MavenExecutor.convertJdkPath
private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) { String separator = launcher.isUnix() ? "/" : "\\"; String java_home = extendedEnv.get("JAVA_HOME"); if (StringUtils.isNotEmpty(java_home)) { if (!StringUtils.endsWith(java_home, separator)) { java_home += separator; } extendedEnv.put("PATH+JDK", java_home + "bin"); } }
java
private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) { String separator = launcher.isUnix() ? "/" : "\\"; String java_home = extendedEnv.get("JAVA_HOME"); if (StringUtils.isNotEmpty(java_home)) { if (!StringUtils.endsWith(java_home, separator)) { java_home += separator; } extendedEnv.put("PATH+JDK", java_home + "bin"); } }
[ "private", "void", "convertJdkPath", "(", "Launcher", "launcher", ",", "EnvVars", "extendedEnv", ")", "{", "String", "separator", "=", "launcher", ".", "isUnix", "(", ")", "?", "\"/\"", ":", "\"\\\\\"", ";", "String", "java_home", "=", "extendedEnv", ".", "g...
The Maven3Builder class is looking for the PATH+JDK environment variable due to legacy code. In The pipeline flow we need to convert the JAVA_HOME to PATH+JDK in order to reuse the code.
[ "The", "Maven3Builder", "class", "is", "looking", "for", "the", "PATH", "+", "JDK", "environment", "variable", "due", "to", "legacy", "code", ".", "In", "The", "pipeline", "flow", "we", "need", "to", "convert", "the", "JAVA_HOME", "to", "PATH", "+", "JDK",...
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/pipeline/common/executors/MavenExecutor.java#L84-L93
hawkular/hawkular-apm
server/rest/src/main/java/org/hawkular/apm/server/rest/RESTServiceUtil.java
RESTServiceUtil.decodeCorrelationIdentifiers
public static void decodeCorrelationIdentifiers(Set<CorrelationIdentifier> correlations, String encoded) { if (encoded != null && !encoded.trim().isEmpty()) { StringTokenizer st = new StringTokenizer(encoded, ","); while (st.hasMoreTokens()) { String token = st.nextToken(); String[] parts = token.split("[|]"); if (parts.length == 2) { String scope = parts[0].trim(); String value = parts[1].trim(); log.tracef("Extracted correlation identifier scope [%s] value [%s]", scope, value); CorrelationIdentifier cid = new CorrelationIdentifier(); cid.setScope(Scope.valueOf(scope)); cid.setValue(value); correlations.add(cid); } } } }
java
public static void decodeCorrelationIdentifiers(Set<CorrelationIdentifier> correlations, String encoded) { if (encoded != null && !encoded.trim().isEmpty()) { StringTokenizer st = new StringTokenizer(encoded, ","); while (st.hasMoreTokens()) { String token = st.nextToken(); String[] parts = token.split("[|]"); if (parts.length == 2) { String scope = parts[0].trim(); String value = parts[1].trim(); log.tracef("Extracted correlation identifier scope [%s] value [%s]", scope, value); CorrelationIdentifier cid = new CorrelationIdentifier(); cid.setScope(Scope.valueOf(scope)); cid.setValue(value); correlations.add(cid); } } } }
[ "public", "static", "void", "decodeCorrelationIdentifiers", "(", "Set", "<", "CorrelationIdentifier", ">", "correlations", ",", "String", "encoded", ")", "{", "if", "(", "encoded", "!=", "null", "&&", "!", "encoded", ".", "trim", "(", ")", ".", "isEmpty", "(...
This method processes a comma separated list of correlation identifiers, defined as a scope|value pair. @param correlations The correlation identifier set @param encoded The string containing the encoded correlation identifiers
[ "This", "method", "processes", "a", "comma", "separated", "list", "of", "correlation", "identifiers", "defined", "as", "a", "scope|value", "pair", "." ]
train
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/rest/src/main/java/org/hawkular/apm/server/rest/RESTServiceUtil.java#L73-L93
pressgang-ccms/PressGangCCMSContentSpec
src/main/java/org/jboss/pressgang/ccms/contentspec/SpecNodeWithRelationships.java
SpecNodeWithRelationships.addRelationshipToTarget
public void addRelationshipToTarget(final Level level, final RelationshipType type) { final TargetRelationship relationship = new TargetRelationship(this, level, type); levelRelationships.add(relationship); relationships.add(relationship); }
java
public void addRelationshipToTarget(final Level level, final RelationshipType type) { final TargetRelationship relationship = new TargetRelationship(this, level, type); levelRelationships.add(relationship); relationships.add(relationship); }
[ "public", "void", "addRelationshipToTarget", "(", "final", "Level", "level", ",", "final", "RelationshipType", "type", ")", "{", "final", "TargetRelationship", "relationship", "=", "new", "TargetRelationship", "(", "this", ",", "level", ",", "type", ")", ";", "l...
Add a relationship to the target level. @param level The target level that is to be related to. @param type The type of the relationship.
[ "Add", "a", "relationship", "to", "the", "target", "level", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/SpecNodeWithRelationships.java#L107-L111
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/WisdomExecutor.java
WisdomExecutor.executeInBackground
public void executeInBackground(AbstractWisdomMojo mojo) throws MojoExecutionException { File script = new File(mojo.getWisdomRootDirectory(), "chameleon.sh"); if (!script.isFile()) { throw new MojoExecutionException("The 'chameleon.sh' file does not exist in " + mojo .getWisdomRootDirectory().getAbsolutePath() + " - cannot launch Wisdom"); } // Remove the RUNNING_PID file if exists. File pid = new File(mojo.getWisdomRootDirectory(), "RUNNING_PID"); if (pid.isFile()) { mojo.getLog().info("The RUNNING_PID file is present, deleting it"); FileUtils.deleteQuietly(pid); } // We create a command line, as we are using th toString method on it. CommandLine cmdLine = new CommandLine(script); appendSystemPropertiesToCommandLine(mojo, cmdLine); try { mojo.getLog().info("Launching Wisdom Server using '" + cmdLine.toString() + "'."); // As we know which command line we are executing, we can safely execute the command. Runtime.getRuntime().exec(cmdLine.toStrings(), null, mojo.getWisdomRootDirectory()); //NOSONAR see comment } catch (IOException e) { throw new MojoExecutionException("Cannot execute Wisdom", e); } }
java
public void executeInBackground(AbstractWisdomMojo mojo) throws MojoExecutionException { File script = new File(mojo.getWisdomRootDirectory(), "chameleon.sh"); if (!script.isFile()) { throw new MojoExecutionException("The 'chameleon.sh' file does not exist in " + mojo .getWisdomRootDirectory().getAbsolutePath() + " - cannot launch Wisdom"); } // Remove the RUNNING_PID file if exists. File pid = new File(mojo.getWisdomRootDirectory(), "RUNNING_PID"); if (pid.isFile()) { mojo.getLog().info("The RUNNING_PID file is present, deleting it"); FileUtils.deleteQuietly(pid); } // We create a command line, as we are using th toString method on it. CommandLine cmdLine = new CommandLine(script); appendSystemPropertiesToCommandLine(mojo, cmdLine); try { mojo.getLog().info("Launching Wisdom Server using '" + cmdLine.toString() + "'."); // As we know which command line we are executing, we can safely execute the command. Runtime.getRuntime().exec(cmdLine.toStrings(), null, mojo.getWisdomRootDirectory()); //NOSONAR see comment } catch (IOException e) { throw new MojoExecutionException("Cannot execute Wisdom", e); } }
[ "public", "void", "executeInBackground", "(", "AbstractWisdomMojo", "mojo", ")", "throws", "MojoExecutionException", "{", "File", "script", "=", "new", "File", "(", "mojo", ".", "getWisdomRootDirectory", "(", ")", ",", "\"chameleon.sh\"", ")", ";", "if", "(", "!...
Launches the Wisdom server in background using the {@literal chameleon.sh} scripts. This method works only on Linux and Mac OS X. @param mojo the mojo @throws MojoExecutionException if the Wisdom instance cannot be started.
[ "Launches", "the", "Wisdom", "server", "in", "background", "using", "the", "{", "@literal", "chameleon", ".", "sh", "}", "scripts", ".", "This", "method", "works", "only", "on", "Linux", "and", "Mac", "OS", "X", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/WisdomExecutor.java#L56-L81
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/KeyDecoder.java
KeyDecoder.decodeDoubleObjDesc
public static Double decodeDoubleObjDesc(byte[] src, int srcOffset) throws CorruptEncodingException { long bits = DataDecoder.decodeDoubleBits(src, srcOffset); if (bits >= 0) { bits ^= 0x7fffffffffffffffL; } return bits == 0x7fffffffffffffffL ? null : Double.longBitsToDouble(bits); }
java
public static Double decodeDoubleObjDesc(byte[] src, int srcOffset) throws CorruptEncodingException { long bits = DataDecoder.decodeDoubleBits(src, srcOffset); if (bits >= 0) { bits ^= 0x7fffffffffffffffL; } return bits == 0x7fffffffffffffffL ? null : Double.longBitsToDouble(bits); }
[ "public", "static", "Double", "decodeDoubleObjDesc", "(", "byte", "[", "]", "src", ",", "int", "srcOffset", ")", "throws", "CorruptEncodingException", "{", "long", "bits", "=", "DataDecoder", ".", "decodeDoubleBits", "(", "src", ",", "srcOffset", ")", ";", "if...
Decodes a Double object from exactly 8 bytes. @param src source of encoded bytes @param srcOffset offset into source array @return Double object or null
[ "Decodes", "a", "Double", "object", "from", "exactly", "8", "bytes", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyDecoder.java#L327-L335
jmxtrans/jmxtrans
jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/TCollectorUDPWriter.java
TCollectorUDPWriter.sendOutput
@Override protected void sendOutput(String metricLine) throws IOException { DatagramPacket packet; byte[] data; data = metricLine.getBytes("UTF-8"); packet = new DatagramPacket(data, 0, data.length, this.address); this.dgSocket.send(packet); }
java
@Override protected void sendOutput(String metricLine) throws IOException { DatagramPacket packet; byte[] data; data = metricLine.getBytes("UTF-8"); packet = new DatagramPacket(data, 0, data.length, this.address); this.dgSocket.send(packet); }
[ "@", "Override", "protected", "void", "sendOutput", "(", "String", "metricLine", ")", "throws", "IOException", "{", "DatagramPacket", "packet", ";", "byte", "[", "]", "data", ";", "data", "=", "metricLine", ".", "getBytes", "(", "\"UTF-8\"", ")", ";", "packe...
Send a single metric to TCollector. @param metricLine - the line containing the metric name, value, and tags for a single metric; excludes the "put" keyword expected by OpenTSDB and the trailing newline character.
[ "Send", "a", "single", "metric", "to", "TCollector", "." ]
train
https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/TCollectorUDPWriter.java#L128-L137
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlWriter.java
HtmlWriter.getWinTitleScript
protected HtmlTree getWinTitleScript(){ HtmlTree scriptTree = HtmlTree.SCRIPT(); if(winTitle != null && winTitle.length() > 0) { String scriptCode = "<!--\n" + " try {\n" + " if (location.href.indexOf('is-external=true') == -1) {\n" + " parent.document.title=\"" + escapeJavaScriptChars(winTitle) + "\";\n" + " }\n" + " }\n" + " catch(err) {\n" + " }\n" + "//-->\n"; RawHtml scriptContent = new RawHtml(scriptCode.replace("\n", DocletConstants.NL)); scriptTree.addContent(scriptContent); } return scriptTree; }
java
protected HtmlTree getWinTitleScript(){ HtmlTree scriptTree = HtmlTree.SCRIPT(); if(winTitle != null && winTitle.length() > 0) { String scriptCode = "<!--\n" + " try {\n" + " if (location.href.indexOf('is-external=true') == -1) {\n" + " parent.document.title=\"" + escapeJavaScriptChars(winTitle) + "\";\n" + " }\n" + " }\n" + " catch(err) {\n" + " }\n" + "//-->\n"; RawHtml scriptContent = new RawHtml(scriptCode.replace("\n", DocletConstants.NL)); scriptTree.addContent(scriptContent); } return scriptTree; }
[ "protected", "HtmlTree", "getWinTitleScript", "(", ")", "{", "HtmlTree", "scriptTree", "=", "HtmlTree", ".", "SCRIPT", "(", ")", ";", "if", "(", "winTitle", "!=", "null", "&&", "winTitle", ".", "length", "(", ")", ">", "0", ")", "{", "String", "scriptCod...
Returns an HtmlTree for the SCRIPT tag. @return an HtmlTree for the SCRIPT tag
[ "Returns", "an", "HtmlTree", "for", "the", "SCRIPT", "tag", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlWriter.java#L176-L192
krotscheck/jersey2-toolkit
jersey2-configuration/src/main/java/net/krotscheck/jersey2/configuration/Jersey2ToolkitConfig.java
Jersey2ToolkitConfig.buildToolkitConfig
private Configuration buildToolkitConfig() { // The toolkit configuration file. try { File configFile = ResourceUtil .getFileForResource("jersey2-toolkit.properties"); return new PropertiesConfiguration(configFile); } catch (ConfigurationException ce) { logger.error("jersey2-toolkit.properties not readable," + " some features may be misconfigured."); // Return a new, empty map configuration so we don't error out. return new MapConfiguration(new HashMap<String, String>()); } }
java
private Configuration buildToolkitConfig() { // The toolkit configuration file. try { File configFile = ResourceUtil .getFileForResource("jersey2-toolkit.properties"); return new PropertiesConfiguration(configFile); } catch (ConfigurationException ce) { logger.error("jersey2-toolkit.properties not readable," + " some features may be misconfigured."); // Return a new, empty map configuration so we don't error out. return new MapConfiguration(new HashMap<String, String>()); } }
[ "private", "Configuration", "buildToolkitConfig", "(", ")", "{", "// The toolkit configuration file.", "try", "{", "File", "configFile", "=", "ResourceUtil", ".", "getFileForResource", "(", "\"jersey2-toolkit.properties\"", ")", ";", "return", "new", "PropertiesConfiguratio...
Builds the configuration object for our toolkit config. @return A Configuration object.
[ "Builds", "the", "configuration", "object", "for", "our", "toolkit", "config", "." ]
train
https://github.com/krotscheck/jersey2-toolkit/blob/11d757bd222dc82ada462caf6730ba4ff85dae04/jersey2-configuration/src/main/java/net/krotscheck/jersey2/configuration/Jersey2ToolkitConfig.java#L81-L95
aws/aws-sdk-java
aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/UpdateIntegrationResult.java
UpdateIntegrationResult.withRequestTemplates
public UpdateIntegrationResult withRequestTemplates(java.util.Map<String, String> requestTemplates) { setRequestTemplates(requestTemplates); return this; }
java
public UpdateIntegrationResult withRequestTemplates(java.util.Map<String, String> requestTemplates) { setRequestTemplates(requestTemplates); return this; }
[ "public", "UpdateIntegrationResult", "withRequestTemplates", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "requestTemplates", ")", "{", "setRequestTemplates", "(", "requestTemplates", ")", ";", "return", "this", ";", "}" ]
<p> Represents a map of Velocity templates that are applied on the request payload based on the value of the Content-Type header sent by the client. The content type value is the key in this map, and the template (as a String) is the value. </p> @param requestTemplates Represents a map of Velocity templates that are applied on the request payload based on the value of the Content-Type header sent by the client. The content type value is the key in this map, and the template (as a String) is the value. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Represents", "a", "map", "of", "Velocity", "templates", "that", "are", "applied", "on", "the", "request", "payload", "based", "on", "the", "value", "of", "the", "Content", "-", "Type", "header", "sent", "by", "the", "client", ".", "The", "con...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/UpdateIntegrationResult.java#L1219-L1222
mgormley/pacaya
src/main/java/edu/jhu/pacaya/gm/model/FactorGraph.java
FactorGraph.addFactor
public void addFactor(Factor factor) { int id = factor.getId(); boolean alreadyAdded = (0 <= id && id < factors.size()); if (alreadyAdded) { if (factors.get(id) != factor) { throw new IllegalStateException("Factor id already set, but factor not yet added."); } } else { // Factor was not yet in the factor graph. // // Check and set the id. if (id != -1 && id != factors.size()) { throw new IllegalStateException("Factor id already set, but incorrect: " + id); } factor.setId(factors.size()); // Add the factor. factors.add(factor); // Add each variable... for (Var var : factor.getVars()) { // Add the variable. addVar(var); numUndirEdges++; } if (bg != null) { log.warn("Discarding BipartiteGraph. This may indicate inefficiency."); } bg = null; } }
java
public void addFactor(Factor factor) { int id = factor.getId(); boolean alreadyAdded = (0 <= id && id < factors.size()); if (alreadyAdded) { if (factors.get(id) != factor) { throw new IllegalStateException("Factor id already set, but factor not yet added."); } } else { // Factor was not yet in the factor graph. // // Check and set the id. if (id != -1 && id != factors.size()) { throw new IllegalStateException("Factor id already set, but incorrect: " + id); } factor.setId(factors.size()); // Add the factor. factors.add(factor); // Add each variable... for (Var var : factor.getVars()) { // Add the variable. addVar(var); numUndirEdges++; } if (bg != null) { log.warn("Discarding BipartiteGraph. This may indicate inefficiency."); } bg = null; } }
[ "public", "void", "addFactor", "(", "Factor", "factor", ")", "{", "int", "id", "=", "factor", ".", "getId", "(", ")", ";", "boolean", "alreadyAdded", "=", "(", "0", "<=", "id", "&&", "id", "<", "factors", ".", "size", "(", ")", ")", ";", "if", "(...
Adds a factor to this factor graph, if not already present, additionally adding any variables in its VarSet which have not already been added. @param var The factor to add. @return The node for this factor.
[ "Adds", "a", "factor", "to", "this", "factor", "graph", "if", "not", "already", "present", "additionally", "adding", "any", "variables", "in", "its", "VarSet", "which", "have", "not", "already", "been", "added", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/model/FactorGraph.java#L88-L116
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java
ExpressRouteCircuitsInner.getPeeringStats
public ExpressRouteCircuitStatsInner getPeeringStats(String resourceGroupName, String circuitName, String peeringName) { return getPeeringStatsWithServiceResponseAsync(resourceGroupName, circuitName, peeringName).toBlocking().single().body(); }
java
public ExpressRouteCircuitStatsInner getPeeringStats(String resourceGroupName, String circuitName, String peeringName) { return getPeeringStatsWithServiceResponseAsync(resourceGroupName, circuitName, peeringName).toBlocking().single().body(); }
[ "public", "ExpressRouteCircuitStatsInner", "getPeeringStats", "(", "String", "resourceGroupName", ",", "String", "circuitName", ",", "String", "peeringName", ")", "{", "return", "getPeeringStatsWithServiceResponseAsync", "(", "resourceGroupName", ",", "circuitName", ",", "p...
Gets all stats from an express route circuit in a resource group. @param resourceGroupName The name of the resource group. @param circuitName The name of the express route circuit. @param peeringName The name of the peering. @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 ExpressRouteCircuitStatsInner object if successful.
[ "Gets", "all", "stats", "from", "an", "express", "route", "circuit", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ExpressRouteCircuitsInner.java#L1501-L1503
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/ExpressionUtils.java
ExpressionUtils.predicateTemplate
public static PredicateTemplate predicateTemplate(String template, List<?> args) { return predicateTemplate(TemplateFactory.DEFAULT.create(template), args); }
java
public static PredicateTemplate predicateTemplate(String template, List<?> args) { return predicateTemplate(TemplateFactory.DEFAULT.create(template), args); }
[ "public", "static", "PredicateTemplate", "predicateTemplate", "(", "String", "template", ",", "List", "<", "?", ">", "args", ")", "{", "return", "predicateTemplate", "(", "TemplateFactory", ".", "DEFAULT", ".", "create", "(", "template", ")", ",", "args", ")",...
Create a new Template 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/ExpressionUtils.java#L165-L167
padrig64/ValidationFramework
validationframework-core/src/main/java/com/google/code/validationframework/base/validator/DefaultMappableValidator.java
DefaultMappableValidator.processDataProvider
private void processDataProvider(final DataProvider<RI> dataProvider) { // Get rules matching the data provider final List<Rule<RI, RO>> mappedRules = dataProvidersToRules.get(dataProvider); if ((mappedRules == null) || mappedRules.isEmpty()) { LOGGER.warn("No matching rule in mappable validator for data provider: " + dataProvider); } else { // Get data to be validated final RI data = dataProvider.getData(); // Process all matching rules for (final Rule<RI, RO> rule : mappedRules) { processRule(rule, data); } } }
java
private void processDataProvider(final DataProvider<RI> dataProvider) { // Get rules matching the data provider final List<Rule<RI, RO>> mappedRules = dataProvidersToRules.get(dataProvider); if ((mappedRules == null) || mappedRules.isEmpty()) { LOGGER.warn("No matching rule in mappable validator for data provider: " + dataProvider); } else { // Get data to be validated final RI data = dataProvider.getData(); // Process all matching rules for (final Rule<RI, RO> rule : mappedRules) { processRule(rule, data); } } }
[ "private", "void", "processDataProvider", "(", "final", "DataProvider", "<", "RI", ">", "dataProvider", ")", "{", "// Get rules matching the data provider", "final", "List", "<", "Rule", "<", "RI", ",", "RO", ">", ">", "mappedRules", "=", "dataProvidersToRules", "...
Process the specified data provider by finding all the mapped rules, and so on. @param dataProvider Data provider to be processed.
[ "Process", "the", "specified", "data", "provider", "by", "finding", "all", "the", "mapped", "rules", "and", "so", "on", "." ]
train
https://github.com/padrig64/ValidationFramework/blob/2dd3c7b3403993db366d24a927645f467ccd1dda/validationframework-core/src/main/java/com/google/code/validationframework/base/validator/DefaultMappableValidator.java#L86-L100
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/objectManager/AbstractTreeMap.java
AbstractTreeMap.headMap
public SortedMap headMap(Object endKey) { // Check for errors if (comparator == null) ((Comparable) endKey).compareTo(endKey); else comparator.compare(endKey, endKey); return makeSubMap(null, endKey); }
java
public SortedMap headMap(Object endKey) { // Check for errors if (comparator == null) ((Comparable) endKey).compareTo(endKey); else comparator.compare(endKey, endKey); return makeSubMap(null, endKey); }
[ "public", "SortedMap", "headMap", "(", "Object", "endKey", ")", "{", "// Check for errors", "if", "(", "comparator", "==", "null", ")", "(", "(", "Comparable", ")", "endKey", ")", ".", "compareTo", "(", "endKey", ")", ";", "else", "comparator", ".", "compa...
Answers a SortedMap of the specified portion of this TreeMap which contains keys less than the end key. The returned SortedMap is backed by this TreeMap so changes to one are reflected by the other. @param endKey the end key @return a submap where the keys are less than <code>endKey</code> @exception ClassCastException when the end key cannot be compared with the keys in this TreeMap @exception NullPointerException when the end key is null and the comparator cannot handle null
[ "Answers", "a", "SortedMap", "of", "the", "specified", "portion", "of", "this", "TreeMap", "which", "contains", "keys", "less", "than", "the", "end", "key", ".", "The", "returned", "SortedMap", "is", "backed", "by", "this", "TreeMap", "so", "changes", "to", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/objectManager/AbstractTreeMap.java#L844-L851
iig-uni-freiburg/SEWOL
ext/org/deckfour/xes/extension/std/XCostExtension.java
XCostExtension.assignType
public void assignType(XAttribute attribute, String type) { if (type != null && type.trim().length() > 0) { XAttributeLiteral attr = (XAttributeLiteral) ATTR_TYPE.clone(); attr.setValue(type); attribute.getAttributes().put(KEY_TYPE, attr); } }
java
public void assignType(XAttribute attribute, String type) { if (type != null && type.trim().length() > 0) { XAttributeLiteral attr = (XAttributeLiteral) ATTR_TYPE.clone(); attr.setValue(type); attribute.getAttributes().put(KEY_TYPE, attr); } }
[ "public", "void", "assignType", "(", "XAttribute", "attribute", ",", "String", "type", ")", "{", "if", "(", "type", "!=", "null", "&&", "type", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "XAttributeLiteral", "attr", "=", "(",...
Assigns any attribute its cost type, as defined by this extension's type attribute. @param attribute Attribute to assign cost type to. @param type The cost type to be assigned.
[ "Assigns", "any", "attribute", "its", "cost", "type", "as", "defined", "by", "this", "extension", "s", "type", "attribute", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/extension/std/XCostExtension.java#L948-L954
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newInitializationException
public static InitializationException newInitializationException(Throwable cause, String message, Object... args) { return new InitializationException(format(message, args), cause); }
java
public static InitializationException newInitializationException(Throwable cause, String message, Object... args) { return new InitializationException(format(message, args), cause); }
[ "public", "static", "InitializationException", "newInitializationException", "(", "Throwable", "cause", ",", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "new", "InitializationException", "(", "format", "(", "message", ",", "args", ")", "...
Constructs and initializes a new {@link InitializationException} with the given {@link Throwable cause} and {@link String message} formatted with the given {@link Object[] arguments}. @param cause {@link Throwable} identified as the reason this {@link InitializationException} was thrown. @param message {@link String} describing the {@link InitializationException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link InitializationException} with the given {@link Throwable cause} and {@link String message}. @see org.cp.elements.lang.InitializationException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "InitializationException", "}", "with", "the", "given", "{", "@link", "Throwable", "cause", "}", "and", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "...
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L453-L455
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/log/LogImpl.java
LogImpl.defaultInit
private synchronized void defaultInit() { if (!_initialized) { _initialized = true; String sinkClasses = System.getProperty("LOG_SINKS","org.browsermob.proxy.jetty.log.OutputStreamLogSink"); StringTokenizer sinkTokens = new StringTokenizer(sinkClasses, ";, "); LogSink sink= null; while (sinkTokens.hasMoreTokens()) { String sinkClassName = sinkTokens.nextToken(); try { Class sinkClass = Loader.loadClass(this.getClass(),sinkClassName); if (org.browsermob.proxy.jetty.log.LogSink.class.isAssignableFrom(sinkClass)) { sink = (LogSink)sinkClass.newInstance(); sink.start(); add(sink); } else // Can't use Code.fail here, that's what we're setting up System.err.println(sinkClass+" is not a org.browsermob.proxy.jetty.log.LogSink"); } catch (Exception e) { e.printStackTrace(); } } } }
java
private synchronized void defaultInit() { if (!_initialized) { _initialized = true; String sinkClasses = System.getProperty("LOG_SINKS","org.browsermob.proxy.jetty.log.OutputStreamLogSink"); StringTokenizer sinkTokens = new StringTokenizer(sinkClasses, ";, "); LogSink sink= null; while (sinkTokens.hasMoreTokens()) { String sinkClassName = sinkTokens.nextToken(); try { Class sinkClass = Loader.loadClass(this.getClass(),sinkClassName); if (org.browsermob.proxy.jetty.log.LogSink.class.isAssignableFrom(sinkClass)) { sink = (LogSink)sinkClass.newInstance(); sink.start(); add(sink); } else // Can't use Code.fail here, that's what we're setting up System.err.println(sinkClass+" is not a org.browsermob.proxy.jetty.log.LogSink"); } catch (Exception e) { e.printStackTrace(); } } } }
[ "private", "synchronized", "void", "defaultInit", "(", ")", "{", "if", "(", "!", "_initialized", ")", "{", "_initialized", "=", "true", ";", "String", "sinkClasses", "=", "System", ".", "getProperty", "(", "\"LOG_SINKS\"", ",", "\"org.browsermob.proxy.jetty.log.Ou...
Default initialization is used the first time we have to log unless a sink has been added with add(). _needInit allows us to distinguish between initial state and disabled state.
[ "Default", "initialization", "is", "used", "the", "first", "time", "we", "have", "to", "log", "unless", "a", "sink", "has", "been", "added", "with", "add", "()", ".", "_needInit", "allows", "us", "to", "distinguish", "between", "initial", "state", "and", "...
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/log/LogImpl.java#L174-L204
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/JSLocalConsumerPoint.java
JSLocalConsumerPoint.checkForMessages
@Override public void checkForMessages() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "checkForMessages", this); try { //start a new thread to run the callback _messageProcessor.startNewThread(new AsynchThread(this, false)); } catch (InterruptedException e) { FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.JSLocalConsumerPoint.checkForMessages", "1:3881:1.22.5.1", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "checkForMessages", e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "checkForMessages"); }
java
@Override public void checkForMessages() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "checkForMessages", this); try { //start a new thread to run the callback _messageProcessor.startNewThread(new AsynchThread(this, false)); } catch (InterruptedException e) { FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.JSLocalConsumerPoint.checkForMessages", "1:3881:1.22.5.1", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "checkForMessages", e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "checkForMessages"); }
[ "@", "Override", "public", "void", "checkForMessages", "(", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"checkForMessages\"", ",", "...
Spin off a thread that checks for any stored messages. This is called by a consumerKeyGroup to try to kick a group back into life after a stopped member detaches and makes the group ready again.
[ "Spin", "off", "a", "thread", "that", "checks", "for", "any", "stored", "messages", ".", "This", "is", "called", "by", "a", "consumerKeyGroup", "to", "try", "to", "kick", "a", "group", "back", "into", "life", "after", "a", "stopped", "member", "detaches", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/JSLocalConsumerPoint.java#L3645-L3672
google/closure-compiler
src/com/google/javascript/jscomp/CoverageInstrumentationCallback.java
CoverageInstrumentationCallback.newInstrumentationNode
private Node newInstrumentationNode(NodeTraversal traversal, Node node) { int lineNumber = node.getLineno(); String arrayName = createArrayName(traversal); // Create instrumentation Node Node getElemNode = IR.getelem( IR.name(arrayName), IR.number(lineNumber - 1)); // Make line number 0-based Node exprNode = IR.exprResult(IR.assign(getElemNode, IR.trueNode())); // Note line as instrumented String fileName = getFileName(traversal); if (!instrumentationData.containsKey(fileName)) { instrumentationData.put(fileName, new FileInstrumentationData(fileName, arrayName)); } instrumentationData.get(fileName).setLineAsInstrumented(lineNumber); return exprNode.useSourceInfoIfMissingFromForTree(node); }
java
private Node newInstrumentationNode(NodeTraversal traversal, Node node) { int lineNumber = node.getLineno(); String arrayName = createArrayName(traversal); // Create instrumentation Node Node getElemNode = IR.getelem( IR.name(arrayName), IR.number(lineNumber - 1)); // Make line number 0-based Node exprNode = IR.exprResult(IR.assign(getElemNode, IR.trueNode())); // Note line as instrumented String fileName = getFileName(traversal); if (!instrumentationData.containsKey(fileName)) { instrumentationData.put(fileName, new FileInstrumentationData(fileName, arrayName)); } instrumentationData.get(fileName).setLineAsInstrumented(lineNumber); return exprNode.useSourceInfoIfMissingFromForTree(node); }
[ "private", "Node", "newInstrumentationNode", "(", "NodeTraversal", "traversal", ",", "Node", "node", ")", "{", "int", "lineNumber", "=", "node", ".", "getLineno", "(", ")", ";", "String", "arrayName", "=", "createArrayName", "(", "traversal", ")", ";", "// Cre...
Creates and return a new instrumentation node. The instrumentation Node is of the form: "arrayName[lineNumber] = true;" Note 1: Node returns a 1-based line number. Note 2: Line numbers in instrumentation are made 0-based. This is done to map to their bit representation in BitField. Thus, there's a one-to-one correspondence of the line number seen on instrumented files and their bit encodings. @return an instrumentation node corresponding to the line number
[ "Creates", "and", "return", "a", "new", "instrumentation", "node", ".", "The", "instrumentation", "Node", "is", "of", "the", "form", ":", "arrayName", "[", "lineNumber", "]", "=", "true", ";", "Note", "1", ":", "Node", "returns", "a", "1", "-", "based", ...
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CoverageInstrumentationCallback.java#L77-L96
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContentEditorHandler.java
CmsContentEditorHandler.putString
private void putString(JSONObject obj, String key, String val) { obj.put(key, new JSONString(val)); }
java
private void putString(JSONObject obj, String key, String val) { obj.put(key, new JSONString(val)); }
[ "private", "void", "putString", "(", "JSONObject", "obj", ",", "String", "key", ",", "String", "val", ")", "{", "obj", ".", "put", "(", "key", ",", "new", "JSONString", "(", "val", ")", ")", ";", "}" ]
Adds a String value to the JSON object.<p> @param obj the object to manipulate @param key the key @param val the value
[ "Adds", "a", "String", "value", "to", "the", "JSON", "object", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContentEditorHandler.java#L664-L667
SeaCloudsEU/SeaCloudsPlatform
planner/optimizer/optimizer-core/src/main/java/eu/seaclouds/platform/planner/optimizer/Topology.java
Topology.replaceElementsIndexes
public void replaceElementsIndexes(TopologyElement element, int toIndex) { int targetIndex = modules.indexOf(element); if (log.isDebugEnabled()) { if (modules == null) { log.warn("Modules in topology points to NULL"); } if (element == null) { log.warn("Element to search in topology points to NULL"); } log.debug("The topology consists of " + modules.size() + " modules. Replacing index " + toIndex + " with " + targetIndex + ". The element name whose index was searched was " + element.getName() + "and the topology was composed of modules: " + toString()); } TopologyElement replaced = modules.set(toIndex, element); modules.set(targetIndex, replaced); }
java
public void replaceElementsIndexes(TopologyElement element, int toIndex) { int targetIndex = modules.indexOf(element); if (log.isDebugEnabled()) { if (modules == null) { log.warn("Modules in topology points to NULL"); } if (element == null) { log.warn("Element to search in topology points to NULL"); } log.debug("The topology consists of " + modules.size() + " modules. Replacing index " + toIndex + " with " + targetIndex + ". The element name whose index was searched was " + element.getName() + "and the topology was composed of modules: " + toString()); } TopologyElement replaced = modules.set(toIndex, element); modules.set(targetIndex, replaced); }
[ "public", "void", "replaceElementsIndexes", "(", "TopologyElement", "element", ",", "int", "toIndex", ")", "{", "int", "targetIndex", "=", "modules", ".", "indexOf", "(", "element", ")", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "if...
@param element @param toIndex Swaps the elements indexes. "Element" gets "toIndex" index and the previous element with index "toIndex" gets the previous index of "element"
[ "@param", "element", "@param", "toIndex", "Swaps", "the", "elements", "indexes", ".", "Element", "gets", "toIndex", "index", "and", "the", "previous", "element", "with", "index", "toIndex", "gets", "the", "previous", "index", "of", "element" ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/planner/optimizer/optimizer-core/src/main/java/eu/seaclouds/platform/planner/optimizer/Topology.java#L118-L133
ttddyy/datasource-proxy
src/main/java/net/ttddyy/dsproxy/support/ProxyDataSourceBuilder.java
ProxyDataSourceBuilder.logSlowQueryBySlf4j
public ProxyDataSourceBuilder logSlowQueryBySlf4j(long thresholdTime, TimeUnit timeUnit, SLF4JLogLevel logLevel) { return logSlowQueryBySlf4j(thresholdTime, timeUnit, logLevel, null); }
java
public ProxyDataSourceBuilder logSlowQueryBySlf4j(long thresholdTime, TimeUnit timeUnit, SLF4JLogLevel logLevel) { return logSlowQueryBySlf4j(thresholdTime, timeUnit, logLevel, null); }
[ "public", "ProxyDataSourceBuilder", "logSlowQueryBySlf4j", "(", "long", "thresholdTime", ",", "TimeUnit", "timeUnit", ",", "SLF4JLogLevel", "logLevel", ")", "{", "return", "logSlowQueryBySlf4j", "(", "thresholdTime", ",", "timeUnit", ",", "logLevel", ",", "null", ")",...
Register {@link SLF4JSlowQueryListener}. @param thresholdTime slow query threshold time @param timeUnit slow query threshold time unit @param logLevel log level for slf4j @return builder @since 1.4.1
[ "Register", "{", "@link", "SLF4JSlowQueryListener", "}", "." ]
train
https://github.com/ttddyy/datasource-proxy/blob/62163ccf9a569a99aa3ad9f9151a32567447a62e/src/main/java/net/ttddyy/dsproxy/support/ProxyDataSourceBuilder.java#L348-L350
bladecoder/blade-ink
src/main/java/com/bladecoder/ink/runtime/Story.java
Story.bindExternalFunction
public void bindExternalFunction(String funcName, ExternalFunction func) throws Exception { ifAsyncWeCant("bind an external function"); Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound."); externals.put(funcName, func); }
java
public void bindExternalFunction(String funcName, ExternalFunction func) throws Exception { ifAsyncWeCant("bind an external function"); Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound."); externals.put(funcName, func); }
[ "public", "void", "bindExternalFunction", "(", "String", "funcName", ",", "ExternalFunction", "func", ")", "throws", "Exception", "{", "ifAsyncWeCant", "(", "\"bind an external function\"", ")", ";", "Assert", "(", "!", "externals", ".", "containsKey", "(", "funcNam...
Most general form of function binding that returns an Object and takes an array of Object parameters. The only way to bind a function with more than 3 arguments. @param funcName EXTERNAL ink function name to bind to. @param func The Java function to bind.
[ "Most", "general", "form", "of", "function", "binding", "that", "returns", "an", "Object", "and", "takes", "an", "array", "of", "Object", "parameters", ".", "The", "only", "way", "to", "bind", "a", "function", "with", "more", "than", "3", "arguments", "." ...
train
https://github.com/bladecoder/blade-ink/blob/930922099f7073f50f956479adaa3cbd47c70225/src/main/java/com/bladecoder/ink/runtime/Story.java#L222-L226
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java
NvdCveUpdater.getMetaFile
protected final MetaProperties getMetaFile(String url) throws UpdateException { try { final String metaUrl = url.substring(0, url.length() - 7) + "meta"; final URL u = new URL(metaUrl); final Downloader d = new Downloader(settings); final String content = d.fetchContent(u, true); return new MetaProperties(content); } catch (MalformedURLException ex) { throw new UpdateException("Meta file url is invalid: " + url, ex); } catch (InvalidDataException ex) { throw new UpdateException("Meta file content is invalid: " + url, ex); } catch (DownloadFailedException ex) { throw new UpdateException("Unable to download meta file: " + url, ex); } }
java
protected final MetaProperties getMetaFile(String url) throws UpdateException { try { final String metaUrl = url.substring(0, url.length() - 7) + "meta"; final URL u = new URL(metaUrl); final Downloader d = new Downloader(settings); final String content = d.fetchContent(u, true); return new MetaProperties(content); } catch (MalformedURLException ex) { throw new UpdateException("Meta file url is invalid: " + url, ex); } catch (InvalidDataException ex) { throw new UpdateException("Meta file content is invalid: " + url, ex); } catch (DownloadFailedException ex) { throw new UpdateException("Unable to download meta file: " + url, ex); } }
[ "protected", "final", "MetaProperties", "getMetaFile", "(", "String", "url", ")", "throws", "UpdateException", "{", "try", "{", "final", "String", "metaUrl", "=", "url", ".", "substring", "(", "0", ",", "url", ".", "length", "(", ")", "-", "7", ")", "+",...
Downloads the NVD CVE Meta file properties. @param url the URL to the NVD CVE JSON file @return the meta file properties @throws UpdateException thrown if the meta file could not be downloaded
[ "Downloads", "the", "NVD", "CVE", "Meta", "file", "properties", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java#L350-L364
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/LockedInodePath.java
LockedInodePath.lockDescendant
public LockedInodePath lockDescendant(AlluxioURI descendantUri, LockPattern lockPattern) throws InvalidPathException { LockedInodePath path = new LockedInodePath(descendantUri, this, PathUtils.getPathComponents(descendantUri.getPath()), lockPattern); path.traverseOrClose(); return path; }
java
public LockedInodePath lockDescendant(AlluxioURI descendantUri, LockPattern lockPattern) throws InvalidPathException { LockedInodePath path = new LockedInodePath(descendantUri, this, PathUtils.getPathComponents(descendantUri.getPath()), lockPattern); path.traverseOrClose(); return path; }
[ "public", "LockedInodePath", "lockDescendant", "(", "AlluxioURI", "descendantUri", ",", "LockPattern", "lockPattern", ")", "throws", "InvalidPathException", "{", "LockedInodePath", "path", "=", "new", "LockedInodePath", "(", "descendantUri", ",", "this", ",", "PathUtils...
Locks a descendant of the current path and returns a new locked inode path. The path is traversed according to the lock pattern. Closing the new path will have no effect on the current path. On failure, all locks taken by this method will be released. @param descendantUri the full descendent uri starting from the root @param lockPattern the lock pattern to lock in @return the new locked path
[ "Locks", "a", "descendant", "of", "the", "current", "path", "and", "returns", "a", "new", "locked", "inode", "path", ".", "The", "path", "is", "traversed", "according", "to", "the", "lock", "pattern", ".", "Closing", "the", "new", "path", "will", "have", ...
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/LockedInodePath.java#L360-L366
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/GroupComparator.java
GroupComparator.compare
@SuppressWarnings("rawtypes") @Override public int compare(ITuple w1, ITuple w2) { int schemaId1 = tupleMRConf.getSchemaIdByName(w1.getSchema().getName()); int schemaId2 = tupleMRConf.getSchemaIdByName(w2.getSchema().getName()); int[] indexes1 = serInfo.getGroupSchemaIndexTranslation(schemaId1); int[] indexes2 = serInfo.getGroupSchemaIndexTranslation(schemaId2); Serializer[] serializers = serInfo.getGroupSchemaSerializers(); return compare(w1.getSchema(), groupCriteria, w1, indexes1, w2, indexes2,serializers); }
java
@SuppressWarnings("rawtypes") @Override public int compare(ITuple w1, ITuple w2) { int schemaId1 = tupleMRConf.getSchemaIdByName(w1.getSchema().getName()); int schemaId2 = tupleMRConf.getSchemaIdByName(w2.getSchema().getName()); int[] indexes1 = serInfo.getGroupSchemaIndexTranslation(schemaId1); int[] indexes2 = serInfo.getGroupSchemaIndexTranslation(schemaId2); Serializer[] serializers = serInfo.getGroupSchemaSerializers(); return compare(w1.getSchema(), groupCriteria, w1, indexes1, w2, indexes2,serializers); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "@", "Override", "public", "int", "compare", "(", "ITuple", "w1", ",", "ITuple", "w2", ")", "{", "int", "schemaId1", "=", "tupleMRConf", ".", "getSchemaIdByName", "(", "w1", ".", "getSchema", "(", ")", "."...
Never called in MapRed jobs. Just for completion and test purposes
[ "Never", "called", "in", "MapRed", "jobs", ".", "Just", "for", "completion", "and", "test", "purposes" ]
train
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/GroupComparator.java#L45-L54
foundation-runtime/monitoring
monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java
RMIRegistryManager.isRMIRegistryRunning
public static boolean isRMIRegistryRunning(Configuration configuration, int port) { try { final Registry registry = RegistryFinder.getInstance().getRegistry(configuration, port); registry.list(); return true; } catch (RemoteException ex) { return false; } catch (Exception e) { return false; } }
java
public static boolean isRMIRegistryRunning(Configuration configuration, int port) { try { final Registry registry = RegistryFinder.getInstance().getRegistry(configuration, port); registry.list(); return true; } catch (RemoteException ex) { return false; } catch (Exception e) { return false; } }
[ "public", "static", "boolean", "isRMIRegistryRunning", "(", "Configuration", "configuration", ",", "int", "port", ")", "{", "try", "{", "final", "Registry", "registry", "=", "RegistryFinder", ".", "getInstance", "(", ")", ".", "getRegistry", "(", "configuration", ...
Checks if rmiregistry is running on the specified port. @param port @return true if rmiregistry is running on the specified port, false otherwise
[ "Checks", "if", "rmiregistry", "is", "running", "on", "the", "specified", "port", "." ]
train
https://github.com/foundation-runtime/monitoring/blob/a85ec72dc5558f787704fb13d9125a5803403ee5/monitoring-jmx-lib/src/main/java/com/cisco/oss/foundation/monitoring/RMIRegistryManager.java#L45-L55
Graylog2/graylog2-server
graylog2-server/src/main/java/org/graylog/plugins/pipelineprocessor/ast/Rule.java
Rule.registerMetrics
public void registerMetrics(MetricRegistry metricRegistry, String pipelineId, String stageId) { if (id() == null) { LOG.debug("Not registering metrics for unsaved rule {}", name()); return; } if (id() != null) { globalExecuted = registerGlobalMeter(metricRegistry, "executed"); localExecuted = registerLocalMeter(metricRegistry, pipelineId, stageId, "executed"); globalFailed = registerGlobalMeter(metricRegistry, "failed"); localFailed = registerLocalMeter(metricRegistry, pipelineId, stageId, "failed"); globalMatched = registerGlobalMeter(metricRegistry, "matched"); localMatched = registerLocalMeter(metricRegistry, pipelineId, stageId, "matched"); globalNotMatched = registerGlobalMeter(metricRegistry, "not-matched"); localNotMatched = registerLocalMeter(metricRegistry, pipelineId, stageId, "not-matched"); } }
java
public void registerMetrics(MetricRegistry metricRegistry, String pipelineId, String stageId) { if (id() == null) { LOG.debug("Not registering metrics for unsaved rule {}", name()); return; } if (id() != null) { globalExecuted = registerGlobalMeter(metricRegistry, "executed"); localExecuted = registerLocalMeter(metricRegistry, pipelineId, stageId, "executed"); globalFailed = registerGlobalMeter(metricRegistry, "failed"); localFailed = registerLocalMeter(metricRegistry, pipelineId, stageId, "failed"); globalMatched = registerGlobalMeter(metricRegistry, "matched"); localMatched = registerLocalMeter(metricRegistry, pipelineId, stageId, "matched"); globalNotMatched = registerGlobalMeter(metricRegistry, "not-matched"); localNotMatched = registerLocalMeter(metricRegistry, pipelineId, stageId, "not-matched"); } }
[ "public", "void", "registerMetrics", "(", "MetricRegistry", "metricRegistry", ",", "String", "pipelineId", ",", "String", "stageId", ")", "{", "if", "(", "id", "(", ")", "==", "null", ")", "{", "LOG", ".", "debug", "(", "\"Not registering metrics for unsaved rul...
Register the metrics attached to this pipeline. @param metricRegistry the registry to add the metrics to
[ "Register", "the", "metrics", "attached", "to", "this", "pipeline", "." ]
train
https://github.com/Graylog2/graylog2-server/blob/50b565dcead6e0a372236d5c2f8530dc5726fa9b/graylog2-server/src/main/java/org/graylog/plugins/pipelineprocessor/ast/Rule.java#L91-L110
lucee/Lucee
core/src/main/java/lucee/runtime/type/util/ComponentUtil.java
ComponentUtil.toIntAccess
public static int toIntAccess(String access) throws ApplicationException { access = StringUtil.toLowerCase(access.trim()); if (access.equals("package")) return Component.ACCESS_PACKAGE; else if (access.equals("private")) return Component.ACCESS_PRIVATE; else if (access.equals("public")) return Component.ACCESS_PUBLIC; else if (access.equals("remote")) return Component.ACCESS_REMOTE; throw new ApplicationException("invalid access type [" + access + "], access types are remote, public, package, private"); }
java
public static int toIntAccess(String access) throws ApplicationException { access = StringUtil.toLowerCase(access.trim()); if (access.equals("package")) return Component.ACCESS_PACKAGE; else if (access.equals("private")) return Component.ACCESS_PRIVATE; else if (access.equals("public")) return Component.ACCESS_PUBLIC; else if (access.equals("remote")) return Component.ACCESS_REMOTE; throw new ApplicationException("invalid access type [" + access + "], access types are remote, public, package, private"); }
[ "public", "static", "int", "toIntAccess", "(", "String", "access", ")", "throws", "ApplicationException", "{", "access", "=", "StringUtil", ".", "toLowerCase", "(", "access", ".", "trim", "(", ")", ")", ";", "if", "(", "access", ".", "equals", "(", "\"pack...
cast a strong access definition to the int type @param access access type @return int access type @throws ExpressionException
[ "cast", "a", "strong", "access", "definition", "to", "the", "int", "type" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/util/ComponentUtil.java#L635-L643
sarl/sarl
main/coreplugins/io.sarl.lang/src-gen/io/sarl/lang/codebuilder/appenders/SarlBehaviorUnitSourceAppender.java
SarlBehaviorUnitSourceAppender.newTypeRef
public JvmParameterizedTypeReference newTypeRef(Notifier context, String typeName) { return this.builder.newTypeRef(context, typeName); }
java
public JvmParameterizedTypeReference newTypeRef(Notifier context, String typeName) { return this.builder.newTypeRef(context, typeName); }
[ "public", "JvmParameterizedTypeReference", "newTypeRef", "(", "Notifier", "context", ",", "String", "typeName", ")", "{", "return", "this", ".", "builder", ".", "newTypeRef", "(", "context", ",", "typeName", ")", ";", "}" ]
Find the reference to the type with the given name. @param context the context for the type reference use @param typeName the fully qualified name of the type @return the type reference.
[ "Find", "the", "reference", "to", "the", "type", "with", "the", "given", "name", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src-gen/io/sarl/lang/codebuilder/appenders/SarlBehaviorUnitSourceAppender.java#L67-L69
virgo47/javasimon
examples/src/main/java/org/javasimon/examples/SimonDataGenerator.java
SimonDataGenerator.addStopwatchSplits
private void addStopwatchSplits(Stopwatch stopwatch, int splitWidth) { final int splits = randomInt(splitWidth / 2, splitWidth); try { lock.lock(); System.out.print(stopwatch.getName() + " " + splits + ": "); for (int i = 0; i < splits; i++) { System.out.print(addStopwatchSplit(stopwatch) + ","); } System.out.println(); } finally { lock.unlock(); } }
java
private void addStopwatchSplits(Stopwatch stopwatch, int splitWidth) { final int splits = randomInt(splitWidth / 2, splitWidth); try { lock.lock(); System.out.print(stopwatch.getName() + " " + splits + ": "); for (int i = 0; i < splits; i++) { System.out.print(addStopwatchSplit(stopwatch) + ","); } System.out.println(); } finally { lock.unlock(); } }
[ "private", "void", "addStopwatchSplits", "(", "Stopwatch", "stopwatch", ",", "int", "splitWidth", ")", "{", "final", "int", "splits", "=", "randomInt", "(", "splitWidth", "/", "2", ",", "splitWidth", ")", ";", "try", "{", "lock", ".", "lock", "(", ")", "...
Generate a Simon of type "Stopwatch" and fill it with some Splits. @param splitWidth Max number of splits per Stopwatch
[ "Generate", "a", "Simon", "of", "type", "Stopwatch", "and", "fill", "it", "with", "some", "Splits", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/examples/src/main/java/org/javasimon/examples/SimonDataGenerator.java#L147-L159
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/sign/in/form/SigninFormPanel.java
SigninFormPanel.newSigninPanel
protected Component newSigninPanel(final String id, final IModel<T> model) { final Component component = new SigninPanel<>(id, model); return component; }
java
protected Component newSigninPanel(final String id, final IModel<T> model) { final Component component = new SigninPanel<>(id, model); return component; }
[ "protected", "Component", "newSigninPanel", "(", "final", "String", "id", ",", "final", "IModel", "<", "T", ">", "model", ")", "{", "final", "Component", "component", "=", "new", "SigninPanel", "<>", "(", "id", ",", "model", ")", ";", "return", "component"...
Factory method for creating the new {@link SigninPanel} that contains the TextField for the email and password. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a Component that contains the TextField for the email and password. @param id the id @param model the model @return the new {@link SigninPanel} that contains the TextField for the email and password.
[ "Factory", "method", "for", "creating", "the", "new", "{", "@link", "SigninPanel", "}", "that", "contains", "the", "TextField", "for", "the", "email", "and", "password", ".", "This", "method", "is", "invoked", "in", "the", "constructor", "from", "the", "deri...
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/sign/in/form/SigninFormPanel.java#L209-L213
GwtMaterialDesign/gwt-material
gwt-material/src/main/java/gwt/material/design/client/ui/MaterialListValueBox.java
MaterialListValueBox.setItemText
public void setItemText(int index, String text) { index += getIndexOffset(); listBox.setItemText(index, text); reload(); }
java
public void setItemText(int index, String text) { index += getIndexOffset(); listBox.setItemText(index, text); reload(); }
[ "public", "void", "setItemText", "(", "int", "index", ",", "String", "text", ")", "{", "index", "+=", "getIndexOffset", "(", ")", ";", "listBox", ".", "setItemText", "(", "index", ",", "text", ")", ";", "reload", "(", ")", ";", "}" ]
Sets the text associated with the item at a given index. @param index the index of the item to be set @param text the item's new text @throws IndexOutOfBoundsException if the index is out of range
[ "Sets", "the", "text", "associated", "with", "the", "item", "at", "a", "given", "index", "." ]
train
https://github.com/GwtMaterialDesign/gwt-material/blob/86feefb282b007c0a44784c09e651a50f257138e/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialListValueBox.java#L718-L722
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/WebhooksInner.java
WebhooksInner.updateAsync
public Observable<WebhookInner> updateAsync(String resourceGroupName, String automationAccountName, String webhookName, WebhookUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, webhookName, parameters).map(new Func1<ServiceResponse<WebhookInner>, WebhookInner>() { @Override public WebhookInner call(ServiceResponse<WebhookInner> response) { return response.body(); } }); }
java
public Observable<WebhookInner> updateAsync(String resourceGroupName, String automationAccountName, String webhookName, WebhookUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, webhookName, parameters).map(new Func1<ServiceResponse<WebhookInner>, WebhookInner>() { @Override public WebhookInner call(ServiceResponse<WebhookInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "WebhookInner", ">", "updateAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "webhookName", ",", "WebhookUpdateParameters", "parameters", ")", "{", "return", "updateWithServiceResponseAsync", "...
Update the webhook identified by webhook name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param webhookName The webhook name. @param parameters The update parameters for webhook. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the WebhookInner object
[ "Update", "the", "webhook", "identified", "by", "webhook", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/WebhooksInner.java#L504-L511
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FileUtil.java
FileUtil.replaceFile
public static void replaceFile(File src, File target) throws IOException { /* renameTo() has two limitations on Windows platform. * src.renameTo(target) fails if * 1) If target already exists OR * 2) If target is already open for reading/writing. */ if (!src.renameTo(target)) { int retries = 5; while (target.exists() && !target.delete() && retries-- >= 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new IOException("replaceFile interrupted."); } } if (!src.renameTo(target)) { throw new IOException("Unable to rename " + src + " to " + target); } } }
java
public static void replaceFile(File src, File target) throws IOException { /* renameTo() has two limitations on Windows platform. * src.renameTo(target) fails if * 1) If target already exists OR * 2) If target is already open for reading/writing. */ if (!src.renameTo(target)) { int retries = 5; while (target.exists() && !target.delete() && retries-- >= 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new IOException("replaceFile interrupted."); } } if (!src.renameTo(target)) { throw new IOException("Unable to rename " + src + " to " + target); } } }
[ "public", "static", "void", "replaceFile", "(", "File", "src", ",", "File", "target", ")", "throws", "IOException", "{", "/* renameTo() has two limitations on Windows platform.\n * src.renameTo(target) fails if\n * 1) If target already exists OR\n * 2) If target is already op...
Move the src file to the name specified by target. @param src the source file @param target the target file @exception IOException If this operation fails
[ "Move", "the", "src", "file", "to", "the", "name", "specified", "by", "target", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileUtil.java#L915-L935
networknt/light-4j
http-url/src/main/java/com/networknt/url/QueryString.java
QueryString.applyOnURL
public URL applyOnURL(URL url) { if (url == null) { return url; } try { return new URL(applyOnURL(url.toString())); } catch (MalformedURLException e) { throw new RuntimeException("Cannot applyl query string to: " + url, e); } }
java
public URL applyOnURL(URL url) { if (url == null) { return url; } try { return new URL(applyOnURL(url.toString())); } catch (MalformedURLException e) { throw new RuntimeException("Cannot applyl query string to: " + url, e); } }
[ "public", "URL", "applyOnURL", "(", "URL", "url", ")", "{", "if", "(", "url", "==", "null", ")", "{", "return", "url", ";", "}", "try", "{", "return", "new", "URL", "(", "applyOnURL", "(", "url", ".", "toString", "(", ")", ")", ")", ";", "}", "...
Apply this url QueryString on the given URL. If a query string already exists, it is replaced by this one. @param url the URL to apply this query string. @return url with query string added
[ "Apply", "this", "url", "QueryString", "on", "the", "given", "URL", ".", "If", "a", "query", "string", "already", "exists", "it", "is", "replaced", "by", "this", "one", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/http-url/src/main/java/com/networknt/url/QueryString.java#L182-L191
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java
KeyChainGroup.importKeysAndEncrypt
public int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey) { // TODO: Firstly check if the aes key can decrypt any of the existing keys successfully. checkState(keyCrypter != null, "Not encrypted"); LinkedList<ECKey> encryptedKeys = Lists.newLinkedList(); for (ECKey key : keys) { if (key.isEncrypted()) throw new IllegalArgumentException("Cannot provide already encrypted keys"); encryptedKeys.add(key.encrypt(keyCrypter, aesKey)); } return importKeys(encryptedKeys); }
java
public int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey) { // TODO: Firstly check if the aes key can decrypt any of the existing keys successfully. checkState(keyCrypter != null, "Not encrypted"); LinkedList<ECKey> encryptedKeys = Lists.newLinkedList(); for (ECKey key : keys) { if (key.isEncrypted()) throw new IllegalArgumentException("Cannot provide already encrypted keys"); encryptedKeys.add(key.encrypt(keyCrypter, aesKey)); } return importKeys(encryptedKeys); }
[ "public", "int", "importKeysAndEncrypt", "(", "final", "List", "<", "ECKey", ">", "keys", ",", "KeyParameter", "aesKey", ")", "{", "// TODO: Firstly check if the aes key can decrypt any of the existing keys successfully.", "checkState", "(", "keyCrypter", "!=", "null", ",",...
Imports the given unencrypted keys into the basic chain, encrypting them along the way with the given key.
[ "Imports", "the", "given", "unencrypted", "keys", "into", "the", "basic", "chain", "encrypting", "them", "along", "the", "way", "with", "the", "given", "key", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L490-L500
k3po/k3po
specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java
Functions.createClientGSSContext
@Function public static GSSContext createClientGSSContext(String server) { try { GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName(server, null); GSSContext context = manager.createContext(serverName, krb5Oid, null, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(true); // Mutual authentication context.requestConf(true); // Will use encryption later context.requestInteg(true); // Will use integrity later return context; } catch (GSSException ex) { throw new RuntimeException("Exception creating client GSSContext", ex); } }
java
@Function public static GSSContext createClientGSSContext(String server) { try { GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName(server, null); GSSContext context = manager.createContext(serverName, krb5Oid, null, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(true); // Mutual authentication context.requestConf(true); // Will use encryption later context.requestInteg(true); // Will use integrity later return context; } catch (GSSException ex) { throw new RuntimeException("Exception creating client GSSContext", ex); } }
[ "@", "Function", "public", "static", "GSSContext", "createClientGSSContext", "(", "String", "server", ")", "{", "try", "{", "GSSManager", "manager", "=", "GSSManager", ".", "getInstance", "(", ")", ";", "GSSName", "serverName", "=", "manager", ".", "createName",...
Create a GSS Context from a clients point of view. @param server the name of the host for which the GSS Context is being created @return the GSS Context that a client can use to exchange security tokens for a secure channel, then wrap()/unpack() messages.
[ "Create", "a", "GSS", "Context", "from", "a", "clients", "point", "of", "view", "." ]
train
https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L67-L86
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java
ExpressRouteCrossConnectionsInner.listRoutesTableSummary
public ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner listRoutesTableSummary(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { return listRoutesTableSummaryWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).toBlocking().last().body(); }
java
public ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner listRoutesTableSummary(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) { return listRoutesTableSummaryWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).toBlocking().last().body(); }
[ "public", "ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner", "listRoutesTableSummary", "(", "String", "resourceGroupName", ",", "String", "crossConnectionName", ",", "String", "peeringName", ",", "String", "devicePath", ")", "{", "return", "listRoutesTableSummaryWit...
Gets the route table summary associated with the express route cross connection in a resource group. @param resourceGroupName The name of the resource group. @param crossConnectionName The name of the ExpressRouteCrossConnection. @param peeringName The name of the peering. @param devicePath The path of the device. @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 ExpressRouteCrossConnectionsRoutesTableSummaryListResultInner object if successful.
[ "Gets", "the", "route", "table", "summary", "associated", "with", "the", "express", "route", "cross", "connection", "in", "a", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/ExpressRouteCrossConnectionsInner.java#L1106-L1108
etnetera/seb
src/main/java/cz/etnetera/seb/configuration/BasicSebConfiguration.java
BasicSebConfiguration.getDefaultDriver
protected WebDriver getDefaultDriver(DesiredCapabilities caps) { String hubUrl = getHubUrl(); if (hubUrl == null) { return new FirefoxDriver(caps); } try { return new RemoteWebDriver(new URL(hubUrl), caps); } catch (MalformedURLException e) { throw new SebException("Unable to construct remote webdriver.", e); } }
java
protected WebDriver getDefaultDriver(DesiredCapabilities caps) { String hubUrl = getHubUrl(); if (hubUrl == null) { return new FirefoxDriver(caps); } try { return new RemoteWebDriver(new URL(hubUrl), caps); } catch (MalformedURLException e) { throw new SebException("Unable to construct remote webdriver.", e); } }
[ "protected", "WebDriver", "getDefaultDriver", "(", "DesiredCapabilities", "caps", ")", "{", "String", "hubUrl", "=", "getHubUrl", "(", ")", ";", "if", "(", "hubUrl", "==", "null", ")", "{", "return", "new", "FirefoxDriver", "(", "caps", ")", ";", "}", "try...
Returns default {@link WebDriver} instance. Override this for different value. @param caps The non null desired capabilities. @return The driver
[ "Returns", "default", "{", "@link", "WebDriver", "}", "instance", ".", "Override", "this", "for", "different", "value", "." ]
train
https://github.com/etnetera/seb/blob/6aed29c7726db12f440c60cfd253de229064ed04/src/main/java/cz/etnetera/seb/configuration/BasicSebConfiguration.java#L165-L175
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.saveAliases
public void saveAliases(CmsRequestContext context, CmsResource resource, List<CmsAlias> aliases) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { if ((aliases.size() > 0) && !(resource.getStructureId().equals(aliases.get(0).getStructureId()))) { throw new IllegalArgumentException("Resource does not match aliases!"); } checkPermissions(context, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.saveAliases(dbc, context.getCurrentProject(), resource.getStructureId(), aliases); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put(I_CmsEventListener.KEY_RESOURCE, resource); eventData.put(I_CmsEventListener.KEY_CHANGE, new Integer(CmsDriverManager.CHANGED_RESOURCE)); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, eventData)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } }
java
public void saveAliases(CmsRequestContext context, CmsResource resource, List<CmsAlias> aliases) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { if ((aliases.size() > 0) && !(resource.getStructureId().equals(aliases.get(0).getStructureId()))) { throw new IllegalArgumentException("Resource does not match aliases!"); } checkPermissions(context, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.saveAliases(dbc, context.getCurrentProject(), resource.getStructureId(), aliases); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put(I_CmsEventListener.KEY_RESOURCE, resource); eventData.put(I_CmsEventListener.KEY_CHANGE, new Integer(CmsDriverManager.CHANGED_RESOURCE)); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, eventData)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } }
[ "public", "void", "saveAliases", "(", "CmsRequestContext", "context", ",", "CmsResource", "resource", ",", "List", "<", "CmsAlias", ">", "aliases", ")", "throws", "CmsException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "con...
Saves the aliases for a given resource.<p> This method completely replaces any existing aliases for the same structure id. @param context the request context @param resource the resource for which the aliases should be written @param aliases the list of aliases to write, where all aliases must have the same structure id as the resource @throws CmsException if something goes wrong
[ "Saves", "the", "aliases", "for", "a", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L5872-L5891
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/Model.java
Model.toJson
public String toJson(boolean pretty, String... attributeNames) { StringBuilder sb = new StringBuilder(); toJsonP(sb, pretty, "", attributeNames); return sb.toString(); }
java
public String toJson(boolean pretty, String... attributeNames) { StringBuilder sb = new StringBuilder(); toJsonP(sb, pretty, "", attributeNames); return sb.toString(); }
[ "public", "String", "toJson", "(", "boolean", "pretty", ",", "String", "...", "attributeNames", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "toJsonP", "(", "sb", ",", "pretty", ",", "\"\"", ",", "attributeNames", ")", ";", ...
Generates a JSON document from content of this model. @param pretty pretty format (human readable), or one line text. @param attributeNames list of attributes to include. No arguments == include all attributes. @return generated JSON.
[ "Generates", "a", "JSON", "document", "from", "content", "of", "this", "model", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L1069-L1073
gsi-upm/BeastTool
beast-tool/src/main/java/es/upm/dit/gsi/beast/reader/Reader.java
Reader.createFileWriter
protected static FileWriter createFileWriter(String scenarioName, String aux_package_path, String dest_dir) throws BeastException { try { return new FileWriter(new File(createFolder(aux_package_path, dest_dir), scenarioName + ".story")); } catch (IOException e) { String message = "ERROR writing the " + scenarioName + ".story file: " + e.toString(); logger.severe(message); throw new BeastException(message, e); } }
java
protected static FileWriter createFileWriter(String scenarioName, String aux_package_path, String dest_dir) throws BeastException { try { return new FileWriter(new File(createFolder(aux_package_path, dest_dir), scenarioName + ".story")); } catch (IOException e) { String message = "ERROR writing the " + scenarioName + ".story file: " + e.toString(); logger.severe(message); throw new BeastException(message, e); } }
[ "protected", "static", "FileWriter", "createFileWriter", "(", "String", "scenarioName", ",", "String", "aux_package_path", ",", "String", "dest_dir", ")", "throws", "BeastException", "{", "try", "{", "return", "new", "FileWriter", "(", "new", "File", "(", "createF...
Method to get the file writer required for the .story files @param scenarioName @param aux_package_path @param dest_dir @return The file writer that generates the .story files for each test @throws BeastException
[ "Method", "to", "get", "the", "file", "writer", "required", "for", "the", ".", "story", "files" ]
train
https://github.com/gsi-upm/BeastTool/blob/cc7fdc75cb818c5d60802aaf32c27829e0ca144c/beast-tool/src/main/java/es/upm/dit/gsi/beast/reader/Reader.java#L342-L353
leancloud/java-sdk-all
android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/hwid/SignOutApi.java
SignOutApi.onConnect
@Override public void onConnect(int rst, HuaweiApiClient client) { if (client == null || !ApiClientMgr.INST.isConnect(client)) { HMSAgentLog.e("client not connted"); onSignOutResult(rst, null); return; } PendingResult<SignOutResult> signOutResult = HuaweiId.HuaweiIdApi.signOut(client); signOutResult.setResultCallback(new ResultCallback<SignOutResult>() { @Override public void onResult(SignOutResult result) { if (result == null) { HMSAgentLog.e("result is null"); onSignOutResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null); return; } Status status = result.getStatus(); if (status == null) { HMSAgentLog.e("status is null"); onSignOutResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null); return; } int rstCode = status.getStatusCode(); HMSAgentLog.d("status=" + status); // 需要重试的错误码,并且可以重试 if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID || rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) { retryTimes--; connect(); } else { onSignOutResult(rstCode, result); } } }); }
java
@Override public void onConnect(int rst, HuaweiApiClient client) { if (client == null || !ApiClientMgr.INST.isConnect(client)) { HMSAgentLog.e("client not connted"); onSignOutResult(rst, null); return; } PendingResult<SignOutResult> signOutResult = HuaweiId.HuaweiIdApi.signOut(client); signOutResult.setResultCallback(new ResultCallback<SignOutResult>() { @Override public void onResult(SignOutResult result) { if (result == null) { HMSAgentLog.e("result is null"); onSignOutResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null); return; } Status status = result.getStatus(); if (status == null) { HMSAgentLog.e("status is null"); onSignOutResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null); return; } int rstCode = status.getStatusCode(); HMSAgentLog.d("status=" + status); // 需要重试的错误码,并且可以重试 if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID || rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) { retryTimes--; connect(); } else { onSignOutResult(rstCode, result); } } }); }
[ "@", "Override", "public", "void", "onConnect", "(", "int", "rst", ",", "HuaweiApiClient", "client", ")", "{", "if", "(", "client", "==", "null", "||", "!", "ApiClientMgr", ".", "INST", ".", "isConnect", "(", "client", ")", ")", "{", "HMSAgentLog", ".", ...
HuaweiApiClient 连接结果回调 @param rst 结果码 @param client HuaweiApiClient 实例
[ "HuaweiApiClient", "连接结果回调" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/hwid/SignOutApi.java#L47-L84
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java
PatternBox.controlsStateChangeThroughControllerSmallMolecule
public static Pattern controlsStateChangeThroughControllerSmallMolecule(Blacklist blacklist) { Pattern p = new Pattern(SequenceEntityReference.class, "upper controller ER"); p.add(linkedER(true), "upper controller ER", "upper controller generic ER"); p.add(erToPE(), "upper controller generic ER", "upper controller simple PE"); p.add(linkToComplex(), "upper controller simple PE", "upper controller PE"); p.add(peToControl(), "upper controller PE", "upper Control"); p.add(controlToConv(), "upper Control", "upper Conversion"); p.add(new NOT(participantER()), "upper Conversion", "upper controller ER"); p.add(new Participant(RelType.OUTPUT, blacklist), "upper Conversion", "controller PE"); p.add(type(SmallMolecule.class), "controller PE"); if (blacklist != null) p.add(new NonUbique(blacklist), "controller PE"); // the linker small mol is at also an input p.add(new NOT(new ConstraintChain( new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "controller PE", "upper Conversion", "controller PE"); p.add(peToControl(), "controller PE", "Control"); p.add(controlToConv(), "Control", "Conversion"); p.add(equal(false), "upper Conversion", "Conversion"); // p.add(nextInteraction(), "upper Conversion", "Conversion"); stateChange(p, "Control"); p.add(type(SequenceEntityReference.class), "changed ER"); p.add(equal(false), "upper controller ER", "changed ER"); p.add(new NOT(participantER()), "Conversion", "upper controller ER"); return p; }
java
public static Pattern controlsStateChangeThroughControllerSmallMolecule(Blacklist blacklist) { Pattern p = new Pattern(SequenceEntityReference.class, "upper controller ER"); p.add(linkedER(true), "upper controller ER", "upper controller generic ER"); p.add(erToPE(), "upper controller generic ER", "upper controller simple PE"); p.add(linkToComplex(), "upper controller simple PE", "upper controller PE"); p.add(peToControl(), "upper controller PE", "upper Control"); p.add(controlToConv(), "upper Control", "upper Conversion"); p.add(new NOT(participantER()), "upper Conversion", "upper controller ER"); p.add(new Participant(RelType.OUTPUT, blacklist), "upper Conversion", "controller PE"); p.add(type(SmallMolecule.class), "controller PE"); if (blacklist != null) p.add(new NonUbique(blacklist), "controller PE"); // the linker small mol is at also an input p.add(new NOT(new ConstraintChain( new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "controller PE", "upper Conversion", "controller PE"); p.add(peToControl(), "controller PE", "Control"); p.add(controlToConv(), "Control", "Conversion"); p.add(equal(false), "upper Conversion", "Conversion"); // p.add(nextInteraction(), "upper Conversion", "Conversion"); stateChange(p, "Control"); p.add(type(SequenceEntityReference.class), "changed ER"); p.add(equal(false), "upper controller ER", "changed ER"); p.add(new NOT(participantER()), "Conversion", "upper controller ER"); return p; }
[ "public", "static", "Pattern", "controlsStateChangeThroughControllerSmallMolecule", "(", "Blacklist", "blacklist", ")", "{", "Pattern", "p", "=", "new", "Pattern", "(", "SequenceEntityReference", ".", "class", ",", "\"upper controller ER\"", ")", ";", "p", ".", "add",...
Pattern for an entity is producing a small molecule, and the small molecule controls state change of another molecule. @param blacklist a skip-list of ubiquitous molecules @return the pattern
[ "Pattern", "for", "an", "entity", "is", "producing", "a", "small", "molecule", "and", "the", "small", "molecule", "controls", "state", "change", "of", "another", "molecule", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L204-L235
google/j2objc
jre_emul/android/platform/libcore/luni/src/main/java/libcore/reflect/Types.java
Types.appendTypeName
@ObjectiveCName("appendTypeName:class:") public static void appendTypeName(StringBuilder out, Class<?> c) { int dimensions = 0; while (c.isArray()) { c = c.getComponentType(); dimensions++; } out.append(c.getName()); for (int d = 0; d < dimensions; d++) { out.append("[]"); } }
java
@ObjectiveCName("appendTypeName:class:") public static void appendTypeName(StringBuilder out, Class<?> c) { int dimensions = 0; while (c.isArray()) { c = c.getComponentType(); dimensions++; } out.append(c.getName()); for (int d = 0; d < dimensions; d++) { out.append("[]"); } }
[ "@", "ObjectiveCName", "(", "\"appendTypeName:class:\"", ")", "public", "static", "void", "appendTypeName", "(", "StringBuilder", "out", ",", "Class", "<", "?", ">", "c", ")", "{", "int", "dimensions", "=", "0", ";", "while", "(", "c", ".", "isArray", "(",...
Appends the best {@link #toString} name for {@code c} to {@code out}. This works around the fact that {@link Class#getName} is lousy for primitive arrays (it writes "[C" instead of "char[]") and {@link Class#getCanonicalName()} is lousy for nested classes (it uses a "." separator rather than a "$" separator).
[ "Appends", "the", "best", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/libcore/reflect/Types.java#L104-L115
calimero-project/calimero-core
src/tuwien/auto/calimero/serial/usb/HidReport.java
HidReport.createFeatureService
public static HidReport createFeatureService(final BusAccessServerService service, final BusAccessServerFeature feature, final byte[] frame) { return new HidReport(service, feature, frame); }
java
public static HidReport createFeatureService(final BusAccessServerService service, final BusAccessServerFeature feature, final byte[] frame) { return new HidReport(service, feature, frame); }
[ "public", "static", "HidReport", "createFeatureService", "(", "final", "BusAccessServerService", "service", ",", "final", "BusAccessServerFeature", "feature", ",", "final", "byte", "[", "]", "frame", ")", "{", "return", "new", "HidReport", "(", "service", ",", "fe...
Creates a new report for use with the Bus Access Server feature service. @param service Bus Access Server service @param feature feature ID @param frame feature protocol data @return the created HID report
[ "Creates", "a", "new", "report", "for", "use", "with", "the", "Bus", "Access", "Server", "feature", "service", "." ]
train
https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/serial/usb/HidReport.java#L126-L130
overturetool/overture
core/interpreter/src/main/java/org/overture/interpreter/assistant/expression/PExpAssistantInterpreter.java
PExpAssistantInterpreter.getValues
public ValueList getValues(PExp exp, ObjectContext ctxt) { try { return exp.apply(af.getExpressionValueCollector(), ctxt);// FIXME: should we handle exceptions like this } catch (AnalysisException e) { return null; // Most have none } }
java
public ValueList getValues(PExp exp, ObjectContext ctxt) { try { return exp.apply(af.getExpressionValueCollector(), ctxt);// FIXME: should we handle exceptions like this } catch (AnalysisException e) { return null; // Most have none } }
[ "public", "ValueList", "getValues", "(", "PExp", "exp", ",", "ObjectContext", "ctxt", ")", "{", "try", "{", "return", "exp", ".", "apply", "(", "af", ".", "getExpressionValueCollector", "(", ")", ",", "ctxt", ")", ";", "// FIXME: should we handle exceptions like...
Return a list of all the updatable values read by the expression. This is used to add listeners to values that affect permission guards, so that the guard may be efficiently re-evaluated when the values change. @param exp @param ctxt The context in which to search for values. @return A list of values read by the expression.
[ "Return", "a", "list", "of", "all", "the", "updatable", "values", "read", "by", "the", "expression", ".", "This", "is", "used", "to", "add", "listeners", "to", "values", "that", "affect", "permission", "guards", "so", "that", "the", "guard", "may", "be", ...
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/assistant/expression/PExpAssistantInterpreter.java#L35-L44
GCRC/nunaliit
nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/StreamUtils.java
StreamUtils.copyStream
static public void copyStream(InputStream is, OutputStream os, int transferBufferSize) throws IOException { if( transferBufferSize < 1 ) { throw new IOException("Transfer buffer size can not be smaller than 1"); } byte[] buffer = new byte[transferBufferSize]; int bytesRead = is.read(buffer); while( bytesRead >= 0 ) { os.write(buffer, 0, bytesRead); bytesRead = is.read(buffer); } }
java
static public void copyStream(InputStream is, OutputStream os, int transferBufferSize) throws IOException { if( transferBufferSize < 1 ) { throw new IOException("Transfer buffer size can not be smaller than 1"); } byte[] buffer = new byte[transferBufferSize]; int bytesRead = is.read(buffer); while( bytesRead >= 0 ) { os.write(buffer, 0, bytesRead); bytesRead = is.read(buffer); } }
[ "static", "public", "void", "copyStream", "(", "InputStream", "is", ",", "OutputStream", "os", ",", "int", "transferBufferSize", ")", "throws", "IOException", "{", "if", "(", "transferBufferSize", "<", "1", ")", "{", "throw", "new", "IOException", "(", "\"Tran...
Copy all the bytes from an input stream to an output stream. @param is Stream to read bytes from @param os Stream to write bytes to @param transferBufferSize Size of buffer used to transfer bytes from one stream to the other @throws IOException
[ "Copy", "all", "the", "bytes", "from", "an", "input", "stream", "to", "an", "output", "stream", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/StreamUtils.java#L31-L44
nohana/Amalgam
amalgam/src/main/java/com/amalgam/app/SupportProgressDialogFragment.java
SupportProgressDialogFragment.newInstance
public static final SupportProgressDialogFragment newInstance(String title, String message, boolean indeterminate) { SupportProgressDialogFragment fragment = new SupportProgressDialogFragment(); Bundle args = new Bundle(); args.putString(ARGS_TITLE, title); args.putString(ARGS_MESSAGE, message); args.putBoolean(ARGS_INDETERMINATE, indeterminate); fragment.setArguments(args); return fragment; }
java
public static final SupportProgressDialogFragment newInstance(String title, String message, boolean indeterminate) { SupportProgressDialogFragment fragment = new SupportProgressDialogFragment(); Bundle args = new Bundle(); args.putString(ARGS_TITLE, title); args.putString(ARGS_MESSAGE, message); args.putBoolean(ARGS_INDETERMINATE, indeterminate); fragment.setArguments(args); return fragment; }
[ "public", "static", "final", "SupportProgressDialogFragment", "newInstance", "(", "String", "title", ",", "String", "message", ",", "boolean", "indeterminate", ")", "{", "SupportProgressDialogFragment", "fragment", "=", "new", "SupportProgressDialogFragment", "(", ")", ...
Create a new instance of the {@link com.amalgam.app.SupportProgressDialogFragment}. @param title the title text, can be null @param message the message text, must not be null. @param indeterminate indeterminate progress or not. @return the instance of the {@link com.amalgam.app.SupportProgressDialogFragment}.
[ "Create", "a", "new", "instance", "of", "the", "{", "@link", "com", ".", "amalgam", ".", "app", ".", "SupportProgressDialogFragment", "}", "." ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/app/SupportProgressDialogFragment.java#L63-L71
googleapis/google-cloud-java
google-cloud-clients/google-cloud-iot/src/main/java/com/google/cloud/iot/v1/DeviceManagerClient.java
DeviceManagerClient.modifyCloudToDeviceConfig
public final DeviceConfig modifyCloudToDeviceConfig(DeviceName name, ByteString binaryData) { ModifyCloudToDeviceConfigRequest request = ModifyCloudToDeviceConfigRequest.newBuilder() .setName(name == null ? null : name.toString()) .setBinaryData(binaryData) .build(); return modifyCloudToDeviceConfig(request); }
java
public final DeviceConfig modifyCloudToDeviceConfig(DeviceName name, ByteString binaryData) { ModifyCloudToDeviceConfigRequest request = ModifyCloudToDeviceConfigRequest.newBuilder() .setName(name == null ? null : name.toString()) .setBinaryData(binaryData) .build(); return modifyCloudToDeviceConfig(request); }
[ "public", "final", "DeviceConfig", "modifyCloudToDeviceConfig", "(", "DeviceName", "name", ",", "ByteString", "binaryData", ")", "{", "ModifyCloudToDeviceConfigRequest", "request", "=", "ModifyCloudToDeviceConfigRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", ...
Modifies the configuration for the device, which is eventually sent from the Cloud IoT Core servers. Returns the modified configuration version and its metadata. <p>Sample code: <pre><code> try (DeviceManagerClient deviceManagerClient = DeviceManagerClient.create()) { DeviceName name = DeviceName.of("[PROJECT]", "[LOCATION]", "[REGISTRY]", "[DEVICE]"); ByteString binaryData = ByteString.copyFromUtf8(""); DeviceConfig response = deviceManagerClient.modifyCloudToDeviceConfig(name, binaryData); } </code></pre> @param name The name of the device. For example, `projects/p0/locations/us-central1/registries/registry0/devices/device0` or `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`. @param binaryData The configuration data for the device. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Modifies", "the", "configuration", "for", "the", "device", "which", "is", "eventually", "sent", "from", "the", "Cloud", "IoT", "Core", "servers", ".", "Returns", "the", "modified", "configuration", "version", "and", "its", "metadata", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-iot/src/main/java/com/google/cloud/iot/v1/DeviceManagerClient.java#L1210-L1218
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/JmsBytesMessageImpl.java
JmsBytesMessageImpl.writeBytes
@Override public void writeBytes(byte[] value, int offset, int length) throws JMSException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "writeBytes", new Object[] { value, offset, length }); try { // Check if the producer has promised not to modify the payload after it's been set checkProducerPromise("writeBytes(byte[], int, int)", "JmsBytesMessageImpl.writeBytes#2"); // Check that we are in write mode checkBodyWriteable("writeBytes"); // Write the byte array to the output stream // We don't check for value==null as JDK1.1.6 DataOutputStream doesn't writeStream.write(value, offset, length); // Invalidate the cached toString object. cachedBytesToString = null; // Ensure that the new data gets exported when the time comes. bodySetInJsMsg = false; } // We don't expect the writeBytes to fail, but we need to catch the exception anyway catch (IOException ex) { // No FFDC code needed // d238447 review. Generate FFDC for this case. throw (JMSException) JmsErrorUtils.newThrowable( ResourceAllocationException.class, "WRITE_PROBLEM_CWSIA0186", null, ex, "JmsBytesMessageImpl.writeBytes#1", this, tc); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "writeBytes"); }
java
@Override public void writeBytes(byte[] value, int offset, int length) throws JMSException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "writeBytes", new Object[] { value, offset, length }); try { // Check if the producer has promised not to modify the payload after it's been set checkProducerPromise("writeBytes(byte[], int, int)", "JmsBytesMessageImpl.writeBytes#2"); // Check that we are in write mode checkBodyWriteable("writeBytes"); // Write the byte array to the output stream // We don't check for value==null as JDK1.1.6 DataOutputStream doesn't writeStream.write(value, offset, length); // Invalidate the cached toString object. cachedBytesToString = null; // Ensure that the new data gets exported when the time comes. bodySetInJsMsg = false; } // We don't expect the writeBytes to fail, but we need to catch the exception anyway catch (IOException ex) { // No FFDC code needed // d238447 review. Generate FFDC for this case. throw (JMSException) JmsErrorUtils.newThrowable( ResourceAllocationException.class, "WRITE_PROBLEM_CWSIA0186", null, ex, "JmsBytesMessageImpl.writeBytes#1", this, tc); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "writeBytes"); }
[ "@", "Override", "public", "void", "writeBytes", "(", "byte", "[", "]", "value", ",", "int", "offset", ",", "int", "length", ")", "throws", "JMSException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEna...
Write a portion of a byte array to the stream message. @param value the byte array value to be written. @param offset the initial offset within the byte array. @param length the number of bytes to use. @exception MessageNotWriteableException if message in read-only mode. @exception JMSException if JMS fails to write message due to some internal JMS error.
[ "Write", "a", "portion", "of", "a", "byte", "array", "to", "the", "stream", "message", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/JmsBytesMessageImpl.java#L1200-L1239
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/AsyncDataStream.java
AsyncDataStream.unorderedWait
public static <IN, OUT> SingleOutputStreamOperator<OUT> unorderedWait( DataStream<IN> in, AsyncFunction<IN, OUT> func, long timeout, TimeUnit timeUnit, int capacity) { return addOperator(in, func, timeUnit.toMillis(timeout), capacity, OutputMode.UNORDERED); }
java
public static <IN, OUT> SingleOutputStreamOperator<OUT> unorderedWait( DataStream<IN> in, AsyncFunction<IN, OUT> func, long timeout, TimeUnit timeUnit, int capacity) { return addOperator(in, func, timeUnit.toMillis(timeout), capacity, OutputMode.UNORDERED); }
[ "public", "static", "<", "IN", ",", "OUT", ">", "SingleOutputStreamOperator", "<", "OUT", ">", "unorderedWait", "(", "DataStream", "<", "IN", ">", "in", ",", "AsyncFunction", "<", "IN", ",", "OUT", ">", "func", ",", "long", "timeout", ",", "TimeUnit", "t...
Add an AsyncWaitOperator. The order of output stream records may be reordered. @param in Input {@link DataStream} @param func {@link AsyncFunction} @param timeout for the asynchronous operation to complete @param timeUnit of the given timeout @param capacity The max number of async i/o operation that can be triggered @param <IN> Type of input record @param <OUT> Type of output record @return A new {@link SingleOutputStreamOperator}.
[ "Add", "an", "AsyncWaitOperator", ".", "The", "order", "of", "output", "stream", "records", "may", "be", "reordered", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/AsyncDataStream.java#L102-L109
jayantk/jklol
src/com/jayantkrish/jklol/models/dynamic/DynamicVariableSet.java
DynamicVariableSet.instantiateVariables
public VariableNumMap instantiateVariables(DynamicAssignment assignment) { List<String> varNames = Lists.newArrayList(); List<Variable> variables = Lists.newArrayList(); List<Integer> variableInds = Lists.newArrayList(); instantiateVariablesHelper(assignment, varNames, variables, variableInds, "", 0); Preconditions.checkState(varNames.size() == variables.size()); return new VariableNumMap(variableInds, varNames, variables); }
java
public VariableNumMap instantiateVariables(DynamicAssignment assignment) { List<String> varNames = Lists.newArrayList(); List<Variable> variables = Lists.newArrayList(); List<Integer> variableInds = Lists.newArrayList(); instantiateVariablesHelper(assignment, varNames, variables, variableInds, "", 0); Preconditions.checkState(varNames.size() == variables.size()); return new VariableNumMap(variableInds, varNames, variables); }
[ "public", "VariableNumMap", "instantiateVariables", "(", "DynamicAssignment", "assignment", ")", "{", "List", "<", "String", ">", "varNames", "=", "Lists", ".", "newArrayList", "(", ")", ";", "List", "<", "Variable", ">", "variables", "=", "Lists", ".", "newAr...
Gets a {@code VariableNumMap} by replicating the plates in {@code this}. {@code assignment} must contain a value (list of assignments) for all plates in {@code this}; these values determine how many times each plate is replicated in the returned {@code VariableNumMap}. If two assignments have the same number of replications of each plate, this method will return the same {@code VariableNumMap}. @param assignment @return
[ "Gets", "a", "{", "@code", "VariableNumMap", "}", "by", "replicating", "the", "plates", "in", "{", "@code", "this", "}", ".", "{", "@code", "assignment", "}", "must", "contain", "a", "value", "(", "list", "of", "assignments", ")", "for", "all", "plates",...
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/dynamic/DynamicVariableSet.java#L179-L187
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/extension/properties/PropertiesCoreExtension.java
PropertiesCoreExtension.addValue
public boolean addValue(String property, String value) { if (!has()) { getOrCreate(); } boolean added = false; if (!hasValue(property, value)) { TRow row = newRow(); row.setValue(COLUMN_PROPERTY, property); row.setValue(COLUMN_VALUE, value); getDao().insert(row); added = true; } return added; }
java
public boolean addValue(String property, String value) { if (!has()) { getOrCreate(); } boolean added = false; if (!hasValue(property, value)) { TRow row = newRow(); row.setValue(COLUMN_PROPERTY, property); row.setValue(COLUMN_VALUE, value); getDao().insert(row); added = true; } return added; }
[ "public", "boolean", "addValue", "(", "String", "property", ",", "String", "value", ")", "{", "if", "(", "!", "has", "(", ")", ")", "{", "getOrCreate", "(", ")", ";", "}", "boolean", "added", "=", "false", ";", "if", "(", "!", "hasValue", "(", "pro...
Add a property value, creating the extension if needed @param property property name @param value value @return true if added, false if already existed
[ "Add", "a", "property", "value", "creating", "the", "extension", "if", "needed" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/extension/properties/PropertiesCoreExtension.java#L307-L320
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/StandardResponsesApi.java
StandardResponsesApi.getCategoryDetails
public ApiSuccessResponse getCategoryDetails(String id, GetCategoryData getCategoryData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = getCategoryDetailsWithHttpInfo(id, getCategoryData); return resp.getData(); }
java
public ApiSuccessResponse getCategoryDetails(String id, GetCategoryData getCategoryData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = getCategoryDetailsWithHttpInfo(id, getCategoryData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "getCategoryDetails", "(", "String", "id", ",", "GetCategoryData", "getCategoryData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "getCategoryDetailsWithHttpInfo", "(", "id", ",", "getCa...
Get the details of a Category. Get details of a Category including category sub tree. Only &#39;id&#39;, &#39;standardResponseId&#39;, and &#39;name&#39; attributes are returned for each Standard Response. @param id id of the Category (required) @param getCategoryData (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "the", "details", "of", "a", "Category", ".", "Get", "details", "of", "a", "Category", "including", "category", "sub", "tree", ".", "Only", "&#39", ";", "id&#39", ";", "&#39", ";", "standardResponseId&#39", ";", "and", "&#39", ";", "name&#39", ";", ...
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/StandardResponsesApi.java#L517-L520