repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
opentelecoms-org/jsmpp | jsmpp-examples/src/main/java/org/jsmpp/examples/gateway/AutoReconnectGateway.java | AutoReconnectGateway.newSession | private SMPPSession newSession() throws IOException {
"""
Create new {@link SMPPSession} complete with the {@link SessionStateListenerImpl}.
@return the {@link SMPPSession}.
@throws IOException if the creation of new session failed.
"""
SMPPSession tmpSession = new SMPPSession(remoteIpAddress, remotePort, bindParam);
tmpSession.addSessionStateListener(new SessionStateListenerImpl());
return tmpSession;
} | java | private SMPPSession newSession() throws IOException {
SMPPSession tmpSession = new SMPPSession(remoteIpAddress, remotePort, bindParam);
tmpSession.addSessionStateListener(new SessionStateListenerImpl());
return tmpSession;
} | [
"private",
"SMPPSession",
"newSession",
"(",
")",
"throws",
"IOException",
"{",
"SMPPSession",
"tmpSession",
"=",
"new",
"SMPPSession",
"(",
"remoteIpAddress",
",",
"remotePort",
",",
"bindParam",
")",
";",
"tmpSession",
".",
"addSessionStateListener",
"(",
"new",
... | Create new {@link SMPPSession} complete with the {@link SessionStateListenerImpl}.
@return the {@link SMPPSession}.
@throws IOException if the creation of new session failed. | [
"Create",
"new",
"{",
"@link",
"SMPPSession",
"}",
"complete",
"with",
"the",
"{",
"@link",
"SessionStateListenerImpl",
"}",
"."
] | train | https://github.com/opentelecoms-org/jsmpp/blob/acc15e73e7431deabc803731971b15323315baaf/jsmpp-examples/src/main/java/org/jsmpp/examples/gateway/AutoReconnectGateway.java#L110-L114 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.storeKeyspaceInstance | public void storeKeyspaceInstance(Keyspace keyspace) {
"""
Store given Keyspace instance to the schema
@param keyspace The Keyspace instance to store
@throws IllegalArgumentException if Keyspace is already stored
"""
if (keyspaceInstances.containsKey(keyspace.getName()))
throw new IllegalArgumentException(String.format("Keyspace %s was already initialized.", keyspace.getName()));
keyspaceInstances.put(keyspace.getName(), keyspace);
} | java | public void storeKeyspaceInstance(Keyspace keyspace)
{
if (keyspaceInstances.containsKey(keyspace.getName()))
throw new IllegalArgumentException(String.format("Keyspace %s was already initialized.", keyspace.getName()));
keyspaceInstances.put(keyspace.getName(), keyspace);
} | [
"public",
"void",
"storeKeyspaceInstance",
"(",
"Keyspace",
"keyspace",
")",
"{",
"if",
"(",
"keyspaceInstances",
".",
"containsKey",
"(",
"keyspace",
".",
"getName",
"(",
")",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
... | Store given Keyspace instance to the schema
@param keyspace The Keyspace instance to store
@throws IllegalArgumentException if Keyspace is already stored | [
"Store",
"given",
"Keyspace",
"instance",
"to",
"the",
"schema"
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L150-L156 |
rundeck/rundeck | rundeck-storage/rundeck-storage-api/src/main/java/org/rundeck/storage/api/PathUtil.java | PathUtil.hasRoot | public static boolean hasRoot(String path, String root) {
"""
@return true if the given path starts with the given root
@param path test path
@param root root
"""
String p = cleanPath(path);
String r = cleanPath(root);
return p.equals(r)
|| r.equals(cleanPath(ROOT.getPath()))
|| p.startsWith(r + SEPARATOR);
} | java | public static boolean hasRoot(String path, String root) {
String p = cleanPath(path);
String r = cleanPath(root);
return p.equals(r)
|| r.equals(cleanPath(ROOT.getPath()))
|| p.startsWith(r + SEPARATOR);
} | [
"public",
"static",
"boolean",
"hasRoot",
"(",
"String",
"path",
",",
"String",
"root",
")",
"{",
"String",
"p",
"=",
"cleanPath",
"(",
"path",
")",
";",
"String",
"r",
"=",
"cleanPath",
"(",
"root",
")",
";",
"return",
"p",
".",
"equals",
"(",
"r",
... | @return true if the given path starts with the given root
@param path test path
@param root root | [
"@return",
"true",
"if",
"the",
"given",
"path",
"starts",
"with",
"the",
"given",
"root"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/rundeck-storage/rundeck-storage-api/src/main/java/org/rundeck/storage/api/PathUtil.java#L148-L154 |
arquillian/arquillian-cube | openshift/api/src/main/java/org/arquillian/cube/openshift/api/Tools.java | Tools.loadProperties | public static Properties loadProperties(Class<?> clazz, String fileName) throws IOException {
"""
Load properties.
@param clazz the class from classpath where the properties are
@param fileName properties file name
@return properties
@throws IOException for any error
"""
Properties properties = new Properties();
try (InputStream is = clazz.getClassLoader().getResourceAsStream(fileName)) {
properties.load(is);
}
return properties;
} | java | public static Properties loadProperties(Class<?> clazz, String fileName) throws IOException {
Properties properties = new Properties();
try (InputStream is = clazz.getClassLoader().getResourceAsStream(fileName)) {
properties.load(is);
}
return properties;
} | [
"public",
"static",
"Properties",
"loadProperties",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"fileName",
")",
"throws",
"IOException",
"{",
"Properties",
"properties",
"=",
"new",
"Properties",
"(",
")",
";",
"try",
"(",
"InputStream",
"is",
"=",... | Load properties.
@param clazz the class from classpath where the properties are
@param fileName properties file name
@return properties
@throws IOException for any error | [
"Load",
"properties",
"."
] | train | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/api/src/main/java/org/arquillian/cube/openshift/api/Tools.java#L63-L69 |
apache/spark | core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeInMemorySorter.java | UnsafeInMemorySorter.getSortedIterator | public UnsafeSorterIterator getSortedIterator() {
"""
Return an iterator over record pointers in sorted order. For efficiency, all calls to
{@code next()} will return the same mutable object.
"""
int offset = 0;
long start = System.nanoTime();
if (sortComparator != null) {
if (this.radixSortSupport != null) {
offset = RadixSort.sortKeyPrefixArray(
array, nullBoundaryPos, (pos - nullBoundaryPos) / 2L, 0, 7,
radixSortSupport.sortDescending(), radixSortSupport.sortSigned());
} else {
MemoryBlock unused = new MemoryBlock(
array.getBaseObject(),
array.getBaseOffset() + pos * 8L,
(array.size() - pos) * 8L);
LongArray buffer = new LongArray(unused);
Sorter<RecordPointerAndKeyPrefix, LongArray> sorter =
new Sorter<>(new UnsafeSortDataFormat(buffer));
sorter.sort(array, 0, pos / 2, sortComparator);
}
}
totalSortTimeNanos += System.nanoTime() - start;
if (nullBoundaryPos > 0) {
assert radixSortSupport != null : "Nulls are only stored separately with radix sort";
LinkedList<UnsafeSorterIterator> queue = new LinkedList<>();
// The null order is either LAST or FIRST, regardless of sorting direction (ASC|DESC)
if (radixSortSupport.nullsFirst()) {
queue.add(new SortedIterator(nullBoundaryPos / 2, 0));
queue.add(new SortedIterator((pos - nullBoundaryPos) / 2, offset));
} else {
queue.add(new SortedIterator((pos - nullBoundaryPos) / 2, offset));
queue.add(new SortedIterator(nullBoundaryPos / 2, 0));
}
return new UnsafeExternalSorter.ChainedIterator(queue);
} else {
return new SortedIterator(pos / 2, offset);
}
} | java | public UnsafeSorterIterator getSortedIterator() {
int offset = 0;
long start = System.nanoTime();
if (sortComparator != null) {
if (this.radixSortSupport != null) {
offset = RadixSort.sortKeyPrefixArray(
array, nullBoundaryPos, (pos - nullBoundaryPos) / 2L, 0, 7,
radixSortSupport.sortDescending(), radixSortSupport.sortSigned());
} else {
MemoryBlock unused = new MemoryBlock(
array.getBaseObject(),
array.getBaseOffset() + pos * 8L,
(array.size() - pos) * 8L);
LongArray buffer = new LongArray(unused);
Sorter<RecordPointerAndKeyPrefix, LongArray> sorter =
new Sorter<>(new UnsafeSortDataFormat(buffer));
sorter.sort(array, 0, pos / 2, sortComparator);
}
}
totalSortTimeNanos += System.nanoTime() - start;
if (nullBoundaryPos > 0) {
assert radixSortSupport != null : "Nulls are only stored separately with radix sort";
LinkedList<UnsafeSorterIterator> queue = new LinkedList<>();
// The null order is either LAST or FIRST, regardless of sorting direction (ASC|DESC)
if (radixSortSupport.nullsFirst()) {
queue.add(new SortedIterator(nullBoundaryPos / 2, 0));
queue.add(new SortedIterator((pos - nullBoundaryPos) / 2, offset));
} else {
queue.add(new SortedIterator((pos - nullBoundaryPos) / 2, offset));
queue.add(new SortedIterator(nullBoundaryPos / 2, 0));
}
return new UnsafeExternalSorter.ChainedIterator(queue);
} else {
return new SortedIterator(pos / 2, offset);
}
} | [
"public",
"UnsafeSorterIterator",
"getSortedIterator",
"(",
")",
"{",
"int",
"offset",
"=",
"0",
";",
"long",
"start",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"if",
"(",
"sortComparator",
"!=",
"null",
")",
"{",
"if",
"(",
"this",
".",
"radixSortS... | Return an iterator over record pointers in sorted order. For efficiency, all calls to
{@code next()} will return the same mutable object. | [
"Return",
"an",
"iterator",
"over",
"record",
"pointers",
"in",
"sorted",
"order",
".",
"For",
"efficiency",
"all",
"calls",
"to",
"{"
] | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/core/src/main/java/org/apache/spark/util/collection/unsafe/sort/UnsafeInMemorySorter.java#L344-L380 |
real-logic/agrona | agrona/src/main/java/org/agrona/SystemUtil.java | SystemUtil.getDurationInNanos | public static long getDurationInNanos(final String propertyName, final long defaultValue) {
"""
Get a string representation of a time duration with an optional suffix of 's', 'ms', 'us', or 'ns' suffix to
indicate seconds, milliseconds, microseconds, or nanoseconds respectively.
<p>
If the resulting duration is greater than {@link Long#MAX_VALUE} then {@link Long#MAX_VALUE} is used.
@param propertyName associated with the duration value.
@param defaultValue to be used if the property is not present.
@return the long value.
@throws NumberFormatException if the value is negative or malformed.
"""
final String propertyValue = getProperty(propertyName);
if (propertyValue != null)
{
final long value = parseDuration(propertyName, propertyValue);
if (value < 0)
{
throw new NumberFormatException(propertyName + " must be positive: " + value);
}
return value;
}
return defaultValue;
} | java | public static long getDurationInNanos(final String propertyName, final long defaultValue)
{
final String propertyValue = getProperty(propertyName);
if (propertyValue != null)
{
final long value = parseDuration(propertyName, propertyValue);
if (value < 0)
{
throw new NumberFormatException(propertyName + " must be positive: " + value);
}
return value;
}
return defaultValue;
} | [
"public",
"static",
"long",
"getDurationInNanos",
"(",
"final",
"String",
"propertyName",
",",
"final",
"long",
"defaultValue",
")",
"{",
"final",
"String",
"propertyValue",
"=",
"getProperty",
"(",
"propertyName",
")",
";",
"if",
"(",
"propertyValue",
"!=",
"nu... | Get a string representation of a time duration with an optional suffix of 's', 'ms', 'us', or 'ns' suffix to
indicate seconds, milliseconds, microseconds, or nanoseconds respectively.
<p>
If the resulting duration is greater than {@link Long#MAX_VALUE} then {@link Long#MAX_VALUE} is used.
@param propertyName associated with the duration value.
@param defaultValue to be used if the property is not present.
@return the long value.
@throws NumberFormatException if the value is negative or malformed. | [
"Get",
"a",
"string",
"representation",
"of",
"a",
"time",
"duration",
"with",
"an",
"optional",
"suffix",
"of",
"s",
"ms",
"us",
"or",
"ns",
"suffix",
"to",
"indicate",
"seconds",
"milliseconds",
"microseconds",
"or",
"nanoseconds",
"respectively",
".",
"<p",... | train | https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/SystemUtil.java#L338-L353 |
wildfly/wildfly-core | platform-mbean/src/main/java/org/jboss/as/platform/mbean/PlatformMBeanUtil.java | PlatformMBeanUtil.getDetypedThreadInfo | public static ModelNode getDetypedThreadInfo(final ThreadInfo threadInfo, boolean includeBlockedTime) {
"""
Utility for converting {@link java.lang.management.ThreadInfo} to a detyped form.
@param threadInfo the thread information data object
@param includeBlockedTime whether the {@link PlatformMBeanConstants#BLOCKED_TIME} attribute is supported
@return the detyped representation
"""
final ModelNode result = new ModelNode();
result.get(PlatformMBeanConstants.THREAD_ID).set(threadInfo.getThreadId());
result.get(PlatformMBeanConstants.THREAD_NAME).set(threadInfo.getThreadName());
result.get(PlatformMBeanConstants.THREAD_STATE).set(threadInfo.getThreadState().name());
if (includeBlockedTime) {
result.get(PlatformMBeanConstants.BLOCKED_TIME).set(threadInfo.getBlockedTime());
} else {
result.get(PlatformMBeanConstants.BLOCKED_TIME);
}
result.get(PlatformMBeanConstants.BLOCKED_COUNT).set(threadInfo.getBlockedCount());
result.get(PlatformMBeanConstants.WAITED_TIME).set(threadInfo.getWaitedTime());
result.get(PlatformMBeanConstants.WAITED_COUNT).set(threadInfo.getWaitedCount());
result.get(PlatformMBeanConstants.LOCK_INFO).set(getDetypedLockInfo(threadInfo.getLockInfo()));
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_NAME), threadInfo.getLockName());
result.get(PlatformMBeanConstants.LOCK_OWNER_ID).set(threadInfo.getLockOwnerId());
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_OWNER_NAME), threadInfo.getLockOwnerName());
final ModelNode stack = result.get(PlatformMBeanConstants.STACK_TRACE);
stack.setEmptyList();
for (StackTraceElement ste : threadInfo.getStackTrace()) {
stack.add(getDetypedStackTraceElement(ste));
}
result.get(PlatformMBeanConstants.SUSPENDED).set(threadInfo.isSuspended());
result.get(PlatformMBeanConstants.IN_NATIVE).set(threadInfo.isInNative());
final ModelNode monitors = result.get(PlatformMBeanConstants.LOCKED_MONITORS);
monitors.setEmptyList();
for (MonitorInfo monitor : threadInfo.getLockedMonitors()) {
monitors.add(getDetypedMonitorInfo(monitor));
}
final ModelNode synchronizers = result.get(PlatformMBeanConstants.LOCKED_SYNCHRONIZERS);
synchronizers.setEmptyList();
for (LockInfo lock : threadInfo.getLockedSynchronizers()) {
synchronizers.add(getDetypedLockInfo(lock));
}
return result;
} | java | public static ModelNode getDetypedThreadInfo(final ThreadInfo threadInfo, boolean includeBlockedTime) {
final ModelNode result = new ModelNode();
result.get(PlatformMBeanConstants.THREAD_ID).set(threadInfo.getThreadId());
result.get(PlatformMBeanConstants.THREAD_NAME).set(threadInfo.getThreadName());
result.get(PlatformMBeanConstants.THREAD_STATE).set(threadInfo.getThreadState().name());
if (includeBlockedTime) {
result.get(PlatformMBeanConstants.BLOCKED_TIME).set(threadInfo.getBlockedTime());
} else {
result.get(PlatformMBeanConstants.BLOCKED_TIME);
}
result.get(PlatformMBeanConstants.BLOCKED_COUNT).set(threadInfo.getBlockedCount());
result.get(PlatformMBeanConstants.WAITED_TIME).set(threadInfo.getWaitedTime());
result.get(PlatformMBeanConstants.WAITED_COUNT).set(threadInfo.getWaitedCount());
result.get(PlatformMBeanConstants.LOCK_INFO).set(getDetypedLockInfo(threadInfo.getLockInfo()));
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_NAME), threadInfo.getLockName());
result.get(PlatformMBeanConstants.LOCK_OWNER_ID).set(threadInfo.getLockOwnerId());
nullSafeSet(result.get(PlatformMBeanConstants.LOCK_OWNER_NAME), threadInfo.getLockOwnerName());
final ModelNode stack = result.get(PlatformMBeanConstants.STACK_TRACE);
stack.setEmptyList();
for (StackTraceElement ste : threadInfo.getStackTrace()) {
stack.add(getDetypedStackTraceElement(ste));
}
result.get(PlatformMBeanConstants.SUSPENDED).set(threadInfo.isSuspended());
result.get(PlatformMBeanConstants.IN_NATIVE).set(threadInfo.isInNative());
final ModelNode monitors = result.get(PlatformMBeanConstants.LOCKED_MONITORS);
monitors.setEmptyList();
for (MonitorInfo monitor : threadInfo.getLockedMonitors()) {
monitors.add(getDetypedMonitorInfo(monitor));
}
final ModelNode synchronizers = result.get(PlatformMBeanConstants.LOCKED_SYNCHRONIZERS);
synchronizers.setEmptyList();
for (LockInfo lock : threadInfo.getLockedSynchronizers()) {
synchronizers.add(getDetypedLockInfo(lock));
}
return result;
} | [
"public",
"static",
"ModelNode",
"getDetypedThreadInfo",
"(",
"final",
"ThreadInfo",
"threadInfo",
",",
"boolean",
"includeBlockedTime",
")",
"{",
"final",
"ModelNode",
"result",
"=",
"new",
"ModelNode",
"(",
")",
";",
"result",
".",
"get",
"(",
"PlatformMBeanCons... | Utility for converting {@link java.lang.management.ThreadInfo} to a detyped form.
@param threadInfo the thread information data object
@param includeBlockedTime whether the {@link PlatformMBeanConstants#BLOCKED_TIME} attribute is supported
@return the detyped representation | [
"Utility",
"for",
"converting",
"{",
"@link",
"java",
".",
"lang",
".",
"management",
".",
"ThreadInfo",
"}",
"to",
"a",
"detyped",
"form",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/platform-mbean/src/main/java/org/jboss/as/platform/mbean/PlatformMBeanUtil.java#L129-L166 |
airomem/airomem | airomem-core/src/main/java/pl/setblack/airomem/core/impl/PersistenceControllerImpl.java | PersistenceControllerImpl.executeAndQuery | public <R> R executeAndQuery(ContextCommand<ROOT, R> cmd) {
"""
Perform command on system.
<p>
Inside command can be any code doing any changes. Such changes are
guaranteed to be preserved (if only command ended without exception).
@param cmd
"""
return Politician.beatAroundTheBush(() -> this.prevayler.execute(new InternalTransaction<>(cmd)));
} | java | public <R> R executeAndQuery(ContextCommand<ROOT, R> cmd) {
return Politician.beatAroundTheBush(() -> this.prevayler.execute(new InternalTransaction<>(cmd)));
} | [
"public",
"<",
"R",
">",
"R",
"executeAndQuery",
"(",
"ContextCommand",
"<",
"ROOT",
",",
"R",
">",
"cmd",
")",
"{",
"return",
"Politician",
".",
"beatAroundTheBush",
"(",
"(",
")",
"->",
"this",
".",
"prevayler",
".",
"execute",
"(",
"new",
"InternalTra... | Perform command on system.
<p>
Inside command can be any code doing any changes. Such changes are
guaranteed to be preserved (if only command ended without exception).
@param cmd | [
"Perform",
"command",
"on",
"system",
".",
"<p",
">",
"Inside",
"command",
"can",
"be",
"any",
"code",
"doing",
"any",
"changes",
".",
"Such",
"changes",
"are",
"guaranteed",
"to",
"be",
"preserved",
"(",
"if",
"only",
"command",
"ended",
"without",
"excep... | train | https://github.com/airomem/airomem/blob/281ce18ff64836fccfb0edab18b8d677f1101a32/airomem-core/src/main/java/pl/setblack/airomem/core/impl/PersistenceControllerImpl.java#L96-L98 |
Azure/azure-sdk-for-java | containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/AgentPoolsInner.java | AgentPoolsInner.beginDelete | public void beginDelete(String resourceGroupName, String managedClusterName, String agentPoolName) {
"""
Deletes an agent pool.
Deletes the agent pool in the specified managed cluster.
@param resourceGroupName The name of the resource group.
@param managedClusterName The name of the managed cluster resource.
@param agentPoolName The name of the agent pool.
@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
"""
beginDeleteWithServiceResponseAsync(resourceGroupName, managedClusterName, agentPoolName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String managedClusterName, String agentPoolName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, managedClusterName, agentPoolName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"managedClusterName",
",",
"String",
"agentPoolName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"managedClusterName",
",",
"agentPoolName",
")",
".",
... | Deletes an agent pool.
Deletes the agent pool in the specified managed cluster.
@param resourceGroupName The name of the resource group.
@param managedClusterName The name of the managed cluster resource.
@param agentPoolName The name of the agent pool.
@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 | [
"Deletes",
"an",
"agent",
"pool",
".",
"Deletes",
"the",
"agent",
"pool",
"in",
"the",
"specified",
"managed",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/AgentPoolsInner.java#L593-L595 |
opentok/Opentok-Java-SDK | src/main/java/com/opentok/OpenTok.java | OpenTok.generateToken | public String generateToken(String sessionId, TokenOptions tokenOptions) throws OpenTokException {
"""
Creates a token for connecting to an OpenTok session. In order to authenticate a user
connecting to an OpenTok session, the client passes a token when connecting to the session.
<p>
The following example shows how to obtain a token that has a role of "subscriber" and
that has a connection metadata string:
<p>
<pre>
import com.opentok.Role;
import com.opentok.TokenOptions;
class Test {
public static void main(String argv[]) throws OpenTokException {
int API_KEY = 0; // Replace with your OpenTok API key (see https://tokbox.com/account).
String API_SECRET = ""; // Replace with your OpenTok API secret.
OpenTok sdk = new OpenTok(API_KEY, API_SECRET);
//Generate a basic session. Or you could use an existing session ID.
String sessionId = System.out.println(sdk.createSession());
// Replace with meaningful metadata for the connection.
String connectionMetadata = "username=Bob,userLevel=4";
// Use the Role value appropriate for the user.
String role = Role.SUBSCRIBER;
// Generate a token:
TokenOptions options = new TokenOptions.Buider().role(role).data(connectionMetadata).build();
String token = sdk.generateToken(sessionId, options);
System.out.println(token);
}
}
</pre>
<p>
For testing, you can also generate tokens by logging in to your <a href="https://tokbox.com/account">TokBox account</a>.
@param sessionId The session ID corresponding to the session to which the user will connect.
@param tokenOptions This TokenOptions object defines options for the token.
These include the following:
<ul>
<li>The role of the token (subscriber, publisher, or moderator)</li>
<li>The expiration time of the token</li>
<li>Connection data describing the end-user</li>
</ul>
@return The token string.
"""
List<String> sessionIdParts = null;
if (sessionId == null || sessionId == "") {
throw new InvalidArgumentException("Session not valid");
}
try {
sessionIdParts = Crypto.decodeSessionId(sessionId);
} catch (UnsupportedEncodingException e) {
throw new InvalidArgumentException("Session ID was not valid");
}
if (!sessionIdParts.contains(Integer.toString(this.apiKey))) {
throw new InvalidArgumentException("Session ID was not valid");
}
// NOTE: kind of wasteful of a Session instance
Session session = new Session(sessionId, apiKey, apiSecret);
return session.generateToken(tokenOptions);
} | java | public String generateToken(String sessionId, TokenOptions tokenOptions) throws OpenTokException {
List<String> sessionIdParts = null;
if (sessionId == null || sessionId == "") {
throw new InvalidArgumentException("Session not valid");
}
try {
sessionIdParts = Crypto.decodeSessionId(sessionId);
} catch (UnsupportedEncodingException e) {
throw new InvalidArgumentException("Session ID was not valid");
}
if (!sessionIdParts.contains(Integer.toString(this.apiKey))) {
throw new InvalidArgumentException("Session ID was not valid");
}
// NOTE: kind of wasteful of a Session instance
Session session = new Session(sessionId, apiKey, apiSecret);
return session.generateToken(tokenOptions);
} | [
"public",
"String",
"generateToken",
"(",
"String",
"sessionId",
",",
"TokenOptions",
"tokenOptions",
")",
"throws",
"OpenTokException",
"{",
"List",
"<",
"String",
">",
"sessionIdParts",
"=",
"null",
";",
"if",
"(",
"sessionId",
"==",
"null",
"||",
"sessionId",... | Creates a token for connecting to an OpenTok session. In order to authenticate a user
connecting to an OpenTok session, the client passes a token when connecting to the session.
<p>
The following example shows how to obtain a token that has a role of "subscriber" and
that has a connection metadata string:
<p>
<pre>
import com.opentok.Role;
import com.opentok.TokenOptions;
class Test {
public static void main(String argv[]) throws OpenTokException {
int API_KEY = 0; // Replace with your OpenTok API key (see https://tokbox.com/account).
String API_SECRET = ""; // Replace with your OpenTok API secret.
OpenTok sdk = new OpenTok(API_KEY, API_SECRET);
//Generate a basic session. Or you could use an existing session ID.
String sessionId = System.out.println(sdk.createSession());
// Replace with meaningful metadata for the connection.
String connectionMetadata = "username=Bob,userLevel=4";
// Use the Role value appropriate for the user.
String role = Role.SUBSCRIBER;
// Generate a token:
TokenOptions options = new TokenOptions.Buider().role(role).data(connectionMetadata).build();
String token = sdk.generateToken(sessionId, options);
System.out.println(token);
}
}
</pre>
<p>
For testing, you can also generate tokens by logging in to your <a href="https://tokbox.com/account">TokBox account</a>.
@param sessionId The session ID corresponding to the session to which the user will connect.
@param tokenOptions This TokenOptions object defines options for the token.
These include the following:
<ul>
<li>The role of the token (subscriber, publisher, or moderator)</li>
<li>The expiration time of the token</li>
<li>Connection data describing the end-user</li>
</ul>
@return The token string. | [
"Creates",
"a",
"token",
"for",
"connecting",
"to",
"an",
"OpenTok",
"session",
".",
"In",
"order",
"to",
"authenticate",
"a",
"user",
"connecting",
"to",
"an",
"OpenTok",
"session",
"the",
"client",
"passes",
"a",
"token",
"when",
"connecting",
"to",
"the",... | train | https://github.com/opentok/Opentok-Java-SDK/blob/d71b7999facc3131c415aebea874ea55776d477f/src/main/java/com/opentok/OpenTok.java#L126-L144 |
airbnb/lottie-android | lottie/src/main/java/com/airbnb/lottie/network/NetworkCache.java | NetworkCache.writeTempCacheFile | File writeTempCacheFile(InputStream stream, FileExtension extension) throws IOException {
"""
Writes an InputStream from a network response to a temporary file. If the file successfully parses
to an composition, {@link #renameTempFile(FileExtension)} should be called to move the file
to its final location for future cache hits.
"""
String fileName = filenameForUrl(url, extension, true);
File file = new File(appContext.getCacheDir(), fileName);
try {
OutputStream output = new FileOutputStream(file);
//noinspection TryFinallyCanBeTryWithResources
try {
byte[] buffer = new byte[1024];
int read;
while ((read = stream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} finally {
stream.close();
}
return file;
} | java | File writeTempCacheFile(InputStream stream, FileExtension extension) throws IOException {
String fileName = filenameForUrl(url, extension, true);
File file = new File(appContext.getCacheDir(), fileName);
try {
OutputStream output = new FileOutputStream(file);
//noinspection TryFinallyCanBeTryWithResources
try {
byte[] buffer = new byte[1024];
int read;
while ((read = stream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} finally {
stream.close();
}
return file;
} | [
"File",
"writeTempCacheFile",
"(",
"InputStream",
"stream",
",",
"FileExtension",
"extension",
")",
"throws",
"IOException",
"{",
"String",
"fileName",
"=",
"filenameForUrl",
"(",
"url",
",",
"extension",
",",
"true",
")",
";",
"File",
"file",
"=",
"new",
"Fil... | Writes an InputStream from a network response to a temporary file. If the file successfully parses
to an composition, {@link #renameTempFile(FileExtension)} should be called to move the file
to its final location for future cache hits. | [
"Writes",
"an",
"InputStream",
"from",
"a",
"network",
"response",
"to",
"a",
"temporary",
"file",
".",
"If",
"the",
"file",
"successfully",
"parses",
"to",
"an",
"composition",
"{"
] | train | https://github.com/airbnb/lottie-android/blob/126dabdc9f586c87822f85fe1128cdad439d30fa/lottie/src/main/java/com/airbnb/lottie/network/NetworkCache.java#L73-L95 |
alkacon/opencms-core | src/org/opencms/workplace/CmsDialog.java | CmsDialog.dialogButtons | public String dialogButtons(int[] buttons, String[] attributes) {
"""
Builds the html for the button row under the dialog content area, including buttons.<p>
@param buttons array of constants of which buttons to include in the row
@param attributes array of Strings for additional button attributes
@return the html for the button row under the dialog content area, including buttons
"""
StringBuffer result = new StringBuffer(256);
result.append(dialogButtonRow(HTML_START));
for (int i = 0; i < buttons.length; i++) {
dialogButtonsHtml(result, buttons[i], attributes[i]);
}
result.append(dialogButtonRow(HTML_END));
return result.toString();
} | java | public String dialogButtons(int[] buttons, String[] attributes) {
StringBuffer result = new StringBuffer(256);
result.append(dialogButtonRow(HTML_START));
for (int i = 0; i < buttons.length; i++) {
dialogButtonsHtml(result, buttons[i], attributes[i]);
}
result.append(dialogButtonRow(HTML_END));
return result.toString();
} | [
"public",
"String",
"dialogButtons",
"(",
"int",
"[",
"]",
"buttons",
",",
"String",
"[",
"]",
"attributes",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
"256",
")",
";",
"result",
".",
"append",
"(",
"dialogButtonRow",
"(",
"HTML_S... | Builds the html for the button row under the dialog content area, including buttons.<p>
@param buttons array of constants of which buttons to include in the row
@param attributes array of Strings for additional button attributes
@return the html for the button row under the dialog content area, including buttons | [
"Builds",
"the",
"html",
"for",
"the",
"button",
"row",
"under",
"the",
"dialog",
"content",
"area",
"including",
"buttons",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsDialog.java#L635-L644 |
bit3/jsass | src/main/java/io/bit3/jsass/Compiler.java | Compiler.compileString | public Output compileString(String string, Options options) throws CompilationException {
"""
Compile string.
@param string The input string.
@param options The compile options.
@return The compilation output.
@throws CompilationException If the compilation failed.
"""
return compileString(string, null, null, options);
} | java | public Output compileString(String string, Options options) throws CompilationException {
return compileString(string, null, null, options);
} | [
"public",
"Output",
"compileString",
"(",
"String",
"string",
",",
"Options",
"options",
")",
"throws",
"CompilationException",
"{",
"return",
"compileString",
"(",
"string",
",",
"null",
",",
"null",
",",
"options",
")",
";",
"}"
] | Compile string.
@param string The input string.
@param options The compile options.
@return The compilation output.
@throws CompilationException If the compilation failed. | [
"Compile",
"string",
"."
] | train | https://github.com/bit3/jsass/blob/fba91d5cb1eb507c7cfde5a261e04b1d328cb1ef/src/main/java/io/bit3/jsass/Compiler.java#L46-L48 |
michel-kraemer/citeproc-java | citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java | CSL.getRunner | private static ScriptRunner getRunner() throws IOException {
"""
Gets or initializes the shared script runner {@link #sharedRunner}
@return the runner
@throws IOException if bundles scripts could not be loaded
"""
if (sharedRunner.get() == null) {
//create JavaScript runner
ScriptRunner runner = ScriptRunnerFactory.createRunner();
//load bundled scripts
try {
runner.loadScript(CSL.class.getResource("dump.js"));
runner.loadScript(CSL.class.getResource("citeproc.js"));
runner.loadScript(CSL.class.getResource("formats.js"));
runner.loadScript(CSL.class.getResource("loadsys.js"));
} catch (ScriptRunnerException e) {
//should never happen because bundled JavaScript files
//should be OK indeed
throw new RuntimeException("Invalid bundled javascript file", e);
}
sharedRunner.set(runner);
}
return sharedRunner.get();
} | java | private static ScriptRunner getRunner() throws IOException {
if (sharedRunner.get() == null) {
//create JavaScript runner
ScriptRunner runner = ScriptRunnerFactory.createRunner();
//load bundled scripts
try {
runner.loadScript(CSL.class.getResource("dump.js"));
runner.loadScript(CSL.class.getResource("citeproc.js"));
runner.loadScript(CSL.class.getResource("formats.js"));
runner.loadScript(CSL.class.getResource("loadsys.js"));
} catch (ScriptRunnerException e) {
//should never happen because bundled JavaScript files
//should be OK indeed
throw new RuntimeException("Invalid bundled javascript file", e);
}
sharedRunner.set(runner);
}
return sharedRunner.get();
} | [
"private",
"static",
"ScriptRunner",
"getRunner",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"sharedRunner",
".",
"get",
"(",
")",
"==",
"null",
")",
"{",
"//create JavaScript runner",
"ScriptRunner",
"runner",
"=",
"ScriptRunnerFactory",
".",
"createRunne... | Gets or initializes the shared script runner {@link #sharedRunner}
@return the runner
@throws IOException if bundles scripts could not be loaded | [
"Gets",
"or",
"initializes",
"the",
"shared",
"script",
"runner",
"{"
] | train | https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java#L405-L425 |
baratine/baratine | framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java | XmlWriter.writeAttribute | public void writeAttribute(String name, Object value) {
"""
Write an attribute with a value, if value is null nothing is written.
@throws IllegalStateException if the is no element is open
"""
if (!_isElementOpen)
throw new IllegalStateException("no open element");
if (value == null)
return;
_isElementOpen = false;
try {
_strategy.writeAttribute(this, name, value);
}
finally {
_isElementOpen = true;
}
} | java | public void writeAttribute(String name, Object value)
{
if (!_isElementOpen)
throw new IllegalStateException("no open element");
if (value == null)
return;
_isElementOpen = false;
try {
_strategy.writeAttribute(this, name, value);
}
finally {
_isElementOpen = true;
}
} | [
"public",
"void",
"writeAttribute",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"!",
"_isElementOpen",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"no open element\"",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"return"... | Write an attribute with a value, if value is null nothing is written.
@throws IllegalStateException if the is no element is open | [
"Write",
"an",
"attribute",
"with",
"a",
"value",
"if",
"value",
"is",
"null",
"nothing",
"is",
"written",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java#L291-L307 |
jeremylong/DependencyCheck | utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java | Settings.setIntIfNotNull | public void setIntIfNotNull(@NotNull final String key, @Nullable final Integer value) {
"""
Sets a property value only if the value is not null.
@param key the key for the property
@param value the value for the property
"""
if (null != value) {
setInt(key, value);
}
} | java | public void setIntIfNotNull(@NotNull final String key, @Nullable final Integer value) {
if (null != value) {
setInt(key, value);
}
} | [
"public",
"void",
"setIntIfNotNull",
"(",
"@",
"NotNull",
"final",
"String",
"key",
",",
"@",
"Nullable",
"final",
"Integer",
"value",
")",
"{",
"if",
"(",
"null",
"!=",
"value",
")",
"{",
"setInt",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
] | Sets a property value only if the value is not null.
@param key the key for the property
@param value the value for the property | [
"Sets",
"a",
"property",
"value",
"only",
"if",
"the",
"value",
"is",
"not",
"null",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java#L757-L761 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/util/FormatUtilities.java | FormatUtilities.getDateTime | static public long getDateTime(String s, String format) {
"""
Returns the given date parsed using the given format.
@param s The formatted date to be parsed
@param format The format to use when parsing the date
@return The given date parsed using the given format
"""
return getDateTime(s, format, true, false);
} | java | static public long getDateTime(String s, String format)
{
return getDateTime(s, format, true, false);
} | [
"static",
"public",
"long",
"getDateTime",
"(",
"String",
"s",
",",
"String",
"format",
")",
"{",
"return",
"getDateTime",
"(",
"s",
",",
"format",
",",
"true",
",",
"false",
")",
";",
"}"
] | Returns the given date parsed using the given format.
@param s The formatted date to be parsed
@param format The format to use when parsing the date
@return The given date parsed using the given format | [
"Returns",
"the",
"given",
"date",
"parsed",
"using",
"the",
"given",
"format",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/FormatUtilities.java#L248-L251 |
aws/aws-sdk-java | aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/util/StepFactory.java | StepFactory.newInstallPigStep | public HadoopJarStepConfig newInstallPigStep(String... pigVersions) {
"""
Step that installs Pig on your job flow.
@param pigVersions the versions of Pig to install.
@return HadoopJarStepConfig that can be passed to your job flow.
"""
if (pigVersions != null && pigVersions.length > 0) {
return newHivePigStep("pig", "--install-pig", "--pig-versions",
StringUtils.join(",", pigVersions));
}
return newHivePigStep("pig", "--install-pig", "--pig-versions", "latest");
} | java | public HadoopJarStepConfig newInstallPigStep(String... pigVersions) {
if (pigVersions != null && pigVersions.length > 0) {
return newHivePigStep("pig", "--install-pig", "--pig-versions",
StringUtils.join(",", pigVersions));
}
return newHivePigStep("pig", "--install-pig", "--pig-versions", "latest");
} | [
"public",
"HadoopJarStepConfig",
"newInstallPigStep",
"(",
"String",
"...",
"pigVersions",
")",
"{",
"if",
"(",
"pigVersions",
"!=",
"null",
"&&",
"pigVersions",
".",
"length",
">",
"0",
")",
"{",
"return",
"newHivePigStep",
"(",
"\"pig\"",
",",
"\"--install-pig... | Step that installs Pig on your job flow.
@param pigVersions the versions of Pig to install.
@return HadoopJarStepConfig that can be passed to your job flow. | [
"Step",
"that",
"installs",
"Pig",
"on",
"your",
"job",
"flow",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/util/StepFactory.java#L247-L253 |
dropbox/dropbox-sdk-java | src/main/java/com/dropbox/core/v1/DbxClientV1.java | DbxClientV1.getFile | public DbxEntry./*@Nullable*/File getFile(String path, /*@Nullable*/String rev, OutputStream target)
throws DbxException, IOException {
"""
Retrieves a file's content and writes it to the given {@code OutputStream}.
<pre>
DbxClientV1 dbxClient = ...
DbxEntry.File md;
File target = new File("Copy of House.jpeg");
OutputStream out = new FileOutputStream(target);
try {
md = dbxClient.getFile("/Photos/House.jpeg", out);
}
finally {
out.close();
}
</pre>
@param rev
The {@link DbxEntry.File#rev rev} of the file to retrieve,
or {@code null} if you want the latest revision of the file.
@return
The downloaded file's metadata, or {@code null}
@throws IOException
If there's an error writing to {@code target}.
"""
Downloader downloader = startGetFile(path, rev);
if (downloader == null) return null;
return downloader.copyBodyAndClose(target);
} | java | public DbxEntry./*@Nullable*/File getFile(String path, /*@Nullable*/String rev, OutputStream target)
throws DbxException, IOException
{
Downloader downloader = startGetFile(path, rev);
if (downloader == null) return null;
return downloader.copyBodyAndClose(target);
} | [
"public",
"DbxEntry",
".",
"/*@Nullable*/",
"File",
"getFile",
"(",
"String",
"path",
",",
"/*@Nullable*/",
"String",
"rev",
",",
"OutputStream",
"target",
")",
"throws",
"DbxException",
",",
"IOException",
"{",
"Downloader",
"downloader",
"=",
"startGetFile",
"("... | Retrieves a file's content and writes it to the given {@code OutputStream}.
<pre>
DbxClientV1 dbxClient = ...
DbxEntry.File md;
File target = new File("Copy of House.jpeg");
OutputStream out = new FileOutputStream(target);
try {
md = dbxClient.getFile("/Photos/House.jpeg", out);
}
finally {
out.close();
}
</pre>
@param rev
The {@link DbxEntry.File#rev rev} of the file to retrieve,
or {@code null} if you want the latest revision of the file.
@return
The downloaded file's metadata, or {@code null}
@throws IOException
If there's an error writing to {@code target}. | [
"Retrieves",
"a",
"file",
"s",
"content",
"and",
"writes",
"it",
"to",
"the",
"given",
"{",
"@code",
"OutputStream",
"}",
"."
] | train | https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L422-L428 |
wiselenium/wiselenium | wiselenium-factory/src/main/java/com/github/wiselenium/factory/util/ClasspathUtils.java | ClasspathUtils.findImplementationClass | @SuppressWarnings("unchecked")
public static <T> Class<? extends T> findImplementationClass(Class<T> clazz) {
"""
Finds the implementation class of a type on the classpath. <br/>
If the class is already a concrete class, returns itself. Otherwise, it searchs for an
implementation class that matches the pattern {classPackage}.impl.{className}Impl . <br/>
A more sofisticated search is planned to be implemented on the future.
@param clazz The class.
@return The implementation of the class.
@since 0.3.0
"""
if (!Modifier.isAbstract(clazz.getModifiers())) return clazz;
String implementationClass = String.format("%s.impl.%sImpl", clazz.getPackage().getName(), clazz.getSimpleName());
try {
return (Class<? extends T>) Class.forName(implementationClass);
} catch (ClassNotFoundException e) {
throw new NoImplementationClassFoundException(clazz, e);
}
} | java | @SuppressWarnings("unchecked")
public static <T> Class<? extends T> findImplementationClass(Class<T> clazz) {
if (!Modifier.isAbstract(clazz.getModifiers())) return clazz;
String implementationClass = String.format("%s.impl.%sImpl", clazz.getPackage().getName(), clazz.getSimpleName());
try {
return (Class<? extends T>) Class.forName(implementationClass);
} catch (ClassNotFoundException e) {
throw new NoImplementationClassFoundException(clazz, e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"Class",
"<",
"?",
"extends",
"T",
">",
"findImplementationClass",
"(",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"if",
"(",
"!",
"Modifier",
".",
"isAbstract",
"(",
... | Finds the implementation class of a type on the classpath. <br/>
If the class is already a concrete class, returns itself. Otherwise, it searchs for an
implementation class that matches the pattern {classPackage}.impl.{className}Impl . <br/>
A more sofisticated search is planned to be implemented on the future.
@param clazz The class.
@return The implementation of the class.
@since 0.3.0 | [
"Finds",
"the",
"implementation",
"class",
"of",
"a",
"type",
"on",
"the",
"classpath",
".",
"<br",
"/",
">",
"If",
"the",
"class",
"is",
"already",
"a",
"concrete",
"class",
"returns",
"itself",
".",
"Otherwise",
"it",
"searchs",
"for",
"an",
"implementat... | train | https://github.com/wiselenium/wiselenium/blob/15de6484d8f516b3d02391d3bd6a56a03e632706/wiselenium-factory/src/main/java/com/github/wiselenium/factory/util/ClasspathUtils.java#L46-L56 |
undertow-io/undertow | core/src/main/java/io/undertow/websockets/core/WebSockets.java | WebSockets.sendClose | public static <T> void sendClose(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) {
"""
Sends a complete close message, invoking the callback when complete
@param data The data to send
@param wsChannel The web socket channel
@param callback The callback to invoke on completion
@param context The context object that will be passed to the callback on completion
"""
CloseMessage sm = new CloseMessage(data);
sendClose(sm, wsChannel, callback, context);
} | java | public static <T> void sendClose(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) {
CloseMessage sm = new CloseMessage(data);
sendClose(sm, wsChannel, callback, context);
} | [
"public",
"static",
"<",
"T",
">",
"void",
"sendClose",
"(",
"final",
"ByteBuffer",
"data",
",",
"final",
"WebSocketChannel",
"wsChannel",
",",
"final",
"WebSocketCallback",
"<",
"T",
">",
"callback",
",",
"T",
"context",
")",
"{",
"CloseMessage",
"sm",
"=",... | Sends a complete close message, invoking the callback when complete
@param data The data to send
@param wsChannel The web socket channel
@param callback The callback to invoke on completion
@param context The context object that will be passed to the callback on completion | [
"Sends",
"a",
"complete",
"close",
"message",
"invoking",
"the",
"callback",
"when",
"complete"
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L781-L784 |
autermann/yaml | src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java | YamlMappingNode.put | public T put(YamlNode key, BigDecimal value) {
"""
Adds the specified {@code key}/{@code value} pair to this mapping.
@param key the key
@param value the value
@return {@code this}
"""
return put(key, getNodeFactory().bigDecimalNode(value));
} | java | public T put(YamlNode key, BigDecimal value) {
return put(key, getNodeFactory().bigDecimalNode(value));
} | [
"public",
"T",
"put",
"(",
"YamlNode",
"key",
",",
"BigDecimal",
"value",
")",
"{",
"return",
"put",
"(",
"key",
",",
"getNodeFactory",
"(",
")",
".",
"bigDecimalNode",
"(",
"value",
")",
")",
";",
"}"
] | Adds the specified {@code key}/{@code value} pair to this mapping.
@param key the key
@param value the value
@return {@code this} | [
"Adds",
"the",
"specified",
"{",
"@code",
"key",
"}",
"/",
"{",
"@code",
"value",
"}",
"pair",
"to",
"this",
"mapping",
"."
] | train | https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java#L708-L710 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxRetentionPolicy.java | BoxRetentionPolicy.createFinitePolicy | public static BoxRetentionPolicy.Info createFinitePolicy(BoxAPIConnection api, String name, int length,
String action, RetentionPolicyParams optionalParams) {
"""
Used to create a new finite retention policy with optional parameters.
@param api the API connection to be used by the created user.
@param name the name of the retention policy.
@param length the duration in days that the retention policy will be active for after being assigned to content.
@param action the disposition action can be "permanently_delete" or "remove_retention".
@param optionalParams the optional parameters.
@return the created retention policy's info.
"""
return createRetentionPolicy(api, name, TYPE_FINITE, length, action, optionalParams);
} | java | public static BoxRetentionPolicy.Info createFinitePolicy(BoxAPIConnection api, String name, int length,
String action, RetentionPolicyParams optionalParams) {
return createRetentionPolicy(api, name, TYPE_FINITE, length, action, optionalParams);
} | [
"public",
"static",
"BoxRetentionPolicy",
".",
"Info",
"createFinitePolicy",
"(",
"BoxAPIConnection",
"api",
",",
"String",
"name",
",",
"int",
"length",
",",
"String",
"action",
",",
"RetentionPolicyParams",
"optionalParams",
")",
"{",
"return",
"createRetentionPolic... | Used to create a new finite retention policy with optional parameters.
@param api the API connection to be used by the created user.
@param name the name of the retention policy.
@param length the duration in days that the retention policy will be active for after being assigned to content.
@param action the disposition action can be "permanently_delete" or "remove_retention".
@param optionalParams the optional parameters.
@return the created retention policy's info. | [
"Used",
"to",
"create",
"a",
"new",
"finite",
"retention",
"policy",
"with",
"optional",
"parameters",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxRetentionPolicy.java#L131-L134 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java | ProjectiveStructureByFactorization.setDepths | public void setDepths( int view , double featureDepths[] ) {
"""
Sets depths for a particular value to the values in the passed in array
@param view
@param featureDepths
"""
if( featureDepths.length < depths.numCols )
throw new IllegalArgumentException("Pixel count must be constant and match "+pixels.numCols);
int N = depths.numCols;
for (int i = 0; i < N; i++) {
depths.set(view,i, featureDepths[i]);
}
} | java | public void setDepths( int view , double featureDepths[] ) {
if( featureDepths.length < depths.numCols )
throw new IllegalArgumentException("Pixel count must be constant and match "+pixels.numCols);
int N = depths.numCols;
for (int i = 0; i < N; i++) {
depths.set(view,i, featureDepths[i]);
}
} | [
"public",
"void",
"setDepths",
"(",
"int",
"view",
",",
"double",
"featureDepths",
"[",
"]",
")",
"{",
"if",
"(",
"featureDepths",
".",
"length",
"<",
"depths",
".",
"numCols",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Pixel count must be constant... | Sets depths for a particular value to the values in the passed in array
@param view
@param featureDepths | [
"Sets",
"depths",
"for",
"a",
"particular",
"value",
"to",
"the",
"values",
"in",
"the",
"passed",
"in",
"array"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java#L135-L143 |
radkovo/SwingBox | src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java | DelegateView.viewToModel | @Override
public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) {
"""
Provides a mapping from the view coordinate space to the logical
coordinate space of the model.
@param x
x coordinate of the view location to convert
@param y
y coordinate of the view location to convert
@param a
the allocated region to render into
@return the location within the model that best represents the given
point in the view
"""
if (view != null)
{
int retValue = view.viewToModel(x, y, a, bias);
return retValue;
}
return -1;
} | java | @Override
public int viewToModel(float x, float y, Shape a, Position.Bias[] bias)
{
if (view != null)
{
int retValue = view.viewToModel(x, y, a, bias);
return retValue;
}
return -1;
} | [
"@",
"Override",
"public",
"int",
"viewToModel",
"(",
"float",
"x",
",",
"float",
"y",
",",
"Shape",
"a",
",",
"Position",
".",
"Bias",
"[",
"]",
"bias",
")",
"{",
"if",
"(",
"view",
"!=",
"null",
")",
"{",
"int",
"retValue",
"=",
"view",
".",
"v... | Provides a mapping from the view coordinate space to the logical
coordinate space of the model.
@param x
x coordinate of the view location to convert
@param y
y coordinate of the view location to convert
@param a
the allocated region to render into
@return the location within the model that best represents the given
point in the view | [
"Provides",
"a",
"mapping",
"from",
"the",
"view",
"coordinate",
"space",
"to",
"the",
"logical",
"coordinate",
"space",
"of",
"the",
"model",
"."
] | train | https://github.com/radkovo/SwingBox/blob/ff370f3dc54d248e4c8852c17513618c83c25984/src/main/java/org/fit/cssbox/swingbox/view/DelegateView.java#L413-L422 |
xiancloud/xian | xian-log/xian-gelf-common/src/main/java/biz/paluch/logging/StackTraceFilter.java | StackTraceFilter.getFilteredStackTrace | @Deprecated
public static String getFilteredStackTrace(Throwable t, boolean shouldFilter) {
"""
Get a filterered stack trace.
@param t the throwable
@param shouldFilter true in case filtering should be performed. Else stack trace as string will be returned.
@return String containing the stack trace.
@deprecated since 1.11.1. Use {@link #getStackTrace(Throwable, int)} to get the stack trace without filtering or
{@link #getFilteredStackTrace(Throwable)} to get the filtered the stack trace.
"""
if (shouldFilter) {
return getFilteredStackTrace(t, 0);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
return sw.getBuffer().toString();
} | java | @Deprecated
public static String getFilteredStackTrace(Throwable t, boolean shouldFilter) {
if (shouldFilter) {
return getFilteredStackTrace(t, 0);
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
return sw.getBuffer().toString();
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"getFilteredStackTrace",
"(",
"Throwable",
"t",
",",
"boolean",
"shouldFilter",
")",
"{",
"if",
"(",
"shouldFilter",
")",
"{",
"return",
"getFilteredStackTrace",
"(",
"t",
",",
"0",
")",
";",
"}",
"StringWriter"... | Get a filterered stack trace.
@param t the throwable
@param shouldFilter true in case filtering should be performed. Else stack trace as string will be returned.
@return String containing the stack trace.
@deprecated since 1.11.1. Use {@link #getStackTrace(Throwable, int)} to get the stack trace without filtering or
{@link #getFilteredStackTrace(Throwable)} to get the filtered the stack trace. | [
"Get",
"a",
"filterered",
"stack",
"trace",
"."
] | train | https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-log/xian-gelf-common/src/main/java/biz/paluch/logging/StackTraceFilter.java#L223-L236 |
googleapis/google-http-java-client | google-http-client/src/main/java/com/google/api/client/json/JsonParser.java | JsonParser.parseAndClose | @Beta
public final <T> T parseAndClose(Class<T> destinationClass, CustomizeJsonParser customizeParser)
throws IOException {
"""
{@link Beta} <br>
Parse a JSON object, array, or value into a new instance of the given destination class using
{@link JsonParser#parse(Class, CustomizeJsonParser)}, and then closes the parser.
@param <T> destination class
@param destinationClass destination class that has a public default constructor to use to
create a new instance
@param customizeParser optional parser customizer or {@code null} for none
@return new instance of the parsed destination class
"""
try {
return parse(destinationClass, customizeParser);
} finally {
close();
}
} | java | @Beta
public final <T> T parseAndClose(Class<T> destinationClass, CustomizeJsonParser customizeParser)
throws IOException {
try {
return parse(destinationClass, customizeParser);
} finally {
close();
}
} | [
"@",
"Beta",
"public",
"final",
"<",
"T",
">",
"T",
"parseAndClose",
"(",
"Class",
"<",
"T",
">",
"destinationClass",
",",
"CustomizeJsonParser",
"customizeParser",
")",
"throws",
"IOException",
"{",
"try",
"{",
"return",
"parse",
"(",
"destinationClass",
",",... | {@link Beta} <br>
Parse a JSON object, array, or value into a new instance of the given destination class using
{@link JsonParser#parse(Class, CustomizeJsonParser)}, and then closes the parser.
@param <T> destination class
@param destinationClass destination class that has a public default constructor to use to
create a new instance
@param customizeParser optional parser customizer or {@code null} for none
@return new instance of the parsed destination class | [
"{",
"@link",
"Beta",
"}",
"<br",
">",
"Parse",
"a",
"JSON",
"object",
"array",
"or",
"value",
"into",
"a",
"new",
"instance",
"of",
"the",
"given",
"destination",
"class",
"using",
"{",
"@link",
"JsonParser#parse",
"(",
"Class",
"CustomizeJsonParser",
")",
... | train | https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/json/JsonParser.java#L160-L168 |
Azure/azure-sdk-for-java | cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java | DatabaseAccountsInner.regenerateKeyAsync | public Observable<Void> regenerateKeyAsync(String resourceGroupName, String accountName, KeyKind keyKind) {
"""
Regenerates an access key for the specified Azure Cosmos DB database account.
@param resourceGroupName Name of an Azure resource group.
@param accountName Cosmos DB database account name.
@param keyKind The access key to regenerate. Possible values include: 'primary', 'secondary', 'primaryReadonly', 'secondaryReadonly'
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return regenerateKeyWithServiceResponseAsync(resourceGroupName, accountName, keyKind).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> regenerateKeyAsync(String resourceGroupName, String accountName, KeyKind keyKind) {
return regenerateKeyWithServiceResponseAsync(resourceGroupName, accountName, keyKind).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"regenerateKeyAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"KeyKind",
"keyKind",
")",
"{",
"return",
"regenerateKeyWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
",",
... | Regenerates an access key for the specified Azure Cosmos DB database account.
@param resourceGroupName Name of an Azure resource group.
@param accountName Cosmos DB database account name.
@param keyKind The access key to regenerate. Possible values include: 'primary', 'secondary', 'primaryReadonly', 'secondaryReadonly'
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Regenerates",
"an",
"access",
"key",
"for",
"the",
"specified",
"Azure",
"Cosmos",
"DB",
"database",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L1827-L1834 |
kotcrab/vis-ui | ui/src/main/java/com/kotcrab/vis/ui/util/dialog/Dialogs.java | Dialogs.showErrorDialog | public static DetailsDialog showErrorDialog (Stage stage, String text, Throwable exception) {
"""
Dialog with title "Error", provided text and exception stacktrace available after pressing 'Details' button.
"""
if (exception == null)
return showErrorDialog(stage, text, (String) null);
else
return showErrorDialog(stage, text, getStackTrace(exception));
} | java | public static DetailsDialog showErrorDialog (Stage stage, String text, Throwable exception) {
if (exception == null)
return showErrorDialog(stage, text, (String) null);
else
return showErrorDialog(stage, text, getStackTrace(exception));
} | [
"public",
"static",
"DetailsDialog",
"showErrorDialog",
"(",
"Stage",
"stage",
",",
"String",
"text",
",",
"Throwable",
"exception",
")",
"{",
"if",
"(",
"exception",
"==",
"null",
")",
"return",
"showErrorDialog",
"(",
"stage",
",",
"text",
",",
"(",
"Strin... | Dialog with title "Error", provided text and exception stacktrace available after pressing 'Details' button. | [
"Dialog",
"with",
"title",
"Error",
"provided",
"text",
"and",
"exception",
"stacktrace",
"available",
"after",
"pressing",
"Details",
"button",
"."
] | train | https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/util/dialog/Dialogs.java#L161-L166 |
sniffy/sniffy | sniffy-core/src/main/java/io/sniffy/LegacySpy.java | LegacySpy.expectNever | @Deprecated
public C expectNever(Threads threadMatcher, Query query) {
"""
Alias for {@link #expectBetween(int, int, Threads, Query)} with arguments 0, 0, {@code threads}, {@code queryType}
@since 2.2
"""
return expect(SqlQueries.noneQueries().threads(threadMatcher).type(adapter(query)));
} | java | @Deprecated
public C expectNever(Threads threadMatcher, Query query) {
return expect(SqlQueries.noneQueries().threads(threadMatcher).type(adapter(query)));
} | [
"@",
"Deprecated",
"public",
"C",
"expectNever",
"(",
"Threads",
"threadMatcher",
",",
"Query",
"query",
")",
"{",
"return",
"expect",
"(",
"SqlQueries",
".",
"noneQueries",
"(",
")",
".",
"threads",
"(",
"threadMatcher",
")",
".",
"type",
"(",
"adapter",
... | Alias for {@link #expectBetween(int, int, Threads, Query)} with arguments 0, 0, {@code threads}, {@code queryType}
@since 2.2 | [
"Alias",
"for",
"{"
] | train | https://github.com/sniffy/sniffy/blob/7bdddb9593e6b6e9fe5c7c87519f864acbc3a5c0/sniffy-core/src/main/java/io/sniffy/LegacySpy.java#L152-L155 |
jbundle/webapp | base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java | BaseOsgiServlet.sendResourceFile | public boolean sendResourceFile(String path, HttpServletResponse response) throws IOException {
"""
Send this resource to the response stream.
@param request
@param response
@return
@throws IOException
"""
URL url = null;
try {
url = ClassServiceUtility.getClassService().getResourceURL(path, baseURL, null, this.getClass().getClassLoader());
} catch (RuntimeException e) {
e.printStackTrace(); // ???
}
if (url == null)
return false; // Not found
InputStream inStream = null;
try {
inStream = url.openStream();
} catch (Exception e) {
return false; // Not found
}
// Todo may want to add cache info (using bundle lastModified).
OutputStream writer = response.getOutputStream();
if (response.getContentType() == null)
{
if (httpContext != null)
response.setContentType(httpContext.getMimeType(path));
else
response.setContentType(FileHttpContext.getDefaultMimeType(path));
}
copyStream(inStream, writer, true); // Ignore errors, as browsers do weird things
writer.close();
inStream.close();
return true;
} | java | public boolean sendResourceFile(String path, HttpServletResponse response) throws IOException
{
URL url = null;
try {
url = ClassServiceUtility.getClassService().getResourceURL(path, baseURL, null, this.getClass().getClassLoader());
} catch (RuntimeException e) {
e.printStackTrace(); // ???
}
if (url == null)
return false; // Not found
InputStream inStream = null;
try {
inStream = url.openStream();
} catch (Exception e) {
return false; // Not found
}
// Todo may want to add cache info (using bundle lastModified).
OutputStream writer = response.getOutputStream();
if (response.getContentType() == null)
{
if (httpContext != null)
response.setContentType(httpContext.getMimeType(path));
else
response.setContentType(FileHttpContext.getDefaultMimeType(path));
}
copyStream(inStream, writer, true); // Ignore errors, as browsers do weird things
writer.close();
inStream.close();
return true;
} | [
"public",
"boolean",
"sendResourceFile",
"(",
"String",
"path",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"URL",
"url",
"=",
"null",
";",
"try",
"{",
"url",
"=",
"ClassServiceUtility",
".",
"getClassService",
"(",
")",
".",
"ge... | Send this resource to the response stream.
@param request
@param response
@return
@throws IOException | [
"Send",
"this",
"resource",
"to",
"the",
"response",
"stream",
"."
] | train | https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java#L88-L118 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/BigtableDataClient.java | BigtableDataClient.readRowAsync | public ApiFuture<Row> readRowAsync(String tableId, String rowKey, @Nullable Filter filter) {
"""
Convenience method for asynchronously reading a single row. If the row does not exist, the
future's value will be null.
<p>Sample code:
<pre>{@code
try (BigtableDataClient bigtableDataClient = BigtableDataClient.create("[PROJECT]", "[INSTANCE]")) {
String tableId = "[TABLE]";
// Build the filter expression
Filters.Filter filter = FILTERS.chain()
.filter(FILTERS.qualifier().regex("prefix.*"))
.filter(FILTERS.limit().cellsPerRow(10));
ApiFuture<Row> futureResult = bigtableDataClient.readRowAsync(tableId, "key", filter);
ApiFutures.addCallback(futureResult, new ApiFutureCallback<Row>() {
public void onFailure(Throwable t) {
if (t instanceof NotFoundException) {
System.out.println("Tried to read a non-existent table");
} else {
t.printStackTrace();
}
}
public void onSuccess(Row row) {
if (result != null) {
System.out.println("Got row: " + result);
}
}
}, MoreExecutors.directExecutor());
}
}</pre>
"""
return readRowAsync(tableId, ByteString.copyFromUtf8(rowKey), filter);
} | java | public ApiFuture<Row> readRowAsync(String tableId, String rowKey, @Nullable Filter filter) {
return readRowAsync(tableId, ByteString.copyFromUtf8(rowKey), filter);
} | [
"public",
"ApiFuture",
"<",
"Row",
">",
"readRowAsync",
"(",
"String",
"tableId",
",",
"String",
"rowKey",
",",
"@",
"Nullable",
"Filter",
"filter",
")",
"{",
"return",
"readRowAsync",
"(",
"tableId",
",",
"ByteString",
".",
"copyFromUtf8",
"(",
"rowKey",
")... | Convenience method for asynchronously reading a single row. If the row does not exist, the
future's value will be null.
<p>Sample code:
<pre>{@code
try (BigtableDataClient bigtableDataClient = BigtableDataClient.create("[PROJECT]", "[INSTANCE]")) {
String tableId = "[TABLE]";
// Build the filter expression
Filters.Filter filter = FILTERS.chain()
.filter(FILTERS.qualifier().regex("prefix.*"))
.filter(FILTERS.limit().cellsPerRow(10));
ApiFuture<Row> futureResult = bigtableDataClient.readRowAsync(tableId, "key", filter);
ApiFutures.addCallback(futureResult, new ApiFutureCallback<Row>() {
public void onFailure(Throwable t) {
if (t instanceof NotFoundException) {
System.out.println("Tried to read a non-existent table");
} else {
t.printStackTrace();
}
}
public void onSuccess(Row row) {
if (result != null) {
System.out.println("Got row: " + result);
}
}
}, MoreExecutors.directExecutor());
}
}</pre> | [
"Convenience",
"method",
"for",
"asynchronously",
"reading",
"a",
"single",
"row",
".",
"If",
"the",
"row",
"does",
"not",
"exist",
"the",
"future",
"s",
"value",
"will",
"be",
"null",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/BigtableDataClient.java#L375-L377 |
alkacon/opencms-core | src/org/opencms/notification/CmsContentNotification.java | CmsContentNotification.buildNotificationListItem | private String buildNotificationListItem(CmsExtendedNotificationCause notificationCause, int row) {
"""
Returns a string representation of this resource info.<p>
@param notificationCause the notification cause
@param row the row number
@return a string representation of this resource info
"""
StringBuffer result = new StringBuffer("<tr class=\"trow");
result.append(row);
result.append("\"><td width=\"100%\">");
String resourcePath = notificationCause.getResource().getRootPath();
String siteRoot = OpenCms.getSiteManager().getSiteRoot(resourcePath);
resourcePath = resourcePath.substring(siteRoot.length());
// append link, if page is available
if ((notificationCause.getResource().getDateReleased() < System.currentTimeMillis())
&& (notificationCause.getResource().getDateExpired() > System.currentTimeMillis())) {
Map<String, String[]> params = new HashMap<String, String[]>();
params.put(CmsWorkplace.PARAM_WP_SITE, new String[] {siteRoot});
params.put(CmsDialog.PARAM_RESOURCE, new String[] {resourcePath});
result.append("<a href=\"");
result.append(
CmsRequestUtil.appendParameters(m_uriWorkplace + "commons/displayresource.jsp", params, false));
result.append("\">");
result.append(resourcePath);
result.append("</a>");
} else {
result.append(resourcePath);
}
result.append("</td><td><div style=\"white-space:nowrap;padding-left:10px;padding-right:10px;\">");
result.append(siteRoot);
result.append("</td><td><div style=\"white-space:nowrap;padding-left:10px;padding-right:10px;\">");
if (notificationCause.getCause() == CmsExtendedNotificationCause.RESOURCE_EXPIRES) {
result.append(m_messages.key(Messages.GUI_EXPIRES_AT_1, new Object[] {notificationCause.getDate()}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendModifyLink(result, notificationCause);
} else if (notificationCause.getCause() == CmsExtendedNotificationCause.RESOURCE_RELEASE) {
result.append(m_messages.key(Messages.GUI_RELEASE_AT_1, new Object[] {notificationCause.getDate()}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendModifyLink(result, notificationCause);
} else if (notificationCause.getCause() == CmsExtendedNotificationCause.RESOURCE_UPDATE_REQUIRED) {
result.append(m_messages.key(Messages.GUI_UPDATE_REQUIRED_1, new Object[] {notificationCause.getDate()}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendEditLink(result, notificationCause);
} else {
result.append(
m_messages.key(
Messages.GUI_UNCHANGED_SINCE_1,
new Object[] {new Integer(CmsDateUtil.getDaysPassedSince(notificationCause.getDate()))}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendEditLink(result, notificationCause);
}
result.append("</tr>");
return result.toString();
} | java | private String buildNotificationListItem(CmsExtendedNotificationCause notificationCause, int row) {
StringBuffer result = new StringBuffer("<tr class=\"trow");
result.append(row);
result.append("\"><td width=\"100%\">");
String resourcePath = notificationCause.getResource().getRootPath();
String siteRoot = OpenCms.getSiteManager().getSiteRoot(resourcePath);
resourcePath = resourcePath.substring(siteRoot.length());
// append link, if page is available
if ((notificationCause.getResource().getDateReleased() < System.currentTimeMillis())
&& (notificationCause.getResource().getDateExpired() > System.currentTimeMillis())) {
Map<String, String[]> params = new HashMap<String, String[]>();
params.put(CmsWorkplace.PARAM_WP_SITE, new String[] {siteRoot});
params.put(CmsDialog.PARAM_RESOURCE, new String[] {resourcePath});
result.append("<a href=\"");
result.append(
CmsRequestUtil.appendParameters(m_uriWorkplace + "commons/displayresource.jsp", params, false));
result.append("\">");
result.append(resourcePath);
result.append("</a>");
} else {
result.append(resourcePath);
}
result.append("</td><td><div style=\"white-space:nowrap;padding-left:10px;padding-right:10px;\">");
result.append(siteRoot);
result.append("</td><td><div style=\"white-space:nowrap;padding-left:10px;padding-right:10px;\">");
if (notificationCause.getCause() == CmsExtendedNotificationCause.RESOURCE_EXPIRES) {
result.append(m_messages.key(Messages.GUI_EXPIRES_AT_1, new Object[] {notificationCause.getDate()}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendModifyLink(result, notificationCause);
} else if (notificationCause.getCause() == CmsExtendedNotificationCause.RESOURCE_RELEASE) {
result.append(m_messages.key(Messages.GUI_RELEASE_AT_1, new Object[] {notificationCause.getDate()}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendModifyLink(result, notificationCause);
} else if (notificationCause.getCause() == CmsExtendedNotificationCause.RESOURCE_UPDATE_REQUIRED) {
result.append(m_messages.key(Messages.GUI_UPDATE_REQUIRED_1, new Object[] {notificationCause.getDate()}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendEditLink(result, notificationCause);
} else {
result.append(
m_messages.key(
Messages.GUI_UNCHANGED_SINCE_1,
new Object[] {new Integer(CmsDateUtil.getDaysPassedSince(notificationCause.getDate()))}));
result.append("</div></td>");
appendConfirmLink(result, notificationCause);
appendEditLink(result, notificationCause);
}
result.append("</tr>");
return result.toString();
} | [
"private",
"String",
"buildNotificationListItem",
"(",
"CmsExtendedNotificationCause",
"notificationCause",
",",
"int",
"row",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
"\"<tr class=\\\"trow\"",
")",
";",
"result",
".",
"append",
"(",
"row",... | Returns a string representation of this resource info.<p>
@param notificationCause the notification cause
@param row the row number
@return a string representation of this resource info | [
"Returns",
"a",
"string",
"representation",
"of",
"this",
"resource",
"info",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/notification/CmsContentNotification.java#L371-L426 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Character.java | Character.codePointCount | public static int codePointCount(CharSequence seq, int beginIndex, int endIndex) {
"""
Returns the number of Unicode code points in the text range of
the specified char sequence. The text range begins at the
specified {@code beginIndex} and extends to the
{@code char} at index {@code endIndex - 1}. Thus the
length (in {@code char}s) of the text range is
{@code endIndex-beginIndex}. Unpaired surrogates within
the text range count as one code point each.
@param seq the char sequence
@param beginIndex the index to the first {@code char} of
the text range.
@param endIndex the index after the last {@code char} of
the text range.
@return the number of Unicode code points in the specified text
range
@exception NullPointerException if {@code seq} is null.
@exception IndexOutOfBoundsException if the
{@code beginIndex} is negative, or {@code endIndex}
is larger than the length of the given sequence, or
{@code beginIndex} is larger than {@code endIndex}.
@since 1.5
"""
int length = seq.length();
if (beginIndex < 0 || endIndex > length || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
int n = endIndex - beginIndex;
for (int i = beginIndex; i < endIndex; ) {
if (isHighSurrogate(seq.charAt(i++)) && i < endIndex &&
isLowSurrogate(seq.charAt(i))) {
n--;
i++;
}
}
return n;
} | java | public static int codePointCount(CharSequence seq, int beginIndex, int endIndex) {
int length = seq.length();
if (beginIndex < 0 || endIndex > length || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
int n = endIndex - beginIndex;
for (int i = beginIndex; i < endIndex; ) {
if (isHighSurrogate(seq.charAt(i++)) && i < endIndex &&
isLowSurrogate(seq.charAt(i))) {
n--;
i++;
}
}
return n;
} | [
"public",
"static",
"int",
"codePointCount",
"(",
"CharSequence",
"seq",
",",
"int",
"beginIndex",
",",
"int",
"endIndex",
")",
"{",
"int",
"length",
"=",
"seq",
".",
"length",
"(",
")",
";",
"if",
"(",
"beginIndex",
"<",
"0",
"||",
"endIndex",
">",
"l... | Returns the number of Unicode code points in the text range of
the specified char sequence. The text range begins at the
specified {@code beginIndex} and extends to the
{@code char} at index {@code endIndex - 1}. Thus the
length (in {@code char}s) of the text range is
{@code endIndex-beginIndex}. Unpaired surrogates within
the text range count as one code point each.
@param seq the char sequence
@param beginIndex the index to the first {@code char} of
the text range.
@param endIndex the index after the last {@code char} of
the text range.
@return the number of Unicode code points in the specified text
range
@exception NullPointerException if {@code seq} is null.
@exception IndexOutOfBoundsException if the
{@code beginIndex} is negative, or {@code endIndex}
is larger than the length of the given sequence, or
{@code beginIndex} is larger than {@code endIndex}.
@since 1.5 | [
"Returns",
"the",
"number",
"of",
"Unicode",
"code",
"points",
"in",
"the",
"text",
"range",
"of",
"the",
"specified",
"char",
"sequence",
".",
"The",
"text",
"range",
"begins",
"at",
"the",
"specified",
"{",
"@code",
"beginIndex",
"}",
"and",
"extends",
"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/lang/Character.java#L5266-L5280 |
stratosphere/stratosphere | stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java | Configuration.getDouble | public double getDouble(String key, double defaultValue) {
"""
Returns the value associated with the given key as a double.
@param key
the key pointing to the associated value
@param defaultValue
the default value which is returned in case there is no value associated with the given key
@return the (default) value associated with the given key
"""
String val = getStringInternal(key);
if (val == null) {
return defaultValue;
} else {
return Double.parseDouble(val);
}
} | java | public double getDouble(String key, double defaultValue) {
String val = getStringInternal(key);
if (val == null) {
return defaultValue;
} else {
return Double.parseDouble(val);
}
} | [
"public",
"double",
"getDouble",
"(",
"String",
"key",
",",
"double",
"defaultValue",
")",
"{",
"String",
"val",
"=",
"getStringInternal",
"(",
"key",
")",
";",
"if",
"(",
"val",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"else",
"{",
... | Returns the value associated with the given key as a double.
@param key
the key pointing to the associated value
@param defaultValue
the default value which is returned in case there is no value associated with the given key
@return the (default) value associated with the given key | [
"Returns",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
"as",
"a",
"double",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java#L302-L309 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java | HttpChannelConfig.parseByteCacheSize | private void parseByteCacheSize(Map<Object, Object> props) {
"""
Check the input configuration for the size of the parse byte cache to use.
@param props
"""
Object value = props.get(HttpConfigConstants.PROPNAME_BYTE_CACHE_SIZE);
if (null != value) {
try {
this.byteCacheSize = rangeLimit(convertInteger(value), HttpConfigConstants.MIN_BYTE_CACHE_SIZE, HttpConfigConstants.MAX_BYTE_CACHE_SIZE);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: byte cache size is " + getByteCacheSize());
}
} catch (NumberFormatException nfe) {
FFDCFilter.processException(nfe, getClass().getName() + ".parseByteCacheSize", "1");
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Invalid bytecache setting of " + value);
}
}
}
} | java | private void parseByteCacheSize(Map<Object, Object> props) {
Object value = props.get(HttpConfigConstants.PROPNAME_BYTE_CACHE_SIZE);
if (null != value) {
try {
this.byteCacheSize = rangeLimit(convertInteger(value), HttpConfigConstants.MIN_BYTE_CACHE_SIZE, HttpConfigConstants.MAX_BYTE_CACHE_SIZE);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: byte cache size is " + getByteCacheSize());
}
} catch (NumberFormatException nfe) {
FFDCFilter.processException(nfe, getClass().getName() + ".parseByteCacheSize", "1");
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Invalid bytecache setting of " + value);
}
}
}
} | [
"private",
"void",
"parseByteCacheSize",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
"props",
")",
"{",
"Object",
"value",
"=",
"props",
".",
"get",
"(",
"HttpConfigConstants",
".",
"PROPNAME_BYTE_CACHE_SIZE",
")",
";",
"if",
"(",
"null",
"!=",
"value",
... | Check the input configuration for the size of the parse byte cache to use.
@param props | [
"Check",
"the",
"input",
"configuration",
"for",
"the",
"size",
"of",
"the",
"parse",
"byte",
"cache",
"to",
"use",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java#L758-L773 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernelGaussian.java | FactoryKernelGaussian.gaussian1D | public static <T extends ImageGray<T>, K extends Kernel1D>
K gaussian1D(Class<T> imageType, double sigma, int radius ) {
"""
Creates a 1D Gaussian kernel of the specified type.
@param imageType The type of image which is to be convolved by this kernel.
@param sigma The distributions stdev. If ≤ 0 then the sigma will be computed from the radius.
@param radius Number of pixels in the kernel's radius. If ≤ 0 then the sigma will be computed from the sigma.
@return The computed Gaussian kernel.
"""
boolean isFloat = GeneralizedImageOps.isFloatingPoint(imageType);
int numBits = GeneralizedImageOps.getNumBits(imageType);
if( numBits < 32 )
numBits = 32;
return gaussian(1,isFloat, numBits, sigma,radius);
} | java | public static <T extends ImageGray<T>, K extends Kernel1D>
K gaussian1D(Class<T> imageType, double sigma, int radius )
{
boolean isFloat = GeneralizedImageOps.isFloatingPoint(imageType);
int numBits = GeneralizedImageOps.getNumBits(imageType);
if( numBits < 32 )
numBits = 32;
return gaussian(1,isFloat, numBits, sigma,radius);
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
",",
"K",
"extends",
"Kernel1D",
">",
"K",
"gaussian1D",
"(",
"Class",
"<",
"T",
">",
"imageType",
",",
"double",
"sigma",
",",
"int",
"radius",
")",
"{",
"boolean",
"isFloat",
"=",
... | Creates a 1D Gaussian kernel of the specified type.
@param imageType The type of image which is to be convolved by this kernel.
@param sigma The distributions stdev. If ≤ 0 then the sigma will be computed from the radius.
@param radius Number of pixels in the kernel's radius. If ≤ 0 then the sigma will be computed from the sigma.
@return The computed Gaussian kernel. | [
"Creates",
"a",
"1D",
"Gaussian",
"kernel",
"of",
"the",
"specified",
"type",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernelGaussian.java#L77-L85 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java | AppServiceEnvironmentsInner.listMultiRoleMetricsWithServiceResponseAsync | public Observable<ServiceResponse<Page<ResourceMetricInner>>> listMultiRoleMetricsWithServiceResponseAsync(final String resourceGroupName, final String name, final String startTime, final String endTime, final String timeGrain, final Boolean details, final String filter) {
"""
Get metrics for a multi-role pool of an App Service Environment.
Get metrics for a multi-role pool of an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@param startTime Beginning time of the metrics query.
@param endTime End time of the metrics query.
@param timeGrain Time granularity of the metrics query.
@param details Specify <code>true</code> to include instance details. The default is <code>false</code>.
@param filter Return only usages/metrics specified in the filter. Filter conforms to odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricInner> object
"""
return listMultiRoleMetricsSinglePageAsync(resourceGroupName, name, startTime, endTime, timeGrain, details, filter)
.concatMap(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Observable<ServiceResponse<Page<ResourceMetricInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceMetricInner>>> call(ServiceResponse<Page<ResourceMetricInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listMultiRoleMetricsNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<ResourceMetricInner>>> listMultiRoleMetricsWithServiceResponseAsync(final String resourceGroupName, final String name, final String startTime, final String endTime, final String timeGrain, final Boolean details, final String filter) {
return listMultiRoleMetricsSinglePageAsync(resourceGroupName, name, startTime, endTime, timeGrain, details, filter)
.concatMap(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Observable<ServiceResponse<Page<ResourceMetricInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceMetricInner>>> call(ServiceResponse<Page<ResourceMetricInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listMultiRoleMetricsNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"ResourceMetricInner",
">",
">",
">",
"listMultiRoleMetricsWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"name",
",",
"final",
"String",
"startTime",
",... | Get metrics for a multi-role pool of an App Service Environment.
Get metrics for a multi-role pool of an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@param startTime Beginning time of the metrics query.
@param endTime End time of the metrics query.
@param timeGrain Time granularity of the metrics query.
@param details Specify <code>true</code> to include instance details. The default is <code>false</code>.
@param filter Return only usages/metrics specified in the filter. Filter conforms to odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq 'Metric2') and startTime eq '2014-01-01T00:00:00Z' and endTime eq '2014-12-31T23:59:59Z' and timeGrain eq duration'[Hour|Minute|Day]'.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricInner> object | [
"Get",
"metrics",
"for",
"a",
"multi",
"-",
"role",
"pool",
"of",
"an",
"App",
"Service",
"Environment",
".",
"Get",
"metrics",
"for",
"a",
"multi",
"-",
"role",
"pool",
"of",
"an",
"App",
"Service",
"Environment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L3298-L3310 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java | TypeUtility.isTypeIncludedIn | public static boolean isTypeIncludedIn(TypeName value, Type... types) {
"""
Checks if is type included in.
@param value
the value
@param types
the types
@return true, if is type included in
"""
for (Type item : types) {
if (value.equals(typeName(item))) {
return true;
}
}
return false;
} | java | public static boolean isTypeIncludedIn(TypeName value, Type... types) {
for (Type item : types) {
if (value.equals(typeName(item))) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"isTypeIncludedIn",
"(",
"TypeName",
"value",
",",
"Type",
"...",
"types",
")",
"{",
"for",
"(",
"Type",
"item",
":",
"types",
")",
"{",
"if",
"(",
"value",
".",
"equals",
"(",
"typeName",
"(",
"item",
")",
")",
")",
"{... | Checks if is type included in.
@param value
the value
@param types
the types
@return true, if is type included in | [
"Checks",
"if",
"is",
"type",
"included",
"in",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java#L64-L72 |
Azure/azure-sdk-for-java | eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java | EventSubscriptionsInner.listRegionalByResourceGroupForTopicType | public List<EventSubscriptionInner> listRegionalByResourceGroupForTopicType(String resourceGroupName, String location, String topicTypeName) {
"""
List all regional event subscriptions under an Azure subscription and resource group for a topic type.
List all event subscriptions from the given location under a specific Azure subscription and resource group and topic type.
@param resourceGroupName The name of the resource group within the user's subscription.
@param location Name of the location
@param topicTypeName Name of the topic type
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<EventSubscriptionInner> object if successful.
"""
return listRegionalByResourceGroupForTopicTypeWithServiceResponseAsync(resourceGroupName, location, topicTypeName).toBlocking().single().body();
} | java | public List<EventSubscriptionInner> listRegionalByResourceGroupForTopicType(String resourceGroupName, String location, String topicTypeName) {
return listRegionalByResourceGroupForTopicTypeWithServiceResponseAsync(resourceGroupName, location, topicTypeName).toBlocking().single().body();
} | [
"public",
"List",
"<",
"EventSubscriptionInner",
">",
"listRegionalByResourceGroupForTopicType",
"(",
"String",
"resourceGroupName",
",",
"String",
"location",
",",
"String",
"topicTypeName",
")",
"{",
"return",
"listRegionalByResourceGroupForTopicTypeWithServiceResponseAsync",
... | List all regional event subscriptions under an Azure subscription and resource group for a topic type.
List all event subscriptions from the given location under a specific Azure subscription and resource group and topic type.
@param resourceGroupName The name of the resource group within the user's subscription.
@param location Name of the location
@param topicTypeName Name of the topic type
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<EventSubscriptionInner> object if successful. | [
"List",
"all",
"regional",
"event",
"subscriptions",
"under",
"an",
"Azure",
"subscription",
"and",
"resource",
"group",
"for",
"a",
"topic",
"type",
".",
"List",
"all",
"event",
"subscriptions",
"from",
"the",
"given",
"location",
"under",
"a",
"specific",
"A... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java#L1463-L1465 |
HeidelTime/heideltime | src/de/unihd/dbs/uima/annotator/heideltime/processors/HolidayProcessor.java | HolidayProcessor.getEasterSunday | public String getEasterSunday(int year, int days) {
"""
Get the date of a day relative to Easter Sunday in a given year. Algorithm used is from the "Physikalisch-Technische Bundesanstalt Braunschweig" PTB.
@author Hans-Peter Pfeiffer
@param year
@param days
@return date
"""
int K = year / 100;
int M = 15 + ( ( 3 * K + 3 ) / 4 ) - ( ( 8 * K + 13 ) / 25 );
int S = 2 - ( (3 * K + 3) / 4 );
int A = year % 19;
int D = ( 19 * A + M ) % 30;
int R = ( D / 29) + ( ( D / 28 ) - ( D / 29 ) * ( A / 11 ) );
int OG = 21 + D - R;
int SZ = 7 - ( year + ( year / 4 ) + S ) % 7;
int OE = 7 - ( OG - SZ ) % 7;
int OS = OG + OE;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
String date;
if( OS <= 31 ) {
date = String.format("%04d-03-%02d", year, OS);
}
else{
date = String.format("%04d-04-%02d", year, ( OS - 31 ) );
}
try{
c.setTime(formatter.parse(date));
c.add(Calendar.DAY_OF_MONTH, days);
date = formatter.format(c.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
} | java | public String getEasterSunday(int year, int days) {
int K = year / 100;
int M = 15 + ( ( 3 * K + 3 ) / 4 ) - ( ( 8 * K + 13 ) / 25 );
int S = 2 - ( (3 * K + 3) / 4 );
int A = year % 19;
int D = ( 19 * A + M ) % 30;
int R = ( D / 29) + ( ( D / 28 ) - ( D / 29 ) * ( A / 11 ) );
int OG = 21 + D - R;
int SZ = 7 - ( year + ( year / 4 ) + S ) % 7;
int OE = 7 - ( OG - SZ ) % 7;
int OS = OG + OE;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
String date;
if( OS <= 31 ) {
date = String.format("%04d-03-%02d", year, OS);
}
else{
date = String.format("%04d-04-%02d", year, ( OS - 31 ) );
}
try{
c.setTime(formatter.parse(date));
c.add(Calendar.DAY_OF_MONTH, days);
date = formatter.format(c.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
} | [
"public",
"String",
"getEasterSunday",
"(",
"int",
"year",
",",
"int",
"days",
")",
"{",
"int",
"K",
"=",
"year",
"/",
"100",
";",
"int",
"M",
"=",
"15",
"+",
"(",
"(",
"3",
"*",
"K",
"+",
"3",
")",
"/",
"4",
")",
"-",
"(",
"(",
"8",
"*",
... | Get the date of a day relative to Easter Sunday in a given year. Algorithm used is from the "Physikalisch-Technische Bundesanstalt Braunschweig" PTB.
@author Hans-Peter Pfeiffer
@param year
@param days
@return date | [
"Get",
"the",
"date",
"of",
"a",
"day",
"relative",
"to",
"Easter",
"Sunday",
"in",
"a",
"given",
"year",
".",
"Algorithm",
"used",
"is",
"from",
"the",
"Physikalisch",
"-",
"Technische",
"Bundesanstalt",
"Braunschweig",
"PTB",
"."
] | train | https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/heideltime/processors/HolidayProcessor.java#L196-L226 |
Impetus/Kundera | src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/AttributeConstraintRule.java | AttributeConstraintRule.validateNull | private boolean validateNull(Object validationObject, Annotation annotate) {
"""
Checks whether a given date is that in past or not
@param validationObject
@param annotate
@return
"""
if (checkNullObject(validationObject))
{
return true;
}
if (!validationObject.equals(null) || validationObject != null)
{
throwValidationException(((Null) annotate).message());
}
return true;
} | java | private boolean validateNull(Object validationObject, Annotation annotate)
{
if (checkNullObject(validationObject))
{
return true;
}
if (!validationObject.equals(null) || validationObject != null)
{
throwValidationException(((Null) annotate).message());
}
return true;
} | [
"private",
"boolean",
"validateNull",
"(",
"Object",
"validationObject",
",",
"Annotation",
"annotate",
")",
"{",
"if",
"(",
"checkNullObject",
"(",
"validationObject",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"validationObject",
".",
"equals... | Checks whether a given date is that in past or not
@param validationObject
@param annotate
@return | [
"Checks",
"whether",
"a",
"given",
"date",
"is",
"that",
"in",
"past",
"or",
"not"
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/AttributeConstraintRule.java#L361-L374 |
stevespringett/CPE-Parser | src/main/java/us/springett/parsers/cpe/CpeParser.java | CpeParser.parse23 | protected static Cpe parse23(String cpeString, boolean lenient) throws CpeParsingException {
"""
Parses a CPE 2.3 Formatted String.
@param cpeString the CPE string to parse
@param lenient when <code>true</code> the parser will put in lenient mode
attempting to parse invalid CPE values.
@return the CPE object represented by the cpeString
@throws CpeParsingException thrown if the cpeString is invalid
"""
if (cpeString == null || cpeString.isEmpty()) {
throw new CpeParsingException("CPE String is null ir enpty - unable to parse");
}
CpeBuilder cb = new CpeBuilder();
Cpe23PartIterator cpe = new Cpe23PartIterator(cpeString);
try {
cb.part(cpe.next());
cb.wfVendor(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfProduct(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfVersion(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfUpdate(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfEdition(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfLanguage(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfSwEdition(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfTargetSw(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfTargetHw(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfOther(Convert.fsToWellFormed(cpe.next(), lenient));
} catch (NoSuchElementException ex) {
throw new CpeParsingException("Invalid CPE (too few components): " + cpeString);
}
if (cpe.hasNext()) {
throw new CpeParsingException("Invalid CPE (too many components): " + cpeString);
}
try {
return cb.build();
} catch (CpeValidationException ex) {
throw new CpeParsingException(ex.getMessage());
}
} | java | protected static Cpe parse23(String cpeString, boolean lenient) throws CpeParsingException {
if (cpeString == null || cpeString.isEmpty()) {
throw new CpeParsingException("CPE String is null ir enpty - unable to parse");
}
CpeBuilder cb = new CpeBuilder();
Cpe23PartIterator cpe = new Cpe23PartIterator(cpeString);
try {
cb.part(cpe.next());
cb.wfVendor(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfProduct(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfVersion(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfUpdate(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfEdition(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfLanguage(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfSwEdition(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfTargetSw(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfTargetHw(Convert.fsToWellFormed(cpe.next(), lenient));
cb.wfOther(Convert.fsToWellFormed(cpe.next(), lenient));
} catch (NoSuchElementException ex) {
throw new CpeParsingException("Invalid CPE (too few components): " + cpeString);
}
if (cpe.hasNext()) {
throw new CpeParsingException("Invalid CPE (too many components): " + cpeString);
}
try {
return cb.build();
} catch (CpeValidationException ex) {
throw new CpeParsingException(ex.getMessage());
}
} | [
"protected",
"static",
"Cpe",
"parse23",
"(",
"String",
"cpeString",
",",
"boolean",
"lenient",
")",
"throws",
"CpeParsingException",
"{",
"if",
"(",
"cpeString",
"==",
"null",
"||",
"cpeString",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"CpeParsin... | Parses a CPE 2.3 Formatted String.
@param cpeString the CPE string to parse
@param lenient when <code>true</code> the parser will put in lenient mode
attempting to parse invalid CPE values.
@return the CPE object represented by the cpeString
@throws CpeParsingException thrown if the cpeString is invalid | [
"Parses",
"a",
"CPE",
"2",
".",
"3",
"Formatted",
"String",
"."
] | train | https://github.com/stevespringett/CPE-Parser/blob/e6324ca020dc0790097d3d62bb98aabf60e56843/src/main/java/us/springett/parsers/cpe/CpeParser.java#L203-L232 |
thorstenwagner/TraJ | src/main/java/de/biomedical_imaging/traJ/TrajectoryUtil.java | TrajectoryUtil.getTrajectoryByID | public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id) {
"""
Finds trajectory by ID
@param t List of Trajectories
@param id ID of the trajectorie
@return Trajectory with ID=id
"""
Trajectory track = null;
for(int i = 0; i < t.size() ; i++){
if(t.get(i).getID()==id){
track = t.get(i);
break;
}
}
return track;
} | java | public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){
Trajectory track = null;
for(int i = 0; i < t.size() ; i++){
if(t.get(i).getID()==id){
track = t.get(i);
break;
}
}
return track;
} | [
"public",
"static",
"Trajectory",
"getTrajectoryByID",
"(",
"List",
"<",
"?",
"extends",
"Trajectory",
">",
"t",
",",
"int",
"id",
")",
"{",
"Trajectory",
"track",
"=",
"null",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"t",
".",
"size",
... | Finds trajectory by ID
@param t List of Trajectories
@param id ID of the trajectorie
@return Trajectory with ID=id | [
"Finds",
"trajectory",
"by",
"ID"
] | train | https://github.com/thorstenwagner/TraJ/blob/505fafb1f2f77a2d67bb2a089a2fdebe2c9bc7cb/src/main/java/de/biomedical_imaging/traJ/TrajectoryUtil.java#L164-L173 |
VoltDB/voltdb | src/frontend/org/voltdb/ExportStatsBase.java | ExportStatsBase.populateColumnSchema | @Override
protected void populateColumnSchema(ArrayList<ColumnInfo> columns) {
"""
Check cluster.py and checkstats.py if order of the columns is changed,
"""
super.populateColumnSchema(columns);
columns.add(new ColumnInfo(VoltSystemProcedure.CNAME_SITE_ID, VoltSystemProcedure.CTYPE_ID));
columns.add(new ColumnInfo(Columns.PARTITION_ID, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.SOURCE_NAME, VoltType.STRING));
columns.add(new ColumnInfo(Columns.EXPORT_TARGET, VoltType.STRING));
columns.add(new ColumnInfo(Columns.ACTIVE, VoltType.STRING));
columns.add(new ColumnInfo(Columns.TUPLE_COUNT, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.TUPLE_PENDING, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.LAST_QUEUED_TIMESTAMP, VoltType.TIMESTAMP));
columns.add(new ColumnInfo(Columns.LAST_ACKED_TIMESTAMP, VoltType.TIMESTAMP));
columns.add(new ColumnInfo(Columns.AVERAGE_LATENCY, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.MAX_LATENCY, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.QUEUE_GAP, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.STATUS, VoltType.STRING));
} | java | @Override
protected void populateColumnSchema(ArrayList<ColumnInfo> columns) {
super.populateColumnSchema(columns);
columns.add(new ColumnInfo(VoltSystemProcedure.CNAME_SITE_ID, VoltSystemProcedure.CTYPE_ID));
columns.add(new ColumnInfo(Columns.PARTITION_ID, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.SOURCE_NAME, VoltType.STRING));
columns.add(new ColumnInfo(Columns.EXPORT_TARGET, VoltType.STRING));
columns.add(new ColumnInfo(Columns.ACTIVE, VoltType.STRING));
columns.add(new ColumnInfo(Columns.TUPLE_COUNT, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.TUPLE_PENDING, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.LAST_QUEUED_TIMESTAMP, VoltType.TIMESTAMP));
columns.add(new ColumnInfo(Columns.LAST_ACKED_TIMESTAMP, VoltType.TIMESTAMP));
columns.add(new ColumnInfo(Columns.AVERAGE_LATENCY, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.MAX_LATENCY, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.QUEUE_GAP, VoltType.BIGINT));
columns.add(new ColumnInfo(Columns.STATUS, VoltType.STRING));
} | [
"@",
"Override",
"protected",
"void",
"populateColumnSchema",
"(",
"ArrayList",
"<",
"ColumnInfo",
">",
"columns",
")",
"{",
"super",
".",
"populateColumnSchema",
"(",
"columns",
")",
";",
"columns",
".",
"add",
"(",
"new",
"ColumnInfo",
"(",
"VoltSystemProcedur... | Check cluster.py and checkstats.py if order of the columns is changed, | [
"Check",
"cluster",
".",
"py",
"and",
"checkstats",
".",
"py",
"if",
"order",
"of",
"the",
"columns",
"is",
"changed"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ExportStatsBase.java#L90-L106 |
pmwmedia/tinylog | benchmarks/src/main/java/org/tinylog/benchmarks/api/WritingBenchmark.java | WritingBenchmark.byteArrayRandomAccessFile | @Benchmark
@BenchmarkMode(Mode.AverageTime)
public void byteArrayRandomAccessFile(final Configuration configuration) throws IOException {
"""
Benchmarks writing via {@link RandomAccessFile} with custom buffering via a byte array.
@param configuration
Configuration with target file
@throws IOException
Failed to write to target file
"""
byte[] buffer = new byte[BUFFER_CAPACITY];
int position = 0;
try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) {
for (long i = 0; i < LINES; ++i) {
if (BUFFER_CAPACITY - position < DATA.length) {
file.write(buffer, 0, position);
position = 0;
}
if (BUFFER_CAPACITY < DATA.length) {
file.write(DATA);
} else {
System.arraycopy(DATA, 0, buffer, position, DATA.length);
position += DATA.length;
}
}
if (position > 0) {
file.write(buffer, 0, position);
}
}
} | java | @Benchmark
@BenchmarkMode(Mode.AverageTime)
public void byteArrayRandomAccessFile(final Configuration configuration) throws IOException {
byte[] buffer = new byte[BUFFER_CAPACITY];
int position = 0;
try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) {
for (long i = 0; i < LINES; ++i) {
if (BUFFER_CAPACITY - position < DATA.length) {
file.write(buffer, 0, position);
position = 0;
}
if (BUFFER_CAPACITY < DATA.length) {
file.write(DATA);
} else {
System.arraycopy(DATA, 0, buffer, position, DATA.length);
position += DATA.length;
}
}
if (position > 0) {
file.write(buffer, 0, position);
}
}
} | [
"@",
"Benchmark",
"@",
"BenchmarkMode",
"(",
"Mode",
".",
"AverageTime",
")",
"public",
"void",
"byteArrayRandomAccessFile",
"(",
"final",
"Configuration",
"configuration",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
... | Benchmarks writing via {@link RandomAccessFile} with custom buffering via a byte array.
@param configuration
Configuration with target file
@throws IOException
Failed to write to target file | [
"Benchmarks",
"writing",
"via",
"{",
"@link",
"RandomAccessFile",
"}",
"with",
"custom",
"buffering",
"via",
"a",
"byte",
"array",
"."
] | train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/benchmarks/src/main/java/org/tinylog/benchmarks/api/WritingBenchmark.java#L115-L141 |
dhemery/hartley | src/main/java/com/dhemery/expressing/Expressive.java | Expressive.assertThat | public <S> void assertThat(S subject, Ticker ticker, Feature<? super S, Boolean> feature) {
"""
Assert that a polled sample of the feature is {@code true}.
<p>Example:</p>
<pre>
{@code
Page settingsPage = ...;
Feature<Page,Boolean> displayed() { ... }
...
assertThat(settingsPage, eventually(), is(displayed()));
}
"""
assertThat(subject, feature, ticker, isQuietlyTrue());
} | java | public <S> void assertThat(S subject, Ticker ticker, Feature<? super S, Boolean> feature) {
assertThat(subject, feature, ticker, isQuietlyTrue());
} | [
"public",
"<",
"S",
">",
"void",
"assertThat",
"(",
"S",
"subject",
",",
"Ticker",
"ticker",
",",
"Feature",
"<",
"?",
"super",
"S",
",",
"Boolean",
">",
"feature",
")",
"{",
"assertThat",
"(",
"subject",
",",
"feature",
",",
"ticker",
",",
"isQuietlyT... | Assert that a polled sample of the feature is {@code true}.
<p>Example:</p>
<pre>
{@code
Page settingsPage = ...;
Feature<Page,Boolean> displayed() { ... }
...
assertThat(settingsPage, eventually(), is(displayed()));
} | [
"Assert",
"that",
"a",
"polled",
"sample",
"of",
"the",
"feature",
"is",
"{",
"@code",
"true",
"}",
".",
"<p",
">",
"Example",
":",
"<",
"/",
"p",
">",
"<pre",
">",
"{",
"@code"
] | train | https://github.com/dhemery/hartley/blob/7754bd6bc12695f2249601b8890da530a61fcf33/src/main/java/com/dhemery/expressing/Expressive.java#L111-L113 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/Validate.java | Validate.exclusiveBetween | public static void exclusiveBetween(final long start, final long end, final long value, final String message) {
"""
Validate that the specified primitive value falls between the two
exclusive values specified; otherwise, throws an exception with the
specified message.
<pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre>
@param start the exclusive start value
@param end the exclusive end value
@param value the value to validate
@param message the exception message if invalid, not null
@throws IllegalArgumentException if the value falls outside the boundaries
@since 3.3
"""
// TODO when breaking BC, consider returning value
if (value <= start || value >= end) {
throw new IllegalArgumentException(message);
}
} | java | public static void exclusiveBetween(final long start, final long end, final long value, final String message) {
// TODO when breaking BC, consider returning value
if (value <= start || value >= end) {
throw new IllegalArgumentException(message);
}
} | [
"public",
"static",
"void",
"exclusiveBetween",
"(",
"final",
"long",
"start",
",",
"final",
"long",
"end",
",",
"final",
"long",
"value",
",",
"final",
"String",
"message",
")",
"{",
"// TODO when breaking BC, consider returning value",
"if",
"(",
"value",
"<=",
... | Validate that the specified primitive value falls between the two
exclusive values specified; otherwise, throws an exception with the
specified message.
<pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre>
@param start the exclusive start value
@param end the exclusive end value
@param value the value to validate
@param message the exception message if invalid, not null
@throws IllegalArgumentException if the value falls outside the boundaries
@since 3.3 | [
"Validate",
"that",
"the",
"specified",
"primitive",
"value",
"falls",
"between",
"the",
"two",
"exclusive",
"values",
"specified",
";",
"otherwise",
"throws",
"an",
"exception",
"with",
"the",
"specified",
"message",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1196-L1201 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java | UtilMath.clamp | public static double clamp(double value, double min, double max) {
"""
Fix a value between an interval.
@param value The value to fix.
@param min The minimum value.
@param max The maximum value.
@return The fixed value.
"""
final double fixed;
if (value < min)
{
fixed = min;
}
else if (value > max)
{
fixed = max;
}
else
{
fixed = value;
}
return fixed;
} | java | public static double clamp(double value, double min, double max)
{
final double fixed;
if (value < min)
{
fixed = min;
}
else if (value > max)
{
fixed = max;
}
else
{
fixed = value;
}
return fixed;
} | [
"public",
"static",
"double",
"clamp",
"(",
"double",
"value",
",",
"double",
"min",
",",
"double",
"max",
")",
"{",
"final",
"double",
"fixed",
";",
"if",
"(",
"value",
"<",
"min",
")",
"{",
"fixed",
"=",
"min",
";",
"}",
"else",
"if",
"(",
"value... | Fix a value between an interval.
@param value The value to fix.
@param min The minimum value.
@param max The maximum value.
@return The fixed value. | [
"Fix",
"a",
"value",
"between",
"an",
"interval",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java#L130-L146 |
rzwitserloot/lombok | src/core/lombok/eclipse/handlers/HandleSuperBuilder.java | HandleSuperBuilder.generateToBuilderMethod | private MethodDeclaration generateToBuilderMethod(String builderClassName, String builderImplClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) {
"""
Generates a <code>toBuilder()</code> method in the annotated class that looks like this:
<pre>
public ParentBuilder<?, ?> toBuilder() {
return new <i>Foobar</i>BuilderImpl().$fillValuesFrom(this);
}
</pre>
"""
int pS = source.sourceStart, pE = source.sourceEnd;
long p = (long) pS << 32 | pE;
MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
out.selector = TO_BUILDER_METHOD_NAME;
out.modifiers = ClassFileConstants.AccPublic;
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND) };
out.returnType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, p);
AllocationExpression newClass = new AllocationExpression();
newClass.type = namePlusTypeParamsToTypeReference(builderImplClassName.toCharArray(), typeParams, p);
MessageSend invokeFillMethod = new MessageSend();
invokeFillMethod.receiver = newClass;
invokeFillMethod.selector = FILL_VALUES_METHOD_NAME;
invokeFillMethod.arguments = new Expression[] {new ThisReference(0, 0)};
out.statements = new Statement[] {new ReturnStatement(invokeFillMethod, pS, pE)};
out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope);
return out;
} | java | private MethodDeclaration generateToBuilderMethod(String builderClassName, String builderImplClassName, EclipseNode type, TypeParameter[] typeParams, ASTNode source) {
int pS = source.sourceStart, pE = source.sourceEnd;
long p = (long) pS << 32 | pE;
MethodDeclaration out = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
out.selector = TO_BUILDER_METHOD_NAME;
out.modifiers = ClassFileConstants.AccPublic;
out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND) };
out.returnType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, p);
AllocationExpression newClass = new AllocationExpression();
newClass.type = namePlusTypeParamsToTypeReference(builderImplClassName.toCharArray(), typeParams, p);
MessageSend invokeFillMethod = new MessageSend();
invokeFillMethod.receiver = newClass;
invokeFillMethod.selector = FILL_VALUES_METHOD_NAME;
invokeFillMethod.arguments = new Expression[] {new ThisReference(0, 0)};
out.statements = new Statement[] {new ReturnStatement(invokeFillMethod, pS, pE)};
out.traverse(new SetGeneratedByVisitor(source), ((TypeDeclaration) type.get()).scope);
return out;
} | [
"private",
"MethodDeclaration",
"generateToBuilderMethod",
"(",
"String",
"builderClassName",
",",
"String",
"builderImplClassName",
",",
"EclipseNode",
"type",
",",
"TypeParameter",
"[",
"]",
"typeParams",
",",
"ASTNode",
"source",
")",
"{",
"int",
"pS",
"=",
"sour... | Generates a <code>toBuilder()</code> method in the annotated class that looks like this:
<pre>
public ParentBuilder<?, ?> toBuilder() {
return new <i>Foobar</i>BuilderImpl().$fillValuesFrom(this);
}
</pre> | [
"Generates",
"a",
"<code",
">",
"toBuilder",
"()",
"<",
"/",
"code",
">",
"method",
"in",
"the",
"annotated",
"class",
"that",
"looks",
"like",
"this",
":",
"<pre",
">",
"public",
"ParentBuilder<",
";",
"?",
"?>",
";",
"toBuilder",
"()",
"{",
"return... | train | https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/eclipse/handlers/HandleSuperBuilder.java#L602-L624 |
albfernandez/itext2 | src/main/java/com/lowagie/text/xml/XmlParser.java | XmlParser.go | public void go(DocListener document, InputSource is) {
"""
Parses a given file.
@param document The document that will listen to the parser
@param is The InputStream with the contents
"""
try {
parser.parse(is, new SAXiTextHandler(document));
}
catch(SAXException se) {
throw new ExceptionConverter(se);
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
} | java | public void go(DocListener document, InputSource is) {
try {
parser.parse(is, new SAXiTextHandler(document));
}
catch(SAXException se) {
throw new ExceptionConverter(se);
}
catch(IOException ioe) {
throw new ExceptionConverter(ioe);
}
} | [
"public",
"void",
"go",
"(",
"DocListener",
"document",
",",
"InputSource",
"is",
")",
"{",
"try",
"{",
"parser",
".",
"parse",
"(",
"is",
",",
"new",
"SAXiTextHandler",
"(",
"document",
")",
")",
";",
"}",
"catch",
"(",
"SAXException",
"se",
")",
"{",... | Parses a given file.
@param document The document that will listen to the parser
@param is The InputStream with the contents | [
"Parses",
"a",
"given",
"file",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/xml/XmlParser.java#L98-L108 |
Azure/azure-sdk-for-java | hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java | ExtensionsInner.beginCreateAsync | public Observable<Void> beginCreateAsync(String resourceGroupName, String clusterName, String extensionName, ExtensionInner parameters) {
"""
Creates an HDInsight cluster extension.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param extensionName The name of the cluster extension.
@param parameters The cluster extensions create request.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful.
"""
return beginCreateWithServiceResponseAsync(resourceGroupName, clusterName, extensionName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> beginCreateAsync(String resourceGroupName, String clusterName, String extensionName, ExtensionInner parameters) {
return beginCreateWithServiceResponseAsync(resourceGroupName, clusterName, extensionName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"beginCreateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"String",
"extensionName",
",",
"ExtensionInner",
"parameters",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resource... | Creates an HDInsight cluster extension.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param extensionName The name of the cluster extension.
@param parameters The cluster extensions create request.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Creates",
"an",
"HDInsight",
"cluster",
"extension",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java#L634-L641 |
alkacon/opencms-core | src/org/opencms/relations/CmsCategoryService.java | CmsCategoryService.internalCategoryRootPath | private String internalCategoryRootPath(String basePath, String categoryPath) {
"""
Composes the category root path by appending the category path to the given category repository path.<p>
@param basePath the category repository path
@param categoryPath the category path
@return the category root path
"""
if (categoryPath.startsWith("/") && basePath.endsWith("/")) {
// one slash too much
return basePath + categoryPath.substring(1);
} else if (!categoryPath.startsWith("/") && !basePath.endsWith("/")) {
// one slash too less
return basePath + "/" + categoryPath;
} else {
return basePath + categoryPath;
}
} | java | private String internalCategoryRootPath(String basePath, String categoryPath) {
if (categoryPath.startsWith("/") && basePath.endsWith("/")) {
// one slash too much
return basePath + categoryPath.substring(1);
} else if (!categoryPath.startsWith("/") && !basePath.endsWith("/")) {
// one slash too less
return basePath + "/" + categoryPath;
} else {
return basePath + categoryPath;
}
} | [
"private",
"String",
"internalCategoryRootPath",
"(",
"String",
"basePath",
",",
"String",
"categoryPath",
")",
"{",
"if",
"(",
"categoryPath",
".",
"startsWith",
"(",
"\"/\"",
")",
"&&",
"basePath",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"{",
"// one slash ... | Composes the category root path by appending the category path to the given category repository path.<p>
@param basePath the category repository path
@param categoryPath the category path
@return the category root path | [
"Composes",
"the",
"category",
"root",
"path",
"by",
"appending",
"the",
"category",
"path",
"to",
"the",
"given",
"category",
"repository",
"path",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsCategoryService.java#L761-L772 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/DoubleIntIndex.java | DoubleIntIndex.setKey | public synchronized void setKey(int i, int key) {
"""
Modifies an existing pair.
@param i the index
@param key the key
"""
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
if (!sortOnValues) {
sorted = false;
}
keys[i] = key;
} | java | public synchronized void setKey(int i, int key) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
if (!sortOnValues) {
sorted = false;
}
keys[i] = key;
} | [
"public",
"synchronized",
"void",
"setKey",
"(",
"int",
"i",
",",
"int",
"key",
")",
"{",
"if",
"(",
"i",
"<",
"0",
"||",
"i",
">=",
"count",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"if",
"(",
"!",
"sortOnValues",
... | Modifies an existing pair.
@param i the index
@param key the key | [
"Modifies",
"an",
"existing",
"pair",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/DoubleIntIndex.java#L99-L110 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/tree/MapPolylineTreeSet.java | MapPolylineTreeSet.getNearestEnd | @Override
@Pure
public P getNearestEnd(double x, double y) {
"""
{@inheritDoc}
The nearest neighbor (NN) algorithm, to find the NN to a given target
point not in the tree, relies on the ability to discard large portions
of the tree by performing a simple test. To perform the NN calculation,
the tree is searched in a depth-first fashion, refining the nearest
distance. First the root node is examined with an initial assumption
that the smallest distance to the next point is infinite. The subdomain
(right or left), which is a hyperrectangle, containing the target point
is searched. This is done recursively until a final minimum region
containing the node is found. The algorithm then (through recursion)
examines each parent node, seeing if it is possible for the other
domain to contain a point that is closer. This is performed by
testing for the possibility of intersection between the hyperrectangle
and the hypersphere (formed by target node and current minimum radius).
If the rectangle that has not been recursively examined yet does not
intersect this sphere, then there is no way that the rectangle can
contain a point that is a better nearest neighbour. This is repeated
until all domains are either searched or discarded, thus leaving the
nearest neighbour as the final result. In addition to this one also
has the distance to the nearest neighbour on hand as well. Finding the
nearest point is an O(logN) operation.
"""
return NearNodeSelector.getNearest(getTree(), x, y);
} | java | @Override
@Pure
public P getNearestEnd(double x, double y) {
return NearNodeSelector.getNearest(getTree(), x, y);
} | [
"@",
"Override",
"@",
"Pure",
"public",
"P",
"getNearestEnd",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"return",
"NearNodeSelector",
".",
"getNearest",
"(",
"getTree",
"(",
")",
",",
"x",
",",
"y",
")",
";",
"}"
] | {@inheritDoc}
The nearest neighbor (NN) algorithm, to find the NN to a given target
point not in the tree, relies on the ability to discard large portions
of the tree by performing a simple test. To perform the NN calculation,
the tree is searched in a depth-first fashion, refining the nearest
distance. First the root node is examined with an initial assumption
that the smallest distance to the next point is infinite. The subdomain
(right or left), which is a hyperrectangle, containing the target point
is searched. This is done recursively until a final minimum region
containing the node is found. The algorithm then (through recursion)
examines each parent node, seeing if it is possible for the other
domain to contain a point that is closer. This is performed by
testing for the possibility of intersection between the hyperrectangle
and the hypersphere (formed by target node and current minimum radius).
If the rectangle that has not been recursively examined yet does not
intersect this sphere, then there is no way that the rectangle can
contain a point that is a better nearest neighbour. This is repeated
until all domains are either searched or discarded, thus leaving the
nearest neighbour as the final result. In addition to this one also
has the distance to the nearest neighbour on hand as well. Finding the
nearest point is an O(logN) operation. | [
"{"
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/tree/MapPolylineTreeSet.java#L152-L156 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/lang/Validator.java | Validator.validateCitizenIdNumber | public static <T extends CharSequence> T validateCitizenIdNumber(T value, String errorMsg) throws ValidateException {
"""
验证是否为身份证号码(18位中国)<br>
出生日期只支持到到2999年
@param <T> 字符串类型
@param value 值
@param errorMsg 验证错误的信息
@return 验证后的值
@throws ValidateException 验证异常
"""
if (false == isCitizenId(value)) {
throw new ValidateException(errorMsg);
}
return value;
} | java | public static <T extends CharSequence> T validateCitizenIdNumber(T value, String errorMsg) throws ValidateException {
if (false == isCitizenId(value)) {
throw new ValidateException(errorMsg);
}
return value;
} | [
"public",
"static",
"<",
"T",
"extends",
"CharSequence",
">",
"T",
"validateCitizenIdNumber",
"(",
"T",
"value",
",",
"String",
"errorMsg",
")",
"throws",
"ValidateException",
"{",
"if",
"(",
"false",
"==",
"isCitizenId",
"(",
"value",
")",
")",
"{",
"throw"... | 验证是否为身份证号码(18位中国)<br>
出生日期只支持到到2999年
@param <T> 字符串类型
@param value 值
@param errorMsg 验证错误的信息
@return 验证后的值
@throws ValidateException 验证异常 | [
"验证是否为身份证号码(18位中国)<br",
">",
"出生日期只支持到到2999年"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Validator.java#L705-L710 |
overturetool/overture | core/interpreter/src/main/java/org/overture/interpreter/runtime/VdmRuntimeError.java | VdmRuntimeError.patternFail | public static Value patternFail(ValueException ve, ILexLocation location)
throws PatternMatchException {
"""
Throw a PatternMatchException with a message from the ValueException.
@param ve
@param location
@return
@throws PatternMatchException
"""
throw new PatternMatchException(ve.number, ve.getMessage(), location);
} | java | public static Value patternFail(ValueException ve, ILexLocation location)
throws PatternMatchException
{
throw new PatternMatchException(ve.number, ve.getMessage(), location);
} | [
"public",
"static",
"Value",
"patternFail",
"(",
"ValueException",
"ve",
",",
"ILexLocation",
"location",
")",
"throws",
"PatternMatchException",
"{",
"throw",
"new",
"PatternMatchException",
"(",
"ve",
".",
"number",
",",
"ve",
".",
"getMessage",
"(",
")",
",",... | Throw a PatternMatchException with a message from the ValueException.
@param ve
@param location
@return
@throws PatternMatchException | [
"Throw",
"a",
"PatternMatchException",
"with",
"a",
"message",
"from",
"the",
"ValueException",
"."
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/runtime/VdmRuntimeError.java#L60-L64 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java | ByteUtils.boolToBytes | public static final void boolToBytes( boolean b, byte[] data, int[] offset ) {
"""
Write the bytes representing <code>b</code> into the byte array
<code>data</code>, starting at index <code>offset [0]</code>, and
increment <code>offset [0]</code> by the number of bytes written; if
<code>data == null</code>, increment <code>offset [0]</code> by the
number of bytes that would have been written otherwise.
@param b the <code>boolean</code> to encode
@param data The byte array to store into, or <code>null</code>.
@param offset A single element array whose first element is the index in
data to begin writing at on function entry, and which on
function exit has been incremented by the number of bytes
written.
"""
if (data != null) {
data[offset[0]] = (byte) (b ? 1 : 0);
}
offset[0] += SIZE_BOOL;
} | java | public static final void boolToBytes( boolean b, byte[] data, int[] offset ) {
if (data != null) {
data[offset[0]] = (byte) (b ? 1 : 0);
}
offset[0] += SIZE_BOOL;
} | [
"public",
"static",
"final",
"void",
"boolToBytes",
"(",
"boolean",
"b",
",",
"byte",
"[",
"]",
"data",
",",
"int",
"[",
"]",
"offset",
")",
"{",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"data",
"[",
"offset",
"[",
"0",
"]",
"]",
"=",
"(",
"b... | Write the bytes representing <code>b</code> into the byte array
<code>data</code>, starting at index <code>offset [0]</code>, and
increment <code>offset [0]</code> by the number of bytes written; if
<code>data == null</code>, increment <code>offset [0]</code> by the
number of bytes that would have been written otherwise.
@param b the <code>boolean</code> to encode
@param data The byte array to store into, or <code>null</code>.
@param offset A single element array whose first element is the index in
data to begin writing at on function entry, and which on
function exit has been incremented by the number of bytes
written. | [
"Write",
"the",
"bytes",
"representing",
"<code",
">",
"b<",
"/",
"code",
">",
"into",
"the",
"byte",
"array",
"<code",
">",
"data<",
"/",
"code",
">",
"starting",
"at",
"index",
"<code",
">",
"offset",
"[",
"0",
"]",
"<",
"/",
"code",
">",
"and",
... | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java#L338-L344 |
jtrfp/javamod | src/main/java/de/quippy/javamod/mixer/dsp/AudioProcessor.java | AudioProcessor.writeSampleData | public int writeSampleData(final byte [] newSampleData, final int offset, int length) {
"""
This method will write the sample data to the dsp buffer
It will convert all sampledata to a stereo or mono float of 1.0<=x<=-1.0
@since 23.12.2011
@param newSampleData
@param offset
@param length
"""
synchronized(lock)
{
System.arraycopy(newSampleData, offset, resultSampleBuffer, 0, length);
int anzSamples = writeIntoFloatArrayBuffer(length);
if (dspEnabled)
{
// call the callbacks for digital signal processing
// ...
anzSamples = callEffects(sampleBuffer, currentWritePosition, anzSamples);
// and recalc from the float array...
length = readFromFloatArrayBuffer(anzSamples);
}
currentWritePosition = (currentWritePosition + anzSamples) % sampleBufferSize;
return length;
}
} | java | public int writeSampleData(final byte [] newSampleData, final int offset, int length)
{
synchronized(lock)
{
System.arraycopy(newSampleData, offset, resultSampleBuffer, 0, length);
int anzSamples = writeIntoFloatArrayBuffer(length);
if (dspEnabled)
{
// call the callbacks for digital signal processing
// ...
anzSamples = callEffects(sampleBuffer, currentWritePosition, anzSamples);
// and recalc from the float array...
length = readFromFloatArrayBuffer(anzSamples);
}
currentWritePosition = (currentWritePosition + anzSamples) % sampleBufferSize;
return length;
}
} | [
"public",
"int",
"writeSampleData",
"(",
"final",
"byte",
"[",
"]",
"newSampleData",
",",
"final",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"System",
".",
"arraycopy",
"(",
"newSampleData",
",",
"offset",
",",... | This method will write the sample data to the dsp buffer
It will convert all sampledata to a stereo or mono float of 1.0<=x<=-1.0
@since 23.12.2011
@param newSampleData
@param offset
@param length | [
"This",
"method",
"will",
"write",
"the",
"sample",
"data",
"to",
"the",
"dsp",
"buffer",
"It",
"will",
"convert",
"all",
"sampledata",
"to",
"a",
"stereo",
"or",
"mono",
"float",
"of",
"1",
".",
"0<",
"=",
"x<",
"=",
"-",
"1",
".",
"0"
] | train | https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/mixer/dsp/AudioProcessor.java#L409-L426 |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java | CoherentManagerConnection.getVariable | public String getVariable(final Channel channel, final String variableName) {
"""
Retrieves and returns the value of a variable associated with a channel.
If the variable is empty or null then an empty string is returned.
@param channel
@param variableName
@return
"""
String value = "";
final GetVarAction var = new GetVarAction(channel, variableName);
try
{
PBX pbx = PBXFactory.getActivePBX();
if (!pbx.waitForChannelToQuiescent(channel, 3000))
throw new PBXException("Channel: " + channel + " cannot be retrieved as it is still in transition.");
ManagerResponse convertedResponse = sendAction(var, 500);
if (convertedResponse != null)
{
value = convertedResponse.getAttribute("value"); //$NON-NLS-1$
if (value == null)
value = "";
CoherentManagerConnection.logger.debug("getVarAction returned name:" + variableName + " value:" + value); //$NON-NLS-1$ //$NON-NLS-2$
}
}
catch (final Exception e)
{
CoherentManagerConnection.logger.debug(e, e);
CoherentManagerConnection.logger.error("getVariable: " + e); //$NON-NLS-1$
}
return value;
} | java | public String getVariable(final Channel channel, final String variableName)
{
String value = "";
final GetVarAction var = new GetVarAction(channel, variableName);
try
{
PBX pbx = PBXFactory.getActivePBX();
if (!pbx.waitForChannelToQuiescent(channel, 3000))
throw new PBXException("Channel: " + channel + " cannot be retrieved as it is still in transition.");
ManagerResponse convertedResponse = sendAction(var, 500);
if (convertedResponse != null)
{
value = convertedResponse.getAttribute("value"); //$NON-NLS-1$
if (value == null)
value = "";
CoherentManagerConnection.logger.debug("getVarAction returned name:" + variableName + " value:" + value); //$NON-NLS-1$ //$NON-NLS-2$
}
}
catch (final Exception e)
{
CoherentManagerConnection.logger.debug(e, e);
CoherentManagerConnection.logger.error("getVariable: " + e); //$NON-NLS-1$
}
return value;
} | [
"public",
"String",
"getVariable",
"(",
"final",
"Channel",
"channel",
",",
"final",
"String",
"variableName",
")",
"{",
"String",
"value",
"=",
"\"\"",
";",
"final",
"GetVarAction",
"var",
"=",
"new",
"GetVarAction",
"(",
"channel",
",",
"variableName",
")",
... | Retrieves and returns the value of a variable associated with a channel.
If the variable is empty or null then an empty string is returned.
@param channel
@param variableName
@return | [
"Retrieves",
"and",
"returns",
"the",
"value",
"of",
"a",
"variable",
"associated",
"with",
"a",
"channel",
".",
"If",
"the",
"variable",
"is",
"empty",
"or",
"null",
"then",
"an",
"empty",
"string",
"is",
"returned",
"."
] | train | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java#L228-L254 |
Netflix/Hystrix | hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/MethodExecutionAction.java | MethodExecutionAction.executeWithArgs | @Override
public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException {
"""
Invokes the method. Also private method also can be invoked.
@return result of execution
"""
if(ExecutionType.ASYNCHRONOUS == executionType){
Closure closure = AsyncClosureFactory.getInstance().createClosure(metaHolder, method, object, args);
return executeClj(closure.getClosureObj(), closure.getClosureMethod());
}
return execute(object, method, args);
} | java | @Override
public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException {
if(ExecutionType.ASYNCHRONOUS == executionType){
Closure closure = AsyncClosureFactory.getInstance().createClosure(metaHolder, method, object, args);
return executeClj(closure.getClosureObj(), closure.getClosureMethod());
}
return execute(object, method, args);
} | [
"@",
"Override",
"public",
"Object",
"executeWithArgs",
"(",
"ExecutionType",
"executionType",
",",
"Object",
"[",
"]",
"args",
")",
"throws",
"CommandActionExecutionException",
"{",
"if",
"(",
"ExecutionType",
".",
"ASYNCHRONOUS",
"==",
"executionType",
")",
"{",
... | Invokes the method. Also private method also can be invoked.
@return result of execution | [
"Invokes",
"the",
"method",
".",
"Also",
"private",
"method",
"also",
"can",
"be",
"invoked",
"."
] | train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/MethodExecutionAction.java#L86-L94 |
google/closure-templates | java/src/com/google/template/soy/passes/PluginResolver.java | PluginResolver.nullResolver | public static PluginResolver nullResolver(Mode mode, ErrorReporter reporter) {
"""
Returns an empty resolver. Useful for tests, or situations where it is known that no plugins
will be needed.
"""
return new PluginResolver(
mode, ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), reporter);
} | java | public static PluginResolver nullResolver(Mode mode, ErrorReporter reporter) {
return new PluginResolver(
mode, ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), reporter);
} | [
"public",
"static",
"PluginResolver",
"nullResolver",
"(",
"Mode",
"mode",
",",
"ErrorReporter",
"reporter",
")",
"{",
"return",
"new",
"PluginResolver",
"(",
"mode",
",",
"ImmutableMap",
".",
"of",
"(",
")",
",",
"ImmutableMap",
".",
"of",
"(",
")",
",",
... | Returns an empty resolver. Useful for tests, or situations where it is known that no plugins
will be needed. | [
"Returns",
"an",
"empty",
"resolver",
".",
"Useful",
"for",
"tests",
"or",
"situations",
"where",
"it",
"is",
"known",
"that",
"no",
"plugins",
"will",
"be",
"needed",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/passes/PluginResolver.java#L48-L51 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/classfile/Modifiers.java | Modifiers.setPublic | public static int setPublic(int modifier, boolean b) {
"""
When set public, the modifier is cleared from being private or
protected.
"""
if (b) {
return (modifier | PUBLIC) & (~PROTECTED & ~PRIVATE);
}
else {
return modifier & ~PUBLIC;
}
} | java | public static int setPublic(int modifier, boolean b) {
if (b) {
return (modifier | PUBLIC) & (~PROTECTED & ~PRIVATE);
}
else {
return modifier & ~PUBLIC;
}
} | [
"public",
"static",
"int",
"setPublic",
"(",
"int",
"modifier",
",",
"boolean",
"b",
")",
"{",
"if",
"(",
"b",
")",
"{",
"return",
"(",
"modifier",
"|",
"PUBLIC",
")",
"&",
"(",
"~",
"PROTECTED",
"&",
"~",
"PRIVATE",
")",
";",
"}",
"else",
"{",
"... | When set public, the modifier is cleared from being private or
protected. | [
"When",
"set",
"public",
"the",
"modifier",
"is",
"cleared",
"from",
"being",
"private",
"or",
"protected",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/Modifiers.java#L34-L41 |
cycorp/api-suite | core-api/src/main/java/com/cyc/kb/exception/InvalidFormulaInContextException.java | InvalidFormulaInContextException.fromThrowable | public static InvalidFormulaInContextException fromThrowable(String message, Throwable cause) {
"""
Converts a Throwable to a InvalidFormulaInContextException with the specified detail message. If the
Throwable is a InvalidFormulaInContextException and if the Throwable's message is identical to the
one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in
a new InvalidFormulaInContextException with the detail message.
@param cause the Throwable to convert
@param message the specified detail message
@return a InvalidFormulaInContextException
"""
return (cause instanceof InvalidFormulaInContextException && Objects.equals(message, cause.getMessage()))
? (InvalidFormulaInContextException) cause
: new InvalidFormulaInContextException(message, cause);
} | java | public static InvalidFormulaInContextException fromThrowable(String message, Throwable cause) {
return (cause instanceof InvalidFormulaInContextException && Objects.equals(message, cause.getMessage()))
? (InvalidFormulaInContextException) cause
: new InvalidFormulaInContextException(message, cause);
} | [
"public",
"static",
"InvalidFormulaInContextException",
"fromThrowable",
"(",
"String",
"message",
",",
"Throwable",
"cause",
")",
"{",
"return",
"(",
"cause",
"instanceof",
"InvalidFormulaInContextException",
"&&",
"Objects",
".",
"equals",
"(",
"message",
",",
"caus... | Converts a Throwable to a InvalidFormulaInContextException with the specified detail message. If the
Throwable is a InvalidFormulaInContextException and if the Throwable's message is identical to the
one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in
a new InvalidFormulaInContextException with the detail message.
@param cause the Throwable to convert
@param message the specified detail message
@return a InvalidFormulaInContextException | [
"Converts",
"a",
"Throwable",
"to",
"a",
"InvalidFormulaInContextException",
"with",
"the",
"specified",
"detail",
"message",
".",
"If",
"the",
"Throwable",
"is",
"a",
"InvalidFormulaInContextException",
"and",
"if",
"the",
"Throwable",
"s",
"message",
"is",
"identi... | train | https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/kb/exception/InvalidFormulaInContextException.java#L63-L67 |
wcm-io-caravan/caravan-commons | performance/src/main/java/io/wcm/caravan/common/performance/PerformanceMetrics.java | PerformanceMetrics.createNext | public PerformanceMetrics createNext(String nextAction, String nextDescriptor, Class nextActionClass) {
"""
Creates new instance of performance metrics. Stores the key and correlation id of the parent metrics instance.
Assigns next level.
@param nextAction a short name of measured operation, typically a first prefix of descriptor
@param nextActionClass a class which implements the action
@param nextDescriptor a full description of measured operation
@return PerformanceMetrics a new instance of performance metrics with stored key and correlationId from the parent
metrics and assigned next level
"""
PerformanceMetrics next = new PerformanceMetrics(key, level + 1, nextAction, nextActionClass, nextDescriptor, correlationId);
next.previous = this;
return next;
} | java | public PerformanceMetrics createNext(String nextAction, String nextDescriptor, Class nextActionClass) {
PerformanceMetrics next = new PerformanceMetrics(key, level + 1, nextAction, nextActionClass, nextDescriptor, correlationId);
next.previous = this;
return next;
} | [
"public",
"PerformanceMetrics",
"createNext",
"(",
"String",
"nextAction",
",",
"String",
"nextDescriptor",
",",
"Class",
"nextActionClass",
")",
"{",
"PerformanceMetrics",
"next",
"=",
"new",
"PerformanceMetrics",
"(",
"key",
",",
"level",
"+",
"1",
",",
"nextAct... | Creates new instance of performance metrics. Stores the key and correlation id of the parent metrics instance.
Assigns next level.
@param nextAction a short name of measured operation, typically a first prefix of descriptor
@param nextActionClass a class which implements the action
@param nextDescriptor a full description of measured operation
@return PerformanceMetrics a new instance of performance metrics with stored key and correlationId from the parent
metrics and assigned next level | [
"Creates",
"new",
"instance",
"of",
"performance",
"metrics",
".",
"Stores",
"the",
"key",
"and",
"correlation",
"id",
"of",
"the",
"parent",
"metrics",
"instance",
".",
"Assigns",
"next",
"level",
"."
] | train | https://github.com/wcm-io-caravan/caravan-commons/blob/12e605bdfeb5a1ce7404e30d9f32274552cb8ce8/performance/src/main/java/io/wcm/caravan/common/performance/PerformanceMetrics.java#L96-L100 |
fabric8io/docker-maven-plugin | src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java | LogRequestor.readFully | private void readFully(InputStream in, byte[] bytes) throws IOException {
"""
This is a copy of ByteStreams.readFully(), with the slight change that it throws
NoBytesReadException if zero bytes are read. Otherwise it is identical.
@param in
@param bytes
@throws IOException
"""
int read = ByteStreams.read(in, bytes, 0, bytes.length);
if (read == 0) {
throw new NoBytesReadException();
} else if (read != bytes.length) {
throw new EOFException("reached end of stream after reading "
+ read + " bytes; " + bytes.length + " bytes expected");
}
} | java | private void readFully(InputStream in, byte[] bytes) throws IOException {
int read = ByteStreams.read(in, bytes, 0, bytes.length);
if (read == 0) {
throw new NoBytesReadException();
} else if (read != bytes.length) {
throw new EOFException("reached end of stream after reading "
+ read + " bytes; " + bytes.length + " bytes expected");
}
} | [
"private",
"void",
"readFully",
"(",
"InputStream",
"in",
",",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"IOException",
"{",
"int",
"read",
"=",
"ByteStreams",
".",
"read",
"(",
"in",
",",
"bytes",
",",
"0",
",",
"bytes",
".",
"length",
")",
";",
"if... | This is a copy of ByteStreams.readFully(), with the slight change that it throws
NoBytesReadException if zero bytes are read. Otherwise it is identical.
@param in
@param bytes
@throws IOException | [
"This",
"is",
"a",
"copy",
"of",
"ByteStreams",
".",
"readFully",
"()",
"with",
"the",
"slight",
"change",
"that",
"it",
"throws",
"NoBytesReadException",
"if",
"zero",
"bytes",
"are",
"read",
".",
"Otherwise",
"it",
"is",
"identical",
"."
] | train | https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java#L126-L134 |
validator/validator | src/nu/validator/gnu/xml/aelfred2/XmlParser.java | XmlParser.fatal | private void fatal(String message, String textFound, String textExpected)
throws SAXException {
"""
Report an error.
@param message
The error message.
@param textFound
The text that caused the error (or null).
@see SAXDriver#error
@see #line
"""
// smart quotes -- 2005-08-20 hsivonen
if (textFound != null) {
message = message + " (found \u201C" + textFound + "\u201D)";
}
if (textExpected != null) {
message = message + " (expected \u201C" + textExpected + "\u201D)";
}
handler.fatal(message);
// "can't happen"
throw new FatalSAXException(message);
} | java | private void fatal(String message, String textFound, String textExpected)
throws SAXException {
// smart quotes -- 2005-08-20 hsivonen
if (textFound != null) {
message = message + " (found \u201C" + textFound + "\u201D)";
}
if (textExpected != null) {
message = message + " (expected \u201C" + textExpected + "\u201D)";
}
handler.fatal(message);
// "can't happen"
throw new FatalSAXException(message);
} | [
"private",
"void",
"fatal",
"(",
"String",
"message",
",",
"String",
"textFound",
",",
"String",
"textExpected",
")",
"throws",
"SAXException",
"{",
"// smart quotes -- 2005-08-20 hsivonen",
"if",
"(",
"textFound",
"!=",
"null",
")",
"{",
"message",
"=",
"message"... | Report an error.
@param message
The error message.
@param textFound
The text that caused the error (or null).
@see SAXDriver#error
@see #line | [
"Report",
"an",
"error",
"."
] | train | https://github.com/validator/validator/blob/c7b7f85b3a364df7d9944753fb5b2cd0ce642889/src/nu/validator/gnu/xml/aelfred2/XmlParser.java#L555-L568 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/VirtualWANsInner.java | VirtualWANsInner.beginCreateOrUpdate | public VirtualWANInner beginCreateOrUpdate(String resourceGroupName, String virtualWANName, VirtualWANInner wANParameters) {
"""
Creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN.
@param resourceGroupName The resource group name of the VirtualWan.
@param virtualWANName The name of the VirtualWAN being created or updated.
@param wANParameters Parameters supplied to create or update VirtualWAN.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VirtualWANInner object if successful.
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualWANName, wANParameters).toBlocking().single().body();
} | java | public VirtualWANInner beginCreateOrUpdate(String resourceGroupName, String virtualWANName, VirtualWANInner wANParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualWANName, wANParameters).toBlocking().single().body();
} | [
"public",
"VirtualWANInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualWANName",
",",
"VirtualWANInner",
"wANParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"virtualWANName",
... | Creates a VirtualWAN resource if it doesn't exist else updates the existing VirtualWAN.
@param resourceGroupName The resource group name of the VirtualWan.
@param virtualWANName The name of the VirtualWAN being created or updated.
@param wANParameters Parameters supplied to create or update VirtualWAN.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VirtualWANInner object if successful. | [
"Creates",
"a",
"VirtualWAN",
"resource",
"if",
"it",
"doesn",
"t",
"exist",
"else",
"updates",
"the",
"existing",
"VirtualWAN",
"."
] | 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/VirtualWANsInner.java#L286-L288 |
w3c/epubcheck | src/main/java/com/adobe/epubcheck/util/DateParser.java | DateParser.checkValueAndNext | private boolean checkValueAndNext(StringTokenizer st, String token) throws
InvalidDateException {
"""
Check if the next token, if exists, has a given value and that the
provided string tokenizer has more tokens after that. It consumes
the token checked against the expected value from the string tokenizer.
@param st The StringTokenizer to check.
@param token The value expected for the next token.
@return <code>true</code> if the token matches the value and there are more tokens.
<code>false</code> if there are no more tokens and we do not have a token to check.
@throws InvalidDateException If the token does not match the value or if there are no
more tokens after the token that matches the expected value.
"""
if (!st.hasMoreTokens())
{
return false;
}
String t = st.nextToken();
if (!t.equals(token))
{
throw new InvalidDateException("Unexpected: " + t);
}
if (!st.hasMoreTokens())
{
throw new InvalidDateException("Incomplete date.");
}
return true;
} | java | private boolean checkValueAndNext(StringTokenizer st, String token) throws
InvalidDateException
{
if (!st.hasMoreTokens())
{
return false;
}
String t = st.nextToken();
if (!t.equals(token))
{
throw new InvalidDateException("Unexpected: " + t);
}
if (!st.hasMoreTokens())
{
throw new InvalidDateException("Incomplete date.");
}
return true;
} | [
"private",
"boolean",
"checkValueAndNext",
"(",
"StringTokenizer",
"st",
",",
"String",
"token",
")",
"throws",
"InvalidDateException",
"{",
"if",
"(",
"!",
"st",
".",
"hasMoreTokens",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"String",
"t",
"=",
"s... | Check if the next token, if exists, has a given value and that the
provided string tokenizer has more tokens after that. It consumes
the token checked against the expected value from the string tokenizer.
@param st The StringTokenizer to check.
@param token The value expected for the next token.
@return <code>true</code> if the token matches the value and there are more tokens.
<code>false</code> if there are no more tokens and we do not have a token to check.
@throws InvalidDateException If the token does not match the value or if there are no
more tokens after the token that matches the expected value. | [
"Check",
"if",
"the",
"next",
"token",
"if",
"exists",
"has",
"a",
"given",
"value",
"and",
"that",
"the",
"provided",
"string",
"tokenizer",
"has",
"more",
"tokens",
"after",
"that",
".",
"It",
"consumes",
"the",
"token",
"checked",
"against",
"the",
"exp... | train | https://github.com/w3c/epubcheck/blob/4d5a24d9f2878a2a5497eb11c036cc18fe2c0a78/src/main/java/com/adobe/epubcheck/util/DateParser.java#L106-L123 |
nebula-plugins/gradle-metrics-plugin | src/main/java/nebula/plugin/metrics/dispatcher/AbstractMetricsDispatcher.java | AbstractMetricsDispatcher.registerEnumModule | @SuppressWarnings("rawtypes")
private static void registerEnumModule(ObjectMapper mapper) {
"""
Register Jackson module that maps enums as lowercase. Per http://stackoverflow.com/a/24173645.
"""
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
@Override
public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
final JavaType type,
BeanDescription beanDesc,
final JsonDeserializer<?> deserializer) {
return new JsonDeserializer<Enum>() {
@Override
public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
@SuppressWarnings("unchecked") Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
}
};
}
});
module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
@Override
public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(value.name().toLowerCase());
}
});
mapper.registerModule(module);
} | java | @SuppressWarnings("rawtypes")
private static void registerEnumModule(ObjectMapper mapper) {
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
@Override
public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
final JavaType type,
BeanDescription beanDesc,
final JsonDeserializer<?> deserializer) {
return new JsonDeserializer<Enum>() {
@Override
public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
@SuppressWarnings("unchecked") Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
}
};
}
});
module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
@Override
public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(value.name().toLowerCase());
}
});
mapper.registerModule(module);
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"private",
"static",
"void",
"registerEnumModule",
"(",
"ObjectMapper",
"mapper",
")",
"{",
"SimpleModule",
"module",
"=",
"new",
"SimpleModule",
"(",
")",
";",
"module",
".",
"setDeserializerModifier",
"(",
"new"... | Register Jackson module that maps enums as lowercase. Per http://stackoverflow.com/a/24173645. | [
"Register",
"Jackson",
"module",
"that",
"maps",
"enums",
"as",
"lowercase",
".",
"Per",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"24173645",
"."
] | train | https://github.com/nebula-plugins/gradle-metrics-plugin/blob/f074e7c2b9a5f5f3ca06bf9fade486e47e80f4a3/src/main/java/nebula/plugin/metrics/dispatcher/AbstractMetricsDispatcher.java#L76-L101 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java | KeyVaultCredentials.buildAuthenticatedRequest | private Pair<Request, HttpMessageSecurity> buildAuthenticatedRequest(Request originalRequest, Response response)
throws IOException {
"""
Builds request with authenticated header. Protects request body if supported.
@param originalRequest
unprotected request without auth token.
@param response
response with unauthorized return code.
@return Pair of protected request and HttpMessageSecurity used for
encryption.
"""
String authenticateHeader = response.header(WWW_AUTHENTICATE);
Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
challengeMap.put("x-ms-message-encryption-key", response.header("x-ms-message-encryption-key"));
challengeMap.put("x-ms-message-signing-key", response.header("x-ms-message-signing-key"));
// Cache the challenge
cache.addCachedChallenge(originalRequest.url(), challengeMap);
return buildAuthenticatedRequest(originalRequest, challengeMap);
} | java | private Pair<Request, HttpMessageSecurity> buildAuthenticatedRequest(Request originalRequest, Response response)
throws IOException {
String authenticateHeader = response.header(WWW_AUTHENTICATE);
Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
challengeMap.put("x-ms-message-encryption-key", response.header("x-ms-message-encryption-key"));
challengeMap.put("x-ms-message-signing-key", response.header("x-ms-message-signing-key"));
// Cache the challenge
cache.addCachedChallenge(originalRequest.url(), challengeMap);
return buildAuthenticatedRequest(originalRequest, challengeMap);
} | [
"private",
"Pair",
"<",
"Request",
",",
"HttpMessageSecurity",
">",
"buildAuthenticatedRequest",
"(",
"Request",
"originalRequest",
",",
"Response",
"response",
")",
"throws",
"IOException",
"{",
"String",
"authenticateHeader",
"=",
"response",
".",
"header",
"(",
"... | Builds request with authenticated header. Protects request body if supported.
@param originalRequest
unprotected request without auth token.
@param response
response with unauthorized return code.
@return Pair of protected request and HttpMessageSecurity used for
encryption. | [
"Builds",
"request",
"with",
"authenticated",
"header",
".",
"Protects",
"request",
"body",
"if",
"supported",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java#L146-L159 |
chrisjenx/Calligraphy | calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyContextWrapper.java | CalligraphyContextWrapper.onActivityCreateView | public static View onActivityCreateView(Activity activity, View parent, View view, String name, Context context, AttributeSet attr) {
"""
You only need to call this <b>IF</b> you call
{@link uk.co.chrisjenx.calligraphy.CalligraphyConfig.Builder#disablePrivateFactoryInjection()}
This will need to be called from the
{@link android.app.Activity#onCreateView(android.view.View, String, android.content.Context, android.util.AttributeSet)}
method to enable view font injection if the view is created inside the activity onCreateView.
You would implement this method like so in you base activity.
<pre>
{@code
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
return CalligraphyContextWrapper.onActivityCreateView(this, parent, super.onCreateView(parent, name, context, attrs), name, context, attrs);
}
}
</pre>
@param activity The activity the original that the ContextWrapper was attached too.
@param parent Parent view from onCreateView
@param view The View Created inside onCreateView or from super.onCreateView
@param name The View name from onCreateView
@param context The context from onCreateView
@param attr The AttributeSet from onCreateView
@return The same view passed in, or null if null passed in.
"""
return get(activity).onActivityCreateView(parent, view, name, context, attr);
} | java | public static View onActivityCreateView(Activity activity, View parent, View view, String name, Context context, AttributeSet attr) {
return get(activity).onActivityCreateView(parent, view, name, context, attr);
} | [
"public",
"static",
"View",
"onActivityCreateView",
"(",
"Activity",
"activity",
",",
"View",
"parent",
",",
"View",
"view",
",",
"String",
"name",
",",
"Context",
"context",
",",
"AttributeSet",
"attr",
")",
"{",
"return",
"get",
"(",
"activity",
")",
".",
... | You only need to call this <b>IF</b> you call
{@link uk.co.chrisjenx.calligraphy.CalligraphyConfig.Builder#disablePrivateFactoryInjection()}
This will need to be called from the
{@link android.app.Activity#onCreateView(android.view.View, String, android.content.Context, android.util.AttributeSet)}
method to enable view font injection if the view is created inside the activity onCreateView.
You would implement this method like so in you base activity.
<pre>
{@code
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
return CalligraphyContextWrapper.onActivityCreateView(this, parent, super.onCreateView(parent, name, context, attrs), name, context, attrs);
}
}
</pre>
@param activity The activity the original that the ContextWrapper was attached too.
@param parent Parent view from onCreateView
@param view The View Created inside onCreateView or from super.onCreateView
@param name The View name from onCreateView
@param context The context from onCreateView
@param attr The AttributeSet from onCreateView
@return The same view passed in, or null if null passed in. | [
"You",
"only",
"need",
"to",
"call",
"this",
"<b",
">",
"IF<",
"/",
"b",
">",
"you",
"call",
"{",
"@link",
"uk",
".",
"co",
".",
"chrisjenx",
".",
"calligraphy",
".",
"CalligraphyConfig",
".",
"Builder#disablePrivateFactoryInjection",
"()",
"}",
"This",
"w... | train | https://github.com/chrisjenx/Calligraphy/blob/085e441954d787bd4ef31f245afe5f2f2a311ea5/calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyContextWrapper.java#L58-L60 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/RDN.java | AVAComparator.compare | @Override
public int compare(AVA a1, AVA a2) {
"""
AVA's containing a standard keyword are ordered alphabetically,
followed by AVA's containing an OID keyword, ordered numerically
"""
boolean a1Has2253 = a1.hasRFC2253Keyword();
boolean a2Has2253 = a2.hasRFC2253Keyword();
if (a1Has2253) {
if (a2Has2253) {
return a1.toRFC2253CanonicalString().compareTo
(a2.toRFC2253CanonicalString());
} else {
return -1;
}
} else {
if (a2Has2253) {
return 1;
} else {
int[] a1Oid = a1.getObjectIdentifier().toIntArray();
int[] a2Oid = a2.getObjectIdentifier().toIntArray();
int pos = 0;
int len = (a1Oid.length > a2Oid.length) ? a2Oid.length :
a1Oid.length;
while (pos < len && a1Oid[pos] == a2Oid[pos]) {
++pos;
}
return (pos == len) ? a1Oid.length - a2Oid.length :
a1Oid[pos] - a2Oid[pos];
}
}
} | java | @Override
public int compare(AVA a1, AVA a2) {
boolean a1Has2253 = a1.hasRFC2253Keyword();
boolean a2Has2253 = a2.hasRFC2253Keyword();
if (a1Has2253) {
if (a2Has2253) {
return a1.toRFC2253CanonicalString().compareTo
(a2.toRFC2253CanonicalString());
} else {
return -1;
}
} else {
if (a2Has2253) {
return 1;
} else {
int[] a1Oid = a1.getObjectIdentifier().toIntArray();
int[] a2Oid = a2.getObjectIdentifier().toIntArray();
int pos = 0;
int len = (a1Oid.length > a2Oid.length) ? a2Oid.length :
a1Oid.length;
while (pos < len && a1Oid[pos] == a2Oid[pos]) {
++pos;
}
return (pos == len) ? a1Oid.length - a2Oid.length :
a1Oid[pos] - a2Oid[pos];
}
}
} | [
"@",
"Override",
"public",
"int",
"compare",
"(",
"AVA",
"a1",
",",
"AVA",
"a2",
")",
"{",
"boolean",
"a1Has2253",
"=",
"a1",
".",
"hasRFC2253Keyword",
"(",
")",
";",
"boolean",
"a2Has2253",
"=",
"a2",
".",
"hasRFC2253Keyword",
"(",
")",
";",
"if",
"("... | AVA's containing a standard keyword are ordered alphabetically,
followed by AVA's containing an OID keyword, ordered numerically | [
"AVA",
"s",
"containing",
"a",
"standard",
"keyword",
"are",
"ordered",
"alphabetically",
"followed",
"by",
"AVA",
"s",
"containing",
"an",
"OID",
"keyword",
"ordered",
"numerically"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/RDN.java#L491-L519 |
google/j2objc | jre_emul/android/frameworks/base/core/java/android/text/TextUtils.java | TextUtils.substring | public static String substring(CharSequence source, int start, int end) {
"""
Create a new String object containing the given range of characters
from the source string. This is different than simply calling
{@link CharSequence#subSequence(int, int) CharSequence.subSequence}
in that it does not preserve any style runs in the source sequence,
allowing a more efficient implementation.
"""
if (source instanceof String)
return ((String) source).substring(start, end);
if (source instanceof StringBuilder)
return ((StringBuilder) source).substring(start, end);
if (source instanceof StringBuffer)
return ((StringBuffer) source).substring(start, end);
char[] temp = obtain(end - start);
getChars(source, start, end, temp, 0);
String ret = new String(temp, 0, end - start);
recycle(temp);
return ret;
} | java | public static String substring(CharSequence source, int start, int end) {
if (source instanceof String)
return ((String) source).substring(start, end);
if (source instanceof StringBuilder)
return ((StringBuilder) source).substring(start, end);
if (source instanceof StringBuffer)
return ((StringBuffer) source).substring(start, end);
char[] temp = obtain(end - start);
getChars(source, start, end, temp, 0);
String ret = new String(temp, 0, end - start);
recycle(temp);
return ret;
} | [
"public",
"static",
"String",
"substring",
"(",
"CharSequence",
"source",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"source",
"instanceof",
"String",
")",
"return",
"(",
"(",
"String",
")",
"source",
")",
".",
"substring",
"(",
"start"... | Create a new String object containing the given range of characters
from the source string. This is different than simply calling
{@link CharSequence#subSequence(int, int) CharSequence.subSequence}
in that it does not preserve any style runs in the source sequence,
allowing a more efficient implementation. | [
"Create",
"a",
"new",
"String",
"object",
"containing",
"the",
"given",
"range",
"of",
"characters",
"from",
"the",
"source",
"string",
".",
"This",
"is",
"different",
"than",
"simply",
"calling",
"{"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/frameworks/base/core/java/android/text/TextUtils.java#L224-L238 |
xcesco/kripton | kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractDataSource.java | AbstractDataSource.onUpgrade | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
"""
On upgrade.
@param db
the db
@param oldVersion
the old version
@param newVersion
the new version
"""
if (AbstractDataSource.this.options.databaseLifecycleHandler != null) {
AbstractDataSource.this.options.databaseLifecycleHandler.onUpdate(db, oldVersion, newVersion, true);
versionChanged = true;
}
} | java | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (AbstractDataSource.this.options.databaseLifecycleHandler != null) {
AbstractDataSource.this.options.databaseLifecycleHandler.onUpdate(db, oldVersion, newVersion, true);
versionChanged = true;
}
} | [
"public",
"void",
"onUpgrade",
"(",
"SQLiteDatabase",
"db",
",",
"int",
"oldVersion",
",",
"int",
"newVersion",
")",
"{",
"if",
"(",
"AbstractDataSource",
".",
"this",
".",
"options",
".",
"databaseLifecycleHandler",
"!=",
"null",
")",
"{",
"AbstractDataSource",... | On upgrade.
@param db
the db
@param oldVersion
the old version
@param newVersion
the new version | [
"On",
"upgrade",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractDataSource.java#L554-L559 |
lecho/hellocharts-android | hellocharts-library/src/lecho/lib/hellocharts/model/Viewport.java | Viewport.writeToParcel | public void writeToParcel(Parcel out, int flags) {
"""
Write this viewport to the specified parcel. To restore a viewport from a parcel, use readFromParcel()
@param out The parcel to write the viewport's coordinates into
"""
out.writeFloat(left);
out.writeFloat(top);
out.writeFloat(right);
out.writeFloat(bottom);
} | java | public void writeToParcel(Parcel out, int flags) {
out.writeFloat(left);
out.writeFloat(top);
out.writeFloat(right);
out.writeFloat(bottom);
} | [
"public",
"void",
"writeToParcel",
"(",
"Parcel",
"out",
",",
"int",
"flags",
")",
"{",
"out",
".",
"writeFloat",
"(",
"left",
")",
";",
"out",
".",
"writeFloat",
"(",
"top",
")",
";",
"out",
".",
"writeFloat",
"(",
"right",
")",
";",
"out",
".",
"... | Write this viewport to the specified parcel. To restore a viewport from a parcel, use readFromParcel()
@param out The parcel to write the viewport's coordinates into | [
"Write",
"this",
"viewport",
"to",
"the",
"specified",
"parcel",
".",
"To",
"restore",
"a",
"viewport",
"from",
"a",
"parcel",
"use",
"readFromParcel",
"()"
] | train | https://github.com/lecho/hellocharts-android/blob/c41419c9afa097452dee823c7eba0e5136aa96bd/hellocharts-library/src/lecho/lib/hellocharts/model/Viewport.java#L370-L375 |
apache/incubator-druid | extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/FixedBucketsHistogram.java | FixedBucketsHistogram.fromByteBuffer | public static FixedBucketsHistogram fromByteBuffer(ByteBuffer buf) {
"""
Deserialization helper method
@param buf Source buffer containing serialized histogram
@return Deserialized object
"""
byte serializationVersion = buf.get();
Preconditions.checkArgument(
serializationVersion == SERIALIZATION_VERSION,
StringUtils.format("Only serialization version %s is supported.", SERIALIZATION_VERSION)
);
byte mode = buf.get();
if (mode == FULL_ENCODING_MODE) {
return fromByteBufferFullNoSerdeHeader(buf);
} else if (mode == SPARSE_ENCODING_MODE) {
return fromBytesSparse(buf);
} else {
throw new ISE("Invalid histogram serde mode: %s", mode);
}
} | java | public static FixedBucketsHistogram fromByteBuffer(ByteBuffer buf)
{
byte serializationVersion = buf.get();
Preconditions.checkArgument(
serializationVersion == SERIALIZATION_VERSION,
StringUtils.format("Only serialization version %s is supported.", SERIALIZATION_VERSION)
);
byte mode = buf.get();
if (mode == FULL_ENCODING_MODE) {
return fromByteBufferFullNoSerdeHeader(buf);
} else if (mode == SPARSE_ENCODING_MODE) {
return fromBytesSparse(buf);
} else {
throw new ISE("Invalid histogram serde mode: %s", mode);
}
} | [
"public",
"static",
"FixedBucketsHistogram",
"fromByteBuffer",
"(",
"ByteBuffer",
"buf",
")",
"{",
"byte",
"serializationVersion",
"=",
"buf",
".",
"get",
"(",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"serializationVersion",
"==",
"SERIALIZATION_VERSION",... | Deserialization helper method
@param buf Source buffer containing serialized histogram
@return Deserialized object | [
"Deserialization",
"helper",
"method"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/FixedBucketsHistogram.java#L926-L941 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java | GeoPackageOverlayFactory.getCompositeOverlay | public static CompositeOverlay getCompositeOverlay(Collection<TileDao> tileDaos, BoundedOverlay overlay) {
"""
Create a composite overlay by first adding tile overlays for the tile DAOs followed by the provided overlay
@param tileDaos collection of tile daos
@param overlay bounded overlay
@return composite overlay
"""
CompositeOverlay compositeOverlay = getCompositeOverlay(tileDaos);
compositeOverlay.addOverlay(overlay);
return compositeOverlay;
} | java | public static CompositeOverlay getCompositeOverlay(Collection<TileDao> tileDaos, BoundedOverlay overlay) {
CompositeOverlay compositeOverlay = getCompositeOverlay(tileDaos);
compositeOverlay.addOverlay(overlay);
return compositeOverlay;
} | [
"public",
"static",
"CompositeOverlay",
"getCompositeOverlay",
"(",
"Collection",
"<",
"TileDao",
">",
"tileDaos",
",",
"BoundedOverlay",
"overlay",
")",
"{",
"CompositeOverlay",
"compositeOverlay",
"=",
"getCompositeOverlay",
"(",
"tileDaos",
")",
";",
"compositeOverla... | Create a composite overlay by first adding tile overlays for the tile DAOs followed by the provided overlay
@param tileDaos collection of tile daos
@param overlay bounded overlay
@return composite overlay | [
"Create",
"a",
"composite",
"overlay",
"by",
"first",
"adding",
"tile",
"overlays",
"for",
"the",
"tile",
"DAOs",
"followed",
"by",
"the",
"provided",
"overlay"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/GeoPackageOverlayFactory.java#L131-L138 |
Nordstrom/JUnit-Foundation | src/main/java/com/nordstrom/automation/junit/RetryHandler.java | RetryHandler.doRetry | static boolean doRetry(FrameworkMethod method, Throwable thrown, AtomicInteger retryCounter) {
"""
Determine if the indicated failure should be retried.
@param method failed test method
@param thrown exception for this failed test
@param retryCounter retry counter (remaining attempts)
@return {@code true} if failed test should be retried; otherwise {@code false}
"""
boolean doRetry = false;
if ((retryCounter.decrementAndGet() > -1) && isRetriable(method, thrown)) {
LOGGER.warn("### RETRY ### {}", method);
doRetry = true;
}
return doRetry;
} | java | static boolean doRetry(FrameworkMethod method, Throwable thrown, AtomicInteger retryCounter) {
boolean doRetry = false;
if ((retryCounter.decrementAndGet() > -1) && isRetriable(method, thrown)) {
LOGGER.warn("### RETRY ### {}", method);
doRetry = true;
}
return doRetry;
} | [
"static",
"boolean",
"doRetry",
"(",
"FrameworkMethod",
"method",
",",
"Throwable",
"thrown",
",",
"AtomicInteger",
"retryCounter",
")",
"{",
"boolean",
"doRetry",
"=",
"false",
";",
"if",
"(",
"(",
"retryCounter",
".",
"decrementAndGet",
"(",
")",
">",
"-",
... | Determine if the indicated failure should be retried.
@param method failed test method
@param thrown exception for this failed test
@param retryCounter retry counter (remaining attempts)
@return {@code true} if failed test should be retried; otherwise {@code false} | [
"Determine",
"if",
"the",
"indicated",
"failure",
"should",
"be",
"retried",
"."
] | train | https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RetryHandler.java#L86-L93 |
kiegroup/drools | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java | DecisionTableImpl.hitToOutput | private Object hitToOutput(EvaluationContext ctx, FEEL feel, DTDecisionRule rule) {
"""
Each hit results in one output value (multiple outputs are collected into a single context value)
"""
List<CompiledExpression> outputEntries = rule.getOutputEntry();
Map<String, Object> values = ctx.getAllValues();
if ( outputEntries.size() == 1 ) {
Object value = feel.evaluate( outputEntries.get( 0 ), values );
return value;
} else {
Map<String, Object> output = new HashMap<>();
for (int i = 0; i < outputs.size(); i++) {
output.put(outputs.get(i).getName(), feel.evaluate(outputEntries.get(i), values));
}
return output;
}
} | java | private Object hitToOutput(EvaluationContext ctx, FEEL feel, DTDecisionRule rule) {
List<CompiledExpression> outputEntries = rule.getOutputEntry();
Map<String, Object> values = ctx.getAllValues();
if ( outputEntries.size() == 1 ) {
Object value = feel.evaluate( outputEntries.get( 0 ), values );
return value;
} else {
Map<String, Object> output = new HashMap<>();
for (int i = 0; i < outputs.size(); i++) {
output.put(outputs.get(i).getName(), feel.evaluate(outputEntries.get(i), values));
}
return output;
}
} | [
"private",
"Object",
"hitToOutput",
"(",
"EvaluationContext",
"ctx",
",",
"FEEL",
"feel",
",",
"DTDecisionRule",
"rule",
")",
"{",
"List",
"<",
"CompiledExpression",
">",
"outputEntries",
"=",
"rule",
".",
"getOutputEntry",
"(",
")",
";",
"Map",
"<",
"String",... | Each hit results in one output value (multiple outputs are collected into a single context value) | [
"Each",
"hit",
"results",
"in",
"one",
"output",
"value",
"(",
"multiple",
"outputs",
"are",
"collected",
"into",
"a",
"single",
"context",
"value",
")"
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java#L301-L314 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/WsTraceRouterImpl.java | WsTraceRouterImpl.routeTo | protected void routeTo(RoutedMessage routedTrace, String logHandlerId) {
"""
Route the traces to the LogHandler identified by the given logHandlerId.
@param msg The fully formatted trace.
@param logRecord The associated LogRecord, in case the LogHandler needs it.
@param logHandlerId The LogHandler ID in which to route.
"""
WsTraceHandler wsTraceHandler = wsTraceHandlerServices.get(logHandlerId);
if (wsTraceHandler != null) {
wsTraceHandler.publish(routedTrace);
}
} | java | protected void routeTo(RoutedMessage routedTrace, String logHandlerId) {
WsTraceHandler wsTraceHandler = wsTraceHandlerServices.get(logHandlerId);
if (wsTraceHandler != null) {
wsTraceHandler.publish(routedTrace);
}
} | [
"protected",
"void",
"routeTo",
"(",
"RoutedMessage",
"routedTrace",
",",
"String",
"logHandlerId",
")",
"{",
"WsTraceHandler",
"wsTraceHandler",
"=",
"wsTraceHandlerServices",
".",
"get",
"(",
"logHandlerId",
")",
";",
"if",
"(",
"wsTraceHandler",
"!=",
"null",
"... | Route the traces to the LogHandler identified by the given logHandlerId.
@param msg The fully formatted trace.
@param logRecord The associated LogRecord, in case the LogHandler needs it.
@param logHandlerId The LogHandler ID in which to route. | [
"Route",
"the",
"traces",
"to",
"the",
"LogHandler",
"identified",
"by",
"the",
"given",
"logHandlerId",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/WsTraceRouterImpl.java#L152-L157 |
baratine/baratine | framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java | XmlWriter.writeBlockElement | public void writeBlockElement(String name, Object text) {
"""
Convenience method, same as doing a startBlockElement(), writeText(text),
endBlockElement().
"""
startBlockElement(name);
writeText(text);
endBlockElement(name);
} | java | public void writeBlockElement(String name, Object text)
{
startBlockElement(name);
writeText(text);
endBlockElement(name);
} | [
"public",
"void",
"writeBlockElement",
"(",
"String",
"name",
",",
"Object",
"text",
")",
"{",
"startBlockElement",
"(",
"name",
")",
";",
"writeText",
"(",
"text",
")",
";",
"endBlockElement",
"(",
"name",
")",
";",
"}"
] | Convenience method, same as doing a startBlockElement(), writeText(text),
endBlockElement(). | [
"Convenience",
"method",
"same",
"as",
"doing",
"a",
"startBlockElement",
"()",
"writeText",
"(",
"text",
")",
"endBlockElement",
"()",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java#L279-L284 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/interceptor/Interceptors.java | Interceptors.doPostIntercept | public static void doPostIntercept( InterceptorContext context, List/*< Interceptor >*/ interceptors )
throws InterceptorException {
"""
Execute a "post" interceptor chain. This will execute the
{@link Interceptor#postInvoke(InterceptorContext, InterceptorChain)}
method to be invoked on each interceptor in a chain.
@param context the context for a set of interceptors
@param interceptors the list of interceptors
@throws InterceptorException
"""
if ( interceptors != null )
{
PostInvokeInterceptorChain chain = new PostInvokeInterceptorChain( context, interceptors );
chain.continueChain();
}
} | java | public static void doPostIntercept( InterceptorContext context, List/*< Interceptor >*/ interceptors )
throws InterceptorException
{
if ( interceptors != null )
{
PostInvokeInterceptorChain chain = new PostInvokeInterceptorChain( context, interceptors );
chain.continueChain();
}
} | [
"public",
"static",
"void",
"doPostIntercept",
"(",
"InterceptorContext",
"context",
",",
"List",
"/*< Interceptor >*/",
"interceptors",
")",
"throws",
"InterceptorException",
"{",
"if",
"(",
"interceptors",
"!=",
"null",
")",
"{",
"PostInvokeInterceptorChain",
"chain",... | Execute a "post" interceptor chain. This will execute the
{@link Interceptor#postInvoke(InterceptorContext, InterceptorChain)}
method to be invoked on each interceptor in a chain.
@param context the context for a set of interceptors
@param interceptors the list of interceptors
@throws InterceptorException | [
"Execute",
"a",
"post",
"interceptor",
"chain",
".",
"This",
"will",
"execute",
"the",
"{"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/interceptor/Interceptors.java#L58-L66 |
VoltDB/voltdb | src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java | JDBC4PreparedStatement.setObject | @Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
"""
Sets the value of the designated parameter with the given object.
"""
checkParameterBounds(parameterIndex);
switch(targetSqlType)
{
case Types.TINYINT:
setByte(parameterIndex, ((Byte)x).byteValue());
break;
case Types.SMALLINT:
setShort(parameterIndex, ((Short)x).shortValue());
break;
case Types.INTEGER:
setInt(parameterIndex, ((Integer)x).intValue());
break;
case Types.BIGINT:
setLong(parameterIndex, ((Long)x).longValue());
break;
case Types.DOUBLE:
setDouble(parameterIndex, ((Double)x).doubleValue());
break;
case Types.DECIMAL:
setBigDecimal(parameterIndex, (BigDecimal)x);
break;
case Types.TIMESTAMP:
setTimestamp(parameterIndex, (Timestamp)x);
break;
case Types.VARBINARY:
case Types.VARCHAR:
case Types.NVARCHAR:
setString(parameterIndex, (String)x);
break;
case Types.OTHER:
setObject(parameterIndex, x);
break;
default:
throw SQLError.get(SQLError.ILLEGAL_ARGUMENT);
}
} | java | @Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
{
checkParameterBounds(parameterIndex);
switch(targetSqlType)
{
case Types.TINYINT:
setByte(parameterIndex, ((Byte)x).byteValue());
break;
case Types.SMALLINT:
setShort(parameterIndex, ((Short)x).shortValue());
break;
case Types.INTEGER:
setInt(parameterIndex, ((Integer)x).intValue());
break;
case Types.BIGINT:
setLong(parameterIndex, ((Long)x).longValue());
break;
case Types.DOUBLE:
setDouble(parameterIndex, ((Double)x).doubleValue());
break;
case Types.DECIMAL:
setBigDecimal(parameterIndex, (BigDecimal)x);
break;
case Types.TIMESTAMP:
setTimestamp(parameterIndex, (Timestamp)x);
break;
case Types.VARBINARY:
case Types.VARCHAR:
case Types.NVARCHAR:
setString(parameterIndex, (String)x);
break;
case Types.OTHER:
setObject(parameterIndex, x);
break;
default:
throw SQLError.get(SQLError.ILLEGAL_ARGUMENT);
}
} | [
"@",
"Override",
"public",
"void",
"setObject",
"(",
"int",
"parameterIndex",
",",
"Object",
"x",
",",
"int",
"targetSqlType",
")",
"throws",
"SQLException",
"{",
"checkParameterBounds",
"(",
"parameterIndex",
")",
";",
"switch",
"(",
"targetSqlType",
")",
"{",
... | Sets the value of the designated parameter with the given object. | [
"Sets",
"the",
"value",
"of",
"the",
"designated",
"parameter",
"with",
"the",
"given",
"object",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java#L469-L507 |
alkacon/opencms-core | src/org/opencms/workflow/CmsDefaultWorkflowManager.java | CmsDefaultWorkflowManager.createProjectBeanFromProject | public static CmsProjectBean createProjectBeanFromProject(CmsObject cms, CmsProject project) {
"""
Creates a project bean from a real project.<p>
@param cms the CMS context
@param project the project
@return the bean containing the project information
"""
CmsProjectBean manProj = new CmsProjectBean(
project.getUuid(),
project.getType().getMode(),
org.opencms.ade.publish.Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key(
org.opencms.ade.publish.Messages.GUI_NORMAL_PROJECT_1,
getOuAwareName(cms, project.getName())),
project.getDescription());
return manProj;
} | java | public static CmsProjectBean createProjectBeanFromProject(CmsObject cms, CmsProject project) {
CmsProjectBean manProj = new CmsProjectBean(
project.getUuid(),
project.getType().getMode(),
org.opencms.ade.publish.Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key(
org.opencms.ade.publish.Messages.GUI_NORMAL_PROJECT_1,
getOuAwareName(cms, project.getName())),
project.getDescription());
return manProj;
} | [
"public",
"static",
"CmsProjectBean",
"createProjectBeanFromProject",
"(",
"CmsObject",
"cms",
",",
"CmsProject",
"project",
")",
"{",
"CmsProjectBean",
"manProj",
"=",
"new",
"CmsProjectBean",
"(",
"project",
".",
"getUuid",
"(",
")",
",",
"project",
".",
"getTyp... | Creates a project bean from a real project.<p>
@param cms the CMS context
@param project the project
@return the bean containing the project information | [
"Creates",
"a",
"project",
"bean",
"from",
"a",
"real",
"project",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workflow/CmsDefaultWorkflowManager.java#L125-L135 |
biojava/biojava | biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java | WorkSheet.addRows | public void addRows(ArrayList<String> rows, String defaultValue) {
"""
Add rows to the worksheet and fill in default value
@param rows
@param defaultValue
"""
CompactCharSequence dv = new CompactCharSequence(defaultValue);
int oldlength = data.length;
int numColumns = 0;
if (data.length > 0 && data[0] != null) {
numColumns = data[0].length;
}
data = (CompactCharSequence[][]) resizeArray(data, data.length + rows.size());
for (int r = 0; r < rows.size(); r++) {
data[oldlength + r] = new CompactCharSequence[numColumns];
for (int c = 0; c < numColumns; c++) {
data[oldlength + r][c] = dv;
}
data[oldlength + r][0] = new CompactCharSequence(rows.get(r));
rowLookup.put(rows.get(r), new HeaderInfo(r + oldlength));
}
} | java | public void addRows(ArrayList<String> rows, String defaultValue) {
CompactCharSequence dv = new CompactCharSequence(defaultValue);
int oldlength = data.length;
int numColumns = 0;
if (data.length > 0 && data[0] != null) {
numColumns = data[0].length;
}
data = (CompactCharSequence[][]) resizeArray(data, data.length + rows.size());
for (int r = 0; r < rows.size(); r++) {
data[oldlength + r] = new CompactCharSequence[numColumns];
for (int c = 0; c < numColumns; c++) {
data[oldlength + r][c] = dv;
}
data[oldlength + r][0] = new CompactCharSequence(rows.get(r));
rowLookup.put(rows.get(r), new HeaderInfo(r + oldlength));
}
} | [
"public",
"void",
"addRows",
"(",
"ArrayList",
"<",
"String",
">",
"rows",
",",
"String",
"defaultValue",
")",
"{",
"CompactCharSequence",
"dv",
"=",
"new",
"CompactCharSequence",
"(",
"defaultValue",
")",
";",
"int",
"oldlength",
"=",
"data",
".",
"length",
... | Add rows to the worksheet and fill in default value
@param rows
@param defaultValue | [
"Add",
"rows",
"to",
"the",
"worksheet",
"and",
"fill",
"in",
"default",
"value"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java#L708-L724 |
pugwoo/nimble-orm | src/main/java/com/pugwoo/dbhelper/sql/SQLUtils.java | SQLUtils.insertWhereAndExpression | public static String insertWhereAndExpression(String whereSql, String condExpression)
throws JSQLParserException {
"""
往where sql里面插入AND关系的表达式。
例如:whereSql为 where a!=3 or a!=2 limit 1
condExpress为 deleted=0
那么返回:where (deleted=0 and (a!=3 or a!=2)) limit 1
@param whereSql 从where起的sql子句,如果有where必须带上where关键字。
@param condExpression 例如a=? 不带where或and关键字。
@return 注意返回字符串前面没有空格
@throws JSQLParserException
"""
if(condExpression == null || condExpression.trim().isEmpty()) {
return whereSql == null ? "" : whereSql;
}
if(whereSql == null || whereSql.trim().isEmpty()) {
return "WHERE " + condExpression;
}
whereSql = whereSql.trim();
if(!whereSql.toUpperCase().startsWith("WHERE ")) {
return "WHERE " + condExpression + " " + whereSql;
}
// 为解决JSqlParse对复杂的condExpression不支持的问题,这里用替换的形式来达到目的
String magic = "A" + UUID.randomUUID().toString().replace("-", "");
String selectSql = "select * from dual "; // 辅助where sql解析用
Statement statement = CCJSqlParserUtil.parse(selectSql + whereSql);
Select selectStatement = (Select) statement;
PlainSelect plainSelect = (PlainSelect)selectStatement.getSelectBody();
Expression ce = CCJSqlParserUtil.parseCondExpression(magic);
Expression oldWhere = plainSelect.getWhere();
Expression newWhere = new FixedAndExpression(oldWhere, ce);
plainSelect.setWhere(newWhere);
String result = plainSelect.toString().substring(selectSql.length());
return result.replace(magic, condExpression);
} | java | public static String insertWhereAndExpression(String whereSql, String condExpression)
throws JSQLParserException {
if(condExpression == null || condExpression.trim().isEmpty()) {
return whereSql == null ? "" : whereSql;
}
if(whereSql == null || whereSql.trim().isEmpty()) {
return "WHERE " + condExpression;
}
whereSql = whereSql.trim();
if(!whereSql.toUpperCase().startsWith("WHERE ")) {
return "WHERE " + condExpression + " " + whereSql;
}
// 为解决JSqlParse对复杂的condExpression不支持的问题,这里用替换的形式来达到目的
String magic = "A" + UUID.randomUUID().toString().replace("-", "");
String selectSql = "select * from dual "; // 辅助where sql解析用
Statement statement = CCJSqlParserUtil.parse(selectSql + whereSql);
Select selectStatement = (Select) statement;
PlainSelect plainSelect = (PlainSelect)selectStatement.getSelectBody();
Expression ce = CCJSqlParserUtil.parseCondExpression(magic);
Expression oldWhere = plainSelect.getWhere();
Expression newWhere = new FixedAndExpression(oldWhere, ce);
plainSelect.setWhere(newWhere);
String result = plainSelect.toString().substring(selectSql.length());
return result.replace(magic, condExpression);
} | [
"public",
"static",
"String",
"insertWhereAndExpression",
"(",
"String",
"whereSql",
",",
"String",
"condExpression",
")",
"throws",
"JSQLParserException",
"{",
"if",
"(",
"condExpression",
"==",
"null",
"||",
"condExpression",
".",
"trim",
"(",
")",
".",
"isEmpty... | 往where sql里面插入AND关系的表达式。
例如:whereSql为 where a!=3 or a!=2 limit 1
condExpress为 deleted=0
那么返回:where (deleted=0 and (a!=3 or a!=2)) limit 1
@param whereSql 从where起的sql子句,如果有where必须带上where关键字。
@param condExpression 例如a=? 不带where或and关键字。
@return 注意返回字符串前面没有空格
@throws JSQLParserException | [
"往where",
"sql里面插入AND关系的表达式。"
] | train | https://github.com/pugwoo/nimble-orm/blob/dd496f3e57029e4f22f9a2f00d18a6513ef94d08/src/main/java/com/pugwoo/dbhelper/sql/SQLUtils.java#L584-L614 |
coursera/courier | generator-api/src/main/java/org/coursera/courier/api/CourierTemplateSpecGenerator.java | CourierTemplateSpecGenerator.checkForClassNameConflict | private void checkForClassNameConflict(String className, DataSchema schema)
throws IllegalArgumentException {
"""
Checks if a class name conflict occurs, if it occurs throws {@link IllegalArgumentException}.
@param className provides the Java class name.
@param schema provides the {@link com.linkedin.data.schema.DataSchema} that would be bound if there is no conflict.
@throws IllegalArgumentException
"""
final DataSchema schemaFromClassName = _classNameToSchemaMap.get(className);
boolean conflict = false;
if (schemaFromClassName != null && schemaFromClassName != schema)
{
final DataSchema.Type schemaType = schema.getType();
if (schemaFromClassName.getType() != schemaType)
{
conflict = true;
}
else if (schema instanceof NamedDataSchema)
{
conflict = true;
}
else if (!schemaFromClassName.equals(schema))
{
assert schemaType == DataSchema.Type.ARRAY || schemaType == DataSchema.Type.MAP;
//
// see schemaForArrayItemsOrMapValues
//
// When the schema bound to the specified class name is different
// from the specified schema, then emit a log message when this occurs.
//
_log.debug("Class name: " + className +
", bound to schema:" + schemaFromClassName +
", instead of schema: " + schema);
}
}
if (conflict)
{
throw new IllegalArgumentException("Class name conflict detected, class name: " + className +
", class already bound to schema: " + schemaFromClassName +
", attempting to rebind to schema: " + schema);
}
} | java | private void checkForClassNameConflict(String className, DataSchema schema)
throws IllegalArgumentException
{
final DataSchema schemaFromClassName = _classNameToSchemaMap.get(className);
boolean conflict = false;
if (schemaFromClassName != null && schemaFromClassName != schema)
{
final DataSchema.Type schemaType = schema.getType();
if (schemaFromClassName.getType() != schemaType)
{
conflict = true;
}
else if (schema instanceof NamedDataSchema)
{
conflict = true;
}
else if (!schemaFromClassName.equals(schema))
{
assert schemaType == DataSchema.Type.ARRAY || schemaType == DataSchema.Type.MAP;
//
// see schemaForArrayItemsOrMapValues
//
// When the schema bound to the specified class name is different
// from the specified schema, then emit a log message when this occurs.
//
_log.debug("Class name: " + className +
", bound to schema:" + schemaFromClassName +
", instead of schema: " + schema);
}
}
if (conflict)
{
throw new IllegalArgumentException("Class name conflict detected, class name: " + className +
", class already bound to schema: " + schemaFromClassName +
", attempting to rebind to schema: " + schema);
}
} | [
"private",
"void",
"checkForClassNameConflict",
"(",
"String",
"className",
",",
"DataSchema",
"schema",
")",
"throws",
"IllegalArgumentException",
"{",
"final",
"DataSchema",
"schemaFromClassName",
"=",
"_classNameToSchemaMap",
".",
"get",
"(",
"className",
")",
";",
... | Checks if a class name conflict occurs, if it occurs throws {@link IllegalArgumentException}.
@param className provides the Java class name.
@param schema provides the {@link com.linkedin.data.schema.DataSchema} that would be bound if there is no conflict.
@throws IllegalArgumentException | [
"Checks",
"if",
"a",
"class",
"name",
"conflict",
"occurs",
"if",
"it",
"occurs",
"throws",
"{",
"@link",
"IllegalArgumentException",
"}",
"."
] | train | https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/CourierTemplateSpecGenerator.java#L292-L328 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/BatchOperation.java | BatchOperation.addEntity | public <T extends IEntity> void addEntity(T entity, OperationEnum operation, String bId) {
"""
Method to add the entity batch operations to the batchItemRequest
@param entity the entity
@param operation the OperationEnum
@param bId the batch Id
"""
BatchItemRequest batchItemRequest = new BatchItemRequest();
batchItemRequest.setBId(bId);
batchItemRequest.setOperation(operation);
batchItemRequest.setIntuitObject(getIntuitObject(entity));
batchItemRequests.add(batchItemRequest);
bIds.add(bId);
} | java | public <T extends IEntity> void addEntity(T entity, OperationEnum operation, String bId) {
BatchItemRequest batchItemRequest = new BatchItemRequest();
batchItemRequest.setBId(bId);
batchItemRequest.setOperation(operation);
batchItemRequest.setIntuitObject(getIntuitObject(entity));
batchItemRequests.add(batchItemRequest);
bIds.add(bId);
} | [
"public",
"<",
"T",
"extends",
"IEntity",
">",
"void",
"addEntity",
"(",
"T",
"entity",
",",
"OperationEnum",
"operation",
",",
"String",
"bId",
")",
"{",
"BatchItemRequest",
"batchItemRequest",
"=",
"new",
"BatchItemRequest",
"(",
")",
";",
"batchItemRequest",
... | Method to add the entity batch operations to the batchItemRequest
@param entity the entity
@param operation the OperationEnum
@param bId the batch Id | [
"Method",
"to",
"add",
"the",
"entity",
"batch",
"operations",
"to",
"the",
"batchItemRequest"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/BatchOperation.java#L95-L104 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newEqualityException | public static EqualityException newEqualityException(Throwable cause, String message, Object... args) {
"""
Constructs and initializes a new {@link EqualityException} 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 EqualityException} was thrown.
@param message {@link String} describing the {@link EqualityException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link EqualityException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.lang.EqualityException
"""
return new EqualityException(format(message, args), cause);
} | java | public static EqualityException newEqualityException(Throwable cause, String message, Object... args) {
return new EqualityException(format(message, args), cause);
} | [
"public",
"static",
"EqualityException",
"newEqualityException",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"new",
"EqualityException",
"(",
"format",
"(",
"message",
",",
"args",
")",
",",
"cause",
"... | Constructs and initializes a new {@link EqualityException} 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 EqualityException} was thrown.
@param message {@link String} describing the {@link EqualityException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link EqualityException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.lang.EqualityException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"EqualityException",
"}",
"with",
"the",
"given",
"{",
"@link",
"Throwable",
"cause",
"}",
"and",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Object... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L341-L343 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java | CQJDBCStorageConnection.appendPattern | protected void appendPattern(StringBuilder sb, QPathEntry entry, boolean indexConstraint) {
"""
Append pattern expression.
Appends String "I.NAME LIKE 'escaped pattern' ESCAPE 'escapeString'" or "I.NAME='pattern'"
to String builder sb.
@param sb StringBuilder
@param entry
@param indexConstraint
"""
String pattern = entry.getAsString(false);
sb.append("(I.NAME");
if (pattern.contains("*"))
{
sb.append(" LIKE '");
sb.append(escapeSpecialChars(pattern));
sb.append("' ESCAPE '");
sb.append(getLikeExpressionEscape());
sb.append("'");
}
else
{
sb.append("='");
sb.append(escape(pattern));
sb.append("'");
}
if (indexConstraint && entry.getIndex() != -1)
{
sb.append(" and I.I_INDEX=");
sb.append(entry.getIndex());
}
sb.append(")");
} | java | protected void appendPattern(StringBuilder sb, QPathEntry entry, boolean indexConstraint)
{
String pattern = entry.getAsString(false);
sb.append("(I.NAME");
if (pattern.contains("*"))
{
sb.append(" LIKE '");
sb.append(escapeSpecialChars(pattern));
sb.append("' ESCAPE '");
sb.append(getLikeExpressionEscape());
sb.append("'");
}
else
{
sb.append("='");
sb.append(escape(pattern));
sb.append("'");
}
if (indexConstraint && entry.getIndex() != -1)
{
sb.append(" and I.I_INDEX=");
sb.append(entry.getIndex());
}
sb.append(")");
} | [
"protected",
"void",
"appendPattern",
"(",
"StringBuilder",
"sb",
",",
"QPathEntry",
"entry",
",",
"boolean",
"indexConstraint",
")",
"{",
"String",
"pattern",
"=",
"entry",
".",
"getAsString",
"(",
"false",
")",
";",
"sb",
".",
"append",
"(",
"\"(I.NAME\"",
... | Append pattern expression.
Appends String "I.NAME LIKE 'escaped pattern' ESCAPE 'escapeString'" or "I.NAME='pattern'"
to String builder sb.
@param sb StringBuilder
@param entry
@param indexConstraint | [
"Append",
"pattern",
"expression",
".",
"Appends",
"String",
"I",
".",
"NAME",
"LIKE",
"escaped",
"pattern",
"ESCAPE",
"escapeString",
"or",
"I",
".",
"NAME",
"=",
"pattern",
"to",
"String",
"builder",
"sb",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java#L2239-L2264 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/Step.java | Step.clickOnByJs | protected void clickOnByJs(PageElement toClick, Object... args) throws TechnicalException, FailureException {
"""
Click on html element by Javascript.
@param toClick
html element
@param args
list of arguments to format the found selector with
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK} message (with screenshot, with exception)
@throws FailureException
if the scenario encounters a functional error
"""
displayMessageAtTheBeginningOfMethod("clickOnByJs: %s in %s", toClick.toString(), toClick.getPage().getApplication());
try {
Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(toClick, args)));
((JavascriptExecutor) getDriver())
.executeScript("document.evaluate(\"" + Utilities.getLocatorValue(toClick, args).replace("\"", "\\\"") + "\", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).click();");
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK), toClick, toClick.getPage().getApplication()), true,
toClick.getPage().getCallBack());
}
} | java | protected void clickOnByJs(PageElement toClick, Object... args) throws TechnicalException, FailureException {
displayMessageAtTheBeginningOfMethod("clickOnByJs: %s in %s", toClick.toString(), toClick.getPage().getApplication());
try {
Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(toClick, args)));
((JavascriptExecutor) getDriver())
.executeScript("document.evaluate(\"" + Utilities.getLocatorValue(toClick, args).replace("\"", "\\\"") + "\", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).click();");
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK), toClick, toClick.getPage().getApplication()), true,
toClick.getPage().getCallBack());
}
} | [
"protected",
"void",
"clickOnByJs",
"(",
"PageElement",
"toClick",
",",
"Object",
"...",
"args",
")",
"throws",
"TechnicalException",
",",
"FailureException",
"{",
"displayMessageAtTheBeginningOfMethod",
"(",
"\"clickOnByJs: %s in %s\"",
",",
"toClick",
".",
"toString",
... | Click on html element by Javascript.
@param toClick
html element
@param args
list of arguments to format the found selector with
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK} message (with screenshot, with exception)
@throws FailureException
if the scenario encounters a functional error | [
"Click",
"on",
"html",
"element",
"by",
"Javascript",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L136-L146 |
UrielCh/ovh-java-sdk | ovh-java-sdk-msServices/src/main/java/net/minidev/ovh/api/ApiOvhMsServices.java | ApiOvhMsServices.serviceName_account_userPrincipalName_sync_POST | public OvhTask serviceName_account_userPrincipalName_sync_POST(String serviceName, String userPrincipalName, OvhSyncLicenseEnum license) throws IOException {
"""
Create new sync account
REST: POST /msServices/{serviceName}/account/{userPrincipalName}/sync
@param license [required] Sync account license
@param serviceName [required] The internal name of your Active Directory organization
@param userPrincipalName [required] User Principal Name
API beta
"""
String qPath = "/msServices/{serviceName}/account/{userPrincipalName}/sync";
StringBuilder sb = path(qPath, serviceName, userPrincipalName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "license", license);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_account_userPrincipalName_sync_POST(String serviceName, String userPrincipalName, OvhSyncLicenseEnum license) throws IOException {
String qPath = "/msServices/{serviceName}/account/{userPrincipalName}/sync";
StringBuilder sb = path(qPath, serviceName, userPrincipalName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "license", license);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_account_userPrincipalName_sync_POST",
"(",
"String",
"serviceName",
",",
"String",
"userPrincipalName",
",",
"OvhSyncLicenseEnum",
"license",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/msServices/{serviceName}/account/{userP... | Create new sync account
REST: POST /msServices/{serviceName}/account/{userPrincipalName}/sync
@param license [required] Sync account license
@param serviceName [required] The internal name of your Active Directory organization
@param userPrincipalName [required] User Principal Name
API beta | [
"Create",
"new",
"sync",
"account"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-msServices/src/main/java/net/minidev/ovh/api/ApiOvhMsServices.java#L173-L180 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.UByteArray | public JBBPDslBuilder UByteArray(final String name, final String sizeExpression) {
"""
Add named unsigned byte array which size calculated through expression.
@param name name of the field, it can be null for anonymous one
@param sizeExpression expression to calculate array size, must ot be null or empty.
@return the builder instance, must not be null
"""
final Item item = new Item(BinType.UBYTE_ARRAY, name, this.byteOrder);
item.sizeExpression = assertExpressionChars(sizeExpression);
this.addItem(item);
return this;
} | java | public JBBPDslBuilder UByteArray(final String name, final String sizeExpression) {
final Item item = new Item(BinType.UBYTE_ARRAY, name, this.byteOrder);
item.sizeExpression = assertExpressionChars(sizeExpression);
this.addItem(item);
return this;
} | [
"public",
"JBBPDslBuilder",
"UByteArray",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"sizeExpression",
")",
"{",
"final",
"Item",
"item",
"=",
"new",
"Item",
"(",
"BinType",
".",
"UBYTE_ARRAY",
",",
"name",
",",
"this",
".",
"byteOrder",
")",
... | Add named unsigned byte array which size calculated through expression.
@param name name of the field, it can be null for anonymous one
@param sizeExpression expression to calculate array size, must ot be null or empty.
@return the builder instance, must not be null | [
"Add",
"named",
"unsigned",
"byte",
"array",
"which",
"size",
"calculated",
"through",
"expression",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L937-L942 |
liferay/com-liferay-commerce | commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java | CPSpecificationOptionWrapper.setDescriptionMap | @Override
public void setDescriptionMap(Map<java.util.Locale, String> descriptionMap) {
"""
Sets the localized descriptions of this cp specification option from the map of locales and localized descriptions.
@param descriptionMap the locales and localized descriptions of this cp specification option
"""
_cpSpecificationOption.setDescriptionMap(descriptionMap);
} | java | @Override
public void setDescriptionMap(Map<java.util.Locale, String> descriptionMap) {
_cpSpecificationOption.setDescriptionMap(descriptionMap);
} | [
"@",
"Override",
"public",
"void",
"setDescriptionMap",
"(",
"Map",
"<",
"java",
".",
"util",
".",
"Locale",
",",
"String",
">",
"descriptionMap",
")",
"{",
"_cpSpecificationOption",
".",
"setDescriptionMap",
"(",
"descriptionMap",
")",
";",
"}"
] | Sets the localized descriptions of this cp specification option from the map of locales and localized descriptions.
@param descriptionMap the locales and localized descriptions of this cp specification option | [
"Sets",
"the",
"localized",
"descriptions",
"of",
"this",
"cp",
"specification",
"option",
"from",
"the",
"map",
"of",
"locales",
"and",
"localized",
"descriptions",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java#L635-L638 |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/PodLogs.java | PodLogs.streamNamespacedPodLog | public InputStream streamNamespacedPodLog(String namespace, String name, String container)
throws ApiException, IOException {
"""
Important note. You must close this stream or else you can leak connections.
"""
return streamNamespacedPodLog(namespace, name, container, null, null, false);
} | java | public InputStream streamNamespacedPodLog(String namespace, String name, String container)
throws ApiException, IOException {
return streamNamespacedPodLog(namespace, name, container, null, null, false);
} | [
"public",
"InputStream",
"streamNamespacedPodLog",
"(",
"String",
"namespace",
",",
"String",
"name",
",",
"String",
"container",
")",
"throws",
"ApiException",
",",
"IOException",
"{",
"return",
"streamNamespacedPodLog",
"(",
"namespace",
",",
"name",
",",
"contain... | Important note. You must close this stream or else you can leak connections. | [
"Important",
"note",
".",
"You",
"must",
"close",
"this",
"stream",
"or",
"else",
"you",
"can",
"leak",
"connections",
"."
] | train | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/PodLogs.java#L65-L68 |
Azure/azure-sdk-for-java | labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/UsersInner.java | UsersInner.getAsync | public Observable<UserInner> getAsync(String resourceGroupName, String labAccountName, String labName, String userName) {
"""
Get user.
@param resourceGroupName The name of the resource group.
@param labAccountName The name of the lab Account.
@param labName The name of the lab.
@param userName The name of the user.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the UserInner object
"""
return getWithServiceResponseAsync(resourceGroupName, labAccountName, labName, userName).map(new Func1<ServiceResponse<UserInner>, UserInner>() {
@Override
public UserInner call(ServiceResponse<UserInner> response) {
return response.body();
}
});
} | java | public Observable<UserInner> getAsync(String resourceGroupName, String labAccountName, String labName, String userName) {
return getWithServiceResponseAsync(resourceGroupName, labAccountName, labName, userName).map(new Func1<ServiceResponse<UserInner>, UserInner>() {
@Override
public UserInner call(ServiceResponse<UserInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"UserInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"labAccountName",
",",
"String",
"labName",
",",
"String",
"userName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"la... | Get user.
@param resourceGroupName The name of the resource group.
@param labAccountName The name of the lab Account.
@param labName The name of the lab.
@param userName The name of the user.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the UserInner object | [
"Get",
"user",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/UsersInner.java#L416-L423 |
sdaschner/jaxrs-analyzer | src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/results/ResultInterpreter.java | ResultInterpreter.updateMethodParameters | private void updateMethodParameters(final Set<MethodParameter> parameters, final Set<MethodParameter> additional) {
"""
Updates {@code parameters} to contain the {@code additional} parameters as well.
Preexisting parameters with identical names are overridden.
"""
additional.forEach(a -> {
// remove preexisting parameters with identical names
final Optional<MethodParameter> existingParameter = parameters.stream().filter(p -> p.getName().equals(a.getName())).findAny();
existingParameter.ifPresent(parameters::remove);
parameters.add(a);
});
} | java | private void updateMethodParameters(final Set<MethodParameter> parameters, final Set<MethodParameter> additional) {
additional.forEach(a -> {
// remove preexisting parameters with identical names
final Optional<MethodParameter> existingParameter = parameters.stream().filter(p -> p.getName().equals(a.getName())).findAny();
existingParameter.ifPresent(parameters::remove);
parameters.add(a);
});
} | [
"private",
"void",
"updateMethodParameters",
"(",
"final",
"Set",
"<",
"MethodParameter",
">",
"parameters",
",",
"final",
"Set",
"<",
"MethodParameter",
">",
"additional",
")",
"{",
"additional",
".",
"forEach",
"(",
"a",
"->",
"{",
"// remove preexisting paramet... | Updates {@code parameters} to contain the {@code additional} parameters as well.
Preexisting parameters with identical names are overridden. | [
"Updates",
"{"
] | train | https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/analysis/results/ResultInterpreter.java#L194-L201 |
lite2073/email-validator | src/com/dominicsayers/isemail/dns/DNSLookup.java | DNSLookup.doLookup | public static int doLookup(String hostName, String dnsType)
throws DNSLookupException {
"""
Counts the number of records found for hostname and the specific type.
Outputs 0 if no record is found or -1 if the hostname is unknown invalid!
@param hostName
The hostname
@param dnsType
The kind of record (A, AAAA, MX, ...)
@return Whether the record is available or not
@throws DNSLookupException
Appears on a fatal error like dnsType invalid or initial
context error.
"""
// JNDI cannot take two-byte chars, so we convert the hostname into Punycode
hostName = UniPunyCode.toPunycodeIfPossible(hostName);
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx;
try {
ictx = new InitialDirContext(env);
} catch (NamingException e) {
throw new DNSInitialContextException(e);
}
Attributes attrs;
try {
attrs = ictx.getAttributes(hostName, new String[] { dnsType });
} catch (NameNotFoundException e) {
// The hostname was not found or is invalid
return -1;
} catch (InvalidAttributeIdentifierException e) {
// The DNS type is invalid
throw new DNSInvalidTypeException(e);
} catch (NamingException e) {
// Unknown reason
throw new DNSLookupException(e);
}
Attribute attr = attrs.get(dnsType);
if (attr == null) {
return 0;
}
return attr.size();
} | java | public static int doLookup(String hostName, String dnsType)
throws DNSLookupException {
// JNDI cannot take two-byte chars, so we convert the hostname into Punycode
hostName = UniPunyCode.toPunycodeIfPossible(hostName);
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx;
try {
ictx = new InitialDirContext(env);
} catch (NamingException e) {
throw new DNSInitialContextException(e);
}
Attributes attrs;
try {
attrs = ictx.getAttributes(hostName, new String[] { dnsType });
} catch (NameNotFoundException e) {
// The hostname was not found or is invalid
return -1;
} catch (InvalidAttributeIdentifierException e) {
// The DNS type is invalid
throw new DNSInvalidTypeException(e);
} catch (NamingException e) {
// Unknown reason
throw new DNSLookupException(e);
}
Attribute attr = attrs.get(dnsType);
if (attr == null) {
return 0;
}
return attr.size();
} | [
"public",
"static",
"int",
"doLookup",
"(",
"String",
"hostName",
",",
"String",
"dnsType",
")",
"throws",
"DNSLookupException",
"{",
"// JNDI cannot take two-byte chars, so we convert the hostname into Punycode\r",
"hostName",
"=",
"UniPunyCode",
".",
"toPunycodeIfPossible",
... | Counts the number of records found for hostname and the specific type.
Outputs 0 if no record is found or -1 if the hostname is unknown invalid!
@param hostName
The hostname
@param dnsType
The kind of record (A, AAAA, MX, ...)
@return Whether the record is available or not
@throws DNSLookupException
Appears on a fatal error like dnsType invalid or initial
context error. | [
"Counts",
"the",
"number",
"of",
"records",
"found",
"for",
"hostname",
"and",
"the",
"specific",
"type",
".",
"Outputs",
"0",
"if",
"no",
"record",
"is",
"found",
"or",
"-",
"1",
"if",
"the",
"hostname",
"is",
"unknown",
"invalid!"
] | train | https://github.com/lite2073/email-validator/blob/cfdda77ed630854b44d62def0d5b7228d5c4e712/src/com/dominicsayers/isemail/dns/DNSLookup.java#L47-L83 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseFloatObj | @Nullable
public static Float parseFloatObj (@Nullable final Object aObject, @Nullable final Float aDefault) {
"""
Parse the given {@link Object} as {@link Float}. Note: both the locale
independent form of a double can be parsed here (e.g. 4.523) as well as a
localized form using the comma as the decimal separator (e.g. the German
4,523).
@param aObject
The object to parse. May be <code>null</code>.
@param aDefault
The default value to be returned if the parsed object cannot be
converted to a float. May be <code>null</code>.
@return <code>aDefault</code> if the object does not represent a valid
value.
"""
final float fValue = parseFloat (aObject, Float.NaN);
return Float.isNaN (fValue) ? aDefault : Float.valueOf (fValue);
} | java | @Nullable
public static Float parseFloatObj (@Nullable final Object aObject, @Nullable final Float aDefault)
{
final float fValue = parseFloat (aObject, Float.NaN);
return Float.isNaN (fValue) ? aDefault : Float.valueOf (fValue);
} | [
"@",
"Nullable",
"public",
"static",
"Float",
"parseFloatObj",
"(",
"@",
"Nullable",
"final",
"Object",
"aObject",
",",
"@",
"Nullable",
"final",
"Float",
"aDefault",
")",
"{",
"final",
"float",
"fValue",
"=",
"parseFloat",
"(",
"aObject",
",",
"Float",
".",... | Parse the given {@link Object} as {@link Float}. Note: both the locale
independent form of a double can be parsed here (e.g. 4.523) as well as a
localized form using the comma as the decimal separator (e.g. the German
4,523).
@param aObject
The object to parse. May be <code>null</code>.
@param aDefault
The default value to be returned if the parsed object cannot be
converted to a float. May be <code>null</code>.
@return <code>aDefault</code> if the object does not represent a valid
value. | [
"Parse",
"the",
"given",
"{",
"@link",
"Object",
"}",
"as",
"{",
"@link",
"Float",
"}",
".",
"Note",
":",
"both",
"the",
"locale",
"independent",
"form",
"of",
"a",
"double",
"can",
"be",
"parsed",
"here",
"(",
"e",
".",
"g",
".",
"4",
".",
"523",
... | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L653-L658 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.