repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/listener/WebSocketServerHandshakeHandler.java | WebSocketServerHandshakeHandler.handleWebSocketHandshake | private void handleWebSocketHandshake(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx)
throws WebSocketConnectorException {
String extensionsHeader = fullHttpRequest.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
DefaultWebSocketHandshaker webSocketHandshaker =
new DefaultWebSocketHandshaker(ctx, serverConnectorFuture, fullHttpRequest, fullHttpRequest.uri(),
extensionsHeader != null);
// Setting common properties to handshaker
webSocketHandshaker.setHttpCarbonRequest(setupHttpCarbonRequest(fullHttpRequest, ctx));
ctx.channel().config().setAutoRead(false);
serverConnectorFuture.notifyWebSocketListener(webSocketHandshaker);
} | java | private void handleWebSocketHandshake(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx)
throws WebSocketConnectorException {
String extensionsHeader = fullHttpRequest.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
DefaultWebSocketHandshaker webSocketHandshaker =
new DefaultWebSocketHandshaker(ctx, serverConnectorFuture, fullHttpRequest, fullHttpRequest.uri(),
extensionsHeader != null);
// Setting common properties to handshaker
webSocketHandshaker.setHttpCarbonRequest(setupHttpCarbonRequest(fullHttpRequest, ctx));
ctx.channel().config().setAutoRead(false);
serverConnectorFuture.notifyWebSocketListener(webSocketHandshaker);
} | [
"private",
"void",
"handleWebSocketHandshake",
"(",
"FullHttpRequest",
"fullHttpRequest",
",",
"ChannelHandlerContext",
"ctx",
")",
"throws",
"WebSocketConnectorException",
"{",
"String",
"extensionsHeader",
"=",
"fullHttpRequest",
".",
"headers",
"(",
")",
".",
"getAsStr... | Handle the WebSocket handshake.
@param fullHttpRequest {@link HttpRequest} of the request. | [
"Handle",
"the",
"WebSocket",
"handshake",
"."
] | train | https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/listener/WebSocketServerHandshakeHandler.java#L154-L166 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/ContainerKeyCache.java | ContainerKeyCache.get | CacheBucketOffset get(long segmentId, UUID keyHash) {
SegmentKeyCache cache;
int generation;
synchronized (this.segmentCaches) {
generation = this.currentCacheGeneration;
cache = this.segmentCaches.get(segmentId);
}
return cache == null ? null : cache.get(keyHash, generation);
} | java | CacheBucketOffset get(long segmentId, UUID keyHash) {
SegmentKeyCache cache;
int generation;
synchronized (this.segmentCaches) {
generation = this.currentCacheGeneration;
cache = this.segmentCaches.get(segmentId);
}
return cache == null ? null : cache.get(keyHash, generation);
} | [
"CacheBucketOffset",
"get",
"(",
"long",
"segmentId",
",",
"UUID",
"keyHash",
")",
"{",
"SegmentKeyCache",
"cache",
";",
"int",
"generation",
";",
"synchronized",
"(",
"this",
".",
"segmentCaches",
")",
"{",
"generation",
"=",
"this",
".",
"currentCacheGeneratio... | Looks up a cached offset for the given Segment and Key Hash.
@param segmentId The Id of the Segment to look up for.
@param keyHash A UUID representing the Key Hash to look up.
@return A {@link CacheBucketOffset} representing the sought result. | [
"Looks",
"up",
"a",
"cached",
"offset",
"for",
"the",
"given",
"Segment",
"and",
"Key",
"Hash",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/ContainerKeyCache.java#L172-L181 |
attribyte/wpdb | src/main/java/org/attribyte/wp/db/DB.java | DB.updatePostExcerpt | public boolean updatePostExcerpt(long postId, final String excerpt) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
Timer.Context ctx = metrics.updatePostTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(updatePostExcerptSQL);
stmt.setString(1, excerpt);
stmt.setLong(2, postId);
return stmt.executeUpdate() > 0;
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt);
}
} | java | public boolean updatePostExcerpt(long postId, final String excerpt) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
Timer.Context ctx = metrics.updatePostTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(updatePostExcerptSQL);
stmt.setString(1, excerpt);
stmt.setLong(2, postId);
return stmt.executeUpdate() > 0;
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt);
}
} | [
"public",
"boolean",
"updatePostExcerpt",
"(",
"long",
"postId",
",",
"final",
"String",
"excerpt",
")",
"throws",
"SQLException",
"{",
"Connection",
"conn",
"=",
"null",
";",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"Timer",
".",
"Context",
"ctx",
"=",
... | Updates the excerpt for a post.
@param postId The post to update.
@param excerpt The new excerpt.
@return Was the post modified?
@throws SQLException on database error or missing post id. | [
"Updates",
"the",
"excerpt",
"for",
"a",
"post",
"."
] | train | https://github.com/attribyte/wpdb/blob/b9adf6131dfb67899ebff770c9bfeb001cc42f30/src/main/java/org/attribyte/wp/db/DB.java#L1550-L1564 |
molgenis/molgenis | molgenis-data-index/src/main/java/org/molgenis/data/index/job/IndexJobService.java | IndexJobService.rebuildIndexOneEntity | private void rebuildIndexOneEntity(String entityTypeId, String untypedEntityId) {
LOG.trace("Indexing [{}].[{}]... ", entityTypeId, untypedEntityId);
// convert entity id string to typed entity id
EntityType entityType = dataService.getEntityType(entityTypeId);
if (null != entityType) {
Object entityId = getTypedValue(untypedEntityId, entityType.getIdAttribute());
String entityFullName = entityType.getId();
Entity actualEntity = dataService.findOneById(entityFullName, entityId);
if (null == actualEntity) {
// Delete
LOG.debug("Index delete [{}].[{}].", entityFullName, entityId);
indexService.deleteById(entityType, entityId);
return;
}
boolean indexEntityExists = indexService.hasIndex(entityType);
if (!indexEntityExists) {
LOG.debug("Create mapping of repository [{}] because it was not exist yet", entityTypeId);
indexService.createIndex(entityType);
}
LOG.debug("Index [{}].[{}].", entityTypeId, entityId);
indexService.index(actualEntity.getEntityType(), actualEntity);
} else {
throw new MolgenisDataException("Unknown EntityType for entityTypeId: " + entityTypeId);
}
} | java | private void rebuildIndexOneEntity(String entityTypeId, String untypedEntityId) {
LOG.trace("Indexing [{}].[{}]... ", entityTypeId, untypedEntityId);
// convert entity id string to typed entity id
EntityType entityType = dataService.getEntityType(entityTypeId);
if (null != entityType) {
Object entityId = getTypedValue(untypedEntityId, entityType.getIdAttribute());
String entityFullName = entityType.getId();
Entity actualEntity = dataService.findOneById(entityFullName, entityId);
if (null == actualEntity) {
// Delete
LOG.debug("Index delete [{}].[{}].", entityFullName, entityId);
indexService.deleteById(entityType, entityId);
return;
}
boolean indexEntityExists = indexService.hasIndex(entityType);
if (!indexEntityExists) {
LOG.debug("Create mapping of repository [{}] because it was not exist yet", entityTypeId);
indexService.createIndex(entityType);
}
LOG.debug("Index [{}].[{}].", entityTypeId, entityId);
indexService.index(actualEntity.getEntityType(), actualEntity);
} else {
throw new MolgenisDataException("Unknown EntityType for entityTypeId: " + entityTypeId);
}
} | [
"private",
"void",
"rebuildIndexOneEntity",
"(",
"String",
"entityTypeId",
",",
"String",
"untypedEntityId",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"Indexing [{}].[{}]... \"",
",",
"entityTypeId",
",",
"untypedEntityId",
")",
";",
"// convert entity id string to typed enti... | Indexes one single entity instance.
@param entityTypeId the id of the entity's repository
@param untypedEntityId the identifier of the entity to update | [
"Indexes",
"one",
"single",
"entity",
"instance",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-index/src/main/java/org/molgenis/data/index/job/IndexJobService.java#L165-L194 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.readAncestor | public CmsFolder readAncestor(String resourcename, CmsResourceFilter filter) throws CmsException {
CmsResource resource = readResource(resourcename, CmsResourceFilter.ALL);
return m_securityManager.readAncestor(m_context, resource, filter);
} | java | public CmsFolder readAncestor(String resourcename, CmsResourceFilter filter) throws CmsException {
CmsResource resource = readResource(resourcename, CmsResourceFilter.ALL);
return m_securityManager.readAncestor(m_context, resource, filter);
} | [
"public",
"CmsFolder",
"readAncestor",
"(",
"String",
"resourcename",
",",
"CmsResourceFilter",
"filter",
")",
"throws",
"CmsException",
"{",
"CmsResource",
"resource",
"=",
"readResource",
"(",
"resourcename",
",",
"CmsResourceFilter",
".",
"ALL",
")",
";",
"return... | Returns the first ancestor folder matching the filter criteria.<p>
If no folder matching the filter criteria is found, null is returned.<p>
@param resourcename the name of the resource to start (full current site relative path)
@param filter the resource filter to match while reading the ancestors
@return the first ancestor folder matching the filter criteria or null if no folder was found
@throws CmsException if something goes wrong | [
"Returns",
"the",
"first",
"ancestor",
"folder",
"matching",
"the",
"filter",
"criteria",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L2325-L2329 |
alkacon/opencms-core | src/org/opencms/gwt/CmsGwtActionElement.java | CmsGwtActionElement.createNoCacheScript | public static String createNoCacheScript(String moduleName, String moduleVersion) {
String result = "<script type=\"text/javascript\" src=\""
+ CmsWorkplace.getResourceUri("ade/" + moduleName + "/" + moduleName + ".nocache.js");
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(moduleVersion)) {
result += "?version=" + moduleVersion + "_" + OpenCms.getSystemInfo().getVersionNumber().hashCode();
}
result += "\"></script>";
return result;
} | java | public static String createNoCacheScript(String moduleName, String moduleVersion) {
String result = "<script type=\"text/javascript\" src=\""
+ CmsWorkplace.getResourceUri("ade/" + moduleName + "/" + moduleName + ".nocache.js");
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(moduleVersion)) {
result += "?version=" + moduleVersion + "_" + OpenCms.getSystemInfo().getVersionNumber().hashCode();
}
result += "\"></script>";
return result;
} | [
"public",
"static",
"String",
"createNoCacheScript",
"(",
"String",
"moduleName",
",",
"String",
"moduleVersion",
")",
"{",
"String",
"result",
"=",
"\"<script type=\\\"text/javascript\\\" src=\\\"\"",
"+",
"CmsWorkplace",
".",
"getResourceUri",
"(",
"\"ade/\"",
"+",
"m... | Returns the script tag for the "*.nocache.js".<p>
@param moduleName the module name to get the script tag for
@param moduleVersion the module version
@return the <code>"<script>"</code> tag for the "*.nocache.js".<p> | [
"Returns",
"the",
"script",
"tag",
"for",
"the",
"*",
".",
"nocache",
".",
"js",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/gwt/CmsGwtActionElement.java#L96-L105 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java | InvalidationAuditDaemon.filterExternalCacheFragmentList | public ArrayList filterExternalCacheFragmentList(String cacheName, ArrayList incomingList) {
InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName);
try {
invalidationTableList.readWriteLock.readLock().lock();
Iterator it = incomingList.iterator();
while (it.hasNext()) {
ExternalInvalidation externalCacheFragment = (ExternalInvalidation) it.next();
if (null == internalFilterExternalCacheFragment(cacheName, invalidationTableList, externalCacheFragment)) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "filterExternalCacheFragmentList(): Filtered OUT cacheName=" + cacheName + " uri=" + externalCacheFragment.getUri());
}
it.remove();
}
}
return incomingList;
} finally {
invalidationTableList.readWriteLock.readLock().unlock();
}
} | java | public ArrayList filterExternalCacheFragmentList(String cacheName, ArrayList incomingList) {
InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName);
try {
invalidationTableList.readWriteLock.readLock().lock();
Iterator it = incomingList.iterator();
while (it.hasNext()) {
ExternalInvalidation externalCacheFragment = (ExternalInvalidation) it.next();
if (null == internalFilterExternalCacheFragment(cacheName, invalidationTableList, externalCacheFragment)) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "filterExternalCacheFragmentList(): Filtered OUT cacheName=" + cacheName + " uri=" + externalCacheFragment.getUri());
}
it.remove();
}
}
return incomingList;
} finally {
invalidationTableList.readWriteLock.readLock().unlock();
}
} | [
"public",
"ArrayList",
"filterExternalCacheFragmentList",
"(",
"String",
"cacheName",
",",
"ArrayList",
"incomingList",
")",
"{",
"InvalidationTableList",
"invalidationTableList",
"=",
"getInvalidationTableList",
"(",
"cacheName",
")",
";",
"try",
"{",
"invalidationTableLis... | This ensures all incoming ExternalCacheFragments have not been
invalidated.
@param incomingList The unfiltered list of ExternalCacheFragments.
@return The filtered list of ExternalCacheFragments. | [
"This",
"ensures",
"all",
"incoming",
"ExternalCacheFragments",
"have",
"not",
"been",
"invalidated",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java#L273-L293 |
yavijava/yavijava | src/main/java/com/vmware/vim25/mo/HostStorageSystem.java | HostStorageSystem.setNFSUser | public void setNFSUser(String user, String password) throws HostConfigFault, RuntimeFault, RemoteException {
getVimService().setNFSUser(getMOR(), user, password);
} | java | public void setNFSUser(String user, String password) throws HostConfigFault, RuntimeFault, RemoteException {
getVimService().setNFSUser(getMOR(), user, password);
} | [
"public",
"void",
"setNFSUser",
"(",
"String",
"user",
",",
"String",
"password",
")",
"throws",
"HostConfigFault",
",",
"RuntimeFault",
",",
"RemoteException",
"{",
"getVimService",
"(",
")",
".",
"setNFSUser",
"(",
"getMOR",
"(",
")",
",",
"user",
",",
"pa... | Set NFS username and password on the host. The specified password is stored encrypted at the host and overwrites
any previous password configuration. This information is only needed when the host has mounted NFS volumes with
security types that require user credentials for accessing data. The password is used to acquire credentials that
the NFS client needs to use in order to secure NFS traffic using RPCSECGSS. The client will access files on all
volumes mounted on this host (that are mounted with the relevant security type) on behalf of specified user.
<p>
At present, this API supports only file system NFSv4.1.
@param user Username
@param password Passowrd
@throws HostConfigFault
@throws RuntimeFault
@throws RemoteException
@since 6.0 | [
"Set",
"NFS",
"username",
"and",
"password",
"on",
"the",
"host",
".",
"The",
"specified",
"password",
"is",
"stored",
"encrypted",
"at",
"the",
"host",
"and",
"overwrites",
"any",
"previous",
"password",
"configuration",
".",
"This",
"information",
"is",
"onl... | train | https://github.com/yavijava/yavijava/blob/27fd2c5826115782d5eeb934f86e3e39240179cd/src/main/java/com/vmware/vim25/mo/HostStorageSystem.java#L535-L537 |
phax/ph-commons | ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java | KeyStoreHelper.loadSecretKey | @Nonnull
public static LoadedKey <KeyStore.SecretKeyEntry> loadSecretKey (@Nonnull final KeyStore aKeyStore,
@Nonnull final String sKeyStorePath,
@Nullable final String sKeyStoreKeyAlias,
@Nullable final char [] aKeyStoreKeyPassword)
{
return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.SecretKeyEntry.class);
} | java | @Nonnull
public static LoadedKey <KeyStore.SecretKeyEntry> loadSecretKey (@Nonnull final KeyStore aKeyStore,
@Nonnull final String sKeyStorePath,
@Nullable final String sKeyStoreKeyAlias,
@Nullable final char [] aKeyStoreKeyPassword)
{
return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.SecretKeyEntry.class);
} | [
"@",
"Nonnull",
"public",
"static",
"LoadedKey",
"<",
"KeyStore",
".",
"SecretKeyEntry",
">",
"loadSecretKey",
"(",
"@",
"Nonnull",
"final",
"KeyStore",
"aKeyStore",
",",
"@",
"Nonnull",
"final",
"String",
"sKeyStorePath",
",",
"@",
"Nullable",
"final",
"String"... | Load the specified secret key entry from the provided key store.
@param aKeyStore
The key store to load the key from. May not be <code>null</code>.
@param sKeyStorePath
Key store path. For nice error messages only. May be
<code>null</code>.
@param sKeyStoreKeyAlias
The alias to be resolved in the key store. Must be non-
<code>null</code> to succeed.
@param aKeyStoreKeyPassword
The key password for the key store. Must be non-<code>null</code> to
succeed.
@return The key loading result. Never <code>null</code>. | [
"Load",
"the",
"specified",
"secret",
"key",
"entry",
"from",
"the",
"provided",
"key",
"store",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java#L360-L367 |
flow/commons | src/main/java/com/flowpowered/commons/store/block/impl/AtomicVariableWidthArray.java | AtomicVariableWidthArray.compareAndSet | public final boolean compareAndSet(int i, int expect, int update) {
if (fullWidth) {
return array.compareAndSet(i, expect, update);
}
boolean success = false;
int index = getIndex(i);
int subIndex = getSubIndex(i);
while (!success) {
int prev = array.get(index);
if (unPack(prev, subIndex) != expect) {
return false;
}
int next = pack(prev, update, subIndex);
success = array.compareAndSet(index, prev, next);
}
return true;
} | java | public final boolean compareAndSet(int i, int expect, int update) {
if (fullWidth) {
return array.compareAndSet(i, expect, update);
}
boolean success = false;
int index = getIndex(i);
int subIndex = getSubIndex(i);
while (!success) {
int prev = array.get(index);
if (unPack(prev, subIndex) != expect) {
return false;
}
int next = pack(prev, update, subIndex);
success = array.compareAndSet(index, prev, next);
}
return true;
} | [
"public",
"final",
"boolean",
"compareAndSet",
"(",
"int",
"i",
",",
"int",
"expect",
",",
"int",
"update",
")",
"{",
"if",
"(",
"fullWidth",
")",
"{",
"return",
"array",
".",
"compareAndSet",
"(",
"i",
",",
"expect",
",",
"update",
")",
";",
"}",
"b... | Sets the element at the given index, but only if the previous value was the expected value.
@param i the index
@param expect the expected value
@param update the new value
@return true on success | [
"Sets",
"the",
"element",
"at",
"the",
"given",
"index",
"but",
"only",
"if",
"the",
"previous",
"value",
"was",
"the",
"expected",
"value",
"."
] | train | https://github.com/flow/commons/blob/0690efdac06fd728fcd7e9cf10f2b1319379c45b/src/main/java/com/flowpowered/commons/store/block/impl/AtomicVariableWidthArray.java#L169-L187 |
powermock/powermock | powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java | PowerMock.createNicePartialMock | public static synchronized <T> T createNicePartialMock(Class<T> type, Class<? super T> where, String... methodNames) {
return createNiceMock(type, Whitebox.getMethods(where, methodNames));
} | java | public static synchronized <T> T createNicePartialMock(Class<T> type, Class<? super T> where, String... methodNames) {
return createNiceMock(type, Whitebox.getMethods(where, methodNames));
} | [
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"createNicePartialMock",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"Class",
"<",
"?",
"super",
"T",
">",
"where",
",",
"String",
"...",
"methodNames",
")",
"{",
"return",
"createNiceMock",
"(",
"typ... | A utility method that may be used to nicely mock several methods in an
easy way (by just passing in the method names of the method you wish to
mock). Note that you cannot uniquely specify a method to mock using this
method if there are several methods with the same name in
{@code type}. This method will mock ALL methods that match the
supplied name regardless of parameter types and signature. If this is the
case you should fall-back on using the
{@link #createMock(Class, Method...)} method instead.
<p/>
With this method you can specify where the class hierarchy the methods
are located. This is useful in, for example, situations where class A
extends B and both have a method called "mockMe" (A overrides B's mockMe
method) and you like to specify the only the "mockMe" method in B should
be mocked. "mockMe" in A should be left intact. In this case you should
do:
<p/>
<pre>
A tested = createPartialMockNice(A.class, B.class, "mockMe");
</pre>
@param <T> The type of the mock.
@param type The type that'll be used to create a mock instance.
@param where Where in the class hierarchy the methods resides.
@param methodNames The names of the methods that should be mocked. If
{@code null}, then this method will have the same effect
as just calling {@link #createMock(Class, Method...)} with the
second parameter as {@code new Method[0]} (i.e. all
methods in that class will be mocked).
@return A mock object of type <T>. | [
"A",
"utility",
"method",
"that",
"may",
"be",
"used",
"to",
"nicely",
"mock",
"several",
"methods",
"in",
"an",
"easy",
"way",
"(",
"by",
"just",
"passing",
"in",
"the",
"method",
"names",
"of",
"the",
"method",
"you",
"wish",
"to",
"mock",
")",
".",
... | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L819-L821 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java | SynchronousRequest.getCurrentDailyAchievements | public DailyAchievement getCurrentDailyAchievements() throws GuildWars2Exception {
try {
Response<DailyAchievement> response = gw2API.getCurrentDailyAchievements().execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | java | public DailyAchievement getCurrentDailyAchievements() throws GuildWars2Exception {
try {
Response<DailyAchievement> response = gw2API.getCurrentDailyAchievements().execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | [
"public",
"DailyAchievement",
"getCurrentDailyAchievements",
"(",
")",
"throws",
"GuildWars2Exception",
"{",
"try",
"{",
"Response",
"<",
"DailyAchievement",
">",
"response",
"=",
"gw2API",
".",
"getCurrentDailyAchievements",
"(",
")",
".",
"execute",
"(",
")",
";",... | For more info on achievements daily API go <a href="https://wiki.guildwars2.com/wiki/API:2/achievements/daily">here</a><br/>
Get list of current daily achievements
@return list of current daily achievements
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see DailyAchievement daily achievement info | [
"For",
"more",
"info",
"on",
"achievements",
"daily",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"achievements",
"/",
"daily",
">",
"here<",
"/",
"a",
">",
"<br... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L686-L694 |
OpenLiberty/open-liberty | dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java | AuditEvent.setTarget | public void setTarget(Map<String, Object> target) {
removeEntriesStartingWith(TARGET);
eventMap.putAll(target);
} | java | public void setTarget(Map<String, Object> target) {
removeEntriesStartingWith(TARGET);
eventMap.putAll(target);
} | [
"public",
"void",
"setTarget",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"target",
")",
"{",
"removeEntriesStartingWith",
"(",
"TARGET",
")",
";",
"eventMap",
".",
"putAll",
"(",
"target",
")",
";",
"}"
] | Set the target keys/values. The provided Map will completely replace
the existing target, i.e. all current target keys/values will be removed
and the new target keys/values will be added.
@param target - Map of all the target keys/values | [
"Set",
"the",
"target",
"keys",
"/",
"values",
".",
"The",
"provided",
"Map",
"will",
"completely",
"replace",
"the",
"existing",
"target",
"i",
".",
"e",
".",
"all",
"current",
"target",
"keys",
"/",
"values",
"will",
"be",
"removed",
"and",
"the",
"new... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java#L343-L346 |
jenkinsci/java-client-api | jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java | JenkinsServer.renameJob | public JenkinsServer renameJob(String oldJobName, String newJobName) throws IOException {
return renameJob(null, oldJobName, newJobName, false);
} | java | public JenkinsServer renameJob(String oldJobName, String newJobName) throws IOException {
return renameJob(null, oldJobName, newJobName, false);
} | [
"public",
"JenkinsServer",
"renameJob",
"(",
"String",
"oldJobName",
",",
"String",
"newJobName",
")",
"throws",
"IOException",
"{",
"return",
"renameJob",
"(",
"null",
",",
"oldJobName",
",",
"newJobName",
",",
"false",
")",
";",
"}"
] | Rename a job
@param oldJobName existing job name.
@param newJobName The new job name.
@throws IOException In case of a failure. | [
"Rename",
"a",
"job"
] | train | https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L861-L863 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java | ClassDocImpl.getClassName | static String getClassName(ClassSymbol c, boolean full) {
if (full) {
return c.getQualifiedName().toString();
} else {
String n = "";
for ( ; c != null; c = c.owner.enclClass()) {
n = c.name + (n.equals("") ? "" : ".") + n;
}
return n;
}
} | java | static String getClassName(ClassSymbol c, boolean full) {
if (full) {
return c.getQualifiedName().toString();
} else {
String n = "";
for ( ; c != null; c = c.owner.enclClass()) {
n = c.name + (n.equals("") ? "" : ".") + n;
}
return n;
}
} | [
"static",
"String",
"getClassName",
"(",
"ClassSymbol",
"c",
",",
"boolean",
"full",
")",
"{",
"if",
"(",
"full",
")",
"{",
"return",
"c",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"String",
"n",
"=",
"\"\""... | Return the class name as a string. If "full" is true the name is
qualified, otherwise it is qualified by its enclosing class(es) only. | [
"Return",
"the",
"class",
"name",
"as",
"a",
"string",
".",
"If",
"full",
"is",
"true",
"the",
"name",
"is",
"qualified",
"otherwise",
"it",
"is",
"qualified",
"by",
"its",
"enclosing",
"class",
"(",
"es",
")",
"only",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ClassDocImpl.java#L416-L426 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java | SVGPath.relativeSmoothCubicTo | public SVGPath relativeSmoothCubicTo(double[] c2xy, double[] xy) {
return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
} | java | public SVGPath relativeSmoothCubicTo(double[] c2xy, double[] xy) {
return append(PATH_SMOOTH_CUBIC_TO_RELATIVE).append(c2xy[0]).append(c2xy[1]).append(xy[0]).append(xy[1]);
} | [
"public",
"SVGPath",
"relativeSmoothCubicTo",
"(",
"double",
"[",
"]",
"c2xy",
",",
"double",
"[",
"]",
"xy",
")",
"{",
"return",
"append",
"(",
"PATH_SMOOTH_CUBIC_TO_RELATIVE",
")",
".",
"append",
"(",
"c2xy",
"[",
"0",
"]",
")",
".",
"append",
"(",
"c2... | Smooth Cubic Bezier line to the given relative coordinates.
@param c2xy second control point
@param xy new coordinates
@return path object, for compact syntax. | [
"Smooth",
"Cubic",
"Bezier",
"line",
"to",
"the",
"given",
"relative",
"coordinates",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L444-L446 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | StrBuilder.appendln | public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
} | java | public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
} | [
"public",
"StrBuilder",
"appendln",
"(",
"final",
"StringBuilder",
"str",
",",
"final",
"int",
"startIndex",
",",
"final",
"int",
"length",
")",
"{",
"return",
"append",
"(",
"str",
",",
"startIndex",
",",
"length",
")",
".",
"appendNewLine",
"(",
")",
";"... | Appends part of a string builder followed by a new line to this string builder.
Appending null will call {@link #appendNull()}.
@param str the string builder to append
@param startIndex the start index, inclusive, must be valid
@param length the length to append, must be valid
@return this, to enable chaining
@since 3.2 | [
"Appends",
"part",
"of",
"a",
"string",
"builder",
"followed",
"by",
"a",
"new",
"line",
"to",
"this",
"string",
"builder",
".",
"Appending",
"null",
"will",
"call",
"{",
"@link",
"#appendNull",
"()",
"}",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrBuilder.java#L1042-L1044 |
fabric8io/fabric8-forge | addons/utils/src/main/java/io/fabric8/forge/addon/utils/MavenHelpers.java | MavenHelpers.getVersion | public static String getVersion(String groupId, String artifactId) {
String key = "" + groupId + "/" + artifactId;
Map<String, String> map = getGroupArtifactVersionMap();
String version = map.get(key);
if (version == null) {
getLOG().warn("Could not find the version for groupId: " + groupId + " artifactId: " + artifactId + " in: " + map);
}
return version;
} | java | public static String getVersion(String groupId, String artifactId) {
String key = "" + groupId + "/" + artifactId;
Map<String, String> map = getGroupArtifactVersionMap();
String version = map.get(key);
if (version == null) {
getLOG().warn("Could not find the version for groupId: " + groupId + " artifactId: " + artifactId + " in: " + map);
}
return version;
} | [
"public",
"static",
"String",
"getVersion",
"(",
"String",
"groupId",
",",
"String",
"artifactId",
")",
"{",
"String",
"key",
"=",
"\"\"",
"+",
"groupId",
"+",
"\"/\"",
"+",
"artifactId",
";",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"getGro... | Returns the version from the list of pre-configured versions of common groupId/artifact pairs | [
"Returns",
"the",
"version",
"from",
"the",
"list",
"of",
"pre",
"-",
"configured",
"versions",
"of",
"common",
"groupId",
"/",
"artifact",
"pairs"
] | train | https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/addons/utils/src/main/java/io/fabric8/forge/addon/utils/MavenHelpers.java#L152-L160 |
apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/statemgr/SchedulerStateManagerAdaptor.java | SchedulerStateManagerAdaptor.getPackingPlan | public PackingPlans.PackingPlan getPackingPlan(String topologyName) {
return awaitResult(delegate.getPackingPlan(null, topologyName));
} | java | public PackingPlans.PackingPlan getPackingPlan(String topologyName) {
return awaitResult(delegate.getPackingPlan(null, topologyName));
} | [
"public",
"PackingPlans",
".",
"PackingPlan",
"getPackingPlan",
"(",
"String",
"topologyName",
")",
"{",
"return",
"awaitResult",
"(",
"delegate",
".",
"getPackingPlan",
"(",
"null",
",",
"topologyName",
")",
")",
";",
"}"
] | Get the packing plan for the given topology
@return PackingPlans.PackingPlan | [
"Get",
"the",
"packing",
"plan",
"for",
"the",
"given",
"topology"
] | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/statemgr/SchedulerStateManagerAdaptor.java#L302-L304 |
tango-controls/JTango | server/src/main/java/org/tango/server/servant/DeviceImpl.java | DeviceImpl.command_inout | @Override
public Any command_inout(final String command, final Any argin) throws DevFailed {
MDC.setContextMap(contextMap);
xlogger.entry();
if (!command.equalsIgnoreCase(DeviceImpl.STATE_NAME) && !command.equalsIgnoreCase(DeviceImpl.STATUS_NAME)) {
checkInitialization();
}
final long request = deviceMonitoring.startRequest("command_inout " + command);
clientIdentity.set(null);
Any argout = null;
try {
argout = commandHandler(command, argin, DevSource.CACHE_DEV, null);
} catch (final Exception e) {
deviceMonitoring.addError();
if (e instanceof DevFailed) {
throw (DevFailed) e;
} else {
// with CORBA, the stack trace is not visible by the client if
// not inserted in DevFailed.
throw DevFailedUtils.newDevFailed(e);
}
} finally {
deviceMonitoring.endRequest(request);
}
xlogger.exit();
return argout;
} | java | @Override
public Any command_inout(final String command, final Any argin) throws DevFailed {
MDC.setContextMap(contextMap);
xlogger.entry();
if (!command.equalsIgnoreCase(DeviceImpl.STATE_NAME) && !command.equalsIgnoreCase(DeviceImpl.STATUS_NAME)) {
checkInitialization();
}
final long request = deviceMonitoring.startRequest("command_inout " + command);
clientIdentity.set(null);
Any argout = null;
try {
argout = commandHandler(command, argin, DevSource.CACHE_DEV, null);
} catch (final Exception e) {
deviceMonitoring.addError();
if (e instanceof DevFailed) {
throw (DevFailed) e;
} else {
// with CORBA, the stack trace is not visible by the client if
// not inserted in DevFailed.
throw DevFailedUtils.newDevFailed(e);
}
} finally {
deviceMonitoring.endRequest(request);
}
xlogger.exit();
return argout;
} | [
"@",
"Override",
"public",
"Any",
"command_inout",
"(",
"final",
"String",
"command",
",",
"final",
"Any",
"argin",
")",
"throws",
"DevFailed",
"{",
"MDC",
".",
"setContextMap",
"(",
"contextMap",
")",
";",
"xlogger",
".",
"entry",
"(",
")",
";",
"if",
"... | Execute a command. IDL 1 version
@param command command name
@param argin command parameters
@return command result
@throws DevFailed | [
"Execute",
"a",
"command",
".",
"IDL",
"1",
"version"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/DeviceImpl.java#L1565-L1591 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPPUtility.java | MPPUtility.getDouble | public static final double getDouble(byte[] data, int offset)
{
double result = Double.longBitsToDouble(getLong(data, offset));
if (Double.isNaN(result))
{
result = 0;
}
return result;
} | java | public static final double getDouble(byte[] data, int offset)
{
double result = Double.longBitsToDouble(getLong(data, offset));
if (Double.isNaN(result))
{
result = 0;
}
return result;
} | [
"public",
"static",
"final",
"double",
"getDouble",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"{",
"double",
"result",
"=",
"Double",
".",
"longBitsToDouble",
"(",
"getLong",
"(",
"data",
",",
"offset",
")",
")",
";",
"if",
"(",
"Double... | This method reads an eight byte double from the input array.
@param data the input array
@param offset offset of double data in the array
@return double value | [
"This",
"method",
"reads",
"an",
"eight",
"byte",
"double",
"from",
"the",
"input",
"array",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPUtility.java#L256-L264 |
googlemaps/google-maps-services-java | src/main/java/com/google/maps/RoadsApi.java | RoadsApi.speedLimits | public static PendingResult<SpeedLimit[]> speedLimits(GeoApiContext context, LatLng... path) {
return context.get(SPEEDS_API_CONFIG, SpeedsResponse.class, "path", join('|', path));
} | java | public static PendingResult<SpeedLimit[]> speedLimits(GeoApiContext context, LatLng... path) {
return context.get(SPEEDS_API_CONFIG, SpeedsResponse.class, "path", join('|', path));
} | [
"public",
"static",
"PendingResult",
"<",
"SpeedLimit",
"[",
"]",
">",
"speedLimits",
"(",
"GeoApiContext",
"context",
",",
"LatLng",
"...",
"path",
")",
"{",
"return",
"context",
".",
"get",
"(",
"SPEEDS_API_CONFIG",
",",
"SpeedsResponse",
".",
"class",
",",
... | Returns the posted speed limit for given road segments. The provided LatLngs will first be
snapped to the most likely roads the vehicle was traveling along.
<p>Note: The accuracy of speed limit data returned by the Google Maps Roads API cannot be
guaranteed. Speed limit data provided is not real-time, and may be estimated, inaccurate,
incomplete, and/or outdated. Inaccuracies in our data may be reported through <a
href="https://www.localguidesconnect.com/t5/News-Updates/Exclusive-Edit-a-road-segment-in-Google-Maps/ba-p/149865">
Google Maps Feedback</a>.
@param context The {@link GeoApiContext} to make requests through.
@param path The collected GPS points as a path.
@return Returns the speed limits as a {@link PendingResult}. | [
"Returns",
"the",
"posted",
"speed",
"limit",
"for",
"given",
"road",
"segments",
".",
"The",
"provided",
"LatLngs",
"will",
"first",
"be",
"snapped",
"to",
"the",
"most",
"likely",
"roads",
"the",
"vehicle",
"was",
"traveling",
"along",
"."
] | train | https://github.com/googlemaps/google-maps-services-java/blob/23d20d1930f80e310d856d2da51d72ee0db4476b/src/main/java/com/google/maps/RoadsApi.java#L111-L113 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java | Validator.validateFalse | @SuppressWarnings("all")
public void validateFalse(boolean value, String name, String message) {
if (value) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.FALSE_KEY.name(), name)));
}
} | java | @SuppressWarnings("all")
public void validateFalse(boolean value, String name, String message) {
if (value) {
addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.FALSE_KEY.name(), name)));
}
} | [
"@",
"SuppressWarnings",
"(",
"\"all\"",
")",
"public",
"void",
"validateFalse",
"(",
"boolean",
"value",
",",
"String",
"name",
",",
"String",
"message",
")",
"{",
"if",
"(",
"value",
")",
"{",
"addError",
"(",
"name",
",",
"Optional",
".",
"ofNullable",
... | Validates a given value to be false
@param value The value to check
@param name The name of the field to display the error message
@param message A custom error message instead of the default one | [
"Validates",
"a",
"given",
"value",
"to",
"be",
"false"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L452-L457 |
mfornos/humanize | humanize-icu/src/main/java/humanize/ICUHumanize.java | ICUHumanize.formatCurrency | public static String formatCurrency(final Number value)
{
DecimalFormat decf = context.get().getCurrencyFormat();
return stripZeros(decf, decf.format(value));
} | java | public static String formatCurrency(final Number value)
{
DecimalFormat decf = context.get().getCurrencyFormat();
return stripZeros(decf, decf.format(value));
} | [
"public",
"static",
"String",
"formatCurrency",
"(",
"final",
"Number",
"value",
")",
"{",
"DecimalFormat",
"decf",
"=",
"context",
".",
"get",
"(",
")",
".",
"getCurrencyFormat",
"(",
")",
";",
"return",
"stripZeros",
"(",
"decf",
",",
"decf",
".",
"forma... | <p>
Smartly formats the given number as a monetary amount.
</p>
<p>
For en_GB:
<table border="0" cellspacing="0" cellpadding="3" width="100%">
<tr>
<th class="colFirst">Input</th>
<th class="colLast">Output</th>
</tr>
<tr>
<td>34</td>
<td>"£34"</td>
</tr>
<tr>
<td>1000</td>
<td>"£1,000"</td>
</tr>
<tr>
<td>12.5</td>
<td>"£12.50"</td>
</tr>
</table>
</p>
@param value
Number to be formatted
@return String representing the monetary amount | [
"<p",
">",
"Smartly",
"formats",
"the",
"given",
"number",
"as",
"a",
"monetary",
"amount",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-icu/src/main/java/humanize/ICUHumanize.java#L630-L634 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.println | public static void println(PrintStream self, Object value) {
self.println(InvokerHelper.toString(value));
} | java | public static void println(PrintStream self, Object value) {
self.println(InvokerHelper.toString(value));
} | [
"public",
"static",
"void",
"println",
"(",
"PrintStream",
"self",
",",
"Object",
"value",
")",
"{",
"self",
".",
"println",
"(",
"InvokerHelper",
".",
"toString",
"(",
"value",
")",
")",
";",
"}"
] | Print a value formatted Groovy style (followed by a newline) to the print stream.
@param self any Object
@param value the value to print
@since 1.6.0 | [
"Print",
"a",
"value",
"formatted",
"Groovy",
"style",
"(",
"followed",
"by",
"a",
"newline",
")",
"to",
"the",
"print",
"stream",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L825-L827 |
getlantern/kaleidoscope | src/main/java/org/kaleidoscope/LocalTrustGraph.java | LocalTrustGraph.addRoute | public void addRoute(final TrustGraphNodeId a, final TrustGraphNodeId b) {
addDirectedRoute(a,b);
addDirectedRoute(b,a);
} | java | public void addRoute(final TrustGraphNodeId a, final TrustGraphNodeId b) {
addDirectedRoute(a,b);
addDirectedRoute(b,a);
} | [
"public",
"void",
"addRoute",
"(",
"final",
"TrustGraphNodeId",
"a",
",",
"final",
"TrustGraphNodeId",
"b",
")",
"{",
"addDirectedRoute",
"(",
"a",
",",
"b",
")",
";",
"addDirectedRoute",
"(",
"b",
",",
"a",
")",
";",
"}"
] | create a bidirectional trust link between the nodes with ids 'a' and 'b'
@param a id of node that will form a trust link with 'b'
@param b id of node that will form a trust link with 'a' | [
"create",
"a",
"bidirectional",
"trust",
"link",
"between",
"the",
"nodes",
"with",
"ids",
"a",
"and",
"b"
] | train | https://github.com/getlantern/kaleidoscope/blob/7516f05724c8f54e5d535d23da9116817c08a09f/src/main/java/org/kaleidoscope/LocalTrustGraph.java#L260-L263 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/PropsCodeGen.java | PropsCodeGen.importConfigProperty | protected void importConfigProperty(Definition def, Writer out) throws IOException
{
if (getConfigProps(def).size() > 0)
{
out.write("import javax.resource.spi.ConfigProperty;\n");
}
} | java | protected void importConfigProperty(Definition def, Writer out) throws IOException
{
if (getConfigProps(def).size() > 0)
{
out.write("import javax.resource.spi.ConfigProperty;\n");
}
} | [
"protected",
"void",
"importConfigProperty",
"(",
"Definition",
"def",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"if",
"(",
"getConfigProps",
"(",
"def",
")",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"out",
".",
"write",
"(",
"\"import j... | import ConfigProperty
@param def definition
@param out Writer
@throws IOException IOException | [
"import",
"ConfigProperty"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/PropsCodeGen.java#L243-L249 |
samskivert/samskivert | src/main/java/com/samskivert/util/RandomUtil.java | RandomUtil.pickRandom | public static <T> T pickRandom (Iterator<T> iter, int count, T skip)
{
if (count < 2) {
throw new IllegalArgumentException(
"Must have at least two elements [count=" + count + "]");
}
int index = getInt(count-1);
T value = null;
do {
value = iter.next();
if (value == skip) {
value = iter.next();
}
} while (index-- > 0);
return value;
} | java | public static <T> T pickRandom (Iterator<T> iter, int count, T skip)
{
if (count < 2) {
throw new IllegalArgumentException(
"Must have at least two elements [count=" + count + "]");
}
int index = getInt(count-1);
T value = null;
do {
value = iter.next();
if (value == skip) {
value = iter.next();
}
} while (index-- > 0);
return value;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"pickRandom",
"(",
"Iterator",
"<",
"T",
">",
"iter",
",",
"int",
"count",
",",
"T",
"skip",
")",
"{",
"if",
"(",
"count",
"<",
"2",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Must have at leas... | Picks a random object from the supplied iterator (which must iterate over exactly
<code>count</code> objects. The specified skip object will be skipped when selecting a
random value. The skipped object must exist exactly once in the set of objects returned by
the iterator.
@return a randomly selected item.
@exception NoSuchElementException thrown if the iterator provides fewer than
<code>count</code> elements. | [
"Picks",
"a",
"random",
"object",
"from",
"the",
"supplied",
"iterator",
"(",
"which",
"must",
"iterate",
"over",
"exactly",
"<code",
">",
"count<",
"/",
"code",
">",
"objects",
".",
"The",
"specified",
"skip",
"object",
"will",
"be",
"skipped",
"when",
"s... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/RandomUtil.java#L430-L446 |
jenkinsci/jenkins | core/src/main/java/hudson/security/csrf/CrumbIssuer.java | CrumbIssuer.validateCrumb | public boolean validateCrumb(ServletRequest request) {
CrumbIssuerDescriptor<CrumbIssuer> desc = getDescriptor();
String crumbField = desc.getCrumbRequestField();
String crumbSalt = desc.getCrumbSalt();
return validateCrumb(request, crumbSalt, request.getParameter(crumbField));
} | java | public boolean validateCrumb(ServletRequest request) {
CrumbIssuerDescriptor<CrumbIssuer> desc = getDescriptor();
String crumbField = desc.getCrumbRequestField();
String crumbSalt = desc.getCrumbSalt();
return validateCrumb(request, crumbSalt, request.getParameter(crumbField));
} | [
"public",
"boolean",
"validateCrumb",
"(",
"ServletRequest",
"request",
")",
"{",
"CrumbIssuerDescriptor",
"<",
"CrumbIssuer",
">",
"desc",
"=",
"getDescriptor",
"(",
")",
";",
"String",
"crumbField",
"=",
"desc",
".",
"getCrumbRequestField",
"(",
")",
";",
"Str... | Get a crumb from a request parameter and validate it against other data
in the current request. The salt and request parameter that is used is
defined by the current configuration.
@param request | [
"Get",
"a",
"crumb",
"from",
"a",
"request",
"parameter",
"and",
"validate",
"it",
"against",
"other",
"data",
"in",
"the",
"current",
"request",
".",
"The",
"salt",
"and",
"request",
"parameter",
"that",
"is",
"used",
"is",
"defined",
"by",
"the",
"curren... | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/csrf/CrumbIssuer.java#L115-L121 |
syphr42/prom | src/main/java/org/syphr/prom/PropertiesManagers.java | PropertiesManagers.newManager | public static <T extends Enum<T> & Defaultable> PropertiesManager<T> newManager(File file,
Class<T> keyType,
Evaluator evaluator,
ExecutorService executor,
final Retriever... retrievers)
{
Translator<T> translator = getEnumTranslator(keyType);
return new PropertiesManager<T>(file,
getDefaultProperties(keyType, translator),
translator,
evaluator,
executor)
{
@Override
protected Retriever createRetriever()
{
return new AddOnRetriever(true, super.createRetriever(), retrievers);
}
};
} | java | public static <T extends Enum<T> & Defaultable> PropertiesManager<T> newManager(File file,
Class<T> keyType,
Evaluator evaluator,
ExecutorService executor,
final Retriever... retrievers)
{
Translator<T> translator = getEnumTranslator(keyType);
return new PropertiesManager<T>(file,
getDefaultProperties(keyType, translator),
translator,
evaluator,
executor)
{
@Override
protected Retriever createRetriever()
{
return new AddOnRetriever(true, super.createRetriever(), retrievers);
}
};
} | [
"public",
"static",
"<",
"T",
"extends",
"Enum",
"<",
"T",
">",
"&",
"Defaultable",
">",
"PropertiesManager",
"<",
"T",
">",
"newManager",
"(",
"File",
"file",
",",
"Class",
"<",
"T",
">",
"keyType",
",",
"Evaluator",
"evaluator",
",",
"ExecutorService",
... | Build a new manager for the given properties file.
@param <T>
the type of key used for the new manager
@param file
the file system location of the properties represented here
@param keyType
the enumeration of keys in the properties file
@param evaluator
the evaluator to convert nested property references into fully
evaluated strings
@param executor
a service to handle potentially long running tasks, such as
interacting with the file system
@param retrievers
a set of retrievers that will be used to resolve extra
property references (i.e. if a nested value reference is found
in a properties file and there is no property to match it, the
given retrievers will be used)
@return a new manager | [
"Build",
"a",
"new",
"manager",
"for",
"the",
"given",
"properties",
"file",
"."
] | train | https://github.com/syphr42/prom/blob/074d67c4ebb3afb0b163fcb0bc4826ee577ac803/src/main/java/org/syphr/prom/PropertiesManagers.java#L329-L349 |
micronaut-projects/micronaut-core | router/src/main/java/io/micronaut/web/router/DefaultRouteBuilder.java | DefaultRouteBuilder.buildRoute | protected UriRoute buildRoute(HttpMethod httpMethod, String uri, Class<?> type, String method, Class... parameterTypes) {
Optional<? extends MethodExecutionHandle<?, Object>> executionHandle = executionHandleLocator.findExecutionHandle(type, method, parameterTypes);
MethodExecutionHandle<?, Object> executableHandle = executionHandle.orElseThrow(() ->
new RoutingException("No such route: " + type.getName() + "." + method)
);
return buildRoute(httpMethod, uri, executableHandle);
} | java | protected UriRoute buildRoute(HttpMethod httpMethod, String uri, Class<?> type, String method, Class... parameterTypes) {
Optional<? extends MethodExecutionHandle<?, Object>> executionHandle = executionHandleLocator.findExecutionHandle(type, method, parameterTypes);
MethodExecutionHandle<?, Object> executableHandle = executionHandle.orElseThrow(() ->
new RoutingException("No such route: " + type.getName() + "." + method)
);
return buildRoute(httpMethod, uri, executableHandle);
} | [
"protected",
"UriRoute",
"buildRoute",
"(",
"HttpMethod",
"httpMethod",
",",
"String",
"uri",
",",
"Class",
"<",
"?",
">",
"type",
",",
"String",
"method",
",",
"Class",
"...",
"parameterTypes",
")",
"{",
"Optional",
"<",
"?",
"extends",
"MethodExecutionHandle... | Build a route.
@param httpMethod The HTTP method
@param uri The URI
@param type The type
@param method The method
@param parameterTypes Parameters
@return an {@link UriRoute} | [
"Build",
"a",
"route",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/router/src/main/java/io/micronaut/web/router/DefaultRouteBuilder.java#L376-L384 |
Hygieia/Hygieia | collectors/build/bamboo/src/main/java/com/capitalone/dashboard/collector/DefaultBambooClient.java | DefaultBambooClient.addChangeSets | private void addChangeSets(Build build, JSONObject buildJson) {
JSONObject changeSet = (JSONObject) buildJson.get("changes");
// Map<String, String> revisionToUrl = new HashMap<>();
// // Build a map of revision to module (scm url). This is not always
// // provided by the Bamboo API, but we can use it if available.
// for (Object revision : getJsonArray(changeSet, "revisions")) {
// JSONObject json = (JSONObject) revision;
// revisionToUrl.put(json.get("revision").toString(), getString(json, "module"));
// }
for (Object item : getJsonArray(changeSet, "change")) {
JSONObject jsonItem = (JSONObject) item;
SCM scm = new SCM();
scm.setScmAuthor(getString(jsonItem, "author"));
scm.setScmCommitLog(getString(jsonItem, "comment"));
scm.setScmCommitTimestamp(getCommitTimestamp(jsonItem));
scm.setScmRevisionNumber(getRevision(jsonItem));
scm.setScmUrl(getString(jsonItem,"commitUrl"));
scm.setNumberOfChanges(getJsonArray((JSONObject)jsonItem.get("files"), "file").size());
build.getSourceChangeSet().add(scm);
}
} | java | private void addChangeSets(Build build, JSONObject buildJson) {
JSONObject changeSet = (JSONObject) buildJson.get("changes");
// Map<String, String> revisionToUrl = new HashMap<>();
// // Build a map of revision to module (scm url). This is not always
// // provided by the Bamboo API, but we can use it if available.
// for (Object revision : getJsonArray(changeSet, "revisions")) {
// JSONObject json = (JSONObject) revision;
// revisionToUrl.put(json.get("revision").toString(), getString(json, "module"));
// }
for (Object item : getJsonArray(changeSet, "change")) {
JSONObject jsonItem = (JSONObject) item;
SCM scm = new SCM();
scm.setScmAuthor(getString(jsonItem, "author"));
scm.setScmCommitLog(getString(jsonItem, "comment"));
scm.setScmCommitTimestamp(getCommitTimestamp(jsonItem));
scm.setScmRevisionNumber(getRevision(jsonItem));
scm.setScmUrl(getString(jsonItem,"commitUrl"));
scm.setNumberOfChanges(getJsonArray((JSONObject)jsonItem.get("files"), "file").size());
build.getSourceChangeSet().add(scm);
}
} | [
"private",
"void",
"addChangeSets",
"(",
"Build",
"build",
",",
"JSONObject",
"buildJson",
")",
"{",
"JSONObject",
"changeSet",
"=",
"(",
"JSONObject",
")",
"buildJson",
".",
"get",
"(",
"\"changes\"",
")",
";",
"// Map<String, String> revisionToUrl = new HashM... | Grabs changeset information for the given build.
@param build a Build
@param buildJson the build JSON object | [
"Grabs",
"changeset",
"information",
"for",
"the",
"given",
"build",
"."
] | train | https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/build/bamboo/src/main/java/com/capitalone/dashboard/collector/DefaultBambooClient.java#L275-L298 |
Bedework/bw-util | bw-util-misc/src/main/java/org/bedework/util/misc/Util.java | Util.compareStrings | public static int compareStrings(final String s1, final String s2) {
if (s1 == null) {
if (s2 != null) {
return -1;
}
return 0;
}
if (s2 == null) {
return 1;
}
return s1.compareTo(s2);
} | java | public static int compareStrings(final String s1, final String s2) {
if (s1 == null) {
if (s2 != null) {
return -1;
}
return 0;
}
if (s2 == null) {
return 1;
}
return s1.compareTo(s2);
} | [
"public",
"static",
"int",
"compareStrings",
"(",
"final",
"String",
"s1",
",",
"final",
"String",
"s2",
")",
"{",
"if",
"(",
"s1",
"==",
"null",
")",
"{",
"if",
"(",
"s2",
"!=",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"0",
";",... | Compare two strings. null is less than any non-null string.
@param s1 first string.
@param s2 second string.
@return int 0 if the s1 is equal to s2;
<0 if s1 is lexicographically less than s2;
>0 if s1 is lexicographically greater than s2. | [
"Compare",
"two",
"strings",
".",
"null",
"is",
"less",
"than",
"any",
"non",
"-",
"null",
"string",
"."
] | train | https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-misc/src/main/java/org/bedework/util/misc/Util.java#L643-L657 |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPageLayout.java | WebPageLayout.printSearchOutput | public void printSearchOutput(WebPage page, ChainWriter out, WebSiteRequest req, HttpServletResponse resp, String query, boolean isEntireSite, List<SearchResult> results, String[] words) throws IOException, SQLException {
startContent(out, req, resp, 1, 600);
printContentTitle(out, req, resp, "Search Results", 1);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
beginLightArea(req, resp, out, "300", true);
out.print(" <form action='' id='search_two' method='post'>\n");
req.printFormFields(out, 4);
out.print(" <table cellspacing='0' cellpadding='0'><tr><td style='white-space:nowrap'>\n"
+ " Word(s) to search for: <input type='text' size='24' name='search_query' value='").encodeXmlAttribute(query).print("' /><br />\n"
+ " Search Location: <input type='radio' name='search_target' value='entire_site'");
if(isEntireSite) out.print(" checked='checked'");
out.print(" /> Entire Site   <input type='radio' name='search_target' value='this_area'");
if(!isEntireSite) out.print(" checked='checked'");
out.print(" /> This Area<br />\n"
+ " <br />\n"
+ " <div style='text-align:center'><input type='submit' class='ao_button' value=' Search ' /></div>\n"
+ " </td></tr></table>\n"
+ " </form>\n"
);
endLightArea(req, resp, out);
endContentLine(out, req, resp, 1, false);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
if (results.isEmpty()) {
if (words.length > 0) {
out.print(
" <b>No matches found</b>\n"
);
}
} else {
beginLightArea(req, resp, out);
out.print(" <table cellspacing='0' cellpadding='0' class='aoLightRow'>\n"
+ " <tr>\n"
+ " <th style='white-space:nowrap'>% Match</th>\n"
+ " <th style='white-space:nowrap'>Title</th>\n"
+ " <th style='white-space:nowrap'> </th>\n"
+ " <th style='white-space:nowrap'>Description</th>\n"
+ " </tr>\n"
);
// Find the highest probability
float highest = results.get(0).getProbability();
// Display the results
int size = results.size();
for (int c = 0; c < size; c++) {
String rowClass= (c & 1) == 0 ? "aoLightRow":"aoDarkRow";
String linkClass = (c & 1) == 0 ? "aoDarkLink":"aoLightLink";
SearchResult result = results.get(c);
String url=result.getUrl();
String title=result.getTitle();
String description=result.getDescription();
out.print(" <tr class='").print(rowClass).print("'>\n"
+ " <td style='white-space:nowrap; text-align:center;'>").print(Math.round(99 * result.getProbability() / highest)).print("%</td>\n"
+ " <td style='white-space:nowrap'><a class='"+linkClass+"' href='").encodeXmlAttribute(resp.encodeURL(url)).print("'>").print(title.length()==0?" ":title).print("</a></td>\n"
+ " <td style='white-space:nowrap'>   </td>\n"
+ " <td style='white-space:nowrap'>").print(description.length()==0?" ":description).print("</td>\n"
+ " </tr>\n");
}
out.print(
" </table>\n"
);
endLightArea(req, resp, out);
}
endContentLine(out, req, resp, 1, false);
endContent(page, out, req, resp, 1);
} | java | public void printSearchOutput(WebPage page, ChainWriter out, WebSiteRequest req, HttpServletResponse resp, String query, boolean isEntireSite, List<SearchResult> results, String[] words) throws IOException, SQLException {
startContent(out, req, resp, 1, 600);
printContentTitle(out, req, resp, "Search Results", 1);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
beginLightArea(req, resp, out, "300", true);
out.print(" <form action='' id='search_two' method='post'>\n");
req.printFormFields(out, 4);
out.print(" <table cellspacing='0' cellpadding='0'><tr><td style='white-space:nowrap'>\n"
+ " Word(s) to search for: <input type='text' size='24' name='search_query' value='").encodeXmlAttribute(query).print("' /><br />\n"
+ " Search Location: <input type='radio' name='search_target' value='entire_site'");
if(isEntireSite) out.print(" checked='checked'");
out.print(" /> Entire Site   <input type='radio' name='search_target' value='this_area'");
if(!isEntireSite) out.print(" checked='checked'");
out.print(" /> This Area<br />\n"
+ " <br />\n"
+ " <div style='text-align:center'><input type='submit' class='ao_button' value=' Search ' /></div>\n"
+ " </td></tr></table>\n"
+ " </form>\n"
);
endLightArea(req, resp, out);
endContentLine(out, req, resp, 1, false);
printContentHorizontalDivider(out, req, resp, 1, false);
startContentLine(out, req, resp, 1, "center", null);
if (results.isEmpty()) {
if (words.length > 0) {
out.print(
" <b>No matches found</b>\n"
);
}
} else {
beginLightArea(req, resp, out);
out.print(" <table cellspacing='0' cellpadding='0' class='aoLightRow'>\n"
+ " <tr>\n"
+ " <th style='white-space:nowrap'>% Match</th>\n"
+ " <th style='white-space:nowrap'>Title</th>\n"
+ " <th style='white-space:nowrap'> </th>\n"
+ " <th style='white-space:nowrap'>Description</th>\n"
+ " </tr>\n"
);
// Find the highest probability
float highest = results.get(0).getProbability();
// Display the results
int size = results.size();
for (int c = 0; c < size; c++) {
String rowClass= (c & 1) == 0 ? "aoLightRow":"aoDarkRow";
String linkClass = (c & 1) == 0 ? "aoDarkLink":"aoLightLink";
SearchResult result = results.get(c);
String url=result.getUrl();
String title=result.getTitle();
String description=result.getDescription();
out.print(" <tr class='").print(rowClass).print("'>\n"
+ " <td style='white-space:nowrap; text-align:center;'>").print(Math.round(99 * result.getProbability() / highest)).print("%</td>\n"
+ " <td style='white-space:nowrap'><a class='"+linkClass+"' href='").encodeXmlAttribute(resp.encodeURL(url)).print("'>").print(title.length()==0?" ":title).print("</a></td>\n"
+ " <td style='white-space:nowrap'>   </td>\n"
+ " <td style='white-space:nowrap'>").print(description.length()==0?" ":description).print("</td>\n"
+ " </tr>\n");
}
out.print(
" </table>\n"
);
endLightArea(req, resp, out);
}
endContentLine(out, req, resp, 1, false);
endContent(page, out, req, resp, 1);
} | [
"public",
"void",
"printSearchOutput",
"(",
"WebPage",
"page",
",",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"String",
"query",
",",
"boolean",
"isEntireSite",
",",
"List",
"<",
"SearchResult",
">",
"results",
... | Prints the content HTML that shows the output of a search. This output must include an
additional search form named <code>"search_two"</code>, with two fields named
<code>"search_query"</code> and <code>"search_target"</code>.
@see WebPage#doPostWithSearch(WebSiteRequest,HttpServletResponse) | [
"Prints",
"the",
"content",
"HTML",
"that",
"shows",
"the",
"output",
"of",
"a",
"search",
".",
"This",
"output",
"must",
"include",
"an",
"additional",
"search",
"form",
"named",
"<code",
">",
"search_two",
"<",
"/",
"code",
">",
"with",
"two",
"fields",
... | train | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPageLayout.java#L93-L160 |
google/flogger | api/src/main/java/com/google/common/flogger/backend/system/DefaultPlatform.java | DefaultPlatform.resolveAttribute | @Nullable
private static <T> T resolveAttribute(String attributeName, Class<T> type) {
String getter = readProperty(attributeName);
if (getter == null) {
return null;
}
int idx = getter.indexOf('#');
if (idx <= 0 || idx == getter.length() - 1) {
error("invalid getter (expected <class>#<method>): %s\n", getter);
return null;
}
return callStaticMethod(getter.substring(0, idx), getter.substring(idx + 1), type);
} | java | @Nullable
private static <T> T resolveAttribute(String attributeName, Class<T> type) {
String getter = readProperty(attributeName);
if (getter == null) {
return null;
}
int idx = getter.indexOf('#');
if (idx <= 0 || idx == getter.length() - 1) {
error("invalid getter (expected <class>#<method>): %s\n", getter);
return null;
}
return callStaticMethod(getter.substring(0, idx), getter.substring(idx + 1), type);
} | [
"@",
"Nullable",
"private",
"static",
"<",
"T",
">",
"T",
"resolveAttribute",
"(",
"String",
"attributeName",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"String",
"getter",
"=",
"readProperty",
"(",
"attributeName",
")",
";",
"if",
"(",
"getter",
"==... | Helper to call a static no-arg getter to obtain an instance of a specified type. This is used
for platform aspects which are optional, but are expected to have a singleton available.
@return the return value of the specified static no-argument method, or null if the method
cannot be called or the returned value is of the wrong type. | [
"Helper",
"to",
"call",
"a",
"static",
"no",
"-",
"arg",
"getter",
"to",
"obtain",
"an",
"instance",
"of",
"a",
"specified",
"type",
".",
"This",
"is",
"used",
"for",
"platform",
"aspects",
"which",
"are",
"optional",
"but",
"are",
"expected",
"to",
"hav... | train | https://github.com/google/flogger/blob/a164967a93a9f4ce92f34319fc0cc7c91a57321c/api/src/main/java/com/google/common/flogger/backend/system/DefaultPlatform.java#L122-L134 |
googleads/googleads-java-lib | examples/adwords_axis/src/main/java/adwords/axis/v201809/misc/GetAllImageAssets.java | GetAllImageAssets.runExample | public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws RemoteException {
// Get the AdGroupAdService.
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
int offset = 0;
boolean morePages = true;
// Create the selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector =
builder
.fields(
AssetField.AssetName,
AssetField.AssetStatus,
AssetField.ImageFileSize,
AssetField.ImageWidth,
AssetField.ImageHeight,
AssetField.ImageFullSizeUrl)
.offset(offset)
.limit(PAGE_SIZE)
// Filter for image assets only.
.equals(AssetField.AssetSubtype, AssetType.IMAGE.getValue())
.build();
int totalEntries = 0;
while (morePages) {
// Get the image assets.
AssetPage page = assetService.get(selector);
// Display the results.
if (page.getEntries() != null && page.getEntries().length > 0) {
totalEntries = page.getTotalNumEntries();
int i = selector.getPaging().getStartIndex();
for (Asset asset : page.getEntries()) {
System.out.printf(
"%d) Image asset with ID %d, name '%s', and status '%s' was found.%n",
i, asset.getAssetId(), asset.getAssetName(), asset.getAssetStatus());
}
}
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
morePages = offset < page.getTotalNumEntries();
}
System.out.printf("Found %d image assets.%n", totalEntries);
} | java | public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws RemoteException {
// Get the AdGroupAdService.
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
int offset = 0;
boolean morePages = true;
// Create the selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector =
builder
.fields(
AssetField.AssetName,
AssetField.AssetStatus,
AssetField.ImageFileSize,
AssetField.ImageWidth,
AssetField.ImageHeight,
AssetField.ImageFullSizeUrl)
.offset(offset)
.limit(PAGE_SIZE)
// Filter for image assets only.
.equals(AssetField.AssetSubtype, AssetType.IMAGE.getValue())
.build();
int totalEntries = 0;
while (morePages) {
// Get the image assets.
AssetPage page = assetService.get(selector);
// Display the results.
if (page.getEntries() != null && page.getEntries().length > 0) {
totalEntries = page.getTotalNumEntries();
int i = selector.getPaging().getStartIndex();
for (Asset asset : page.getEntries()) {
System.out.printf(
"%d) Image asset with ID %d, name '%s', and status '%s' was found.%n",
i, asset.getAssetId(), asset.getAssetName(), asset.getAssetStatus());
}
}
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
morePages = offset < page.getTotalNumEntries();
}
System.out.printf("Found %d image assets.%n", totalEntries);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdWordsServicesInterface",
"adWordsServices",
",",
"AdWordsSession",
"session",
")",
"throws",
"RemoteException",
"{",
"// Get the AdGroupAdService.",
"AssetServiceInterface",
"assetService",
"=",
"adWordsServices",
".",
"get",
... | Runs the example.
@param adWordsServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/adwords_axis/src/main/java/adwords/axis/v201809/misc/GetAllImageAssets.java#L108-L155 |
jhy/jsoup | src/main/java/org/jsoup/nodes/Document.java | Document.createElement | public Element createElement(String tagName) {
return new Element(Tag.valueOf(tagName, ParseSettings.preserveCase), this.baseUri());
} | java | public Element createElement(String tagName) {
return new Element(Tag.valueOf(tagName, ParseSettings.preserveCase), this.baseUri());
} | [
"public",
"Element",
"createElement",
"(",
"String",
"tagName",
")",
"{",
"return",
"new",
"Element",
"(",
"Tag",
".",
"valueOf",
"(",
"tagName",
",",
"ParseSettings",
".",
"preserveCase",
")",
",",
"this",
".",
"baseUri",
"(",
")",
")",
";",
"}"
] | Create a new Element, with this document's base uri. Does not make the new element a child of this document.
@param tagName element tag name (e.g. {@code a})
@return new element | [
"Create",
"a",
"new",
"Element",
"with",
"this",
"document",
"s",
"base",
"uri",
".",
"Does",
"not",
"make",
"the",
"new",
"element",
"a",
"child",
"of",
"this",
"document",
"."
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/Document.java#L109-L111 |
grails/grails-core | grails-core/src/main/groovy/grails/util/GrailsMetaClassUtils.java | GrailsMetaClassUtils.invokeMethodIfExists | public static Object invokeMethodIfExists(Object instance, String methodName, Object[] args) {
MetaClass metaClass = getMetaClass(instance);
List<MetaMethod> methodList = metaClass.respondsTo(instance, methodName, args);
if (methodList != null && !methodList.isEmpty()) {
return metaClass.invokeMethod(instance, methodName, args);
}
return null;
} | java | public static Object invokeMethodIfExists(Object instance, String methodName, Object[] args) {
MetaClass metaClass = getMetaClass(instance);
List<MetaMethod> methodList = metaClass.respondsTo(instance, methodName, args);
if (methodList != null && !methodList.isEmpty()) {
return metaClass.invokeMethod(instance, methodName, args);
}
return null;
} | [
"public",
"static",
"Object",
"invokeMethodIfExists",
"(",
"Object",
"instance",
",",
"String",
"methodName",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"MetaClass",
"metaClass",
"=",
"getMetaClass",
"(",
"instance",
")",
";",
"List",
"<",
"MetaMethod",
">",
... | Invokes a method if it exists otherwise returns null
@param instance The instance
@param methodName The method name
@param args The arguments
@return The result of the method call or null | [
"Invokes",
"a",
"method",
"if",
"it",
"exists",
"otherwise",
"returns",
"null"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsMetaClassUtils.java#L241-L248 |
networknt/light-4j | dump/src/main/java/com/networknt/dump/RootDumper.java | RootDumper.dumpResponse | public void dumpResponse(Map<String, Object> result) {
if(!dumpConfig.isResponseEnabled()) { return; }
Map<String, Object> responseResult = new LinkedHashMap<>();
for(IResponseDumpable dumper: dumperFactory.createResponseDumpers(dumpConfig, exchange)) {
if (dumper.isApplicableForResponse()) {
dumper.dumpResponse(responseResult);
}
}
result.put(DumpConstants.RESPONSE, responseResult);
} | java | public void dumpResponse(Map<String, Object> result) {
if(!dumpConfig.isResponseEnabled()) { return; }
Map<String, Object> responseResult = new LinkedHashMap<>();
for(IResponseDumpable dumper: dumperFactory.createResponseDumpers(dumpConfig, exchange)) {
if (dumper.isApplicableForResponse()) {
dumper.dumpResponse(responseResult);
}
}
result.put(DumpConstants.RESPONSE, responseResult);
} | [
"public",
"void",
"dumpResponse",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"result",
")",
"{",
"if",
"(",
"!",
"dumpConfig",
".",
"isResponseEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"Map",
"<",
"String",
",",
"Object",
">",
"responseResu... | create dumpers that can dump http response info, and put http response info into Map<String, Object> result
@param result a Map<String, Object> to put http response info to | [
"create",
"dumpers",
"that",
"can",
"dump",
"http",
"response",
"info",
"and",
"put",
"http",
"response",
"info",
"into",
"Map<String",
"Object",
">",
"result"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/dump/src/main/java/com/networknt/dump/RootDumper.java#L59-L69 |
spotify/helios | helios-client/src/main/java/com/spotify/helios/common/JobValidator.java | JobValidator.validateJobImage | private Set<String> validateJobImage(final String image) {
final Set<String> errors = Sets.newHashSet();
if (image == null) {
errors.add("Image was not specified.");
} else {
// Validate image name
validateImageReference(image, errors);
}
return errors;
} | java | private Set<String> validateJobImage(final String image) {
final Set<String> errors = Sets.newHashSet();
if (image == null) {
errors.add("Image was not specified.");
} else {
// Validate image name
validateImageReference(image, errors);
}
return errors;
} | [
"private",
"Set",
"<",
"String",
">",
"validateJobImage",
"(",
"final",
"String",
"image",
")",
"{",
"final",
"Set",
"<",
"String",
">",
"errors",
"=",
"Sets",
".",
"newHashSet",
"(",
")",
";",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"errors",
".... | Validate the Job's image by checking it's not null or empty and has the right format.
@param image The image String
@return A set of error Strings | [
"Validate",
"the",
"Job",
"s",
"image",
"by",
"checking",
"it",
"s",
"not",
"null",
"or",
"empty",
"and",
"has",
"the",
"right",
"format",
"."
] | train | https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-client/src/main/java/com/spotify/helios/common/JobValidator.java#L235-L246 |
openengsb/openengsb | components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/Diff.java | Diff.addNewObjects | private void addNewObjects(List<EDBObject> tempList) {
for (EDBObject b : tempList) {
String oid = b.getOID();
ObjectDiff odiff = new ObjectDiff(this.startCommit, this.endCommit, null, b);
if (odiff.getDifferenceCount() > 0) {
diff.put(oid, odiff);
}
}
} | java | private void addNewObjects(List<EDBObject> tempList) {
for (EDBObject b : tempList) {
String oid = b.getOID();
ObjectDiff odiff = new ObjectDiff(this.startCommit, this.endCommit, null, b);
if (odiff.getDifferenceCount() > 0) {
diff.put(oid, odiff);
}
}
} | [
"private",
"void",
"addNewObjects",
"(",
"List",
"<",
"EDBObject",
">",
"tempList",
")",
"{",
"for",
"(",
"EDBObject",
"b",
":",
"tempList",
")",
"{",
"String",
"oid",
"=",
"b",
".",
"getOID",
"(",
")",
";",
"ObjectDiff",
"odiff",
"=",
"new",
"ObjectDi... | add all new object to the diff collection. As base to indicate if an object is new, the list of elements from the
end state which are left is taken. | [
"add",
"all",
"new",
"object",
"to",
"the",
"diff",
"collection",
".",
"As",
"base",
"to",
"indicate",
"if",
"an",
"object",
"is",
"new",
"the",
"list",
"of",
"elements",
"from",
"the",
"end",
"state",
"which",
"are",
"left",
"is",
"taken",
"."
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/Diff.java#L93-L101 |
spotbugs/spotbugs | eclipsePlugin/src/edu/umd/cs/findbugs/plugin/eclipse/quickfix/util/ASTUtil.java | ASTUtil.getTypeDeclaration | public static TypeDeclaration getTypeDeclaration(CompilationUnit compilationUnit, ClassAnnotation classAnno)
throws TypeDeclarationNotFoundException {
requireNonNull(classAnno, "class annotation");
return getTypeDeclaration(compilationUnit, classAnno.getClassName());
} | java | public static TypeDeclaration getTypeDeclaration(CompilationUnit compilationUnit, ClassAnnotation classAnno)
throws TypeDeclarationNotFoundException {
requireNonNull(classAnno, "class annotation");
return getTypeDeclaration(compilationUnit, classAnno.getClassName());
} | [
"public",
"static",
"TypeDeclaration",
"getTypeDeclaration",
"(",
"CompilationUnit",
"compilationUnit",
",",
"ClassAnnotation",
"classAnno",
")",
"throws",
"TypeDeclarationNotFoundException",
"{",
"requireNonNull",
"(",
"classAnno",
",",
"\"class annotation\"",
")",
";",
"r... | Returns the <CODE>TypeDeclaration</CODE> for the specified
<CODE>ClassAnnotation</CODE>. The type has to be declared in the
specified <CODE>CompilationUnit</CODE>.
@param compilationUnit
The <CODE>CompilationUnit</CODE>, where the
<CODE>TypeDeclaration</CODE> is declared in.
@param classAnno
The <CODE>ClassAnnotation</CODE>, which contains the class
name of the <CODE>TypeDeclaration</CODE>.
@return the <CODE>TypeDeclaration</CODE> found in the specified
<CODE>CompilationUnit</CODE>.
@throws TypeDeclarationNotFoundException
if no matching <CODE>TypeDeclaration</CODE> was found. | [
"Returns",
"the",
"<CODE",
">",
"TypeDeclaration<",
"/",
"CODE",
">",
"for",
"the",
"specified",
"<CODE",
">",
"ClassAnnotation<",
"/",
"CODE",
">",
".",
"The",
"type",
"has",
"to",
"be",
"declared",
"in",
"the",
"specified",
"<CODE",
">",
"CompilationUnit<"... | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/edu/umd/cs/findbugs/plugin/eclipse/quickfix/util/ASTUtil.java#L228-L232 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/MemcachedClient.java | MemcachedClient.asyncGets | @Override
public OperationFuture<CASValue<Object>> asyncGets(final String key) {
return asyncGets(key, transcoder);
} | java | @Override
public OperationFuture<CASValue<Object>> asyncGets(final String key) {
return asyncGets(key, transcoder);
} | [
"@",
"Override",
"public",
"OperationFuture",
"<",
"CASValue",
"<",
"Object",
">",
">",
"asyncGets",
"(",
"final",
"String",
"key",
")",
"{",
"return",
"asyncGets",
"(",
"key",
",",
"transcoder",
")",
";",
"}"
] | Gets (with CAS support) the given key asynchronously and decode using the
default transcoder.
@param key the key to fetch
@return a future that will hold the return value of the fetch
@throws IllegalStateException in the rare circumstance where queue is too
full to accept any more requests | [
"Gets",
"(",
"with",
"CAS",
"support",
")",
"the",
"given",
"key",
"asynchronously",
"and",
"decode",
"using",
"the",
"default",
"transcoder",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedClient.java#L1116-L1119 |
facebookarchive/hadoop-20 | src/contrib/corona/src/java/org/apache/hadoop/corona/Utilities.java | Utilities.removeReference | public static Object removeReference(List l, Object o) {
Iterator iter = l.iterator();
while (iter.hasNext()) {
Object no = iter.next();
if (no == o) {
iter.remove();
return o;
}
}
return null;
} | java | public static Object removeReference(List l, Object o) {
Iterator iter = l.iterator();
while (iter.hasNext()) {
Object no = iter.next();
if (no == o) {
iter.remove();
return o;
}
}
return null;
} | [
"public",
"static",
"Object",
"removeReference",
"(",
"List",
"l",
",",
"Object",
"o",
")",
"{",
"Iterator",
"iter",
"=",
"l",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"Object",
"no",
"=",
"iter",
".... | Remove the object o from the list l. Different from l.remove(o)
because this method only removes it if it is the same object
@param l the list to remove from
@param o the object to remove
@return removed object if it was found in the list, null otherwise | [
"Remove",
"the",
"object",
"o",
"from",
"the",
"list",
"l",
".",
"Different",
"from",
"l",
".",
"remove",
"(",
"o",
")",
"because",
"this",
"method",
"only",
"removes",
"it",
"if",
"it",
"is",
"the",
"same",
"object"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/Utilities.java#L112-L122 |
intendia-oss/rxjava-gwt | src/main/modified/io/reactivex/super/io/reactivex/Flowable.java | Flowable.repeatWhen | @CheckReturnValue
@BackpressureSupport(BackpressureKind.FULL)
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? extends Publisher<?>> handler) {
ObjectHelper.requireNonNull(handler, "handler is null");
return RxJavaPlugins.onAssembly(new FlowableRepeatWhen<T>(this, handler));
} | java | @CheckReturnValue
@BackpressureSupport(BackpressureKind.FULL)
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> repeatWhen(final Function<? super Flowable<Object>, ? extends Publisher<?>> handler) {
ObjectHelper.requireNonNull(handler, "handler is null");
return RxJavaPlugins.onAssembly(new FlowableRepeatWhen<T>(this, handler));
} | [
"@",
"CheckReturnValue",
"@",
"BackpressureSupport",
"(",
"BackpressureKind",
".",
"FULL",
")",
"@",
"SchedulerSupport",
"(",
"SchedulerSupport",
".",
"NONE",
")",
"public",
"final",
"Flowable",
"<",
"T",
">",
"repeatWhen",
"(",
"final",
"Function",
"<",
"?",
... | Returns a Flowable that emits the same values as the source Publisher with the exception of an
{@code onComplete}. An {@code onComplete} notification from the source will result in the emission of
a {@code void} item to the Publisher provided as an argument to the {@code notificationHandler}
function. If that Publisher calls {@code onComplete} or {@code onError} then {@code repeatWhen} will
call {@code onComplete} or {@code onError} on the child subscription. Otherwise, this Publisher will
resubscribe to the source Publisher.
<p>
<img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatWhen.f.png" alt="">
<dl>
<dt><b>Backpressure:</b></dt>
<dd>The operator honors downstream backpressure and expects the source {@code Publisher} to honor backpressure as well.
If this expectation is violated, the operator <em>may</em> throw an {@code IllegalStateException}.</dd>
<dt><b>Scheduler:</b></dt>
<dd>{@code repeatWhen} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param handler
receives a Publisher of notifications with which a user can complete or error, aborting the repeat.
@return the source Publisher modified with repeat logic
@see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> | [
"Returns",
"a",
"Flowable",
"that",
"emits",
"the",
"same",
"values",
"as",
"the",
"source",
"Publisher",
"with",
"the",
"exception",
"of",
"an",
"{",
"@code",
"onComplete",
"}",
".",
"An",
"{",
"@code",
"onComplete",
"}",
"notification",
"from",
"the",
"s... | train | https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L12389-L12395 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java | SynchronousRequest.getTPTransaction | public List<Transaction> getTPTransaction(String API, Transaction.Time time, Transaction.Type type) throws GuildWars2Exception {
isParamValid(new ParamChecker(ParamType.API, API));
if (time == null || type == null)
throw new GuildWars2Exception(ErrorCode.TransTime, "Transaction time/type cannot be empty");
try {
Response<List<Transaction>> response = gw2API.getTPTransaction(time.getValue(), type.getValue(), API).execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | java | public List<Transaction> getTPTransaction(String API, Transaction.Time time, Transaction.Type type) throws GuildWars2Exception {
isParamValid(new ParamChecker(ParamType.API, API));
if (time == null || type == null)
throw new GuildWars2Exception(ErrorCode.TransTime, "Transaction time/type cannot be empty");
try {
Response<List<Transaction>> response = gw2API.getTPTransaction(time.getValue(), type.getValue(), API).execute();
if (!response.isSuccessful()) throwError(response.code(), response.errorBody());
return response.body();
} catch (IOException e) {
throw new GuildWars2Exception(ErrorCode.Network, "Network Error: " + e.getMessage());
}
} | [
"public",
"List",
"<",
"Transaction",
">",
"getTPTransaction",
"(",
"String",
"API",
",",
"Transaction",
".",
"Time",
"time",
",",
"Transaction",
".",
"Type",
"type",
")",
"throws",
"GuildWars2Exception",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"... | For more info on Transaction API go <a href="https://wiki.guildwars2.com/wiki/API:2/commerce/transactions">here</a><br/>
Get transaction info linked to given API key
@param API API key
@param time current | History
@param type buy | sell
@return list of transaction base on the selection, if there is nothing, return empty list
@throws GuildWars2Exception see {@link ErrorCode} for detail
@see Transaction transaction info | [
"For",
"more",
"info",
"on",
"Transaction",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"commerce",
"/",
"transactions",
">",
"here<",
"/",
"a",
">",
"<br",
"/",... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/SynchronousRequest.java#L1330-L1341 |
JOML-CI/JOML | src/org/joml/Matrix4f.java | Matrix4f.translationRotateScale | public Matrix4f translationRotateScale(float tx, float ty, float tz,
float qx, float qy, float qz, float qw,
float scale) {
return translationRotateScale(tx, ty, tz, qx, qy, qz, qw, scale, scale, scale);
} | java | public Matrix4f translationRotateScale(float tx, float ty, float tz,
float qx, float qy, float qz, float qw,
float scale) {
return translationRotateScale(tx, ty, tz, qx, qy, qz, qw, scale, scale, scale);
} | [
"public",
"Matrix4f",
"translationRotateScale",
"(",
"float",
"tx",
",",
"float",
"ty",
",",
"float",
"tz",
",",
"float",
"qx",
",",
"float",
"qy",
",",
"float",
"qz",
",",
"float",
"qw",
",",
"float",
"scale",
")",
"{",
"return",
"translationRotateScale",... | Set <code>this</code> matrix to <code>T * R * S</code>, where <code>T</code> is a translation by the given <code>(tx, ty, tz)</code>,
<code>R</code> is a rotation transformation specified by the quaternion <code>(qx, qy, qz, qw)</code>, and <code>S</code> is a scaling transformation
which scales all three axes by <code>scale</code>.
<p>
When transforming a vector by the resulting matrix the scaling transformation will be applied first, then the rotation and
at last the translation.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
This method is equivalent to calling: <code>translation(tx, ty, tz).rotate(quat).scale(scale)</code>
@see #translation(float, float, float)
@see #rotate(Quaternionfc)
@see #scale(float)
@param tx
the number of units by which to translate the x-component
@param ty
the number of units by which to translate the y-component
@param tz
the number of units by which to translate the z-component
@param qx
the x-coordinate of the vector part of the quaternion
@param qy
the y-coordinate of the vector part of the quaternion
@param qz
the z-coordinate of the vector part of the quaternion
@param qw
the scalar part of the quaternion
@param scale
the scaling factor for all three axes
@return this | [
"Set",
"<code",
">",
"this<",
"/",
"code",
">",
"matrix",
"to",
"<code",
">",
"T",
"*",
"R",
"*",
"S<",
"/",
"code",
">",
"where",
"<code",
">",
"T<",
"/",
"code",
">",
"is",
"a",
"translation",
"by",
"the",
"given",
"<code",
">",
"(",
"tx",
"t... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L4107-L4111 |
moparisthebest/beehive | beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/DomUtils.java | DomUtils.getChildElementText | static String getChildElementText(Element parent, String name) {
// Get children
List list = DomUtils.getChildElementsByName(parent, name);
if (list.size() == 1) {
Element child = (Element) list.get(0);
StringBuffer buf = new StringBuffer();
NodeList children = child.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == Node.TEXT_NODE ||
node.getNodeType() == Node.CDATA_SECTION_NODE) {
Text text = (Text) node;
buf.append(text.getData().trim());
}
}
return buf.toString();
} else {
return null;
}
} | java | static String getChildElementText(Element parent, String name) {
// Get children
List list = DomUtils.getChildElementsByName(parent, name);
if (list.size() == 1) {
Element child = (Element) list.get(0);
StringBuffer buf = new StringBuffer();
NodeList children = child.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == Node.TEXT_NODE ||
node.getNodeType() == Node.CDATA_SECTION_NODE) {
Text text = (Text) node;
buf.append(text.getData().trim());
}
}
return buf.toString();
} else {
return null;
}
} | [
"static",
"String",
"getChildElementText",
"(",
"Element",
"parent",
",",
"String",
"name",
")",
"{",
"// Get children",
"List",
"list",
"=",
"DomUtils",
".",
"getChildElementsByName",
"(",
"parent",
",",
"name",
")",
";",
"if",
"(",
"list",
".",
"size",
"("... | <p>Returns the text value of a child element. Returns
<code>null</code> if there is no child element found.</p>
@param parent parent element
@param name name of the child element
@return text value | [
"<p",
">",
"Returns",
"the",
"text",
"value",
"of",
"a",
"child",
"element",
".",
"Returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"there",
"is",
"no",
"child",
"element",
"found",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-ejb-control/src/main/java/org/apache/beehive/controls/system/ejb/internal/DomUtils.java#L94-L117 |
wuman/JReadability | src/main/java/com/wuman/jreadability/Readability.java | Readability.getElementsByTag | private static Elements getElementsByTag(Element e, String tag) {
Elements es = e.getElementsByTag(tag);
es.remove(e);
return es;
} | java | private static Elements getElementsByTag(Element e, String tag) {
Elements es = e.getElementsByTag(tag);
es.remove(e);
return es;
} | [
"private",
"static",
"Elements",
"getElementsByTag",
"(",
"Element",
"e",
",",
"String",
"tag",
")",
"{",
"Elements",
"es",
"=",
"e",
".",
"getElementsByTag",
"(",
"tag",
")",
";",
"es",
".",
"remove",
"(",
"e",
")",
";",
"return",
"es",
";",
"}"
] | Jsoup's Element.getElementsByTag(Element e) includes e itself, which is
different from W3C standards. This utility function is exclusive of the
Element e.
@param e
@param tag
@return | [
"Jsoup",
"s",
"Element",
".",
"getElementsByTag",
"(",
"Element",
"e",
")",
"includes",
"e",
"itself",
"which",
"is",
"different",
"from",
"W3C",
"standards",
".",
"This",
"utility",
"function",
"is",
"exclusive",
"of",
"the",
"Element",
"e",
"."
] | train | https://github.com/wuman/JReadability/blob/16c18c42402bd13c6e024c2fd3a86dd28ba53e74/src/main/java/com/wuman/jreadability/Readability.java#L880-L884 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/vpn/vpnsessionpolicy.java | vpnsessionpolicy.get | public static vpnsessionpolicy get(nitro_service service, String name) throws Exception{
vpnsessionpolicy obj = new vpnsessionpolicy();
obj.set_name(name);
vpnsessionpolicy response = (vpnsessionpolicy) obj.get_resource(service);
return response;
} | java | public static vpnsessionpolicy get(nitro_service service, String name) throws Exception{
vpnsessionpolicy obj = new vpnsessionpolicy();
obj.set_name(name);
vpnsessionpolicy response = (vpnsessionpolicy) obj.get_resource(service);
return response;
} | [
"public",
"static",
"vpnsessionpolicy",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"vpnsessionpolicy",
"obj",
"=",
"new",
"vpnsessionpolicy",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"... | Use this API to fetch vpnsessionpolicy resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"vpnsessionpolicy",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/vpn/vpnsessionpolicy.java#L324-L329 |
heroku/heroku.jar | heroku-api/src/main/java/com/heroku/api/request/RequestConfig.java | RequestConfig.withOptions | public RequestConfig withOptions(Heroku.RequestKey key, Map<String, String> data) {
RequestConfig newConfig = copy();
newConfig.config.put(key, new Either(new Data(data)));
return newConfig;
} | java | public RequestConfig withOptions(Heroku.RequestKey key, Map<String, String> data) {
RequestConfig newConfig = copy();
newConfig.config.put(key, new Either(new Data(data)));
return newConfig;
} | [
"public",
"RequestConfig",
"withOptions",
"(",
"Heroku",
".",
"RequestKey",
"key",
",",
"Map",
"<",
"String",
",",
"String",
">",
"data",
")",
"{",
"RequestConfig",
"newConfig",
"=",
"copy",
"(",
")",
";",
"newConfig",
".",
"config",
".",
"put",
"(",
"ke... | Sets a {@link com.heroku.api.Heroku.RequestKey} parameter.
@param key Heroku request key
@param data arbitrary key/value map
@return A new {@link RequestConfig} | [
"Sets",
"a",
"{"
] | train | https://github.com/heroku/heroku.jar/blob/d9e52991293159498c10c498c6f91fcdd637378e/heroku-api/src/main/java/com/heroku/api/request/RequestConfig.java#L66-L70 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java | FaceListsImpl.deleteFace | public void deleteFace(String faceListId, UUID persistedFaceId) {
deleteFaceWithServiceResponseAsync(faceListId, persistedFaceId).toBlocking().single().body();
} | java | public void deleteFace(String faceListId, UUID persistedFaceId) {
deleteFaceWithServiceResponseAsync(faceListId, persistedFaceId).toBlocking().single().body();
} | [
"public",
"void",
"deleteFace",
"(",
"String",
"faceListId",
",",
"UUID",
"persistedFaceId",
")",
"{",
"deleteFaceWithServiceResponseAsync",
"(",
"faceListId",
",",
"persistedFaceId",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
... | Delete an existing face from a face list (given by a persisitedFaceId and a faceListId). Persisted image related to the face will also be deleted.
@param faceListId Id referencing a particular face list.
@param persistedFaceId Id referencing a particular persistedFaceId of an existing face.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws APIErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Delete",
"an",
"existing",
"face",
"from",
"a",
"face",
"list",
"(",
"given",
"by",
"a",
"persisitedFaceId",
"and",
"a",
"faceListId",
")",
".",
"Persisted",
"image",
"related",
"to",
"the",
"face",
"will",
"also",
"be",
"deleted",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java#L665-L667 |
bbottema/simple-java-mail | modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java | ConfigLoader.valueOrProperty | @Nullable
private static <T> T valueOrProperty(@Nullable final T value, @Nonnull final Property property, @Nullable final T defaultValue) {
if (!valueNullOrEmpty(value)) {
LOGGER.trace("using provided argument value {} for property {}", value, property);
return value;
} else if (hasProperty(property)) {
final T propertyValue = getProperty(property);
LOGGER.trace("using value {} from config file for property {}", propertyValue, property);
return propertyValue;
} else {
LOGGER.trace("no value provided as argument or in config file for property {}, using default value {}", property, defaultValue);
return defaultValue;
}
} | java | @Nullable
private static <T> T valueOrProperty(@Nullable final T value, @Nonnull final Property property, @Nullable final T defaultValue) {
if (!valueNullOrEmpty(value)) {
LOGGER.trace("using provided argument value {} for property {}", value, property);
return value;
} else if (hasProperty(property)) {
final T propertyValue = getProperty(property);
LOGGER.trace("using value {} from config file for property {}", propertyValue, property);
return propertyValue;
} else {
LOGGER.trace("no value provided as argument or in config file for property {}, using default value {}", property, defaultValue);
return defaultValue;
}
} | [
"@",
"Nullable",
"private",
"static",
"<",
"T",
">",
"T",
"valueOrProperty",
"(",
"@",
"Nullable",
"final",
"T",
"value",
",",
"@",
"Nonnull",
"final",
"Property",
"property",
",",
"@",
"Nullable",
"final",
"T",
"defaultValue",
")",
"{",
"if",
"(",
"!",
... | Returns the given value if not null and not empty, otherwise tries to resolve the given property and if still not found resort to the default value if
provided.
<p>
Null or blank values are never allowed, so they are always ignored.
@return The value if not null or else the value from config file if provided or else <code>defaultValue</code>. | [
"Returns",
"the",
"given",
"value",
"if",
"not",
"null",
"and",
"not",
"empty",
"otherwise",
"tries",
"to",
"resolve",
"the",
"given",
"property",
"and",
"if",
"still",
"not",
"found",
"resort",
"to",
"the",
"default",
"value",
"if",
"provided",
".",
"<p",... | train | https://github.com/bbottema/simple-java-mail/blob/b03635328aeecd525e35eddfef8f5b9a184559d8/modules/core-module/src/main/java/org/simplejavamail/config/ConfigLoader.java#L171-L184 |
iig-uni-freiburg/SEWOL | src/de/uni/freiburg/iig/telematik/sewol/context/constraint/ConstraintContext.java | ConstraintContext.removeRoutingConstraintsOnAttribute | private void removeRoutingConstraintsOnAttribute(String attribute, boolean notifyListeners) {
for (String activity : activities) {
removeRoutingConstraintsOnAttribute(activity, attribute, notifyListeners);
}
} | java | private void removeRoutingConstraintsOnAttribute(String attribute, boolean notifyListeners) {
for (String activity : activities) {
removeRoutingConstraintsOnAttribute(activity, attribute, notifyListeners);
}
} | [
"private",
"void",
"removeRoutingConstraintsOnAttribute",
"(",
"String",
"attribute",
",",
"boolean",
"notifyListeners",
")",
"{",
"for",
"(",
"String",
"activity",
":",
"activities",
")",
"{",
"removeRoutingConstraintsOnAttribute",
"(",
"activity",
",",
"attribute",
... | Removes all routing constraints that relate to the given attribute
@param attribute
@param notifyListeners | [
"Removes",
"all",
"routing",
"constraints",
"that",
"relate",
"to",
"the",
"given",
"attribute"
] | train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/src/de/uni/freiburg/iig/telematik/sewol/context/constraint/ConstraintContext.java#L152-L156 |
doanduyhai/Achilles | achilles-core/src/main/java/info/archinnov/achilles/bootstrap/AbstractManagerFactoryBuilder.java | AbstractManagerFactoryBuilder.withParameter | public T withParameter(ConfigurationParameters parameter, Object value) {
configMap.put(parameter, value);
return getThis();
} | java | public T withParameter(ConfigurationParameters parameter, Object value) {
configMap.put(parameter, value);
return getThis();
} | [
"public",
"T",
"withParameter",
"(",
"ConfigurationParameters",
"parameter",
",",
"Object",
"value",
")",
"{",
"configMap",
".",
"put",
"(",
"parameter",
",",
"value",
")",
";",
"return",
"getThis",
"(",
")",
";",
"}"
] | Pass an arbitrary parameter to configure Achilles
@param parameter an instance of the ConfigurationParameters enum
@param value the value of the parameter
@return ManagerFactoryBuilder | [
"Pass",
"an",
"arbitrary",
"parameter",
"to",
"configure",
"Achilles"
] | train | https://github.com/doanduyhai/Achilles/blob/8281c33100e72c993e570592ae1a5306afac6813/achilles-core/src/main/java/info/archinnov/achilles/bootstrap/AbstractManagerFactoryBuilder.java#L471-L474 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.document_POST | public OvhDocument document_POST(String name, OvhSafeKeyValue<String>[] tags) throws IOException {
String qPath = "/me/document";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "name", name);
addBody(o, "tags", tags);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhDocument.class);
} | java | public OvhDocument document_POST(String name, OvhSafeKeyValue<String>[] tags) throws IOException {
String qPath = "/me/document";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "name", name);
addBody(o, "tags", tags);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhDocument.class);
} | [
"public",
"OvhDocument",
"document_POST",
"(",
"String",
"name",
",",
"OvhSafeKeyValue",
"<",
"String",
">",
"[",
"]",
"tags",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/document\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",... | Create new document
REST: POST /me/document
@param name [required] File name
@param tags [required] File tags | [
"Create",
"new",
"document"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L2596-L2604 |
deeplearning4j/deeplearning4j | datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/ImageLoader.java | ImageLoader.toRaveledTensor | public INDArray toRaveledTensor(BufferedImage image) {
try {
image = scalingIfNeed(image, false);
return toINDArrayBGR(image).ravel();
} catch (Exception e) {
throw new RuntimeException("Unable to load image", e);
}
} | java | public INDArray toRaveledTensor(BufferedImage image) {
try {
image = scalingIfNeed(image, false);
return toINDArrayBGR(image).ravel();
} catch (Exception e) {
throw new RuntimeException("Unable to load image", e);
}
} | [
"public",
"INDArray",
"toRaveledTensor",
"(",
"BufferedImage",
"image",
")",
"{",
"try",
"{",
"image",
"=",
"scalingIfNeed",
"(",
"image",
",",
"false",
")",
";",
"return",
"toINDArrayBGR",
"(",
"image",
")",
".",
"ravel",
"(",
")",
";",
"}",
"catch",
"(... | Convert an image in to a raveled tensor of
the bgr values of the image
@param image the image to parse
@return the raveled tensor of bgr values | [
"Convert",
"an",
"image",
"in",
"to",
"a",
"raveled",
"tensor",
"of",
"the",
"bgr",
"values",
"of",
"the",
"image"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/ImageLoader.java#L179-L186 |
cloudfoundry-community/cf-java-component | cf-spring/src/main/java/cf/spring/servicebroker/AccessorUtils.java | AccessorUtils.invokeMethod | public static Object invokeMethod(Object object, Method method, Object... args) throws Throwable {
try {
return method.invoke(object, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
} | java | public static Object invokeMethod(Object object, Method method, Object... args) throws Throwable {
try {
return method.invoke(object, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
} | [
"public",
"static",
"Object",
"invokeMethod",
"(",
"Object",
"object",
",",
"Method",
"method",
",",
"Object",
"...",
"args",
")",
"throws",
"Throwable",
"{",
"try",
"{",
"return",
"method",
".",
"invoke",
"(",
"object",
",",
"args",
")",
";",
"}",
"catc... | Invokes the method of the specified object with some method arguments. | [
"Invokes",
"the",
"method",
"of",
"the",
"specified",
"object",
"with",
"some",
"method",
"arguments",
"."
] | train | https://github.com/cloudfoundry-community/cf-java-component/blob/9d7d54f2b599f3e4f4706bc0c471e144065671fa/cf-spring/src/main/java/cf/spring/servicebroker/AccessorUtils.java#L66-L72 |
lessthanoptimal/BoofCV | main/boofcv-io/src/main/java/boofcv/io/image/ConvertBufferedImage.java | ConvertBufferedImage.convertTo | public static BufferedImage convertTo(GrayU8 src, BufferedImage dst) {
dst = checkInputs(src, dst);
DataBuffer buffer = dst.getRaster().getDataBuffer();
try {
if (buffer.getDataType() == DataBuffer.TYPE_BYTE && isKnownByteFormat(dst) ) {
ConvertRaster.grayToBuffered(src, (DataBufferByte)buffer, dst.getRaster());
} else if (buffer.getDataType() == DataBuffer.TYPE_INT) {
ConvertRaster.grayToBuffered(src, (DataBufferInt)buffer, dst.getRaster());
} else {
ConvertRaster.grayToBuffered(src, dst);
}
// hack so that it knows the buffer has been modified
dst.setRGB(0,0,dst.getRGB(0,0));
} catch( java.security.AccessControlException e) {
ConvertRaster.grayToBuffered(src, dst);
}
return dst;
} | java | public static BufferedImage convertTo(GrayU8 src, BufferedImage dst) {
dst = checkInputs(src, dst);
DataBuffer buffer = dst.getRaster().getDataBuffer();
try {
if (buffer.getDataType() == DataBuffer.TYPE_BYTE && isKnownByteFormat(dst) ) {
ConvertRaster.grayToBuffered(src, (DataBufferByte)buffer, dst.getRaster());
} else if (buffer.getDataType() == DataBuffer.TYPE_INT) {
ConvertRaster.grayToBuffered(src, (DataBufferInt)buffer, dst.getRaster());
} else {
ConvertRaster.grayToBuffered(src, dst);
}
// hack so that it knows the buffer has been modified
dst.setRGB(0,0,dst.getRGB(0,0));
} catch( java.security.AccessControlException e) {
ConvertRaster.grayToBuffered(src, dst);
}
return dst;
} | [
"public",
"static",
"BufferedImage",
"convertTo",
"(",
"GrayU8",
"src",
",",
"BufferedImage",
"dst",
")",
"{",
"dst",
"=",
"checkInputs",
"(",
"src",
",",
"dst",
")",
";",
"DataBuffer",
"buffer",
"=",
"dst",
".",
"getRaster",
"(",
")",
".",
"getDataBuffer"... | Converts a {@link GrayU8} into a BufferedImage. If the buffered image
has multiple channels then the input image is copied into each channel.
@param src Input image.
@param dst Where the converted image is written to. If null a new image is created.
@return Converted image. | [
"Converts",
"a",
"{",
"@link",
"GrayU8",
"}",
"into",
"a",
"BufferedImage",
".",
"If",
"the",
"buffered",
"image",
"has",
"multiple",
"channels",
"then",
"the",
"input",
"image",
"is",
"copied",
"into",
"each",
"channel",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-io/src/main/java/boofcv/io/image/ConvertBufferedImage.java#L693-L712 |
gallandarakhneorg/afc | core/util/src/main/java/org/arakhne/afc/util/ListUtil.java | ListUtil.addIfAbsent | @Inline(value = "add($1, $2, $3, false, false)")
public static <E> int addIfAbsent(List<E> list, Comparator<? super E> comparator, E data) {
return add(list, comparator, data, false, false);
} | java | @Inline(value = "add($1, $2, $3, false, false)")
public static <E> int addIfAbsent(List<E> list, Comparator<? super E> comparator, E data) {
return add(list, comparator, data, false, false);
} | [
"@",
"Inline",
"(",
"value",
"=",
"\"add($1, $2, $3, false, false)\"",
")",
"public",
"static",
"<",
"E",
">",
"int",
"addIfAbsent",
"(",
"List",
"<",
"E",
">",
"list",
",",
"Comparator",
"<",
"?",
"super",
"E",
">",
"comparator",
",",
"E",
"data",
")",
... | Add the given element in the main list using a dichotomic algorithm if the element is not already present.
<p>This function ensure that the comparator is invoked as: <code>comparator(data, dataAlreadyInList)</code>.
@param <E> is the type of the elements in the list.
@param list is the list to change.
@param comparator is the comparator of elements.
@param data is the data to insert.
@return the index where the element was inserted, or <code>-1</code>
if the element was not inserted.
@since 14.0 | [
"Add",
"the",
"given",
"element",
"in",
"the",
"main",
"list",
"using",
"a",
"dichotomic",
"algorithm",
"if",
"the",
"element",
"is",
"not",
"already",
"present",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/util/src/main/java/org/arakhne/afc/util/ListUtil.java#L92-L95 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.photos_upload | public T photos_upload(File photo, Long albumId)
throws FacebookException, IOException {
return photos_upload(photo, /*caption*/null, albumId);
} | java | public T photos_upload(File photo, Long albumId)
throws FacebookException, IOException {
return photos_upload(photo, /*caption*/null, albumId);
} | [
"public",
"T",
"photos_upload",
"(",
"File",
"photo",
",",
"Long",
"albumId",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"return",
"photos_upload",
"(",
"photo",
",",
"/*caption*/",
"null",
",",
"albumId",
")",
";",
"}"
] | Uploads a photo to Facebook.
@param photo an image file
@param albumId the album into which the photo should be uploaded
@return a T with the standard Facebook photo information
@see <a href="http://wiki.developers.facebook.com/index.php/Photos.upload">
Developers wiki: Photos.upload</a> | [
"Uploads",
"a",
"photo",
"to",
"Facebook",
"."
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1308-L1311 |
tvesalainen/util | util/src/main/java/org/vesalainen/math/AbstractPoint.java | AbstractPoint.searchX | public static final int searchX(Point[] points, Point key)
{
return Arrays.binarySearch(points, key, xcomp);
} | java | public static final int searchX(Point[] points, Point key)
{
return Arrays.binarySearch(points, key, xcomp);
} | [
"public",
"static",
"final",
"int",
"searchX",
"(",
"Point",
"[",
"]",
"points",
",",
"Point",
"key",
")",
"{",
"return",
"Arrays",
".",
"binarySearch",
"(",
"points",
",",
"key",
",",
"xcomp",
")",
";",
"}"
] | Searches given key in array in x-order
@param points
@param key
@return Like in Arrays.binarySearch
@see java.util.Arrays | [
"Searches",
"given",
"key",
"in",
"array",
"in",
"x",
"-",
"order"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/math/AbstractPoint.java#L293-L296 |
samskivert/samskivert | src/main/java/com/samskivert/jdbc/JDBCUtil.java | JDBCUtil.dropIndex | public static boolean dropIndex (Connection conn, String table, String cname, String iname)
throws SQLException
{
if (!tableContainsIndex(conn, table, cname, iname)) {
return false;
}
String update = "ALTER TABLE " + table + " DROP INDEX " + iname;
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(update);
if (stmt.executeUpdate() == 1) {
log.info("Database index '" + iname + "' removed from table '" + table + "'.");
}
} finally {
close(stmt);
}
return true;
} | java | public static boolean dropIndex (Connection conn, String table, String cname, String iname)
throws SQLException
{
if (!tableContainsIndex(conn, table, cname, iname)) {
return false;
}
String update = "ALTER TABLE " + table + " DROP INDEX " + iname;
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(update);
if (stmt.executeUpdate() == 1) {
log.info("Database index '" + iname + "' removed from table '" + table + "'.");
}
} finally {
close(stmt);
}
return true;
} | [
"public",
"static",
"boolean",
"dropIndex",
"(",
"Connection",
"conn",
",",
"String",
"table",
",",
"String",
"cname",
",",
"String",
"iname",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"!",
"tableContainsIndex",
"(",
"conn",
",",
"table",
",",
"cname",
... | Removes a named index from the specified table.
@return true if the index was dropped, false if it did not exist in the first place. | [
"Removes",
"a",
"named",
"index",
"from",
"the",
"specified",
"table",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/jdbc/JDBCUtil.java#L560-L578 |
voldemort/voldemort | src/java/voldemort/utils/UpdateClusterUtils.java | UpdateClusterUtils.updateCluster | public static Cluster updateCluster(Cluster currentCluster, List<Node> updatedNodeList) {
List<Node> newNodeList = new ArrayList<Node>(updatedNodeList);
for(Node currentNode: currentCluster.getNodes()) {
if(!updatedNodeList.contains(currentNode))
newNodeList.add(currentNode);
}
Collections.sort(newNodeList);
return new Cluster(currentCluster.getName(),
newNodeList,
Lists.newArrayList(currentCluster.getZones()));
} | java | public static Cluster updateCluster(Cluster currentCluster, List<Node> updatedNodeList) {
List<Node> newNodeList = new ArrayList<Node>(updatedNodeList);
for(Node currentNode: currentCluster.getNodes()) {
if(!updatedNodeList.contains(currentNode))
newNodeList.add(currentNode);
}
Collections.sort(newNodeList);
return new Cluster(currentCluster.getName(),
newNodeList,
Lists.newArrayList(currentCluster.getZones()));
} | [
"public",
"static",
"Cluster",
"updateCluster",
"(",
"Cluster",
"currentCluster",
",",
"List",
"<",
"Node",
">",
"updatedNodeList",
")",
"{",
"List",
"<",
"Node",
">",
"newNodeList",
"=",
"new",
"ArrayList",
"<",
"Node",
">",
"(",
"updatedNodeList",
")",
";"... | Concatenates the list of current nodes in the given cluster with the new
nodes provided and returns an updated cluster metadata. <br>
If the nodes being updated already exist in the current metadata, we take
the updated ones
@param currentCluster The current cluster metadata
@param updatedNodeList The list of new nodes to be added
@return New cluster metadata containing both the sets of nodes | [
"Concatenates",
"the",
"list",
"of",
"current",
"nodes",
"in",
"the",
"given",
"cluster",
"with",
"the",
"new",
"nodes",
"provided",
"and",
"returns",
"an",
"updated",
"cluster",
"metadata",
".",
"<br",
">",
"If",
"the",
"nodes",
"being",
"updated",
"already... | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/UpdateClusterUtils.java#L120-L131 |
aws/aws-sdk-java | aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/ReEncryptRequest.java | ReEncryptRequest.withSourceEncryptionContext | public ReEncryptRequest withSourceEncryptionContext(java.util.Map<String, String> sourceEncryptionContext) {
setSourceEncryptionContext(sourceEncryptionContext);
return this;
} | java | public ReEncryptRequest withSourceEncryptionContext(java.util.Map<String, String> sourceEncryptionContext) {
setSourceEncryptionContext(sourceEncryptionContext);
return this;
} | [
"public",
"ReEncryptRequest",
"withSourceEncryptionContext",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"sourceEncryptionContext",
")",
"{",
"setSourceEncryptionContext",
"(",
"sourceEncryptionContext",
")",
";",
"return",
"this",
";",
... | <p>
Encryption context used to encrypt and decrypt the data specified in the <code>CiphertextBlob</code> parameter.
</p>
@param sourceEncryptionContext
Encryption context used to encrypt and decrypt the data specified in the <code>CiphertextBlob</code>
parameter.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Encryption",
"context",
"used",
"to",
"encrypt",
"and",
"decrypt",
"the",
"data",
"specified",
"in",
"the",
"<code",
">",
"CiphertextBlob<",
"/",
"code",
">",
"parameter",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/ReEncryptRequest.java#L206-L209 |
google/auto | value/src/main/java/com/google/auto/value/processor/TemplateVars.java | TemplateVars.readerFromUrl | private static Reader readerFromUrl(String resourceName) throws IOException {
URL resourceUrl = TemplateVars.class.getResource(resourceName);
InputStream in;
try {
if (resourceUrl.getProtocol().equalsIgnoreCase("file")) {
in = inputStreamFromFile(resourceUrl);
} else if (resourceUrl.getProtocol().equalsIgnoreCase("jar")) {
in = inputStreamFromJar(resourceUrl);
} else {
throw new AssertionError("Template fallback logic fails for: " + resourceUrl);
}
} catch (URISyntaxException e) {
throw new IOException(e);
}
return new InputStreamReader(in, StandardCharsets.UTF_8);
} | java | private static Reader readerFromUrl(String resourceName) throws IOException {
URL resourceUrl = TemplateVars.class.getResource(resourceName);
InputStream in;
try {
if (resourceUrl.getProtocol().equalsIgnoreCase("file")) {
in = inputStreamFromFile(resourceUrl);
} else if (resourceUrl.getProtocol().equalsIgnoreCase("jar")) {
in = inputStreamFromJar(resourceUrl);
} else {
throw new AssertionError("Template fallback logic fails for: " + resourceUrl);
}
} catch (URISyntaxException e) {
throw new IOException(e);
}
return new InputStreamReader(in, StandardCharsets.UTF_8);
} | [
"private",
"static",
"Reader",
"readerFromUrl",
"(",
"String",
"resourceName",
")",
"throws",
"IOException",
"{",
"URL",
"resourceUrl",
"=",
"TemplateVars",
".",
"class",
".",
"getResource",
"(",
"resourceName",
")",
";",
"InputStream",
"in",
";",
"try",
"{",
... | through the getResourceAsStream should be a lot more efficient than reopening the jar. | [
"through",
"the",
"getResourceAsStream",
"should",
"be",
"a",
"lot",
"more",
"efficient",
"than",
"reopening",
"the",
"jar",
"."
] | train | https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/value/src/main/java/com/google/auto/value/processor/TemplateVars.java#L156-L171 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/rename/CmsRenameDialog.java | CmsRenameDialog.loadAndShow | public void loadAndShow() {
CmsRpcAction<CmsRenameInfoBean> infoAction = new CmsRpcAction<CmsRenameInfoBean>() {
@Override
public void execute() {
start(0, true);
CmsCoreProvider.getVfsService().getRenameInfo(m_structureId, this);
}
@Override
protected void onResponse(CmsRenameInfoBean renameInfo) {
stop(false);
CmsRenameView view = new CmsRenameView(renameInfo, m_renameHandler);
for (CmsPushButton button : view.getDialogButtons()) {
addButton(button);
}
setMainContent(view);
view.setDialog(CmsRenameDialog.this);
center();
}
};
infoAction.execute();
} | java | public void loadAndShow() {
CmsRpcAction<CmsRenameInfoBean> infoAction = new CmsRpcAction<CmsRenameInfoBean>() {
@Override
public void execute() {
start(0, true);
CmsCoreProvider.getVfsService().getRenameInfo(m_structureId, this);
}
@Override
protected void onResponse(CmsRenameInfoBean renameInfo) {
stop(false);
CmsRenameView view = new CmsRenameView(renameInfo, m_renameHandler);
for (CmsPushButton button : view.getDialogButtons()) {
addButton(button);
}
setMainContent(view);
view.setDialog(CmsRenameDialog.this);
center();
}
};
infoAction.execute();
} | [
"public",
"void",
"loadAndShow",
"(",
")",
"{",
"CmsRpcAction",
"<",
"CmsRenameInfoBean",
">",
"infoAction",
"=",
"new",
"CmsRpcAction",
"<",
"CmsRenameInfoBean",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"{",
"start",
"(",
... | Loads the necessary data for the rename dialog from the server and then displays the rename dialog.<p> | [
"Loads",
"the",
"necessary",
"data",
"for",
"the",
"rename",
"dialog",
"from",
"the",
"server",
"and",
"then",
"displays",
"the",
"rename",
"dialog",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/rename/CmsRenameDialog.java#L68-L93 |
GCRC/nunaliit | nunaliit2-json/src/main/java/org/json/XMLTokener.java | XMLTokener.unescapeEntity | static String unescapeEntity(String e) {
// validate
if (e == null || e.isEmpty()) {
return "";
}
// if our entity is an encoded unicode point, parse it.
if (e.charAt(0) == '#') {
int cp;
if (e.charAt(1) == 'x') {
// hex encoded unicode
cp = Integer.parseInt(e.substring(2), 16);
} else {
// decimal encoded unicode
cp = Integer.parseInt(e.substring(1));
}
return new String(new int[] {cp},0,1);
}
Character knownEntity = entity.get(e);
if(knownEntity==null) {
// we don't know the entity so keep it encoded
return '&' + e + ';';
}
return knownEntity.toString();
} | java | static String unescapeEntity(String e) {
// validate
if (e == null || e.isEmpty()) {
return "";
}
// if our entity is an encoded unicode point, parse it.
if (e.charAt(0) == '#') {
int cp;
if (e.charAt(1) == 'x') {
// hex encoded unicode
cp = Integer.parseInt(e.substring(2), 16);
} else {
// decimal encoded unicode
cp = Integer.parseInt(e.substring(1));
}
return new String(new int[] {cp},0,1);
}
Character knownEntity = entity.get(e);
if(knownEntity==null) {
// we don't know the entity so keep it encoded
return '&' + e + ';';
}
return knownEntity.toString();
} | [
"static",
"String",
"unescapeEntity",
"(",
"String",
"e",
")",
"{",
"// validate",
"if",
"(",
"e",
"==",
"null",
"||",
"e",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"\"\"",
";",
"}",
"// if our entity is an encoded unicode point, parse it.",
"if",
"(",
... | Unescapes an XML entity encoding;
@param e entity (only the actual entity value, not the preceding & or ending ;
@return | [
"Unescapes",
"an",
"XML",
"entity",
"encoding",
";"
] | train | https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-json/src/main/java/org/json/XMLTokener.java#L159-L182 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/PhotosetsApi.java | PhotosetsApi.editPhotos | public Response editPhotos(String photosetId, String primaryPhotoId, List<String> photoIds) throws JinxException {
JinxUtils.validateParams(photosetId, primaryPhotoId, photoIds);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photosets.editPhotos");
params.put("photoset_id", photosetId);
params.put("primary_photo_id", primaryPhotoId);
StringBuilder builder = new StringBuilder();
for (String id : photoIds) {
builder.append(id).append(',');
}
builder.deleteCharAt(builder.length() - 1);
params.put("photo_ids", builder.toString());
return jinx.flickrPost(params, Response.class);
} | java | public Response editPhotos(String photosetId, String primaryPhotoId, List<String> photoIds) throws JinxException {
JinxUtils.validateParams(photosetId, primaryPhotoId, photoIds);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.photosets.editPhotos");
params.put("photoset_id", photosetId);
params.put("primary_photo_id", primaryPhotoId);
StringBuilder builder = new StringBuilder();
for (String id : photoIds) {
builder.append(id).append(',');
}
builder.deleteCharAt(builder.length() - 1);
params.put("photo_ids", builder.toString());
return jinx.flickrPost(params, Response.class);
} | [
"public",
"Response",
"editPhotos",
"(",
"String",
"photosetId",
",",
"String",
"primaryPhotoId",
",",
"List",
"<",
"String",
">",
"photoIds",
")",
"throws",
"JinxException",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"photosetId",
",",
"primaryPhotoId",
",",
... | Modify the photos in a photoset. Use this method to add, remove and re-order photos.
<br>
This method requires authentication with 'write' permission.
<br>
This method has no specific response - It returns an empty success response if it completes without error.
@param photosetId id of the photoset to modify. The photoset must belong to the calling user. Required.
@param primaryPhotoId id of the photo to use as the 'primary' photo for the set. This id must also be passed along in photo_ids list argument. Required.
@param photoIds list of photo ids to include in the set. They will appear in the set in the order sent. This list must contain the primary photo id. All photos must belong to the owner of the set. This list of photos replaces the existing list. Call addPhoto to append a photo to a set. Required.
@return success response if it completes without error.
@throws JinxException if required parameters are null, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.photosets.editPhotos.html">flickr.photosets.editPhotos</a> | [
"Modify",
"the",
"photos",
"in",
"a",
"photoset",
".",
"Use",
"this",
"method",
"to",
"add",
"remove",
"and",
"re",
"-",
"order",
"photos",
".",
"<br",
">",
"This",
"method",
"requires",
"authentication",
"with",
"write",
"permission",
".",
"<br",
">",
"... | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PhotosetsApi.java#L162-L176 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/event/FieldToUpperHandler.java | FieldToUpperHandler.doSetData | public int doSetData(Object objData, boolean bDisplayOption, int iMoveMode)
{
if (objData instanceof String)
objData = ((String)objData).toUpperCase();
return super.doSetData(objData, bDisplayOption, iMoveMode);
} | java | public int doSetData(Object objData, boolean bDisplayOption, int iMoveMode)
{
if (objData instanceof String)
objData = ((String)objData).toUpperCase();
return super.doSetData(objData, bDisplayOption, iMoveMode);
} | [
"public",
"int",
"doSetData",
"(",
"Object",
"objData",
",",
"boolean",
"bDisplayOption",
",",
"int",
"iMoveMode",
")",
"{",
"if",
"(",
"objData",
"instanceof",
"String",
")",
"objData",
"=",
"(",
"(",
"String",
")",
"objData",
")",
".",
"toUpperCase",
"("... | Move the physical binary data to this field.
@param objData the raw data to set the basefield to.
@param bDisplayOption If true, display the change.
@param iMoveMode The type of move being done (init/read/screen).
@return The error code (or NORMAL_RETURN if okay). | [
"Move",
"the",
"physical",
"binary",
"data",
"to",
"this",
"field",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/FieldToUpperHandler.java#L55-L60 |
overturetool/overture | ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java | VdmBreakpointPropertyPage.createComposite | protected Composite createComposite(Composite parent, int numColumns)
{
return SWTFactory.createComposite(parent, parent.getFont(), numColumns, 1, GridData.FILL_HORIZONTAL, 0, 0);
} | java | protected Composite createComposite(Composite parent, int numColumns)
{
return SWTFactory.createComposite(parent, parent.getFont(), numColumns, 1, GridData.FILL_HORIZONTAL, 0, 0);
} | [
"protected",
"Composite",
"createComposite",
"(",
"Composite",
"parent",
",",
"int",
"numColumns",
")",
"{",
"return",
"SWTFactory",
".",
"createComposite",
"(",
"parent",
",",
"parent",
".",
"getFont",
"(",
")",
",",
"numColumns",
",",
"1",
",",
"GridData",
... | Creates a fully configured composite with the given number of columns
@param parent
@param numColumns
@return the configured composite | [
"Creates",
"a",
"fully",
"configured",
"composite",
"with",
"the",
"given",
"number",
"of",
"columns"
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java#L490-L493 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/date/DateModifier.java | DateModifier.modifyField | private static void modifyField(Calendar calendar, int field, ModifyType modifyType) {
// Console.log("# {} {}", DateField.of(field), calendar.getActualMinimum(field));
switch (modifyType) {
case TRUNCATE:
calendar.set(field, DateUtil.getBeginValue(calendar, field));
break;
case CEILING:
calendar.set(field, DateUtil.getEndValue(calendar, field));
break;
case ROUND:
int min = DateUtil.getBeginValue(calendar, field);
int max = DateUtil.getEndValue(calendar, field);
int href;
if (Calendar.DAY_OF_WEEK == field) {
// 星期特殊处理,假设周一是第一天,中间的为周四
href = (min + 3) % 7;
} else {
href = (max - min) / 2 + 1;
}
int value = calendar.get(field);
calendar.set(field, (value < href) ? min : max);
break;
}
} | java | private static void modifyField(Calendar calendar, int field, ModifyType modifyType) {
// Console.log("# {} {}", DateField.of(field), calendar.getActualMinimum(field));
switch (modifyType) {
case TRUNCATE:
calendar.set(field, DateUtil.getBeginValue(calendar, field));
break;
case CEILING:
calendar.set(field, DateUtil.getEndValue(calendar, field));
break;
case ROUND:
int min = DateUtil.getBeginValue(calendar, field);
int max = DateUtil.getEndValue(calendar, field);
int href;
if (Calendar.DAY_OF_WEEK == field) {
// 星期特殊处理,假设周一是第一天,中间的为周四
href = (min + 3) % 7;
} else {
href = (max - min) / 2 + 1;
}
int value = calendar.get(field);
calendar.set(field, (value < href) ? min : max);
break;
}
} | [
"private",
"static",
"void",
"modifyField",
"(",
"Calendar",
"calendar",
",",
"int",
"field",
",",
"ModifyType",
"modifyType",
")",
"{",
"// Console.log(\"# {} {}\", DateField.of(field), calendar.getActualMinimum(field));\r",
"switch",
"(",
"modifyType",
")",
"{",
"case",
... | 修改日期字段值
@param calendar {@link Calendar}
@param field 字段,见{@link Calendar}
@param modifyType {@link ModifyType} | [
"修改日期字段值"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateModifier.java#L98-L121 |
Jasig/uPortal | uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java | PortletAdministrationHelper.createNewPortletDefinitionForm | private PortletDefinitionForm createNewPortletDefinitionForm() {
final PortletDefinitionForm form = new PortletDefinitionForm();
// pre-populate with top-level category
final IEntityGroup portletCategoriesGroup =
GroupService.getDistinguishedGroup(IPortletDefinition.DISTINGUISHED_GROUP);
form.addCategory(
new JsonEntityBean(
portletCategoriesGroup,
groupListHelper.getEntityType(portletCategoriesGroup)));
// pre-populate with top-level group
final IEntityGroup everyoneGroup =
GroupService.getDistinguishedGroup(IPerson.DISTINGUISHED_GROUP);
final JsonEntityBean everyoneBean =
new JsonEntityBean(everyoneGroup, groupListHelper.getEntityType(everyoneGroup));
form.setPrincipals(Collections.singleton(everyoneBean), true);
return form;
} | java | private PortletDefinitionForm createNewPortletDefinitionForm() {
final PortletDefinitionForm form = new PortletDefinitionForm();
// pre-populate with top-level category
final IEntityGroup portletCategoriesGroup =
GroupService.getDistinguishedGroup(IPortletDefinition.DISTINGUISHED_GROUP);
form.addCategory(
new JsonEntityBean(
portletCategoriesGroup,
groupListHelper.getEntityType(portletCategoriesGroup)));
// pre-populate with top-level group
final IEntityGroup everyoneGroup =
GroupService.getDistinguishedGroup(IPerson.DISTINGUISHED_GROUP);
final JsonEntityBean everyoneBean =
new JsonEntityBean(everyoneGroup, groupListHelper.getEntityType(everyoneGroup));
form.setPrincipals(Collections.singleton(everyoneBean), true);
return form;
} | [
"private",
"PortletDefinitionForm",
"createNewPortletDefinitionForm",
"(",
")",
"{",
"final",
"PortletDefinitionForm",
"form",
"=",
"new",
"PortletDefinitionForm",
"(",
")",
";",
"// pre-populate with top-level category",
"final",
"IEntityGroup",
"portletCategoriesGroup",
"=",
... | /*
Create a {@code PortletDefinitionForm} and pre-populate it with default categories and principal permissions. | [
"/",
"*",
"Create",
"a",
"{"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/portletadmin/PortletAdministrationHelper.java#L266-L285 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkProxy.java | WorkProxy.contextSetupFailure | private WorkCompletedException contextSetupFailure(Object context, String errorCode, Throwable cause) {
if (context instanceof WorkContextLifecycleListener)
((WorkContextLifecycleListener) context).contextSetupFailed(errorCode);
String message = null;
if (WorkContextErrorCodes.DUPLICATE_CONTEXTS.equals(errorCode))
message = Utils.getMessage("J2CA8624.work.context.duplicate", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (WorkContextErrorCodes.UNSUPPORTED_CONTEXT_TYPE.equals(errorCode))
message = Utils.getMessage("J2CA8625.work.context.unavailable", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (cause != null)
message = cause.getMessage();
WorkCompletedException wcex = new WorkCompletedException(message, errorCode);
if (cause != null)
wcex.initCause(cause);
return wcex;
} | java | private WorkCompletedException contextSetupFailure(Object context, String errorCode, Throwable cause) {
if (context instanceof WorkContextLifecycleListener)
((WorkContextLifecycleListener) context).contextSetupFailed(errorCode);
String message = null;
if (WorkContextErrorCodes.DUPLICATE_CONTEXTS.equals(errorCode))
message = Utils.getMessage("J2CA8624.work.context.duplicate", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (WorkContextErrorCodes.UNSUPPORTED_CONTEXT_TYPE.equals(errorCode))
message = Utils.getMessage("J2CA8625.work.context.unavailable", bootstrapContext.resourceAdapterID, context.getClass().getName());
else if (cause != null)
message = cause.getMessage();
WorkCompletedException wcex = new WorkCompletedException(message, errorCode);
if (cause != null)
wcex.initCause(cause);
return wcex;
} | [
"private",
"WorkCompletedException",
"contextSetupFailure",
"(",
"Object",
"context",
",",
"String",
"errorCode",
",",
"Throwable",
"cause",
")",
"{",
"if",
"(",
"context",
"instanceof",
"WorkContextLifecycleListener",
")",
"(",
"(",
"WorkContextLifecycleListener",
")",... | Handle a work context setup failure.
@param workContext the work context.
@param errorCode error code from javax.resource.spi.work.WorkContextErrorCodes
@param cause Throwable to chain as the cause. Can be null.
@return WorkCompletedException to raise the the invoker. | [
"Handle",
"a",
"work",
"context",
"setup",
"failure",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkProxy.java#L325-L343 |
dynjs/dynjs | src/main/java/org/dynjs/runtime/modules/ModuleProvider.java | ModuleProvider.setLocalVar | public static void setLocalVar(ExecutionContext context, String name, Object value) {
LexicalEnvironment localEnv = context.getLexicalEnvironment();
localEnv.getRecord().createMutableBinding(context, name, false);
localEnv.getRecord().setMutableBinding(context, name, value, false);
} | java | public static void setLocalVar(ExecutionContext context, String name, Object value) {
LexicalEnvironment localEnv = context.getLexicalEnvironment();
localEnv.getRecord().createMutableBinding(context, name, false);
localEnv.getRecord().setMutableBinding(context, name, value, false);
} | [
"public",
"static",
"void",
"setLocalVar",
"(",
"ExecutionContext",
"context",
",",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"LexicalEnvironment",
"localEnv",
"=",
"context",
".",
"getLexicalEnvironment",
"(",
")",
";",
"localEnv",
".",
"getRecord",
"... | A convenience for module providers. Sets a scoped variable on the provided
ExecutionContext.
@param context The execution context to bind the variable to
@param name The name of the variable
@param value The value to set the variable to | [
"A",
"convenience",
"for",
"module",
"providers",
".",
"Sets",
"a",
"scoped",
"variable",
"on",
"the",
"provided",
"ExecutionContext",
"."
] | train | https://github.com/dynjs/dynjs/blob/4bc6715eff8768f8cd92c6a167d621bbfc1e1a91/src/main/java/org/dynjs/runtime/modules/ModuleProvider.java#L45-L49 |
Jasig/uPortal | uPortal-security/uPortal-security-xslt/src/main/java/org/apereo/portal/security/xslt/XalanGroupMembershipHelperBean.java | XalanGroupMembershipHelperBean.isUserDeepMemberOfGroupName | @Override
public boolean isUserDeepMemberOfGroupName(String userName, String groupName) {
final EntityIdentifier[] results =
GroupService.searchForGroups(
groupName, GroupService.SearchMethod.DISCRETE, IPerson.class);
if (results == null || results.length == 0) {
return false;
}
if (results.length > 1) {
this.logger.warn(
results.length
+ " groups were found for '"
+ groupName
+ "'. The first result will be used.");
}
final IGroupMember group = GroupService.getGroupMember(results[0]);
final IEntity entity = GroupService.getEntity(userName, IPerson.class);
if (entity == null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("No user found for key '" + userName + "'");
}
return false;
}
return group.asGroup().deepContains(entity);
} | java | @Override
public boolean isUserDeepMemberOfGroupName(String userName, String groupName) {
final EntityIdentifier[] results =
GroupService.searchForGroups(
groupName, GroupService.SearchMethod.DISCRETE, IPerson.class);
if (results == null || results.length == 0) {
return false;
}
if (results.length > 1) {
this.logger.warn(
results.length
+ " groups were found for '"
+ groupName
+ "'. The first result will be used.");
}
final IGroupMember group = GroupService.getGroupMember(results[0]);
final IEntity entity = GroupService.getEntity(userName, IPerson.class);
if (entity == null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("No user found for key '" + userName + "'");
}
return false;
}
return group.asGroup().deepContains(entity);
} | [
"@",
"Override",
"public",
"boolean",
"isUserDeepMemberOfGroupName",
"(",
"String",
"userName",
",",
"String",
"groupName",
")",
"{",
"final",
"EntityIdentifier",
"[",
"]",
"results",
"=",
"GroupService",
".",
"searchForGroups",
"(",
"groupName",
",",
"GroupService"... | /* (non-Javadoc)
@see org.apereo.portal.security.xslt.IXalanGroupMembershipHelper#isUserDeepMemberOfGroupName(java.lang.String, java.lang.String)
groupName is case sensitive. | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")",
"@see",
"org",
".",
"apereo",
".",
"portal",
".",
"security",
".",
"xslt",
".",
"IXalanGroupMembershipHelper#isUserDeepMemberOfGroupName",
"(",
"java",
".",
"lang",
".",
"String",
"java",
".",
"lang",
".",
"String",... | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-xslt/src/main/java/org/apereo/portal/security/xslt/XalanGroupMembershipHelperBean.java#L121-L150 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/ScrollableDataTableModelExample.java | ScrollableDataTableModelExample.createTable | private WDataTable createTable() {
WDataTable table = new WDataTable();
table.addColumn(new WTableColumn("First name", WText.class));
table.addColumn(new WTableColumn("Last name", WText.class));
table.addColumn(new WTableColumn("DOB", WText.class));
table.setPaginationMode(PaginationMode.DYNAMIC);
table.setRowsPerPage(1);
table.setDataModel(createTableModel());
return table;
} | java | private WDataTable createTable() {
WDataTable table = new WDataTable();
table.addColumn(new WTableColumn("First name", WText.class));
table.addColumn(new WTableColumn("Last name", WText.class));
table.addColumn(new WTableColumn("DOB", WText.class));
table.setPaginationMode(PaginationMode.DYNAMIC);
table.setRowsPerPage(1);
table.setDataModel(createTableModel());
return table;
} | [
"private",
"WDataTable",
"createTable",
"(",
")",
"{",
"WDataTable",
"table",
"=",
"new",
"WDataTable",
"(",
")",
";",
"table",
".",
"addColumn",
"(",
"new",
"WTableColumn",
"(",
"\"First name\"",
",",
"WText",
".",
"class",
")",
")",
";",
"table",
".",
... | Creates and configures the table to be used by the example. The table is configured with global rather than user
data. Although this is not a realistic scenario, it will suffice for this example.
@return a new configured table. | [
"Creates",
"and",
"configures",
"the",
"table",
"to",
"be",
"used",
"by",
"the",
"example",
".",
"The",
"table",
"is",
"configured",
"with",
"global",
"rather",
"than",
"user",
"data",
".",
"Although",
"this",
"is",
"not",
"a",
"realistic",
"scenario",
"it... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/ScrollableDataTableModelExample.java#L40-L51 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java | DistributionBeanQuery.loadBeans | @Override
protected List<ProxyDistribution> loadBeans(final int startIndex, final int count) {
Page<DistributionSet> distBeans;
final List<ProxyDistribution> proxyDistributions = new ArrayList<>();
if (startIndex == 0 && firstPageDistributionSets != null) {
distBeans = firstPageDistributionSets;
} else if (pinnedTarget != null) {
final DistributionSetFilterBuilder distributionSetFilterBuilder = new DistributionSetFilterBuilder()
.setIsDeleted(false).setIsComplete(true).setSearchText(searchText)
.setSelectDSWithNoTag(noTagClicked).setTagNames(distributionTags);
distBeans = getDistributionSetManagement().findByFilterAndAssignedInstalledDsOrderedByLinkTarget(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilterBuilder,
pinnedTarget.getControllerId());
} else if (distributionTags.isEmpty() && StringUtils.isEmpty(searchText) && !noTagClicked) {
// if no search filters available
distBeans = getDistributionSetManagement()
.findByCompleted(new OffsetBasedPageRequest(startIndex, count, sort), true);
} else {
final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false)
.setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked)
.setTagNames(distributionTags).build();
distBeans = getDistributionSetManagement().findByDistributionSetFilter(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilter);
}
for (final DistributionSet distributionSet : distBeans) {
final ProxyDistribution proxyDistribution = new ProxyDistribution();
proxyDistribution.setName(distributionSet.getName());
proxyDistribution.setDescription(distributionSet.getDescription());
proxyDistribution.setId(distributionSet.getId());
proxyDistribution.setDistId(distributionSet.getId());
proxyDistribution.setVersion(distributionSet.getVersion());
proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt()));
proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt()));
proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet));
proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet));
proxyDistribution.setNameVersion(
HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion()));
proxyDistributions.add(proxyDistribution);
}
return proxyDistributions;
} | java | @Override
protected List<ProxyDistribution> loadBeans(final int startIndex, final int count) {
Page<DistributionSet> distBeans;
final List<ProxyDistribution> proxyDistributions = new ArrayList<>();
if (startIndex == 0 && firstPageDistributionSets != null) {
distBeans = firstPageDistributionSets;
} else if (pinnedTarget != null) {
final DistributionSetFilterBuilder distributionSetFilterBuilder = new DistributionSetFilterBuilder()
.setIsDeleted(false).setIsComplete(true).setSearchText(searchText)
.setSelectDSWithNoTag(noTagClicked).setTagNames(distributionTags);
distBeans = getDistributionSetManagement().findByFilterAndAssignedInstalledDsOrderedByLinkTarget(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilterBuilder,
pinnedTarget.getControllerId());
} else if (distributionTags.isEmpty() && StringUtils.isEmpty(searchText) && !noTagClicked) {
// if no search filters available
distBeans = getDistributionSetManagement()
.findByCompleted(new OffsetBasedPageRequest(startIndex, count, sort), true);
} else {
final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false)
.setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked)
.setTagNames(distributionTags).build();
distBeans = getDistributionSetManagement().findByDistributionSetFilter(
new OffsetBasedPageRequest(startIndex, count, sort), distributionSetFilter);
}
for (final DistributionSet distributionSet : distBeans) {
final ProxyDistribution proxyDistribution = new ProxyDistribution();
proxyDistribution.setName(distributionSet.getName());
proxyDistribution.setDescription(distributionSet.getDescription());
proxyDistribution.setId(distributionSet.getId());
proxyDistribution.setDistId(distributionSet.getId());
proxyDistribution.setVersion(distributionSet.getVersion());
proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt()));
proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt()));
proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet));
proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet));
proxyDistribution.setNameVersion(
HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion()));
proxyDistributions.add(proxyDistribution);
}
return proxyDistributions;
} | [
"@",
"Override",
"protected",
"List",
"<",
"ProxyDistribution",
">",
"loadBeans",
"(",
"final",
"int",
"startIndex",
",",
"final",
"int",
"count",
")",
"{",
"Page",
"<",
"DistributionSet",
">",
"distBeans",
";",
"final",
"List",
"<",
"ProxyDistribution",
">",
... | Load all the Distribution set.
@param startIndex
as page start
@param count
as total data | [
"Load",
"all",
"the",
"Distribution",
"set",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java#L97-L139 |
apache/flink | flink-java/src/main/java/org/apache/flink/api/java/operators/join/JoinOperatorSetsBase.java | JoinOperatorSetsBase.where | public JoinOperatorSetsPredicateBase where(String... fields) {
return new JoinOperatorSetsPredicateBase(new Keys.ExpressionKeys<>(fields, input1.getType()));
} | java | public JoinOperatorSetsPredicateBase where(String... fields) {
return new JoinOperatorSetsPredicateBase(new Keys.ExpressionKeys<>(fields, input1.getType()));
} | [
"public",
"JoinOperatorSetsPredicateBase",
"where",
"(",
"String",
"...",
"fields",
")",
"{",
"return",
"new",
"JoinOperatorSetsPredicateBase",
"(",
"new",
"Keys",
".",
"ExpressionKeys",
"<>",
"(",
"fields",
",",
"input1",
".",
"getType",
"(",
")",
")",
")",
"... | Continues a Join transformation.
<p>Defines the fields of the first join {@link DataSet} that should be used as grouping keys. Fields
are the names of member fields of the underlying type of the data set.
@param fields The fields of the first join DataSets that should be used as keys.
@return An incomplete Join transformation.
Call {@link org.apache.flink.api.java.operators.join.JoinOperatorSetsBase.JoinOperatorSetsPredicateBase#equalTo(int...)} or
{@link org.apache.flink.api.java.operators.join.JoinOperatorSetsBase.JoinOperatorSetsPredicateBase#equalTo(KeySelector)}
to continue the Join.
@see Tuple
@see DataSet | [
"Continues",
"a",
"Join",
"transformation",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-java/src/main/java/org/apache/flink/api/java/operators/join/JoinOperatorSetsBase.java#L109-L111 |
alkacon/opencms-core | src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java | CmsEditablePositionCalculator.intersectsHorizontally | protected boolean intersectsHorizontally(CmsPositionBean p1, CmsPositionBean p2) {
return intersectIntervals(p1.getLeft(), p1.getLeft() + WIDTH, p2.getLeft(), p2.getLeft() + WIDTH);
} | java | protected boolean intersectsHorizontally(CmsPositionBean p1, CmsPositionBean p2) {
return intersectIntervals(p1.getLeft(), p1.getLeft() + WIDTH, p2.getLeft(), p2.getLeft() + WIDTH);
} | [
"protected",
"boolean",
"intersectsHorizontally",
"(",
"CmsPositionBean",
"p1",
",",
"CmsPositionBean",
"p2",
")",
"{",
"return",
"intersectIntervals",
"(",
"p1",
".",
"getLeft",
"(",
")",
",",
"p1",
".",
"getLeft",
"(",
")",
"+",
"WIDTH",
",",
"p2",
".",
... | Checks whether two positions intersect horizontally.<p>
@param p1 the first position
@param p2 the second position
@return true if the positions intersect horizontally | [
"Checks",
"whether",
"two",
"positions",
"intersect",
"horizontally",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/editprovider/client/CmsEditablePositionCalculator.java#L172-L175 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/TransformXMLInterceptor.java | TransformXMLInterceptor.initTemplates | private static Templates initTemplates() {
try {
URL xsltURL = ThemeUtil.class.getResource(RESOURCE_NAME);
if (xsltURL != null) {
Source xsltSource = new StreamSource(xsltURL.openStream(), xsltURL.toExternalForm());
TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
Templates templates = factory.newTemplates(xsltSource);
LOG.debug("Generated XSLT templates for: " + RESOURCE_NAME);
return templates;
} else {
// Server-side XSLT enabled but theme resource not on classpath.
throw new IllegalStateException(RESOURCE_NAME + " not on classpath");
}
} catch (IOException | TransformerConfigurationException ex) {
throw new SystemException("Could not create transformer for " + RESOURCE_NAME, ex);
}
} | java | private static Templates initTemplates() {
try {
URL xsltURL = ThemeUtil.class.getResource(RESOURCE_NAME);
if (xsltURL != null) {
Source xsltSource = new StreamSource(xsltURL.openStream(), xsltURL.toExternalForm());
TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
Templates templates = factory.newTemplates(xsltSource);
LOG.debug("Generated XSLT templates for: " + RESOURCE_NAME);
return templates;
} else {
// Server-side XSLT enabled but theme resource not on classpath.
throw new IllegalStateException(RESOURCE_NAME + " not on classpath");
}
} catch (IOException | TransformerConfigurationException ex) {
throw new SystemException("Could not create transformer for " + RESOURCE_NAME, ex);
}
} | [
"private",
"static",
"Templates",
"initTemplates",
"(",
")",
"{",
"try",
"{",
"URL",
"xsltURL",
"=",
"ThemeUtil",
".",
"class",
".",
"getResource",
"(",
"RESOURCE_NAME",
")",
";",
"if",
"(",
"xsltURL",
"!=",
"null",
")",
"{",
"Source",
"xsltSource",
"=",
... | Statically initialize the XSLT templates that are cached for all future transforms.
@return the XSLT Templates. | [
"Statically",
"initialize",
"the",
"XSLT",
"templates",
"that",
"are",
"cached",
"for",
"all",
"future",
"transforms",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/TransformXMLInterceptor.java#L221-L237 |
alipay/sofa-rpc | extension-impl/registry-zk/src/main/java/com/alipay/sofa/rpc/registry/zk/ZookeeperProviderObserver.java | ZookeeperProviderObserver.updateProvider | public void updateProvider(ConsumerConfig config, String providerPath, ChildData data, List<ChildData> currentData)
throws UnsupportedEncodingException {
if (LOGGER.isInfoEnabled(config.getAppName())) {
LOGGER.infoWithApp(config.getAppName(),
"Receive update provider: path=[" + data.getPath() + "]" + ", data=[" +
StringSerializer.decode(data.getData()) + "]" + ", stat=[" + data.getStat() + "]" + ", list=[" +
currentData.size() + "]");
}
notifyListeners(config, providerPath, currentData, false);
} | java | public void updateProvider(ConsumerConfig config, String providerPath, ChildData data, List<ChildData> currentData)
throws UnsupportedEncodingException {
if (LOGGER.isInfoEnabled(config.getAppName())) {
LOGGER.infoWithApp(config.getAppName(),
"Receive update provider: path=[" + data.getPath() + "]" + ", data=[" +
StringSerializer.decode(data.getData()) + "]" + ", stat=[" + data.getStat() + "]" + ", list=[" +
currentData.size() + "]");
}
notifyListeners(config, providerPath, currentData, false);
} | [
"public",
"void",
"updateProvider",
"(",
"ConsumerConfig",
"config",
",",
"String",
"providerPath",
",",
"ChildData",
"data",
",",
"List",
"<",
"ChildData",
">",
"currentData",
")",
"throws",
"UnsupportedEncodingException",
"{",
"if",
"(",
"LOGGER",
".",
"isInfoEn... | Update Provider
@param config ConsumerConfig
@param providerPath Provider path of zookeeper
@param data Event data
@param currentData provider data list
@throws UnsupportedEncodingException decode error | [
"Update",
"Provider"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/registry-zk/src/main/java/com/alipay/sofa/rpc/registry/zk/ZookeeperProviderObserver.java#L83-L92 |
mgm-tp/jfunk | jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailService.java | MailService.findMessage | public MailMessage findMessage(final String accountReservationKey, final Predicate<MailMessage> condition) {
return findMessage(accountReservationKey, condition, defaultTimeoutSeconds);
} | java | public MailMessage findMessage(final String accountReservationKey, final Predicate<MailMessage> condition) {
return findMessage(accountReservationKey, condition, defaultTimeoutSeconds);
} | [
"public",
"MailMessage",
"findMessage",
"(",
"final",
"String",
"accountReservationKey",
",",
"final",
"Predicate",
"<",
"MailMessage",
">",
"condition",
")",
"{",
"return",
"findMessage",
"(",
"accountReservationKey",
",",
"condition",
",",
"defaultTimeoutSeconds",
"... | Tries to find a message for the mail account reserved under the specified
{@code accountReservationKey} applying the specified {@code condition} until it times out
using the default timeout ( {@link EmailConstants#MAIL_TIMEOUT_SECONDS} and
{@link EmailConstants#MAIL_SLEEP_MILLIS}).
@param accountReservationKey
the key under which the account has been reserved
@param condition
the condition a message must meet
@return the mail message | [
"Tries",
"to",
"find",
"a",
"message",
"for",
"the",
"mail",
"account",
"reserved",
"under",
"the",
"specified",
"{",
"@code",
"accountReservationKey",
"}",
"applying",
"the",
"specified",
"{",
"@code",
"condition",
"}",
"until",
"it",
"times",
"out",
"using",... | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailService.java#L79-L81 |
Pi4J/pi4j | pi4j-core/src/main/java/com/pi4j/io/gpio/NanoPiPin.java | NanoPiPin.createDigitalPin | protected static Pin createDigitalPin(int address, String name) {
return createDigitalPin(NanoPiGpioProvider.NAME, address, name);
} | java | protected static Pin createDigitalPin(int address, String name) {
return createDigitalPin(NanoPiGpioProvider.NAME, address, name);
} | [
"protected",
"static",
"Pin",
"createDigitalPin",
"(",
"int",
"address",
",",
"String",
"name",
")",
"{",
"return",
"createDigitalPin",
"(",
"NanoPiGpioProvider",
".",
"NAME",
",",
"address",
",",
"name",
")",
";",
"}"
] | this pin is permanently pulled up; pin pull settings do not work | [
"this",
"pin",
"is",
"permanently",
"pulled",
"up",
";",
"pin",
"pull",
"settings",
"do",
"not",
"work"
] | train | https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/gpio/NanoPiPin.java#L74-L76 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java | PathBuilder.get | @SuppressWarnings("unchecked")
public <A extends Comparable<?>> TimePath<A> get(TimePath<A> path) {
TimePath<A> newPath = getTime(toString(path), (Class<A>) path.getType());
return addMetadataOf(newPath, path);
} | java | @SuppressWarnings("unchecked")
public <A extends Comparable<?>> TimePath<A> get(TimePath<A> path) {
TimePath<A> newPath = getTime(toString(path), (Class<A>) path.getType());
return addMetadataOf(newPath, path);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"A",
"extends",
"Comparable",
"<",
"?",
">",
">",
"TimePath",
"<",
"A",
">",
"get",
"(",
"TimePath",
"<",
"A",
">",
"path",
")",
"{",
"TimePath",
"<",
"A",
">",
"newPath",
"=",
"getTi... | Create a new Time typed path
@param <A>
@param path existing path
@return property path | [
"Create",
"a",
"new",
"Time",
"typed",
"path"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java#L501-L505 |
sarl/sarl | main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/cast/CastScopeSession.java | CastScopeSession.createCastOperatorScope | protected IScope createCastOperatorScope(EObject context, EReference reference, IResolvedTypes resolvedTypes) {
if (!(context instanceof SarlCastedExpression)) {
return IScope.NULLSCOPE;
}
final SarlCastedExpression call = (SarlCastedExpression) context;
final XExpression receiver = call.getTarget();
if (receiver == null) {
return IScope.NULLSCOPE;
}
return getFeatureScopes().createFeatureCallScopeForReceiver(call, receiver, getParent(), resolvedTypes);
} | java | protected IScope createCastOperatorScope(EObject context, EReference reference, IResolvedTypes resolvedTypes) {
if (!(context instanceof SarlCastedExpression)) {
return IScope.NULLSCOPE;
}
final SarlCastedExpression call = (SarlCastedExpression) context;
final XExpression receiver = call.getTarget();
if (receiver == null) {
return IScope.NULLSCOPE;
}
return getFeatureScopes().createFeatureCallScopeForReceiver(call, receiver, getParent(), resolvedTypes);
} | [
"protected",
"IScope",
"createCastOperatorScope",
"(",
"EObject",
"context",
",",
"EReference",
"reference",
",",
"IResolvedTypes",
"resolvedTypes",
")",
"{",
"if",
"(",
"!",
"(",
"context",
"instanceof",
"SarlCastedExpression",
")",
")",
"{",
"return",
"IScope",
... | create a scope for cast operator.
@param context the context.
@param reference the reference to the internal feature.
@param resolvedTypes the resolved types.
@return the scope. | [
"create",
"a",
"scope",
"for",
"cast",
"operator",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/cast/CastScopeSession.java#L78-L88 |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/Assembler.java | Assembler.if_tcmpge | public void if_tcmpge(TypeMirror type, String target) throws IOException
{
pushType(type);
if_tcmpge(target);
popType();
} | java | public void if_tcmpge(TypeMirror type, String target) throws IOException
{
pushType(type);
if_tcmpge(target);
popType();
} | [
"public",
"void",
"if_tcmpge",
"(",
"TypeMirror",
"type",
",",
"String",
"target",
")",
"throws",
"IOException",
"{",
"pushType",
"(",
"type",
")",
";",
"if_tcmpge",
"(",
"target",
")",
";",
"popType",
"(",
")",
";",
"}"
] | ge succeeds if and only if value1 >= value2
<p>Stack: ..., value1, value2 => ...
@param type
@param target
@throws IOException | [
"ge",
"succeeds",
"if",
"and",
"only",
"if",
"value1",
">",
";",
"=",
"value2",
"<p",
">",
"Stack",
":",
"...",
"value1",
"value2",
"=",
">",
";",
"..."
] | train | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/Assembler.java#L656-L661 |
ngageoint/geopackage-java | src/main/java/mil/nga/geopackage/tiles/features/DefaultFeatureTiles.java | DefaultFeatureTiles.drawPolygon | private boolean drawPolygon(double simplifyTolerance,
BoundingBox boundingBox, ProjectionTransform transform,
FeatureTileGraphics graphics, Polygon polygon,
FeatureStyle featureStyle) {
Area polygonArea = getArea(simplifyTolerance, boundingBox, transform,
polygon);
return drawPolygon(graphics, polygonArea, featureStyle);
} | java | private boolean drawPolygon(double simplifyTolerance,
BoundingBox boundingBox, ProjectionTransform transform,
FeatureTileGraphics graphics, Polygon polygon,
FeatureStyle featureStyle) {
Area polygonArea = getArea(simplifyTolerance, boundingBox, transform,
polygon);
return drawPolygon(graphics, polygonArea, featureStyle);
} | [
"private",
"boolean",
"drawPolygon",
"(",
"double",
"simplifyTolerance",
",",
"BoundingBox",
"boundingBox",
",",
"ProjectionTransform",
"transform",
",",
"FeatureTileGraphics",
"graphics",
",",
"Polygon",
"polygon",
",",
"FeatureStyle",
"featureStyle",
")",
"{",
"Area",... | Draw a Polygon
@param simplifyTolerance
simplify tolerance in meters
@param boundingBox
bounding box
@param transform
projection transform
@param graphics
feature tile graphics
@param polygon
polygon
@param featureStyle
feature style
@return true if drawn | [
"Draw",
"a",
"Polygon"
] | train | https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/tiles/features/DefaultFeatureTiles.java#L481-L488 |
indeedeng/util | io/src/main/java/com/indeed/util/io/Files.java | Files.isChanged | private static boolean isChanged(final byte[] bytes, final int length, final String filepath) throws IOException {
Preconditions.checkArgument(length >= 0, "invalid length value: %s", length);
Preconditions.checkArgument(bytes.length >= length, "invalid length value: %s", length);
File file = new File(filepath);
if (!file.exists()) {
return true;
}
if (file.length() != length) {
return true;
}
final int BUFLEN = 1048576; // 1 megabyte
byte[] buffer = new byte[BUFLEN];
InputStream is = new FileInputStream(file);
try {
int len;
for (int offset = 0; ; offset += len) {
len = is.read(buffer);
if (len < 0) break; // eof
if (!arrayCompare(bytes, offset, buffer, 0, len)) return true;
}
return false;
} finally {
is.close();
}
} | java | private static boolean isChanged(final byte[] bytes, final int length, final String filepath) throws IOException {
Preconditions.checkArgument(length >= 0, "invalid length value: %s", length);
Preconditions.checkArgument(bytes.length >= length, "invalid length value: %s", length);
File file = new File(filepath);
if (!file.exists()) {
return true;
}
if (file.length() != length) {
return true;
}
final int BUFLEN = 1048576; // 1 megabyte
byte[] buffer = new byte[BUFLEN];
InputStream is = new FileInputStream(file);
try {
int len;
for (int offset = 0; ; offset += len) {
len = is.read(buffer);
if (len < 0) break; // eof
if (!arrayCompare(bytes, offset, buffer, 0, len)) return true;
}
return false;
} finally {
is.close();
}
} | [
"private",
"static",
"boolean",
"isChanged",
"(",
"final",
"byte",
"[",
"]",
"bytes",
",",
"final",
"int",
"length",
",",
"final",
"String",
"filepath",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"length",
">=",
"0",
",",
... | Returns true iff the bytes in an array are different from the bytes
contained in the given file, or if the file does not exist. | [
"Returns",
"true",
"iff",
"the",
"bytes",
"in",
"an",
"array",
"are",
"different",
"from",
"the",
"bytes",
"contained",
"in",
"the",
"given",
"file",
"or",
"if",
"the",
"file",
"does",
"not",
"exist",
"."
] | train | https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/io/src/main/java/com/indeed/util/io/Files.java#L376-L401 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java | CPDefinitionLinkPersistenceImpl.findByCPDefinitionId | @Override
public List<CPDefinitionLink> findByCPDefinitionId(long CPDefinitionId,
int start, int end) {
return findByCPDefinitionId(CPDefinitionId, start, end, null);
} | java | @Override
public List<CPDefinitionLink> findByCPDefinitionId(long CPDefinitionId,
int start, int end) {
return findByCPDefinitionId(CPDefinitionId, start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinitionLink",
">",
"findByCPDefinitionId",
"(",
"long",
"CPDefinitionId",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findByCPDefinitionId",
"(",
"CPDefinitionId",
",",
"start",
",",
"end",
",",
"n... | Returns a range of all the cp definition links where CPDefinitionId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDefinitionLinkModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CPDefinitionId the cp definition ID
@param start the lower bound of the range of cp definition links
@param end the upper bound of the range of cp definition links (not inclusive)
@return the range of matching cp definition links | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"definition",
"links",
"where",
"CPDefinitionId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java#L1533-L1537 |
gdx-libs/gdx-kiwi | src/com/github/czyzby/kiwi/util/common/Comparables.java | Comparables.nullSafeCompare | public static <Value extends Comparable<Value>> int nullSafeCompare(final Value first, final Value second) {
if (first == null) {
return second == null ? EQUAL_COMPARE_RESULT : LOWER_THAN_COMPARE_RESULT;
}
return second == null ? GREATER_THAN_COMPARE_RESULT : first.compareTo(second);
} | java | public static <Value extends Comparable<Value>> int nullSafeCompare(final Value first, final Value second) {
if (first == null) {
return second == null ? EQUAL_COMPARE_RESULT : LOWER_THAN_COMPARE_RESULT;
}
return second == null ? GREATER_THAN_COMPARE_RESULT : first.compareTo(second);
} | [
"public",
"static",
"<",
"Value",
"extends",
"Comparable",
"<",
"Value",
">",
">",
"int",
"nullSafeCompare",
"(",
"final",
"Value",
"first",
",",
"final",
"Value",
"second",
")",
"{",
"if",
"(",
"first",
"==",
"null",
")",
"{",
"return",
"second",
"==",
... | Safely compares two values that might be null. Null value is considered lower than non-null, even if the
non-null value is minimal in its range.
@return comparison result of first and second value. | [
"Safely",
"compares",
"two",
"values",
"that",
"might",
"be",
"null",
".",
"Null",
"value",
"is",
"considered",
"lower",
"than",
"non",
"-",
"null",
"even",
"if",
"the",
"non",
"-",
"null",
"value",
"is",
"minimal",
"in",
"its",
"range",
"."
] | train | https://github.com/gdx-libs/gdx-kiwi/blob/0172ee7534162f33b939bcdc4de089bc9579dd62/src/com/github/czyzby/kiwi/util/common/Comparables.java#L72-L77 |
facebookarchive/hadoop-20 | src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/LocalStore.java | LocalStore.copyToHDFS | public static void copyToHDFS(String localFile, String hdfsFile) throws IOException {
String hadoopConfPath;
if (Environment.getProperty("hadoop.conf.path") == null)
hadoopConfPath = "../../../conf";
else
hadoopConfPath = Environment.getProperty("hadoop.conf.path");
// Read the configuration for the Hadoop environment
Configuration hadoopConf = new Configuration();
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-default.xml"));
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-site.xml"));
// System.out.println(hadoopConf.get("hadoop.tmp.dir"));
// System.out.println(hadoopConf.get("fs.default.name"));
FileSystem fs = FileSystem.get(hadoopConf);
// HadoopDFS deals with Path
Path inFile = new Path("file://" + localFile);
Path outFile = new Path(hadoopConf.get("fs.default.name") + hdfsFile);
// Read from and write to new file
Environment.logInfo("Uploading to HDFS (file " + outFile + ") ...");
fs.copyFromLocalFile(false, inFile, outFile);
} | java | public static void copyToHDFS(String localFile, String hdfsFile) throws IOException {
String hadoopConfPath;
if (Environment.getProperty("hadoop.conf.path") == null)
hadoopConfPath = "../../../conf";
else
hadoopConfPath = Environment.getProperty("hadoop.conf.path");
// Read the configuration for the Hadoop environment
Configuration hadoopConf = new Configuration();
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-default.xml"));
hadoopConf.addResource(new Path(hadoopConfPath + "/hadoop-site.xml"));
// System.out.println(hadoopConf.get("hadoop.tmp.dir"));
// System.out.println(hadoopConf.get("fs.default.name"));
FileSystem fs = FileSystem.get(hadoopConf);
// HadoopDFS deals with Path
Path inFile = new Path("file://" + localFile);
Path outFile = new Path(hadoopConf.get("fs.default.name") + hdfsFile);
// Read from and write to new file
Environment.logInfo("Uploading to HDFS (file " + outFile + ") ...");
fs.copyFromLocalFile(false, inFile, outFile);
} | [
"public",
"static",
"void",
"copyToHDFS",
"(",
"String",
"localFile",
",",
"String",
"hdfsFile",
")",
"throws",
"IOException",
"{",
"String",
"hadoopConfPath",
";",
"if",
"(",
"Environment",
".",
"getProperty",
"(",
"\"hadoop.conf.path\"",
")",
"==",
"null",
")"... | Copy a local file to HDFS
@param localFile the filename of the local file
@param hdfsFile the HDFS filename to copy to | [
"Copy",
"a",
"local",
"file",
"to",
"HDFS"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/LocalStore.java#L229-L254 |
Harium/keel | src/main/java/com/harium/keel/catalano/statistics/HistogramStatistics.java | HistogramStatistics.Kurtosis | public static double Kurtosis(int[] values){
double mean = Mean(values);
double std = StdDev(values, mean);
return Kurtosis(values, mean, std);
} | java | public static double Kurtosis(int[] values){
double mean = Mean(values);
double std = StdDev(values, mean);
return Kurtosis(values, mean, std);
} | [
"public",
"static",
"double",
"Kurtosis",
"(",
"int",
"[",
"]",
"values",
")",
"{",
"double",
"mean",
"=",
"Mean",
"(",
"values",
")",
";",
"double",
"std",
"=",
"StdDev",
"(",
"values",
",",
"mean",
")",
";",
"return",
"Kurtosis",
"(",
"values",
","... | Calculate Kurtosis value.
@param values Values.
@return Returns kurtosis value of the specified histogram array. | [
"Calculate",
"Kurtosis",
"value",
"."
] | train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/statistics/HistogramStatistics.java#L114-L118 |
anotheria/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/action/BaseAJAXMoskitoUIAction.java | BaseAJAXMoskitoUIAction.writeTextToResponse | private static void writeTextToResponse(final HttpServletResponse res, final JSONResponse jsonResponse) throws IOException {
writeTextToResponse(res, jsonResponse.toString());
} | java | private static void writeTextToResponse(final HttpServletResponse res, final JSONResponse jsonResponse) throws IOException {
writeTextToResponse(res, jsonResponse.toString());
} | [
"private",
"static",
"void",
"writeTextToResponse",
"(",
"final",
"HttpServletResponse",
"res",
",",
"final",
"JSONResponse",
"jsonResponse",
")",
"throws",
"IOException",
"{",
"writeTextToResponse",
"(",
"res",
",",
"jsonResponse",
".",
"toString",
"(",
")",
")",
... | Writes specified text to response and flushes the stream.
@param res
{@link HttpServletRequest}
@param jsonResponse
{@link JSONResponse}
@throws java.io.IOException
if an input or output exception occurred | [
"Writes",
"specified",
"text",
"to",
"response",
"and",
"flushes",
"the",
"stream",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-webui/src/main/java/net/anotheria/moskito/webui/shared/action/BaseAJAXMoskitoUIAction.java#L98-L100 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java | HtmlDocletWriter.getDocLink | public Content getDocLink(LinkInfoImpl.Kind context, ClassDoc classDoc, MemberDoc doc,
Content label) {
if (! (doc.isIncluded() ||
Util.isLinkable(classDoc, configuration))) {
return label;
} else if (doc instanceof ExecutableMemberDoc) {
ExecutableMemberDoc emd = (ExecutableMemberDoc) doc;
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(getAnchor(emd))));
} else if (doc instanceof MemberDoc) {
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(doc.name())));
} else {
return label;
}
} | java | public Content getDocLink(LinkInfoImpl.Kind context, ClassDoc classDoc, MemberDoc doc,
Content label) {
if (! (doc.isIncluded() ||
Util.isLinkable(classDoc, configuration))) {
return label;
} else if (doc instanceof ExecutableMemberDoc) {
ExecutableMemberDoc emd = (ExecutableMemberDoc) doc;
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(getAnchor(emd))));
} else if (doc instanceof MemberDoc) {
return getLink(new LinkInfoImpl(configuration, context, classDoc)
.label(label).where(getName(doc.name())));
} else {
return label;
}
} | [
"public",
"Content",
"getDocLink",
"(",
"LinkInfoImpl",
".",
"Kind",
"context",
",",
"ClassDoc",
"classDoc",
",",
"MemberDoc",
"doc",
",",
"Content",
"label",
")",
"{",
"if",
"(",
"!",
"(",
"doc",
".",
"isIncluded",
"(",
")",
"||",
"Util",
".",
"isLinkab... | Return the link for the given member.
@param context the id of the context where the link will be added
@param classDoc the classDoc that we should link to. This is not
necessarily equal to doc.containingClass(). We may be
inheriting comments
@param doc the member being linked to
@param label the label for the link
@return the link for the given member | [
"Return",
"the",
"link",
"for",
"the",
"given",
"member",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L1317-L1332 |
wildfly/wildfly-core | logging/src/main/java/org/jboss/as/logging/LoggingSubsystemParser.java | LoggingSubsystemParser.parseFilter | static void parseFilter(final ModelNode operation, final XMLExtendedStreamReader reader) throws XMLStreamException {
final StringBuilder filter = new StringBuilder();
parseFilterChildren(filter, false, reader);
operation.get(FILTER_SPEC.getName()).set(filter.toString());
} | java | static void parseFilter(final ModelNode operation, final XMLExtendedStreamReader reader) throws XMLStreamException {
final StringBuilder filter = new StringBuilder();
parseFilterChildren(filter, false, reader);
operation.get(FILTER_SPEC.getName()).set(filter.toString());
} | [
"static",
"void",
"parseFilter",
"(",
"final",
"ModelNode",
"operation",
",",
"final",
"XMLExtendedStreamReader",
"reader",
")",
"throws",
"XMLStreamException",
"{",
"final",
"StringBuilder",
"filter",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"parseFilterChildren",... | A helper to parse the deprecated {@code filter} for schema versions {@code 1.0} and {@code 1.1}. This parses the
XML and creates a {@code filter-spec} expression. The expression is set as the value for the {@code filter-spec}
attribute on the operation.
@param operation the operation to add the parsed filter to
@param reader the reader used to read the filter
@throws XMLStreamException if a parsing error occurs | [
"A",
"helper",
"to",
"parse",
"the",
"deprecated",
"{",
"@code",
"filter",
"}",
"for",
"schema",
"versions",
"{",
"@code",
"1",
".",
"0",
"}",
"and",
"{",
"@code",
"1",
".",
"1",
"}",
".",
"This",
"parses",
"the",
"XML",
"and",
"creates",
"a",
"{",... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/logging/src/main/java/org/jboss/as/logging/LoggingSubsystemParser.java#L182-L186 |
netty/netty | example/src/main/java/io/netty/example/http2/helloworld/client/HttpResponseHandler.java | HttpResponseHandler.awaitResponses | public void awaitResponses(long timeout, TimeUnit unit) {
Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet().iterator();
while (itr.hasNext()) {
Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
ChannelFuture writeFuture = entry.getValue().getKey();
if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
}
if (!writeFuture.isSuccess()) {
throw new RuntimeException(writeFuture.cause());
}
ChannelPromise promise = entry.getValue().getValue();
if (!promise.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
}
if (!promise.isSuccess()) {
throw new RuntimeException(promise.cause());
}
System.out.println("---Stream id: " + entry.getKey() + " received---");
itr.remove();
}
} | java | public void awaitResponses(long timeout, TimeUnit unit) {
Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet().iterator();
while (itr.hasNext()) {
Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
ChannelFuture writeFuture = entry.getValue().getKey();
if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
}
if (!writeFuture.isSuccess()) {
throw new RuntimeException(writeFuture.cause());
}
ChannelPromise promise = entry.getValue().getValue();
if (!promise.awaitUninterruptibly(timeout, unit)) {
throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
}
if (!promise.isSuccess()) {
throw new RuntimeException(promise.cause());
}
System.out.println("---Stream id: " + entry.getKey() + " received---");
itr.remove();
}
} | [
"public",
"void",
"awaitResponses",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"Iterator",
"<",
"Entry",
"<",
"Integer",
",",
"Entry",
"<",
"ChannelFuture",
",",
"ChannelPromise",
">",
">",
">",
"itr",
"=",
"streamidPromiseMap",
".",
"entrySe... | Wait (sequentially) for a time duration for each anticipated response
@param timeout Value of time to wait for each response
@param unit Units associated with {@code timeout}
@see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise) | [
"Wait",
"(",
"sequentially",
")",
"for",
"a",
"time",
"duration",
"for",
"each",
"anticipated",
"response"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/example/src/main/java/io/netty/example/http2/helloworld/client/HttpResponseHandler.java#L66-L87 |
diffplug/durian | src/com/diffplug/common/base/FieldsAndGetters.java | FieldsAndGetters.dumpNonNull | public static void dumpNonNull(String name, Object obj, StringPrinter printer) {
dumpIf(name, obj, Predicates.alwaysTrue(), entry -> entry.getValue() != null, printer);
} | java | public static void dumpNonNull(String name, Object obj, StringPrinter printer) {
dumpIf(name, obj, Predicates.alwaysTrue(), entry -> entry.getValue() != null, printer);
} | [
"public",
"static",
"void",
"dumpNonNull",
"(",
"String",
"name",
",",
"Object",
"obj",
",",
"StringPrinter",
"printer",
")",
"{",
"dumpIf",
"(",
"name",
",",
"obj",
",",
"Predicates",
".",
"alwaysTrue",
"(",
")",
",",
"entry",
"->",
"entry",
".",
"getVa... | Dumps all non-null fields and getters of {@code obj} to {@code printer}.
@see #dumpIf | [
"Dumps",
"all",
"non",
"-",
"null",
"fields",
"and",
"getters",
"of",
"{"
] | train | https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/FieldsAndGetters.java#L193-L195 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getSecretAsync | public Observable<SecretBundle> getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) {
return getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).map(new Func1<ServiceResponse<SecretBundle>, SecretBundle>() {
@Override
public SecretBundle call(ServiceResponse<SecretBundle> response) {
return response.body();
}
});
} | java | public Observable<SecretBundle> getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) {
return getSecretWithServiceResponseAsync(vaultBaseUrl, secretName, secretVersion).map(new Func1<ServiceResponse<SecretBundle>, SecretBundle>() {
@Override
public SecretBundle call(ServiceResponse<SecretBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SecretBundle",
">",
"getSecretAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"secretName",
",",
"String",
"secretVersion",
")",
"{",
"return",
"getSecretWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"secretName",
",",
"secre... | Get a specified secret from a given key vault.
The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param secretName The name of the secret.
@param secretVersion The version of the secret.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SecretBundle object | [
"Get",
"a",
"specified",
"secret",
"from",
"a",
"given",
"key",
"vault",
".",
"The",
"GET",
"operation",
"is",
"applicable",
"to",
"any",
"secret",
"stored",
"in",
"Azure",
"Key",
"Vault",
".",
"This",
"operation",
"requires",
"the",
"secrets",
"/",
"get",... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L3857-L3864 |
alkacon/opencms-core | src/org/opencms/module/CmsModuleXmlHandler.java | CmsModuleXmlHandler.addDependency | public void addDependency(String name, String version) {
CmsModuleVersion moduleVersion = new CmsModuleVersion(version);
CmsModuleDependency dependency = new CmsModuleDependency(name, moduleVersion);
m_dependencies.add(dependency);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_MOD_DEPENDENCY_2, name, version));
}
} | java | public void addDependency(String name, String version) {
CmsModuleVersion moduleVersion = new CmsModuleVersion(version);
CmsModuleDependency dependency = new CmsModuleDependency(name, moduleVersion);
m_dependencies.add(dependency);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_MOD_DEPENDENCY_2, name, version));
}
} | [
"public",
"void",
"addDependency",
"(",
"String",
"name",
",",
"String",
"version",
")",
"{",
"CmsModuleVersion",
"moduleVersion",
"=",
"new",
"CmsModuleVersion",
"(",
"version",
")",
";",
"CmsModuleDependency",
"dependency",
"=",
"new",
"CmsModuleDependency",
"(",
... | Adds a module dependency to the current module.<p>
@param name the module name of the dependency
@param version the module version of the dependency | [
"Adds",
"a",
"module",
"dependency",
"to",
"the",
"current",
"module",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleXmlHandler.java#L548-L558 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.