repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/containers/StreamSegmentContainerMetadata.java
StreamSegmentContainerMetadata.isEligibleForEviction
private boolean isEligibleForEviction(SegmentMetadata metadata, long sequenceNumberCutoff) { """ Determines whether the Segment with given metadata can be evicted, based on the the given Sequence Number Threshold. A Segment will not be chosen for eviction if {@link SegmentMetadata#isPinned()} is true. @param metadata The Metadata for the Segment that is considered for eviction. @param sequenceNumberCutoff A Sequence Number that indicates the cutoff threshold. A Segment is eligible for eviction if it has a LastUsed value smaller than this threshold. One exception to this rule is deleted segments, which only need to be truncated out of the Log. @return True if the Segment can be evicted, false otherwise. """ return !metadata.isPinned() && (metadata.getLastUsed() < sequenceNumberCutoff || metadata.isDeleted() && metadata.getLastUsed() <= this.lastTruncatedSequenceNumber.get()); }
java
private boolean isEligibleForEviction(SegmentMetadata metadata, long sequenceNumberCutoff) { return !metadata.isPinned() && (metadata.getLastUsed() < sequenceNumberCutoff || metadata.isDeleted() && metadata.getLastUsed() <= this.lastTruncatedSequenceNumber.get()); }
[ "private", "boolean", "isEligibleForEviction", "(", "SegmentMetadata", "metadata", ",", "long", "sequenceNumberCutoff", ")", "{", "return", "!", "metadata", ".", "isPinned", "(", ")", "&&", "(", "metadata", ".", "getLastUsed", "(", ")", "<", "sequenceNumberCutoff"...
Determines whether the Segment with given metadata can be evicted, based on the the given Sequence Number Threshold. A Segment will not be chosen for eviction if {@link SegmentMetadata#isPinned()} is true. @param metadata The Metadata for the Segment that is considered for eviction. @param sequenceNumberCutoff A Sequence Number that indicates the cutoff threshold. A Segment is eligible for eviction if it has a LastUsed value smaller than this threshold. One exception to this rule is deleted segments, which only need to be truncated out of the Log. @return True if the Segment can be evicted, false otherwise.
[ "Determines", "whether", "the", "Segment", "with", "given", "metadata", "can", "be", "evicted", "based", "on", "the", "the", "given", "Sequence", "Number", "Threshold", ".", "A", "Segment", "will", "not", "be", "chosen", "for", "eviction", "if", "{", "@link"...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/containers/StreamSegmentContainerMetadata.java#L297-L301
looly/hutool
hutool-core/src/main/java/cn/hutool/core/bean/copier/BeanCopier.java
BeanCopier.create
public static <T> BeanCopier<T> create(Object source, T dest, CopyOptions copyOptions) { """ 创建BeanCopier @param <T> 目标Bean类型 @param source 来源对象,可以是Bean或者Map @param dest 目标Bean对象 @param copyOptions 拷贝属性选项 @return BeanCopier """ return create(source, dest, dest.getClass(), copyOptions); }
java
public static <T> BeanCopier<T> create(Object source, T dest, CopyOptions copyOptions) { return create(source, dest, dest.getClass(), copyOptions); }
[ "public", "static", "<", "T", ">", "BeanCopier", "<", "T", ">", "create", "(", "Object", "source", ",", "T", "dest", ",", "CopyOptions", "copyOptions", ")", "{", "return", "create", "(", "source", ",", "dest", ",", "dest", ".", "getClass", "(", ")", ...
创建BeanCopier @param <T> 目标Bean类型 @param source 来源对象,可以是Bean或者Map @param dest 目标Bean对象 @param copyOptions 拷贝属性选项 @return BeanCopier
[ "创建BeanCopier" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/copier/BeanCopier.java#L54-L56
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddress.java
IPAddress.toAddressString
@Override public IPAddressString toAddressString() { """ Generates an IPAddressString object for this IPAddress object. <p> This same IPAddress object can be retrieved from the resulting IPAddressString object using {@link IPAddressString#getAddress()} <p> In general, users are intended to create IPAddress objects from IPAddressString objects, while the reverse direction is generally not all that useful. <p> However, the reverse direction can be useful under certain circumstances. <p> Not all IPAddressString objects can be converted to IPAddress objects, as is the case with IPAddressString objects corresponding to the types IPType.INVALID and IPType.EMPTY. <p> Not all IPAddressString objects can be converted to IPAddress objects without specifying the IP version, as is the case with IPAddressString objects corresponding to the types IPType.PREFIX and IPType.ALL. <p> So in the event you wish to store a collection of IPAddress objects with a collection of IPAddressString objects, and not all the IPAddressString objects can be converted to IPAddress objects, then you may wish to use a collection of only IPAddressString objects, in which case this method is useful. @return an IPAddressString object for this IPAddress. """ if(fromString == null) { IPAddressStringParameters params = createFromStringParams(); fromString = new IPAddressString(this, params); /* address string creation */ } return getAddressfromString(); }
java
@Override public IPAddressString toAddressString() { if(fromString == null) { IPAddressStringParameters params = createFromStringParams(); fromString = new IPAddressString(this, params); /* address string creation */ } return getAddressfromString(); }
[ "@", "Override", "public", "IPAddressString", "toAddressString", "(", ")", "{", "if", "(", "fromString", "==", "null", ")", "{", "IPAddressStringParameters", "params", "=", "createFromStringParams", "(", ")", ";", "fromString", "=", "new", "IPAddressString", "(", ...
Generates an IPAddressString object for this IPAddress object. <p> This same IPAddress object can be retrieved from the resulting IPAddressString object using {@link IPAddressString#getAddress()} <p> In general, users are intended to create IPAddress objects from IPAddressString objects, while the reverse direction is generally not all that useful. <p> However, the reverse direction can be useful under certain circumstances. <p> Not all IPAddressString objects can be converted to IPAddress objects, as is the case with IPAddressString objects corresponding to the types IPType.INVALID and IPType.EMPTY. <p> Not all IPAddressString objects can be converted to IPAddress objects without specifying the IP version, as is the case with IPAddressString objects corresponding to the types IPType.PREFIX and IPType.ALL. <p> So in the event you wish to store a collection of IPAddress objects with a collection of IPAddressString objects, and not all the IPAddressString objects can be converted to IPAddress objects, then you may wish to use a collection of only IPAddressString objects, in which case this method is useful. @return an IPAddressString object for this IPAddress.
[ "Generates", "an", "IPAddressString", "object", "for", "this", "IPAddress", "object", ".", "<p", ">", "This", "same", "IPAddress", "object", "can", "be", "retrieved", "from", "the", "resulting", "IPAddressString", "object", "using", "{", "@link", "IPAddressString#...
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddress.java#L1016-L1023
line/armeria
core/src/main/java/com/linecorp/armeria/server/AbstractHttpService.java
AbstractHttpService.doDelete
protected HttpResponse doDelete(ServiceRequestContext ctx, HttpRequest req) throws Exception { """ Handles a {@link HttpMethod#DELETE DELETE} request. This method sends a {@link HttpStatus#METHOD_NOT_ALLOWED 405 Method Not Allowed} response by default. """ final HttpResponseWriter res = HttpResponse.streaming(); doDelete(ctx, req, res); return res; }
java
protected HttpResponse doDelete(ServiceRequestContext ctx, HttpRequest req) throws Exception { final HttpResponseWriter res = HttpResponse.streaming(); doDelete(ctx, req, res); return res; }
[ "protected", "HttpResponse", "doDelete", "(", "ServiceRequestContext", "ctx", ",", "HttpRequest", "req", ")", "throws", "Exception", "{", "final", "HttpResponseWriter", "res", "=", "HttpResponse", ".", "streaming", "(", ")", ";", "doDelete", "(", "ctx", ",", "re...
Handles a {@link HttpMethod#DELETE DELETE} request. This method sends a {@link HttpStatus#METHOD_NOT_ALLOWED 405 Method Not Allowed} response by default.
[ "Handles", "a", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/AbstractHttpService.java#L238-L242
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/entry/JournalEntry.java
JournalEntry.setRecoveryValue
public void setRecoveryValue(URI attribute, String value) { """ convenience method for setting values into the Context recovery space. """ checkOpen(); context.setRecoveryValue(attribute, value); }
java
public void setRecoveryValue(URI attribute, String value) { checkOpen(); context.setRecoveryValue(attribute, value); }
[ "public", "void", "setRecoveryValue", "(", "URI", "attribute", ",", "String", "value", ")", "{", "checkOpen", "(", ")", ";", "context", ".", "setRecoveryValue", "(", "attribute", ",", "value", ")", ";", "}" ]
convenience method for setting values into the Context recovery space.
[ "convenience", "method", "for", "setting", "values", "into", "the", "Context", "recovery", "space", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/entry/JournalEntry.java#L109-L112
dottydingo/hyperion
client/src/main/java/com/dottydingo/hyperion/client/HyperionClient.java
HyperionClient.serializeBody
protected String serializeBody(Request request) { """ Serialize the request body @param request The data service request @return The JSON representation of the request """ try { return objectMapper.writeValueAsString(request.getRequestBody()); } catch (JsonProcessingException e) { throw new ClientMarshallingException("Error writing request.",e); } }
java
protected String serializeBody(Request request) { try { return objectMapper.writeValueAsString(request.getRequestBody()); } catch (JsonProcessingException e) { throw new ClientMarshallingException("Error writing request.",e); } }
[ "protected", "String", "serializeBody", "(", "Request", "request", ")", "{", "try", "{", "return", "objectMapper", ".", "writeValueAsString", "(", "request", ".", "getRequestBody", "(", ")", ")", ";", "}", "catch", "(", "JsonProcessingException", "e", ")", "{"...
Serialize the request body @param request The data service request @return The JSON representation of the request
[ "Serialize", "the", "request", "body" ]
train
https://github.com/dottydingo/hyperion/blob/c4d119c90024a88c0335d7d318e9ccdb70149764/client/src/main/java/com/dottydingo/hyperion/client/HyperionClient.java#L388-L398
ganglia/jmxetric
src/main/java/info/ganglia/jmxetric/GangliaXmlConfigurationService.java
GangliaXmlConfigurationService.getGangliaConfig
private String getGangliaConfig(String cmdLine, Node ganglia, String attributeName, String defaultValue) { """ Gets a configuration parameter for Ganglia. First checks if it was given on the command line arguments. If it is not available, it looks for the value in the XML node. @param cmdLine command line value for this attribute @param ganglia the XML node @param attributeName name of the attribute @param defaultValue default value if this attribute cannot be found @return the string value of the specified attribute """ if (cmdLine == null) { return selectParameterFromNode(ganglia, attributeName, defaultValue); } else { return cmdLine; } }
java
private String getGangliaConfig(String cmdLine, Node ganglia, String attributeName, String defaultValue) { if (cmdLine == null) { return selectParameterFromNode(ganglia, attributeName, defaultValue); } else { return cmdLine; } }
[ "private", "String", "getGangliaConfig", "(", "String", "cmdLine", ",", "Node", "ganglia", ",", "String", "attributeName", ",", "String", "defaultValue", ")", "{", "if", "(", "cmdLine", "==", "null", ")", "{", "return", "selectParameterFromNode", "(", "ganglia",...
Gets a configuration parameter for Ganglia. First checks if it was given on the command line arguments. If it is not available, it looks for the value in the XML node. @param cmdLine command line value for this attribute @param ganglia the XML node @param attributeName name of the attribute @param defaultValue default value if this attribute cannot be found @return the string value of the specified attribute
[ "Gets", "a", "configuration", "parameter", "for", "Ganglia", ".", "First", "checks", "if", "it", "was", "given", "on", "the", "command", "line", "arguments", ".", "If", "it", "is", "not", "available", "it", "looks", "for", "the", "value", "in", "the", "X...
train
https://github.com/ganglia/jmxetric/blob/0b21edb9bd75e0b2df8370ad1c77a1ea47f502ca/src/main/java/info/ganglia/jmxetric/GangliaXmlConfigurationService.java#L178-L185
palatable/lambda
src/main/java/com/jnape/palatable/lambda/optics/lenses/CollectionLens.java
CollectionLens.asStream
@SuppressWarnings("RedundantTypeArguments") public static <X, CX extends Collection<X>> Lens.Simple<CX, Stream<X>> asStream( Function<? super CX, ? extends CX> copyFn) { """ Convenience static factory method for creating a lens that focuses on a Collection as a Stream. <p> Note that this lens is effectively lawful, though difficult to prove given the intrinsically stateful and inequitable nature of {@link Stream}. @param copyFn the copying function @param <X> the collection element type @param <CX> the type of the collection @return a lens that focuses on a Collection as a stream. """ return simpleLens(Collection<X>::stream, (xsL, xsS) -> { CX updated = copyFn.apply(xsL); updated.clear(); xsS.forEach(updated::add); return updated; }); }
java
@SuppressWarnings("RedundantTypeArguments") public static <X, CX extends Collection<X>> Lens.Simple<CX, Stream<X>> asStream( Function<? super CX, ? extends CX> copyFn) { return simpleLens(Collection<X>::stream, (xsL, xsS) -> { CX updated = copyFn.apply(xsL); updated.clear(); xsS.forEach(updated::add); return updated; }); }
[ "@", "SuppressWarnings", "(", "\"RedundantTypeArguments\"", ")", "public", "static", "<", "X", ",", "CX", "extends", "Collection", "<", "X", ">", ">", "Lens", ".", "Simple", "<", "CX", ",", "Stream", "<", "X", ">", ">", "asStream", "(", "Function", "<", ...
Convenience static factory method for creating a lens that focuses on a Collection as a Stream. <p> Note that this lens is effectively lawful, though difficult to prove given the intrinsically stateful and inequitable nature of {@link Stream}. @param copyFn the copying function @param <X> the collection element type @param <CX> the type of the collection @return a lens that focuses on a Collection as a stream.
[ "Convenience", "static", "factory", "method", "for", "creating", "a", "lens", "that", "focuses", "on", "a", "Collection", "as", "a", "Stream", ".", "<p", ">", "Note", "that", "this", "lens", "is", "effectively", "lawful", "though", "difficult", "to", "prove"...
train
https://github.com/palatable/lambda/blob/b643ba836c5916d1d8193822e5efb4e7b40c489a/src/main/java/com/jnape/palatable/lambda/optics/lenses/CollectionLens.java#L66-L75
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.deleteImages
public void deleteImages(UUID projectId, List<String> imageIds) { """ Delete images from the set of training images. @param projectId The project id @param imageIds Ids of the images to be deleted. Limted to 256 images per batch @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ deleteImagesWithServiceResponseAsync(projectId, imageIds).toBlocking().single().body(); }
java
public void deleteImages(UUID projectId, List<String> imageIds) { deleteImagesWithServiceResponseAsync(projectId, imageIds).toBlocking().single().body(); }
[ "public", "void", "deleteImages", "(", "UUID", "projectId", ",", "List", "<", "String", ">", "imageIds", ")", "{", "deleteImagesWithServiceResponseAsync", "(", "projectId", ",", "imageIds", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "bod...
Delete images from the set of training images. @param projectId The project id @param imageIds Ids of the images to be deleted. Limted to 256 images per batch @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Delete", "images", "from", "the", "set", "of", "training", "images", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L4014-L4016
sarl/sarl
products/sarlc/src/main/java/io/sarl/lang/sarlc/modules/configs/CompilerConfigModule.java
CompilerConfigModule.providesJavaBatchCompiler
@SuppressWarnings("static-method") @Provides @Singleton public IJavaBatchCompiler providesJavaBatchCompiler(Injector injector, Provider<SarlConfig> config) { """ Provide a Java batch compiler based on the Bootique configuration. @param injector the injector. @param config the bootique configuration. @return the batch compiler. @since 0.8 """ final SarlConfig cfg = config.get(); final IJavaBatchCompiler compiler = cfg.getCompiler().getJavaCompiler().newCompilerInstance(); injector.injectMembers(compiler); return compiler; }
java
@SuppressWarnings("static-method") @Provides @Singleton public IJavaBatchCompiler providesJavaBatchCompiler(Injector injector, Provider<SarlConfig> config) { final SarlConfig cfg = config.get(); final IJavaBatchCompiler compiler = cfg.getCompiler().getJavaCompiler().newCompilerInstance(); injector.injectMembers(compiler); return compiler; }
[ "@", "SuppressWarnings", "(", "\"static-method\"", ")", "@", "Provides", "@", "Singleton", "public", "IJavaBatchCompiler", "providesJavaBatchCompiler", "(", "Injector", "injector", ",", "Provider", "<", "SarlConfig", ">", "config", ")", "{", "final", "SarlConfig", "...
Provide a Java batch compiler based on the Bootique configuration. @param injector the injector. @param config the bootique configuration. @return the batch compiler. @since 0.8
[ "Provide", "a", "Java", "batch", "compiler", "based", "on", "the", "Bootique", "configuration", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/products/sarlc/src/main/java/io/sarl/lang/sarlc/modules/configs/CompilerConfigModule.java#L190-L198
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/Utilities.java
Utilities.adjustTableHeight
public static void adjustTableHeight(final JTable table) { """ Fixe la taille exacte d'une JTable à celle nécessaire pour afficher les données. @param table JTable """ table.setPreferredScrollableViewportSize( new Dimension(-1, table.getPreferredSize().height)); // on utilise invokeLater pour configurer le scrollPane car lors de l'exécution ce cette méthode // la table n'est pas encore dans son scrollPane parent SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final JScrollPane scrollPane = MSwingUtilities.getAncestorOfClass(JScrollPane.class, table); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // Puisqu'il n'y a pas d'ascenceur sur ce scrollPane, // il est inutile que la mollette de souris serve à bouger cet ascenseur, // mais il est très utile en revanche que ce scrollPane ne bloque pas l'utilisation // de la mollette de souris pour le scrollPane global de l'onglet principal. // On commence par enlever le listener au cas où la méthode soit appelée deux fois sur la même table. scrollPane.removeMouseWheelListener(DELEGATE_TO_PARENT_MOUSE_WHEEL_LISTENER); scrollPane.addMouseWheelListener(DELEGATE_TO_PARENT_MOUSE_WHEEL_LISTENER); } }); }
java
public static void adjustTableHeight(final JTable table) { table.setPreferredScrollableViewportSize( new Dimension(-1, table.getPreferredSize().height)); // on utilise invokeLater pour configurer le scrollPane car lors de l'exécution ce cette méthode // la table n'est pas encore dans son scrollPane parent SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final JScrollPane scrollPane = MSwingUtilities.getAncestorOfClass(JScrollPane.class, table); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // Puisqu'il n'y a pas d'ascenceur sur ce scrollPane, // il est inutile que la mollette de souris serve à bouger cet ascenseur, // mais il est très utile en revanche que ce scrollPane ne bloque pas l'utilisation // de la mollette de souris pour le scrollPane global de l'onglet principal. // On commence par enlever le listener au cas où la méthode soit appelée deux fois sur la même table. scrollPane.removeMouseWheelListener(DELEGATE_TO_PARENT_MOUSE_WHEEL_LISTENER); scrollPane.addMouseWheelListener(DELEGATE_TO_PARENT_MOUSE_WHEEL_LISTENER); } }); }
[ "public", "static", "void", "adjustTableHeight", "(", "final", "JTable", "table", ")", "{", "table", ".", "setPreferredScrollableViewportSize", "(", "new", "Dimension", "(", "-", "1", ",", "table", ".", "getPreferredSize", "(", ")", ".", "height", ")", ")", ...
Fixe la taille exacte d'une JTable à celle nécessaire pour afficher les données. @param table JTable
[ "Fixe", "la", "taille", "exacte", "d", "une", "JTable", "à", "celle", "nécessaire", "pour", "afficher", "les", "données", "." ]
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/Utilities.java#L101-L121
pedrovgs/Nox
nox/src/main/java/com/github/pedrovgs/nox/NoxView.java
NoxView.drawNoxItemDrawable
private void drawNoxItemDrawable(Canvas canvas, int left, int top, Drawable drawable) { """ Draws a NoxItem drawable during the onDraw method given a canvas object and all the information needed to draw the Drawable passed as parameter. """ if (drawable != null) { int itemSize = (int) noxConfig.getNoxItemSize(); drawable.setBounds(left, top, left + itemSize, top + itemSize); drawable.draw(canvas); } }
java
private void drawNoxItemDrawable(Canvas canvas, int left, int top, Drawable drawable) { if (drawable != null) { int itemSize = (int) noxConfig.getNoxItemSize(); drawable.setBounds(left, top, left + itemSize, top + itemSize); drawable.draw(canvas); } }
[ "private", "void", "drawNoxItemDrawable", "(", "Canvas", "canvas", ",", "int", "left", ",", "int", "top", ",", "Drawable", "drawable", ")", "{", "if", "(", "drawable", "!=", "null", ")", "{", "int", "itemSize", "=", "(", "int", ")", "noxConfig", ".", "...
Draws a NoxItem drawable during the onDraw method given a canvas object and all the information needed to draw the Drawable passed as parameter.
[ "Draws", "a", "NoxItem", "drawable", "during", "the", "onDraw", "method", "given", "a", "canvas", "object", "and", "all", "the", "information", "needed", "to", "draw", "the", "Drawable", "passed", "as", "parameter", "." ]
train
https://github.com/pedrovgs/Nox/blob/b4dfe37895e1b7bf2084d60139931dd4fb12f3f4/nox/src/main/java/com/github/pedrovgs/nox/NoxView.java#L353-L359
TakahikoKawasaki/nv-cipher
src/main/java/com/neovisionaries/security/AESCipher.java
AESCipher.setKey
public AESCipher setKey(String key, byte[] iv) { """ Set cipher initialization parameters. @param key Secret key. The value is converted to a byte array by {@code key.getBytes("UTF-8")} and used as the first argument of {@link #setKey(byte[], byte[])}. If {@code null} is given, {@code null} is passed to {@link #setKey(byte[], byte[])}. @param iv Initial vector. The value is pass to {@link #setKey(byte[], byte[])} as the second argument as is. @return {@code this} object. @since 1.2 """ byte[] key2 = Utils.getBytesUTF8(key); return setKey(key2, iv); }
java
public AESCipher setKey(String key, byte[] iv) { byte[] key2 = Utils.getBytesUTF8(key); return setKey(key2, iv); }
[ "public", "AESCipher", "setKey", "(", "String", "key", ",", "byte", "[", "]", "iv", ")", "{", "byte", "[", "]", "key2", "=", "Utils", ".", "getBytesUTF8", "(", "key", ")", ";", "return", "setKey", "(", "key2", ",", "iv", ")", ";", "}" ]
Set cipher initialization parameters. @param key Secret key. The value is converted to a byte array by {@code key.getBytes("UTF-8")} and used as the first argument of {@link #setKey(byte[], byte[])}. If {@code null} is given, {@code null} is passed to {@link #setKey(byte[], byte[])}. @param iv Initial vector. The value is pass to {@link #setKey(byte[], byte[])} as the second argument as is. @return {@code this} object. @since 1.2
[ "Set", "cipher", "initialization", "parameters", "." ]
train
https://github.com/TakahikoKawasaki/nv-cipher/blob/d01aa4f53611e2724ae03633060f55bacf549175/src/main/java/com/neovisionaries/security/AESCipher.java#L308-L313
b3log/latke
latke-core/src/main/java/org/b3log/latke/util/Templates.java
Templates.hasExpression
public static boolean hasExpression(final Template template, final String expression) { """ Determines whether exists a variable specified by the given expression in the specified template. @param template the specified template @param expression the given expression, for example, "${aVariable}", "&lt;#list recentComments as comment&gt;" @return {@code true} if it exists, returns {@code false} otherwise """ final TemplateElement rootTreeNode = template.getRootTreeNode(); return hasExpression(template, expression, rootTreeNode); }
java
public static boolean hasExpression(final Template template, final String expression) { final TemplateElement rootTreeNode = template.getRootTreeNode(); return hasExpression(template, expression, rootTreeNode); }
[ "public", "static", "boolean", "hasExpression", "(", "final", "Template", "template", ",", "final", "String", "expression", ")", "{", "final", "TemplateElement", "rootTreeNode", "=", "template", ".", "getRootTreeNode", "(", ")", ";", "return", "hasExpression", "("...
Determines whether exists a variable specified by the given expression in the specified template. @param template the specified template @param expression the given expression, for example, "${aVariable}", "&lt;#list recentComments as comment&gt;" @return {@code true} if it exists, returns {@code false} otherwise
[ "Determines", "whether", "exists", "a", "variable", "specified", "by", "the", "given", "expression", "in", "the", "specified", "template", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Templates.java#L53-L57
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
ArrowSerde.createDims
public static int createDims(FlatBufferBuilder bufferBuilder,INDArray arr) { """ Create the dimensions for the flatbuffer builder @param bufferBuilder the buffer builder to use @param arr the input array @return """ int[] tensorDimOffsets = new int[arr.rank()]; int[] nameOffset = new int[arr.rank()]; for(int i = 0; i < tensorDimOffsets.length; i++) { nameOffset[i] = bufferBuilder.createString(""); tensorDimOffsets[i] = TensorDim.createTensorDim(bufferBuilder,arr.size(i),nameOffset[i]); } return Tensor.createShapeVector(bufferBuilder,tensorDimOffsets); }
java
public static int createDims(FlatBufferBuilder bufferBuilder,INDArray arr) { int[] tensorDimOffsets = new int[arr.rank()]; int[] nameOffset = new int[arr.rank()]; for(int i = 0; i < tensorDimOffsets.length; i++) { nameOffset[i] = bufferBuilder.createString(""); tensorDimOffsets[i] = TensorDim.createTensorDim(bufferBuilder,arr.size(i),nameOffset[i]); } return Tensor.createShapeVector(bufferBuilder,tensorDimOffsets); }
[ "public", "static", "int", "createDims", "(", "FlatBufferBuilder", "bufferBuilder", ",", "INDArray", "arr", ")", "{", "int", "[", "]", "tensorDimOffsets", "=", "new", "int", "[", "arr", ".", "rank", "(", ")", "]", ";", "int", "[", "]", "nameOffset", "=",...
Create the dimensions for the flatbuffer builder @param bufferBuilder the buffer builder to use @param arr the input array @return
[ "Create", "the", "dimensions", "for", "the", "flatbuffer", "builder" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java#L139-L148
neo4j/neo4j-java-driver
driver/src/main/java/org/neo4j/driver/internal/util/Futures.java
Futures.combineErrors
public static CompletionException combineErrors( Throwable error1, Throwable error2 ) { """ Combine given errors into a single {@link CompletionException} to be rethrown from inside a {@link CompletionStage} chain. @param error1 the first error or {@code null}. @param error2 the second error or {@code null}. @return {@code null} if both errors are null, {@link CompletionException} otherwise. """ if ( error1 != null && error2 != null ) { Throwable cause1 = completionExceptionCause( error1 ); Throwable cause2 = completionExceptionCause( error2 ); if ( cause1 != cause2 ) { cause1.addSuppressed( cause2 ); } return asCompletionException( cause1 ); } else if ( error1 != null ) { return asCompletionException( error1 ); } else if ( error2 != null ) { return asCompletionException( error2 ); } else { return null; } }
java
public static CompletionException combineErrors( Throwable error1, Throwable error2 ) { if ( error1 != null && error2 != null ) { Throwable cause1 = completionExceptionCause( error1 ); Throwable cause2 = completionExceptionCause( error2 ); if ( cause1 != cause2 ) { cause1.addSuppressed( cause2 ); } return asCompletionException( cause1 ); } else if ( error1 != null ) { return asCompletionException( error1 ); } else if ( error2 != null ) { return asCompletionException( error2 ); } else { return null; } }
[ "public", "static", "CompletionException", "combineErrors", "(", "Throwable", "error1", ",", "Throwable", "error2", ")", "{", "if", "(", "error1", "!=", "null", "&&", "error2", "!=", "null", ")", "{", "Throwable", "cause1", "=", "completionExceptionCause", "(", ...
Combine given errors into a single {@link CompletionException} to be rethrown from inside a {@link CompletionStage} chain. @param error1 the first error or {@code null}. @param error2 the second error or {@code null}. @return {@code null} if both errors are null, {@link CompletionException} otherwise.
[ "Combine", "given", "errors", "into", "a", "single", "{", "@link", "CompletionException", "}", "to", "be", "rethrown", "from", "inside", "a", "{", "@link", "CompletionStage", "}", "chain", "." ]
train
https://github.com/neo4j/neo4j-java-driver/blob/8dad6c48251fa1ab7017e72d9998a24fa2337a22/driver/src/main/java/org/neo4j/driver/internal/util/Futures.java#L181-L205
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.getExploded
@Nonnull @ReturnsMutableCopy public static ICommonsList <String> getExploded (final char cSep, @Nullable final String sElements) { """ Take a concatenated String and return a {@link ICommonsList} of all elements in the passed string, using specified separator string. @param cSep The separator character to use. @param sElements The concatenated String to convert. May be <code>null</code> or empty. @return The {@link ICommonsList} represented by the passed string. Never <code>null</code>. If the passed input string is <code>null</code> or "" an empty list is returned. """ return getExploded (cSep, sElements, -1); }
java
@Nonnull @ReturnsMutableCopy public static ICommonsList <String> getExploded (final char cSep, @Nullable final String sElements) { return getExploded (cSep, sElements, -1); }
[ "@", "Nonnull", "@", "ReturnsMutableCopy", "public", "static", "ICommonsList", "<", "String", ">", "getExploded", "(", "final", "char", "cSep", ",", "@", "Nullable", "final", "String", "sElements", ")", "{", "return", "getExploded", "(", "cSep", ",", "sElement...
Take a concatenated String and return a {@link ICommonsList} of all elements in the passed string, using specified separator string. @param cSep The separator character to use. @param sElements The concatenated String to convert. May be <code>null</code> or empty. @return The {@link ICommonsList} represented by the passed string. Never <code>null</code>. If the passed input string is <code>null</code> or "" an empty list is returned.
[ "Take", "a", "concatenated", "String", "and", "return", "a", "{", "@link", "ICommonsList", "}", "of", "all", "elements", "in", "the", "passed", "string", "using", "specified", "separator", "string", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2083-L2088
jenkinsci/jenkins
core/src/main/java/hudson/scm/ChangeLogAnnotator.java
ChangeLogAnnotator.annotate
public void annotate(Run<?,?> build, Entry change, MarkupText text) { """ Called by Hudson to allow markups to be added to the changelog text. <p> This method is invoked each time a page is rendered, so implementations of this method should not take too long to execute. Also note that this method may be invoked concurrently by multiple threads. <p> If there's any error during the processing, it should be recorded in {@link Logger} and the method should return normally. @param build Build that owns this changelog. From here you can access broader contextual information, like the project, or it settings. Never null. @param change The changelog entry for which this method is adding markup. Never null. @param text The text and markups. Implementation of this method is expected to add additional annotations into this object. If other annotators are registered, the object may already contain some markups when this method is invoked. Never null. {@link MarkupText#getText()} on this instance will return the same string as {@link Entry#getMsgEscaped()}. @since 1.568 """ if (build instanceof AbstractBuild && Util.isOverridden(ChangeLogAnnotator.class, getClass(), "annotate", AbstractBuild.class, Entry.class, MarkupText.class)) { annotate((AbstractBuild) build, change, text); } else { Logger.getLogger(ChangeLogAnnotator.class.getName()).log(Level.WARNING, "You must override the newer overload of annotate from {0}", getClass().getName()); } }
java
public void annotate(Run<?,?> build, Entry change, MarkupText text) { if (build instanceof AbstractBuild && Util.isOverridden(ChangeLogAnnotator.class, getClass(), "annotate", AbstractBuild.class, Entry.class, MarkupText.class)) { annotate((AbstractBuild) build, change, text); } else { Logger.getLogger(ChangeLogAnnotator.class.getName()).log(Level.WARNING, "You must override the newer overload of annotate from {0}", getClass().getName()); } }
[ "public", "void", "annotate", "(", "Run", "<", "?", ",", "?", ">", "build", ",", "Entry", "change", ",", "MarkupText", "text", ")", "{", "if", "(", "build", "instanceof", "AbstractBuild", "&&", "Util", ".", "isOverridden", "(", "ChangeLogAnnotator", ".", ...
Called by Hudson to allow markups to be added to the changelog text. <p> This method is invoked each time a page is rendered, so implementations of this method should not take too long to execute. Also note that this method may be invoked concurrently by multiple threads. <p> If there's any error during the processing, it should be recorded in {@link Logger} and the method should return normally. @param build Build that owns this changelog. From here you can access broader contextual information, like the project, or it settings. Never null. @param change The changelog entry for which this method is adding markup. Never null. @param text The text and markups. Implementation of this method is expected to add additional annotations into this object. If other annotators are registered, the object may already contain some markups when this method is invoked. Never null. {@link MarkupText#getText()} on this instance will return the same string as {@link Entry#getMsgEscaped()}. @since 1.568
[ "Called", "by", "Hudson", "to", "allow", "markups", "to", "be", "added", "to", "the", "changelog", "text", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/scm/ChangeLogAnnotator.java#L81-L87
Steveice10/OpenNBT
src/main/java/com/github/steveice10/opennbt/NBTIO.java
NBTIO.readFile
public static CompoundTag readFile(String path, boolean compressed, boolean littleEndian) throws IOException { """ Reads the root CompoundTag from the given file. @param path Path of the file. @param compressed Whether the NBT file is compressed. @param littleEndian Whether the NBT file is little endian. @return The read compound tag. @throws java.io.IOException If an I/O error occurs. """ return readFile(new File(path), compressed, littleEndian); }
java
public static CompoundTag readFile(String path, boolean compressed, boolean littleEndian) throws IOException { return readFile(new File(path), compressed, littleEndian); }
[ "public", "static", "CompoundTag", "readFile", "(", "String", "path", ",", "boolean", "compressed", ",", "boolean", "littleEndian", ")", "throws", "IOException", "{", "return", "readFile", "(", "new", "File", "(", "path", ")", ",", "compressed", ",", "littleEn...
Reads the root CompoundTag from the given file. @param path Path of the file. @param compressed Whether the NBT file is compressed. @param littleEndian Whether the NBT file is little endian. @return The read compound tag. @throws java.io.IOException If an I/O error occurs.
[ "Reads", "the", "root", "CompoundTag", "from", "the", "given", "file", "." ]
train
https://github.com/Steveice10/OpenNBT/blob/9bf4adb2afd206a21bc4309c85d642494d1fb536/src/main/java/com/github/steveice10/opennbt/NBTIO.java#L59-L61
NetsOSS/embedded-jetty
src/main/java/eu/nets/oss/jetty/EmbeddedJettyBuilder.java
EmbeddedJettyBuilder.createRootServletContextHandler
public ServletContextHandlerBuilder createRootServletContextHandler(String subPath, RequestLog requestLogger) { """ Example requestLogger: <pre> NCSARequestLog requestLog = new NCSARequestLog("logs/my-app-jetty-web-yyyy_mm_dd.request.log"); requestLog.setRetainDays(90); requestLog.setAppend(true); requestLog.setExtended(false); requestLog.setLogTimeZone("Europe/Oslo"); // or GMT </pre> https://wiki.eclipse.org/Jetty/Howto/Configure_Request_Logs """ if (requestLogger == null) { throw new RuntimeException("RequestLogger cannot be null"); } return createRootServletContextHandlerInternal(subPath, requestLogger); }
java
public ServletContextHandlerBuilder createRootServletContextHandler(String subPath, RequestLog requestLogger) { if (requestLogger == null) { throw new RuntimeException("RequestLogger cannot be null"); } return createRootServletContextHandlerInternal(subPath, requestLogger); }
[ "public", "ServletContextHandlerBuilder", "createRootServletContextHandler", "(", "String", "subPath", ",", "RequestLog", "requestLogger", ")", "{", "if", "(", "requestLogger", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"RequestLogger cannot be nul...
Example requestLogger: <pre> NCSARequestLog requestLog = new NCSARequestLog("logs/my-app-jetty-web-yyyy_mm_dd.request.log"); requestLog.setRetainDays(90); requestLog.setAppend(true); requestLog.setExtended(false); requestLog.setLogTimeZone("Europe/Oslo"); // or GMT </pre> https://wiki.eclipse.org/Jetty/Howto/Configure_Request_Logs
[ "Example", "requestLogger", ":", "<pre", ">", "NCSARequestLog", "requestLog", "=", "new", "NCSARequestLog", "(", "logs", "/", "my", "-", "app", "-", "jetty", "-", "web", "-", "yyyy_mm_dd", ".", "request", ".", "log", ")", ";", "requestLog", ".", "setRetain...
train
https://github.com/NetsOSS/embedded-jetty/blob/c2535867ad4887c4a43a8aa7f95b711ff54c8542/src/main/java/eu/nets/oss/jetty/EmbeddedJettyBuilder.java#L281-L286
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/ftp/Ftp.java
Ftp.init
public Ftp init(String host, int port, String user, String password, FtpMode mode) { """ 初始化连接 @param host 域名或IP @param port 端口 @param user 用户名 @param password 密码 @param mode 模式 @return this """ final FTPClient client = new FTPClient(); client.setControlEncoding(this.charset.toString()); try { // 连接ftp服务器 client.connect(host, port); // 登录ftp服务器 client.login(user, password); } catch (IOException e) { throw new FtpException(e); } final int replyCode = client.getReplyCode(); // 是否成功登录服务器 if (false == FTPReply.isPositiveCompletion(replyCode)) { try { client.disconnect(); } catch (IOException e) { // ignore } throw new FtpException("Login failed for user [{}], reply code is: [{}]", user, replyCode); } this.client = client; if (mode != null ) { setMode(mode); } return this; }
java
public Ftp init(String host, int port, String user, String password, FtpMode mode) { final FTPClient client = new FTPClient(); client.setControlEncoding(this.charset.toString()); try { // 连接ftp服务器 client.connect(host, port); // 登录ftp服务器 client.login(user, password); } catch (IOException e) { throw new FtpException(e); } final int replyCode = client.getReplyCode(); // 是否成功登录服务器 if (false == FTPReply.isPositiveCompletion(replyCode)) { try { client.disconnect(); } catch (IOException e) { // ignore } throw new FtpException("Login failed for user [{}], reply code is: [{}]", user, replyCode); } this.client = client; if (mode != null ) { setMode(mode); } return this; }
[ "public", "Ftp", "init", "(", "String", "host", ",", "int", "port", ",", "String", "user", ",", "String", "password", ",", "FtpMode", "mode", ")", "{", "final", "FTPClient", "client", "=", "new", "FTPClient", "(", ")", ";", "client", ".", "setControlEnco...
初始化连接 @param host 域名或IP @param port 端口 @param user 用户名 @param password 密码 @param mode 模式 @return this
[ "初始化连接" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/ftp/Ftp.java#L132-L157
iipc/webarchive-commons
src/main/java/org/archive/format/http/HttpHeaders.java
HttpHeaders.set
public void set(String name, String value) { """ Add a new Header with the given name/value, or replace an existing value if a Header already exists with name @param name @param value """ HttpHeader header = get(name); if(header == null) { add(name,value); } else { header.setValue(value); } }
java
public void set(String name, String value) { HttpHeader header = get(name); if(header == null) { add(name,value); } else { header.setValue(value); } }
[ "public", "void", "set", "(", "String", "name", ",", "String", "value", ")", "{", "HttpHeader", "header", "=", "get", "(", "name", ")", ";", "if", "(", "header", "==", "null", ")", "{", "add", "(", "name", ",", "value", ")", ";", "}", "else", "{"...
Add a new Header with the given name/value, or replace an existing value if a Header already exists with name @param name @param value
[ "Add", "a", "new", "Header", "with", "the", "given", "name", "/", "value", "or", "replace", "an", "existing", "value", "if", "a", "Header", "already", "exists", "with", "name" ]
train
https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/format/http/HttpHeaders.java#L120-L127
diffplug/durian
src/com/diffplug/common/base/TreeQuery.java
TreeQuery.findByPath
public static <T> Optional<T> findByPath(TreeDef<T> treeDef, T node, List<T> path, Function<? super T, ?> mapper) { """ Finds a child TreeNode based on its path. <p> Searches the child nodes for the first element, then that node's children for the second element, etc. @param treeDef defines a tree @param node starting point for the search @param path the path of nodes which we're looking @param mapper maps elements to some value for comparison between the tree and the path """ return findByPath(treeDef, node, mapper, path, mapper); }
java
public static <T> Optional<T> findByPath(TreeDef<T> treeDef, T node, List<T> path, Function<? super T, ?> mapper) { return findByPath(treeDef, node, mapper, path, mapper); }
[ "public", "static", "<", "T", ">", "Optional", "<", "T", ">", "findByPath", "(", "TreeDef", "<", "T", ">", "treeDef", ",", "T", "node", ",", "List", "<", "T", ">", "path", ",", "Function", "<", "?", "super", "T", ",", "?", ">", "mapper", ")", "...
Finds a child TreeNode based on its path. <p> Searches the child nodes for the first element, then that node's children for the second element, etc. @param treeDef defines a tree @param node starting point for the search @param path the path of nodes which we're looking @param mapper maps elements to some value for comparison between the tree and the path
[ "Finds", "a", "child", "TreeNode", "based", "on", "its", "path", ".", "<p", ">", "Searches", "the", "child", "nodes", "for", "the", "first", "element", "then", "that", "node", "s", "children", "for", "the", "second", "element", "etc", "." ]
train
https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/TreeQuery.java#L304-L306
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/managementgraph/ManagementGraph.java
ManagementGraph.getGroupVerticesInTopologicalOrder
public List<ManagementGroupVertex> getGroupVerticesInTopologicalOrder() { """ Returns a list of group vertices sorted in topological order. @return a list of group vertices sorted in topological order """ final List<ManagementGroupVertex> topologicalSort = new ArrayList<ManagementGroupVertex>(); final Deque<ManagementGroupVertex> noIncomingEdges = new ArrayDeque<ManagementGroupVertex>(); final Map<ManagementGroupVertex, Integer> indegrees = new HashMap<ManagementGroupVertex, Integer>(); final Iterator<ManagementGroupVertex> it = new ManagementGroupVertexIterator(this, true, -1); while (it.hasNext()) { final ManagementGroupVertex groupVertex = it.next(); indegrees.put(groupVertex, Integer.valueOf(groupVertex.getNumberOfBackwardEdges())); if (groupVertex.getNumberOfBackwardEdges() == 0) { noIncomingEdges.add(groupVertex); } } while (!noIncomingEdges.isEmpty()) { final ManagementGroupVertex groupVertex = noIncomingEdges.removeFirst(); topologicalSort.add(groupVertex); // Decrease indegree of connected vertices for (int i = 0; i < groupVertex.getNumberOfForwardEdges(); i++) { final ManagementGroupVertex targetVertex = groupVertex.getForwardEdge(i).getTarget(); Integer indegree = indegrees.get(targetVertex); indegree = Integer.valueOf(indegree.intValue() - 1); indegrees.put(targetVertex, indegree); if (indegree.intValue() == 0) { noIncomingEdges.add(targetVertex); } } } return topologicalSort; }
java
public List<ManagementGroupVertex> getGroupVerticesInTopologicalOrder() { final List<ManagementGroupVertex> topologicalSort = new ArrayList<ManagementGroupVertex>(); final Deque<ManagementGroupVertex> noIncomingEdges = new ArrayDeque<ManagementGroupVertex>(); final Map<ManagementGroupVertex, Integer> indegrees = new HashMap<ManagementGroupVertex, Integer>(); final Iterator<ManagementGroupVertex> it = new ManagementGroupVertexIterator(this, true, -1); while (it.hasNext()) { final ManagementGroupVertex groupVertex = it.next(); indegrees.put(groupVertex, Integer.valueOf(groupVertex.getNumberOfBackwardEdges())); if (groupVertex.getNumberOfBackwardEdges() == 0) { noIncomingEdges.add(groupVertex); } } while (!noIncomingEdges.isEmpty()) { final ManagementGroupVertex groupVertex = noIncomingEdges.removeFirst(); topologicalSort.add(groupVertex); // Decrease indegree of connected vertices for (int i = 0; i < groupVertex.getNumberOfForwardEdges(); i++) { final ManagementGroupVertex targetVertex = groupVertex.getForwardEdge(i).getTarget(); Integer indegree = indegrees.get(targetVertex); indegree = Integer.valueOf(indegree.intValue() - 1); indegrees.put(targetVertex, indegree); if (indegree.intValue() == 0) { noIncomingEdges.add(targetVertex); } } } return topologicalSort; }
[ "public", "List", "<", "ManagementGroupVertex", ">", "getGroupVerticesInTopologicalOrder", "(", ")", "{", "final", "List", "<", "ManagementGroupVertex", ">", "topologicalSort", "=", "new", "ArrayList", "<", "ManagementGroupVertex", ">", "(", ")", ";", "final", "Dequ...
Returns a list of group vertices sorted in topological order. @return a list of group vertices sorted in topological order
[ "Returns", "a", "list", "of", "group", "vertices", "sorted", "in", "topological", "order", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/managementgraph/ManagementGraph.java#L332-L365
vipshop/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java
Formats.leftStr
public static String leftStr(String str, int length) { """ Returns a substring of the given string, representing the 'length' most-left characters """ return str.substring(0, Math.min(str.length(), length)); }
java
public static String leftStr(String str, int length) { return str.substring(0, Math.min(str.length(), length)); }
[ "public", "static", "String", "leftStr", "(", "String", "str", ",", "int", "length", ")", "{", "return", "str", ".", "substring", "(", "0", ",", "Math", ".", "min", "(", "str", ".", "length", "(", ")", ",", "length", ")", ")", ";", "}" ]
Returns a substring of the given string, representing the 'length' most-left characters
[ "Returns", "a", "substring", "of", "the", "given", "string", "representing", "the", "length", "most", "-", "left", "characters" ]
train
https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjtop/src/main/java/com/vip/vjtools/vjtop/util/Formats.java#L192-L194
alipay/sofa-rpc
extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java
SofaConfigs.getBooleanValue
public static boolean getBooleanValue(String appName, String key, boolean defaultValue) { """ 获取Boolean格式的Config @param appName 应用名 @param key 配置项 @param defaultValue 默认值 @return 配置 """ String ret = getStringValue0(appName, key); return StringUtils.isEmpty(ret) ? defaultValue : CommonUtils.parseBoolean(ret, defaultValue); }
java
public static boolean getBooleanValue(String appName, String key, boolean defaultValue) { String ret = getStringValue0(appName, key); return StringUtils.isEmpty(ret) ? defaultValue : CommonUtils.parseBoolean(ret, defaultValue); }
[ "public", "static", "boolean", "getBooleanValue", "(", "String", "appName", ",", "String", "key", ",", "boolean", "defaultValue", ")", "{", "String", "ret", "=", "getStringValue0", "(", "appName", ",", "key", ")", ";", "return", "StringUtils", ".", "isEmpty", ...
获取Boolean格式的Config @param appName 应用名 @param key 配置项 @param defaultValue 默认值 @return 配置
[ "获取Boolean格式的Config" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java#L144-L147
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java
EmoTableAllTablesReportDAO.convertToTableReportEntry
@Nullable private TableReportEntry convertToTableReportEntry(Map<String, Object> map, Predicate<String> placementFilter, Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) { """ Accepts a row from the table report and returns it converted into a TableReportEntry. If the row is deleted or if it doesn't match all of the configured filters then null is returned. """ if (Intrinsic.isDeleted(map)) { return null; } final String tableName = Intrinsic.getId(map); List<TableReportEntryTable> tables = Lists.newArrayListWithExpectedSize(map.size()); for (Map.Entry<String, Object> entry : toMap(map.get("tables")).entrySet()) { TableReportEntryTable entryTable = convertToTableReportEntryTable(entry.getKey(), toMap(entry.getValue()), placementFilter, droppedFilter, facadeFilter); if (entryTable != null) { tables.add(entryTable); } } // If all tables were filtered then return null if (tables.isEmpty()) { return null; } return new TableReportEntry(tableName, tables); }
java
@Nullable private TableReportEntry convertToTableReportEntry(Map<String, Object> map, Predicate<String> placementFilter, Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) { if (Intrinsic.isDeleted(map)) { return null; } final String tableName = Intrinsic.getId(map); List<TableReportEntryTable> tables = Lists.newArrayListWithExpectedSize(map.size()); for (Map.Entry<String, Object> entry : toMap(map.get("tables")).entrySet()) { TableReportEntryTable entryTable = convertToTableReportEntryTable(entry.getKey(), toMap(entry.getValue()), placementFilter, droppedFilter, facadeFilter); if (entryTable != null) { tables.add(entryTable); } } // If all tables were filtered then return null if (tables.isEmpty()) { return null; } return new TableReportEntry(tableName, tables); }
[ "@", "Nullable", "private", "TableReportEntry", "convertToTableReportEntry", "(", "Map", "<", "String", ",", "Object", ">", "map", ",", "Predicate", "<", "String", ">", "placementFilter", ",", "Predicate", "<", "Boolean", ">", "droppedFilter", ",", "Predicate", ...
Accepts a row from the table report and returns it converted into a TableReportEntry. If the row is deleted or if it doesn't match all of the configured filters then null is returned.
[ "Accepts", "a", "row", "from", "the", "table", "report", "and", "returns", "it", "converted", "into", "a", "TableReportEntry", ".", "If", "the", "row", "is", "deleted", "or", "if", "it", "doesn", "t", "match", "all", "of", "the", "configured", "filters", ...
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L306-L332
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/UUIDFactory.java
UUIDFactory.nameUUIDv5FromBytes
public static UUID nameUUIDv5FromBytes(byte[] name) { """ Creates a type 5 (name based) {@code UUID} based on the specified byte array. This method is effectively identical to {@link UUID#nameUUIDFromBytes}, except that this method uses a SHA1 hash instead of the MD5 hash used in the type 3 {@code UUID}s. RFC 4122 states that "SHA-1 is preferred" over MD5, without giving a reason for why. @param name a byte array to be used to construct a {@code UUID} @return a {@code UUID} generated from the specified array. @see <a href="http://tools.ietf.org/html/rfc4122#section-4.3">RFC 4122 4.3. Algorithm for Creating a Name-Based UUID</a> @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 appendix A</a> @see UUID#nameUUIDFromBytes(byte[]) """ // Based on code from OpenJDK UUID#nameUUIDFromBytes + private byte[] constructor MessageDigest md; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("SHA1 not supported"); } byte[] sha1Bytes = md.digest(name); sha1Bytes[6] &= 0x0f; /* clear version */ sha1Bytes[6] |= 0x50; /* set to version 5 */ sha1Bytes[8] &= 0x3f; /* clear variant */ sha1Bytes[8] |= 0x80; /* set to IETF variant */ long msb = 0; long lsb = 0; // NOTE: According to RFC 4122, only first 16 bytes are used, meaning // bytes 17-20 in the 160 bit SHA1 hash are simply discarded in this case... for (int i=0; i<8; i++) { msb = (msb << 8) | (sha1Bytes[i] & 0xff); } for (int i=8; i<16; i++) { lsb = (lsb << 8) | (sha1Bytes[i] & 0xff); } return new UUID(msb, lsb); }
java
public static UUID nameUUIDv5FromBytes(byte[] name) { // Based on code from OpenJDK UUID#nameUUIDFromBytes + private byte[] constructor MessageDigest md; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("SHA1 not supported"); } byte[] sha1Bytes = md.digest(name); sha1Bytes[6] &= 0x0f; /* clear version */ sha1Bytes[6] |= 0x50; /* set to version 5 */ sha1Bytes[8] &= 0x3f; /* clear variant */ sha1Bytes[8] |= 0x80; /* set to IETF variant */ long msb = 0; long lsb = 0; // NOTE: According to RFC 4122, only first 16 bytes are used, meaning // bytes 17-20 in the 160 bit SHA1 hash are simply discarded in this case... for (int i=0; i<8; i++) { msb = (msb << 8) | (sha1Bytes[i] & 0xff); } for (int i=8; i<16; i++) { lsb = (lsb << 8) | (sha1Bytes[i] & 0xff); } return new UUID(msb, lsb); }
[ "public", "static", "UUID", "nameUUIDv5FromBytes", "(", "byte", "[", "]", "name", ")", "{", "// Based on code from OpenJDK UUID#nameUUIDFromBytes + private byte[] constructor", "MessageDigest", "md", ";", "try", "{", "md", "=", "MessageDigest", ".", "getInstance", "(", ...
Creates a type 5 (name based) {@code UUID} based on the specified byte array. This method is effectively identical to {@link UUID#nameUUIDFromBytes}, except that this method uses a SHA1 hash instead of the MD5 hash used in the type 3 {@code UUID}s. RFC 4122 states that "SHA-1 is preferred" over MD5, without giving a reason for why. @param name a byte array to be used to construct a {@code UUID} @return a {@code UUID} generated from the specified array. @see <a href="http://tools.ietf.org/html/rfc4122#section-4.3">RFC 4122 4.3. Algorithm for Creating a Name-Based UUID</a> @see <a href="http://tools.ietf.org/html/rfc4122#appendix-A">RFC 4122 appendix A</a> @see UUID#nameUUIDFromBytes(byte[])
[ "Creates", "a", "type", "5", "(", "name", "based", ")", "{", "@code", "UUID", "}", "based", "on", "the", "specified", "byte", "array", ".", "This", "method", "is", "effectively", "identical", "to", "{", "@link", "UUID#nameUUIDFromBytes", "}", "except", "th...
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/UUIDFactory.java#L165-L195
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/JcrPropertyDefinition.java
JcrPropertyDefinition.canCastToTypeAndSatisfyConstraints
boolean canCastToTypeAndSatisfyConstraints( Value value, JcrSession session ) { """ Returns <code>true</code> if <code>value</code> can be cast to <code>property.getRequiredType()</code> per the type conversion rules in section 3.6.4 of the JCR 2.0 specification AND <code>value</code> satisfies the constraints (if any) for the property definition. If the property definition has a required type of {@link PropertyType#UNDEFINED}, the cast will be considered to have succeeded and the value constraints (if any) will be interpreted using the semantics for the type specified in <code>value.getType()</code>. @param value the value to be validated @param session the session in which the constraints are to be checked; may not be null @return <code>true</code> if the value can be cast to the required type for the property definition (if it exists) and satisfies the constraints for the property (if any exist). @see PropertyDefinition#getValueConstraints() @see #satisfiesConstraints(Value,JcrSession) """ try { assert value instanceof JcrValue : "Illegal implementation of Value interface"; ((JcrValue)value).asType(getRequiredType()); // throws ValueFormatException if there's a problem return satisfiesConstraints(value, session); } catch (javax.jcr.ValueFormatException | org.modeshape.jcr.value.ValueFormatException vfe) { // Cast failed return false; } }
java
boolean canCastToTypeAndSatisfyConstraints( Value value, JcrSession session ) { try { assert value instanceof JcrValue : "Illegal implementation of Value interface"; ((JcrValue)value).asType(getRequiredType()); // throws ValueFormatException if there's a problem return satisfiesConstraints(value, session); } catch (javax.jcr.ValueFormatException | org.modeshape.jcr.value.ValueFormatException vfe) { // Cast failed return false; } }
[ "boolean", "canCastToTypeAndSatisfyConstraints", "(", "Value", "value", ",", "JcrSession", "session", ")", "{", "try", "{", "assert", "value", "instanceof", "JcrValue", ":", "\"Illegal implementation of Value interface\"", ";", "(", "(", "JcrValue", ")", "value", ")",...
Returns <code>true</code> if <code>value</code> can be cast to <code>property.getRequiredType()</code> per the type conversion rules in section 3.6.4 of the JCR 2.0 specification AND <code>value</code> satisfies the constraints (if any) for the property definition. If the property definition has a required type of {@link PropertyType#UNDEFINED}, the cast will be considered to have succeeded and the value constraints (if any) will be interpreted using the semantics for the type specified in <code>value.getType()</code>. @param value the value to be validated @param session the session in which the constraints are to be checked; may not be null @return <code>true</code> if the value can be cast to the required type for the property definition (if it exists) and satisfies the constraints for the property (if any exist). @see PropertyDefinition#getValueConstraints() @see #satisfiesConstraints(Value,JcrSession)
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "<code", ">", "value<", "/", "code", ">", "can", "be", "cast", "to", "<code", ">", "property", ".", "getRequiredType", "()", "<", "/", "code", ">", "per", "the", "type", "conversion", "rules", ...
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/JcrPropertyDefinition.java#L408-L418
zaproxy/zaproxy
src/org/parosproxy/paros/model/Session.java
Session.exportContext
public void exportContext (Context c, File file) throws ConfigurationException { """ Export the specified context to a file @param c @param file @throws ConfigurationException """ ZapXmlConfiguration config = new ZapXmlConfiguration(); config.setProperty(Context.CONTEXT_CONFIG_NAME, c.getName()); config.setProperty(Context.CONTEXT_CONFIG_DESC, c.getDescription()); config.setProperty(Context.CONTEXT_CONFIG_INSCOPE, c.isInScope()); config.setProperty(Context.CONTEXT_CONFIG_INC_REGEXES, c.getIncludeInContextRegexs()); config.setProperty(Context.CONTEXT_CONFIG_EXC_REGEXES, c.getExcludeFromContextRegexs()); config.setProperty(Context.CONTEXT_CONFIG_TECH_INCLUDE, techListToStringList(c.getTechSet().getIncludeTech())); config.setProperty(Context.CONTEXT_CONFIG_TECH_EXCLUDE, techListToStringList(c.getTechSet().getExcludeTech())); config.setProperty(Context.CONTEXT_CONFIG_URLPARSER_CLASS, c.getUrlParamParser().getClass().getCanonicalName()); config.setProperty(Context.CONTEXT_CONFIG_URLPARSER_CONFIG, c.getUrlParamParser().getConfig()); config.setProperty(Context.CONTEXT_CONFIG_POSTPARSER_CLASS, c.getPostParamParser().getClass().getCanonicalName()); config.setProperty(Context.CONTEXT_CONFIG_POSTPARSER_CONFIG, c.getPostParamParser().getConfig()); for (StructuralNodeModifier snm : c.getDataDrivenNodes()) { config.addProperty(Context.CONTEXT_CONFIG_DATA_DRIVEN_NODES, snm.getConfig()); } model.exportContext(c, config); config.save(file); }
java
public void exportContext (Context c, File file) throws ConfigurationException { ZapXmlConfiguration config = new ZapXmlConfiguration(); config.setProperty(Context.CONTEXT_CONFIG_NAME, c.getName()); config.setProperty(Context.CONTEXT_CONFIG_DESC, c.getDescription()); config.setProperty(Context.CONTEXT_CONFIG_INSCOPE, c.isInScope()); config.setProperty(Context.CONTEXT_CONFIG_INC_REGEXES, c.getIncludeInContextRegexs()); config.setProperty(Context.CONTEXT_CONFIG_EXC_REGEXES, c.getExcludeFromContextRegexs()); config.setProperty(Context.CONTEXT_CONFIG_TECH_INCLUDE, techListToStringList(c.getTechSet().getIncludeTech())); config.setProperty(Context.CONTEXT_CONFIG_TECH_EXCLUDE, techListToStringList(c.getTechSet().getExcludeTech())); config.setProperty(Context.CONTEXT_CONFIG_URLPARSER_CLASS, c.getUrlParamParser().getClass().getCanonicalName()); config.setProperty(Context.CONTEXT_CONFIG_URLPARSER_CONFIG, c.getUrlParamParser().getConfig()); config.setProperty(Context.CONTEXT_CONFIG_POSTPARSER_CLASS, c.getPostParamParser().getClass().getCanonicalName()); config.setProperty(Context.CONTEXT_CONFIG_POSTPARSER_CONFIG, c.getPostParamParser().getConfig()); for (StructuralNodeModifier snm : c.getDataDrivenNodes()) { config.addProperty(Context.CONTEXT_CONFIG_DATA_DRIVEN_NODES, snm.getConfig()); } model.exportContext(c, config); config.save(file); }
[ "public", "void", "exportContext", "(", "Context", "c", ",", "File", "file", ")", "throws", "ConfigurationException", "{", "ZapXmlConfiguration", "config", "=", "new", "ZapXmlConfiguration", "(", ")", ";", "config", ".", "setProperty", "(", "Context", ".", "CONT...
Export the specified context to a file @param c @param file @throws ConfigurationException
[ "Export", "the", "specified", "context", "to", "a", "file" ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/model/Session.java#L1346-L1366
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getTitleInfo
public void getTitleInfo(int[] ids, Callback<List<Title>> callback) throws GuildWars2Exception, NullPointerException { """ For more info on titles API go <a href="https://wiki.guildwars2.com/wiki/API:2/titles">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param ids list of title id @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws GuildWars2Exception empty ID list @throws NullPointerException if given {@link Callback} is empty @see Title title info """ isParamValid(new ParamChecker(ids)); gw2API.getTitleInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
java
public void getTitleInfo(int[] ids, Callback<List<Title>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getTitleInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
[ "public", "void", "getTitleInfo", "(", "int", "[", "]", "ids", ",", "Callback", "<", "List", "<", "Title", ">", ">", "callback", ")", "throws", "GuildWars2Exception", ",", "NullPointerException", "{", "isParamValid", "(", "new", "ParamChecker", "(", "ids", "...
For more info on titles API go <a href="https://wiki.guildwars2.com/wiki/API:2/titles">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions @param ids list of title id @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws GuildWars2Exception empty ID list @throws NullPointerException if given {@link Callback} is empty @see Title title info
[ "For", "more", "info", "on", "titles", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "titles", ">", "here<", "/", "a", ">", "<br", "/", ">", "Give", "user", "t...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2495-L2498
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/task/DataSinkTask.java
DataSinkTask.initInputReaders
@SuppressWarnings("unchecked") private void initInputReaders() throws Exception { """ Initializes the input readers of the DataSinkTask. @throws RuntimeException Thrown in case of invalid task input configuration. """ MutableReader<?> inputReader; int numGates = 0; // ---------------- create the input readers --------------------- // in case where a logical input unions multiple physical inputs, create a union reader final int groupSize = this.config.getGroupSize(0); numGates += groupSize; if (groupSize == 1) { // non-union case inputReader = new MutableRecordReader<DeserializationDelegate<IT>>(this); } else if (groupSize > 1){ // union case MutableRecordReader<IOReadableWritable>[] readers = new MutableRecordReader[groupSize]; for (int j = 0; j < groupSize; ++j) { readers[j] = new MutableRecordReader<IOReadableWritable>(this); } inputReader = new MutableUnionRecordReader<IOReadableWritable>(readers); } else { throw new Exception("Illegal input group size in task configuration: " + groupSize); } this.inputTypeSerializerFactory = this.config.getInputSerializer(0, this.userCodeClassLoader); if (this.inputTypeSerializerFactory.getDataType() == Record.class) { // record specific deserialization MutableReader<Record> reader = (MutableReader<Record>) inputReader; this.reader = (MutableObjectIterator<IT>)new RecordReaderIterator(reader); } else { // generic data type serialization MutableReader<DeserializationDelegate<?>> reader = (MutableReader<DeserializationDelegate<?>>) inputReader; @SuppressWarnings({ "rawtypes" }) final MutableObjectIterator<?> iter = new ReaderIterator(reader, this.inputTypeSerializerFactory.getSerializer()); this.reader = (MutableObjectIterator<IT>)iter; } // final sanity check if (numGates != this.config.getNumInputs()) { throw new Exception("Illegal configuration: Number of input gates and group sizes are not consistent."); } }
java
@SuppressWarnings("unchecked") private void initInputReaders() throws Exception { MutableReader<?> inputReader; int numGates = 0; // ---------------- create the input readers --------------------- // in case where a logical input unions multiple physical inputs, create a union reader final int groupSize = this.config.getGroupSize(0); numGates += groupSize; if (groupSize == 1) { // non-union case inputReader = new MutableRecordReader<DeserializationDelegate<IT>>(this); } else if (groupSize > 1){ // union case MutableRecordReader<IOReadableWritable>[] readers = new MutableRecordReader[groupSize]; for (int j = 0; j < groupSize; ++j) { readers[j] = new MutableRecordReader<IOReadableWritable>(this); } inputReader = new MutableUnionRecordReader<IOReadableWritable>(readers); } else { throw new Exception("Illegal input group size in task configuration: " + groupSize); } this.inputTypeSerializerFactory = this.config.getInputSerializer(0, this.userCodeClassLoader); if (this.inputTypeSerializerFactory.getDataType() == Record.class) { // record specific deserialization MutableReader<Record> reader = (MutableReader<Record>) inputReader; this.reader = (MutableObjectIterator<IT>)new RecordReaderIterator(reader); } else { // generic data type serialization MutableReader<DeserializationDelegate<?>> reader = (MutableReader<DeserializationDelegate<?>>) inputReader; @SuppressWarnings({ "rawtypes" }) final MutableObjectIterator<?> iter = new ReaderIterator(reader, this.inputTypeSerializerFactory.getSerializer()); this.reader = (MutableObjectIterator<IT>)iter; } // final sanity check if (numGates != this.config.getNumInputs()) { throw new Exception("Illegal configuration: Number of input gates and group sizes are not consistent."); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "initInputReaders", "(", ")", "throws", "Exception", "{", "MutableReader", "<", "?", ">", "inputReader", ";", "int", "numGates", "=", "0", ";", "// ---------------- create the input readers ------...
Initializes the input readers of the DataSinkTask. @throws RuntimeException Thrown in case of invalid task input configuration.
[ "Initializes", "the", "input", "readers", "of", "the", "DataSinkTask", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/task/DataSinkTask.java#L310-L353
Azure/azure-sdk-for-java
batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/JobsInner.java
JobsInner.beginTerminateAsync
public Observable<Void> beginTerminateAsync(String resourceGroupName, String workspaceName, String experimentName, String jobName) { """ Terminates a job. @param resourceGroupName Name of the resource group to which the resource belongs. @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param experimentName The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param jobName The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return beginTerminateWithServiceResponseAsync(resourceGroupName, workspaceName, experimentName, jobName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> beginTerminateAsync(String resourceGroupName, String workspaceName, String experimentName, String jobName) { return beginTerminateWithServiceResponseAsync(resourceGroupName, workspaceName, experimentName, jobName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "beginTerminateAsync", "(", "String", "resourceGroupName", ",", "String", "workspaceName", ",", "String", "experimentName", ",", "String", "jobName", ")", "{", "return", "beginTerminateWithServiceResponseAsync", "(", "resourceGr...
Terminates a job. @param resourceGroupName Name of the resource group to which the resource belongs. @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param experimentName The name of the experiment. Experiment names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param jobName The name of the job within the specified resource group. Job names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Terminates", "a", "job", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/JobsInner.java#L1285-L1292
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/views/overlay/OverlayItem.java
OverlayItem.getMarker
public Drawable getMarker(final int stateBitset) { """ /* (copied from Google API docs) Returns the marker that should be used when drawing this item on the map. A null value means that the default marker should be drawn. Different markers can be returned for different states. The different markers can have different bounds. The default behavior is to call {@link setState(android.graphics.drawable.Drawable, int)} on the overlay item's marker, if it exists, and then return it. @param stateBitset The current state. @return The marker for the current state, or null if the default marker for the overlay should be used. """ // marker not specified if (mMarker == null) { return null; } // set marker state appropriately setState(mMarker, stateBitset); return mMarker; }
java
public Drawable getMarker(final int stateBitset) { // marker not specified if (mMarker == null) { return null; } // set marker state appropriately setState(mMarker, stateBitset); return mMarker; }
[ "public", "Drawable", "getMarker", "(", "final", "int", "stateBitset", ")", "{", "// marker not specified", "if", "(", "mMarker", "==", "null", ")", "{", "return", "null", ";", "}", "// set marker state appropriately", "setState", "(", "mMarker", ",", "stateBitset...
/* (copied from Google API docs) Returns the marker that should be used when drawing this item on the map. A null value means that the default marker should be drawn. Different markers can be returned for different states. The different markers can have different bounds. The default behavior is to call {@link setState(android.graphics.drawable.Drawable, int)} on the overlay item's marker, if it exists, and then return it. @param stateBitset The current state. @return The marker for the current state, or null if the default marker for the overlay should be used.
[ "/", "*", "(", "copied", "from", "Google", "API", "docs", ")", "Returns", "the", "marker", "that", "should", "be", "used", "when", "drawing", "this", "item", "on", "the", "map", ".", "A", "null", "value", "means", "that", "the", "default", "marker", "s...
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/OverlayItem.java#L104-L113
akquinet/needle
src/main/java/de/akquinet/jbosscc/needle/db/transaction/TransactionHelper.java
TransactionHelper.saveObject
public final <T> T saveObject(final T obj) throws Exception { """ Saves the given object in the database. @param <T> type of given object obj @param obj object to save @return saved object @throws Exception save objects failed """ return executeInTransaction(new Runnable<T>() { @Override public T run(final EntityManager entityManager) { return persist(obj, entityManager); } }); }
java
public final <T> T saveObject(final T obj) throws Exception { return executeInTransaction(new Runnable<T>() { @Override public T run(final EntityManager entityManager) { return persist(obj, entityManager); } }); }
[ "public", "final", "<", "T", ">", "T", "saveObject", "(", "final", "T", "obj", ")", "throws", "Exception", "{", "return", "executeInTransaction", "(", "new", "Runnable", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "T", "run", "(", "final",...
Saves the given object in the database. @param <T> type of given object obj @param obj object to save @return saved object @throws Exception save objects failed
[ "Saves", "the", "given", "object", "in", "the", "database", "." ]
train
https://github.com/akquinet/needle/blob/8b411c521246b8212882485edc01644f9aac7e24/src/main/java/de/akquinet/jbosscc/needle/db/transaction/TransactionHelper.java#L29-L36
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/PeerManager.java
PeerManager.unproxyRemoteObject
public void unproxyRemoteObject (DObjectAddress addr) { """ Unsubscribes from and clears a proxied object. The caller must be sure that there are no remaining subscribers to the object on this local server. """ Tuple<Subscriber<?>, DObject> bits = _proxies.remove(addr); if (bits == null) { log.warning("Requested to clear unknown proxy", "addr", addr); return; } // If it's local, just remove the subscriber we added and bail if (Objects.equal(addr.nodeName, _nodeName)) { bits.right.removeSubscriber(bits.left); return; } // clear out the local object manager's proxy mapping _omgr.clearProxyObject(addr.oid, bits.right); final Client peer = getPeerClient(addr.nodeName); if (peer == null) { log.warning("Unable to unsubscribe from proxy, missing peer", "addr", addr); return; } // restore the object's omgr reference to our ClientDObjectMgr and its oid back to the // remote oid so that it can properly finish the unsubscription process bits.right.setOid(addr.oid); bits.right.setManager(peer.getDObjectManager()); // finally unsubscribe from the object on our peer peer.getDObjectManager().unsubscribeFromObject(addr.oid, bits.left); }
java
public void unproxyRemoteObject (DObjectAddress addr) { Tuple<Subscriber<?>, DObject> bits = _proxies.remove(addr); if (bits == null) { log.warning("Requested to clear unknown proxy", "addr", addr); return; } // If it's local, just remove the subscriber we added and bail if (Objects.equal(addr.nodeName, _nodeName)) { bits.right.removeSubscriber(bits.left); return; } // clear out the local object manager's proxy mapping _omgr.clearProxyObject(addr.oid, bits.right); final Client peer = getPeerClient(addr.nodeName); if (peer == null) { log.warning("Unable to unsubscribe from proxy, missing peer", "addr", addr); return; } // restore the object's omgr reference to our ClientDObjectMgr and its oid back to the // remote oid so that it can properly finish the unsubscription process bits.right.setOid(addr.oid); bits.right.setManager(peer.getDObjectManager()); // finally unsubscribe from the object on our peer peer.getDObjectManager().unsubscribeFromObject(addr.oid, bits.left); }
[ "public", "void", "unproxyRemoteObject", "(", "DObjectAddress", "addr", ")", "{", "Tuple", "<", "Subscriber", "<", "?", ">", ",", "DObject", ">", "bits", "=", "_proxies", ".", "remove", "(", "addr", ")", ";", "if", "(", "bits", "==", "null", ")", "{", ...
Unsubscribes from and clears a proxied object. The caller must be sure that there are no remaining subscribers to the object on this local server.
[ "Unsubscribes", "from", "and", "clears", "a", "proxied", "object", ".", "The", "caller", "must", "be", "sure", "that", "there", "are", "no", "remaining", "subscribers", "to", "the", "object", "on", "this", "local", "server", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/PeerManager.java#L698-L729
structurizr/java
structurizr-core/src/com/structurizr/documentation/DocumentationTemplate.java
DocumentationTemplate.addSection
public Section addSection(Container container, String title, Format format, String content) { """ Adds a section relating to a {@link Container}. @param container the {@link Container} the documentation content relates to @param title the section title @param format the {@link Format} of the documentation content @param content a String containing the documentation content @return a documentation {@link Section} """ return add(container, title, format, content); }
java
public Section addSection(Container container, String title, Format format, String content) { return add(container, title, format, content); }
[ "public", "Section", "addSection", "(", "Container", "container", ",", "String", "title", ",", "Format", "format", ",", "String", "content", ")", "{", "return", "add", "(", "container", ",", "title", ",", "format", ",", "content", ")", ";", "}" ]
Adds a section relating to a {@link Container}. @param container the {@link Container} the documentation content relates to @param title the section title @param format the {@link Format} of the documentation content @param content a String containing the documentation content @return a documentation {@link Section}
[ "Adds", "a", "section", "relating", "to", "a", "{", "@link", "Container", "}", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/DocumentationTemplate.java#L113-L115
kuali/ojb-1.0.4
src/java/org/apache/ojb/odmg/TransactionImpl.java
TransactionImpl.prepareCommit
protected void prepareCommit() throws TransactionAbortedException, LockNotGrantedException { """ Prepare does the actual work of moving the changes at the object level into storage (the underlying rdbms for instance). prepare Can be called multiple times, and does not release locks. @throws TransactionAbortedException if the transaction has been aborted for any reason. @throws IllegalStateException Method called if transaction is not in the proper state to perform this operation @throws TransactionNotInProgressException if the transaction is closed. """ if (txStatus == Status.STATUS_MARKED_ROLLBACK) { throw new TransactionAbortedExceptionOJB("Prepare Transaction: tx already marked for rollback"); } if (txStatus != Status.STATUS_ACTIVE) { throw new IllegalStateException("Prepare Transaction: tx status is not 'active', status is " + TxUtil.getStatusString(txStatus)); } try { txStatus = Status.STATUS_PREPARING; doWriteObjects(false); txStatus = Status.STATUS_PREPARED; } catch (RuntimeException e) { log.error("Could not prepare for commit", e); txStatus = Status.STATUS_MARKED_ROLLBACK; throw e; } }
java
protected void prepareCommit() throws TransactionAbortedException, LockNotGrantedException { if (txStatus == Status.STATUS_MARKED_ROLLBACK) { throw new TransactionAbortedExceptionOJB("Prepare Transaction: tx already marked for rollback"); } if (txStatus != Status.STATUS_ACTIVE) { throw new IllegalStateException("Prepare Transaction: tx status is not 'active', status is " + TxUtil.getStatusString(txStatus)); } try { txStatus = Status.STATUS_PREPARING; doWriteObjects(false); txStatus = Status.STATUS_PREPARED; } catch (RuntimeException e) { log.error("Could not prepare for commit", e); txStatus = Status.STATUS_MARKED_ROLLBACK; throw e; } }
[ "protected", "void", "prepareCommit", "(", ")", "throws", "TransactionAbortedException", ",", "LockNotGrantedException", "{", "if", "(", "txStatus", "==", "Status", ".", "STATUS_MARKED_ROLLBACK", ")", "{", "throw", "new", "TransactionAbortedExceptionOJB", "(", "\"Prepar...
Prepare does the actual work of moving the changes at the object level into storage (the underlying rdbms for instance). prepare Can be called multiple times, and does not release locks. @throws TransactionAbortedException if the transaction has been aborted for any reason. @throws IllegalStateException Method called if transaction is not in the proper state to perform this operation @throws TransactionNotInProgressException if the transaction is closed.
[ "Prepare", "does", "the", "actual", "work", "of", "moving", "the", "changes", "at", "the", "object", "level", "into", "storage", "(", "the", "underlying", "rdbms", "for", "instance", ")", ".", "prepare", "Can", "be", "called", "multiple", "times", "and", "...
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/odmg/TransactionImpl.java#L749-L771
apache/incubator-atlas
common/src/main/java/org/apache/atlas/utils/ParamChecker.java
ParamChecker.notEmpty
public static <T> Collection<T> notEmpty(Collection<T> list, String name) { """ Check that a list is not null and not empty. @param list the list of T. @param name parameter name for the exception message. """ notNull(list, name); if (list.isEmpty()) { throw new IllegalArgumentException(String.format("Collection %s is empty", name)); } return list; }
java
public static <T> Collection<T> notEmpty(Collection<T> list, String name) { notNull(list, name); if (list.isEmpty()) { throw new IllegalArgumentException(String.format("Collection %s is empty", name)); } return list; }
[ "public", "static", "<", "T", ">", "Collection", "<", "T", ">", "notEmpty", "(", "Collection", "<", "T", ">", "list", ",", "String", "name", ")", "{", "notNull", "(", "list", ",", "name", ")", ";", "if", "(", "list", ".", "isEmpty", "(", ")", ")"...
Check that a list is not null and not empty. @param list the list of T. @param name parameter name for the exception message.
[ "Check", "that", "a", "list", "is", "not", "null", "and", "not", "empty", "." ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/common/src/main/java/org/apache/atlas/utils/ParamChecker.java#L78-L84
samskivert/samskivert
src/main/java/com/samskivert/swing/Controller.java
Controller.createActionButton
public static JButton createActionButton (String label, String command) { """ Creates a button and configures it with the specified label and action command and adds {@link #DISPATCHER} as an action listener. """ JButton button = new JButton(label); configureAction(button, command); return button; }
java
public static JButton createActionButton (String label, String command) { JButton button = new JButton(label); configureAction(button, command); return button; }
[ "public", "static", "JButton", "createActionButton", "(", "String", "label", ",", "String", "command", ")", "{", "JButton", "button", "=", "new", "JButton", "(", "label", ")", ";", "configureAction", "(", "button", ",", "command", ")", ";", "return", "button...
Creates a button and configures it with the specified label and action command and adds {@link #DISPATCHER} as an action listener.
[ "Creates", "a", "button", "and", "configures", "it", "with", "the", "specified", "label", "and", "action", "command", "and", "adds", "{" ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/Controller.java#L135-L140
apache/groovy
src/main/java/org/codehaus/groovy/syntax/Types.java
Types.makePostfix
public static void makePostfix(CSTNode node, boolean throwIfInvalid) { """ Converts a node from a generic type to a specific postfix type. Throws a <code>GroovyBugError</code> if the type can't be converted. """ switch (node.getMeaning()) { case PLUS_PLUS: node.setMeaning(POSTFIX_PLUS_PLUS); break; case MINUS_MINUS: node.setMeaning(POSTFIX_MINUS_MINUS); break; default: if (throwIfInvalid) { throw new GroovyBugError("cannot convert to postfix for type [" + node.getMeaning() + "]"); } } }
java
public static void makePostfix(CSTNode node, boolean throwIfInvalid) { switch (node.getMeaning()) { case PLUS_PLUS: node.setMeaning(POSTFIX_PLUS_PLUS); break; case MINUS_MINUS: node.setMeaning(POSTFIX_MINUS_MINUS); break; default: if (throwIfInvalid) { throw new GroovyBugError("cannot convert to postfix for type [" + node.getMeaning() + "]"); } } }
[ "public", "static", "void", "makePostfix", "(", "CSTNode", "node", ",", "boolean", "throwIfInvalid", ")", "{", "switch", "(", "node", ".", "getMeaning", "(", ")", ")", "{", "case", "PLUS_PLUS", ":", "node", ".", "setMeaning", "(", "POSTFIX_PLUS_PLUS", ")", ...
Converts a node from a generic type to a specific postfix type. Throws a <code>GroovyBugError</code> if the type can't be converted.
[ "Converts", "a", "node", "from", "a", "generic", "type", "to", "a", "specific", "postfix", "type", ".", "Throws", "a", "<code", ">", "GroovyBugError<", "/", "code", ">", "if", "the", "type", "can", "t", "be", "converted", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/syntax/Types.java#L887-L904
tempodb/tempodb-java
src/main/java/com/tempodb/Client.java
Client.readSingleValue
public Cursor<SingleValue> readSingleValue(Filter filter, DateTime timestamp) { """ Returns a cursor of single value for a set of series <p>The returned values (datapoints) can be null if there are no datapoints in the series or in the specified direction. The system default timezone is used. The direction is set to EXACT. @param filter The filter of series to read from @param timestamp The timestamp to read a value at @return A cursor over the values at the specified timestamp @see Cursor @see SingleValue @since 1.1.0 """ return readSingleValue(filter, timestamp, DateTimeZone.getDefault(), Direction.EXACT); }
java
public Cursor<SingleValue> readSingleValue(Filter filter, DateTime timestamp) { return readSingleValue(filter, timestamp, DateTimeZone.getDefault(), Direction.EXACT); }
[ "public", "Cursor", "<", "SingleValue", ">", "readSingleValue", "(", "Filter", "filter", ",", "DateTime", "timestamp", ")", "{", "return", "readSingleValue", "(", "filter", ",", "timestamp", ",", "DateTimeZone", ".", "getDefault", "(", ")", ",", "Direction", "...
Returns a cursor of single value for a set of series <p>The returned values (datapoints) can be null if there are no datapoints in the series or in the specified direction. The system default timezone is used. The direction is set to EXACT. @param filter The filter of series to read from @param timestamp The timestamp to read a value at @return A cursor over the values at the specified timestamp @see Cursor @see SingleValue @since 1.1.0
[ "Returns", "a", "cursor", "of", "single", "value", "for", "a", "set", "of", "series", "<p", ">", "The", "returned", "values", "(", "datapoints", ")", "can", "be", "null", "if", "there", "are", "no", "datapoints", "in", "the", "series", "or", "in", "the...
train
https://github.com/tempodb/tempodb-java/blob/5733f204fe4c8dda48916ba1f67cf44f5a3f9c69/src/main/java/com/tempodb/Client.java#L490-L492
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/listeners/AddResourcesListener.java
AddResourcesListener.addBasicJSResource
public static void addBasicJSResource(String library, String resource) { """ Registers a core JS file that needs to be included in the header of the HTML file, but after jQuery and AngularJS. @param library The name of the sub-folder of the resources folder. @param resource The name of the resource file within the library folder. """ addResource(resource, library, resource, BASIC_JS_RESOURCE_KEY); }
java
public static void addBasicJSResource(String library, String resource) { addResource(resource, library, resource, BASIC_JS_RESOURCE_KEY); }
[ "public", "static", "void", "addBasicJSResource", "(", "String", "library", ",", "String", "resource", ")", "{", "addResource", "(", "resource", ",", "library", ",", "resource", ",", "BASIC_JS_RESOURCE_KEY", ")", ";", "}" ]
Registers a core JS file that needs to be included in the header of the HTML file, but after jQuery and AngularJS. @param library The name of the sub-folder of the resources folder. @param resource The name of the resource file within the library folder.
[ "Registers", "a", "core", "JS", "file", "that", "needs", "to", "be", "included", "in", "the", "header", "of", "the", "HTML", "file", "but", "after", "jQuery", "and", "AngularJS", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/listeners/AddResourcesListener.java#L849-L851
reactor/reactor-netty
src/main/java/reactor/netty/FutureMono.java
FutureMono.disposableWriteAndFlush
public static Mono<Void> disposableWriteAndFlush(Channel channel, Publisher<?> dataStream) { """ Write the passed {@link Publisher} and return a disposable {@link Mono}. <p> In addition, current method allows interaction with downstream context, so it may be transferred to implicitly connected upstream <p> Example: <p> <pre><code> Flux&lt;String&gt; dataStream = Flux.just("a", "b", "c"); FutureMono.deferFutureWithContext((subscriberContext) -> context().channel() .writeAndFlush(PublisherContext.withContext(dataStream, subscriberContext))); </code></pre> @param dataStream the publisher to write @return A {@link Mono} forwarding {@link Future} success, failure and cancel """ return new DeferredWriteMono(channel, dataStream); }
java
public static Mono<Void> disposableWriteAndFlush(Channel channel, Publisher<?> dataStream) { return new DeferredWriteMono(channel, dataStream); }
[ "public", "static", "Mono", "<", "Void", ">", "disposableWriteAndFlush", "(", "Channel", "channel", ",", "Publisher", "<", "?", ">", "dataStream", ")", "{", "return", "new", "DeferredWriteMono", "(", "channel", ",", "dataStream", ")", ";", "}" ]
Write the passed {@link Publisher} and return a disposable {@link Mono}. <p> In addition, current method allows interaction with downstream context, so it may be transferred to implicitly connected upstream <p> Example: <p> <pre><code> Flux&lt;String&gt; dataStream = Flux.just("a", "b", "c"); FutureMono.deferFutureWithContext((subscriberContext) -> context().channel() .writeAndFlush(PublisherContext.withContext(dataStream, subscriberContext))); </code></pre> @param dataStream the publisher to write @return A {@link Mono} forwarding {@link Future} success, failure and cancel
[ "Write", "the", "passed", "{", "@link", "Publisher", "}", "and", "return", "a", "disposable", "{", "@link", "Mono", "}", ".", "<p", ">", "In", "addition", "current", "method", "allows", "interaction", "with", "downstream", "context", "so", "it", "may", "be...
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/FutureMono.java#L100-L103
landawn/AbacusUtil
src/com/landawn/abacus/util/Pair.java
Pair.setIf
public <E extends Exception> boolean setIf(final L newLeft, final R newRight, Try.TriPredicate<? super Pair<L, R>, ? super L, ? super R, E> predicate) throws E { """ Set to the specified <code>newLeft</code> and <code>newRight</code> and returns <code>true</code> if <code>predicate</code> returns true. Otherwise returns <code>false</code> without setting the left/right to new values. @param newLeft @param newRight @param predicate - the first parameter is current pair, the second parameter is the <code>newLeft</code>, the third parameter is the <code>newRight</code>. @return """ if (predicate.test(this, newLeft, newRight)) { this.left = newLeft; this.right = newRight; return true; } return false; }
java
public <E extends Exception> boolean setIf(final L newLeft, final R newRight, Try.TriPredicate<? super Pair<L, R>, ? super L, ? super R, E> predicate) throws E { if (predicate.test(this, newLeft, newRight)) { this.left = newLeft; this.right = newRight; return true; } return false; }
[ "public", "<", "E", "extends", "Exception", ">", "boolean", "setIf", "(", "final", "L", "newLeft", ",", "final", "R", "newRight", ",", "Try", ".", "TriPredicate", "<", "?", "super", "Pair", "<", "L", ",", "R", ">", ",", "?", "super", "L", ",", "?",...
Set to the specified <code>newLeft</code> and <code>newRight</code> and returns <code>true</code> if <code>predicate</code> returns true. Otherwise returns <code>false</code> without setting the left/right to new values. @param newLeft @param newRight @param predicate - the first parameter is current pair, the second parameter is the <code>newLeft</code>, the third parameter is the <code>newRight</code>. @return
[ "Set", "to", "the", "specified", "<code", ">", "newLeft<", "/", "code", ">", "and", "<code", ">", "newRight<", "/", "code", ">", "and", "returns", "<code", ">", "true<", "/", "code", ">", "if", "<code", ">", "predicate<", "/", "code", ">", "returns", ...
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Pair.java#L155-L164
paypal/SeLion
dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/JsonDataProviderImpl.java
JsonDataProviderImpl.getDataByFilter
@Override public Iterator<Object[]> getDataByFilter(DataProviderFilter dataFilter) { """ Gets JSON data from a resource by applying the given filter. @param dataFilter an implementation class of {@link DataProviderFilter} """ Preconditions.checkArgument(resource != null, "File resource cannot be null"); logger.entering(dataFilter); Class<?> arrayType; JsonReader reader = null; try { reader = new JsonReader(getReader(resource)); arrayType = Array.newInstance(resource.getCls(), 0).getClass(); Gson myJson = new Gson(); Object[] mappedData = myJson.fromJson(reader, arrayType); return prepareDataAsObjectArrayList(mappedData, dataFilter).iterator(); } catch (Exception e) { throw new DataProviderException(e.getMessage(), e); } finally { IOUtils.closeQuietly(reader); } }
java
@Override public Iterator<Object[]> getDataByFilter(DataProviderFilter dataFilter) { Preconditions.checkArgument(resource != null, "File resource cannot be null"); logger.entering(dataFilter); Class<?> arrayType; JsonReader reader = null; try { reader = new JsonReader(getReader(resource)); arrayType = Array.newInstance(resource.getCls(), 0).getClass(); Gson myJson = new Gson(); Object[] mappedData = myJson.fromJson(reader, arrayType); return prepareDataAsObjectArrayList(mappedData, dataFilter).iterator(); } catch (Exception e) { throw new DataProviderException(e.getMessage(), e); } finally { IOUtils.closeQuietly(reader); } }
[ "@", "Override", "public", "Iterator", "<", "Object", "[", "]", ">", "getDataByFilter", "(", "DataProviderFilter", "dataFilter", ")", "{", "Preconditions", ".", "checkArgument", "(", "resource", "!=", "null", ",", "\"File resource cannot be null\"", ")", ";", "log...
Gets JSON data from a resource by applying the given filter. @param dataFilter an implementation class of {@link DataProviderFilter}
[ "Gets", "JSON", "data", "from", "a", "resource", "by", "applying", "the", "given", "filter", "." ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/JsonDataProviderImpl.java#L184-L201
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/DependencyFinder.java
DependencyFinder.getArtifactFileFromPluginDependencies
public static File getArtifactFileFromPluginDependencies(AbstractWisdomMojo mojo, String artifactId, String type) { """ Gets the file of the dependency with the given artifact id from the plugin dependencies (i.e. from the dependencies of the wisdom-maven-plugin itself, and not from the current 'under-build' project). @param mojo the mojo, cannot be {@code null} @param artifactId the name of the artifact to find, cannot be {@code null} @param type the extension of the artifact to find, should not be {@code null} @return the artifact file, {@code null} if not found """ Preconditions.checkNotNull(mojo); Preconditions.checkNotNull(artifactId); Preconditions.checkNotNull(type); for (Artifact artifact : mojo.pluginDependencies) { if (artifact.getArtifactId().equals(artifactId) && artifact.getType().equals(type)) { return artifact.getFile(); } } return null; }
java
public static File getArtifactFileFromPluginDependencies(AbstractWisdomMojo mojo, String artifactId, String type) { Preconditions.checkNotNull(mojo); Preconditions.checkNotNull(artifactId); Preconditions.checkNotNull(type); for (Artifact artifact : mojo.pluginDependencies) { if (artifact.getArtifactId().equals(artifactId) && artifact.getType().equals(type)) { return artifact.getFile(); } } return null; }
[ "public", "static", "File", "getArtifactFileFromPluginDependencies", "(", "AbstractWisdomMojo", "mojo", ",", "String", "artifactId", ",", "String", "type", ")", "{", "Preconditions", ".", "checkNotNull", "(", "mojo", ")", ";", "Preconditions", ".", "checkNotNull", "...
Gets the file of the dependency with the given artifact id from the plugin dependencies (i.e. from the dependencies of the wisdom-maven-plugin itself, and not from the current 'under-build' project). @param mojo the mojo, cannot be {@code null} @param artifactId the name of the artifact to find, cannot be {@code null} @param type the extension of the artifact to find, should not be {@code null} @return the artifact file, {@code null} if not found
[ "Gets", "the", "file", "of", "the", "dependency", "with", "the", "given", "artifact", "id", "from", "the", "plugin", "dependencies", "(", "i", ".", "e", ".", "from", "the", "dependencies", "of", "the", "wisdom", "-", "maven", "-", "plugin", "itself", "an...
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/DependencyFinder.java#L51-L63
maddingo/sojo
src/main/java/net/sf/sojo/core/ConversionIterator.java
ConversionIterator.fireAfterConvertRecursion
private ConversionContext fireAfterConvertRecursion(final ConversionContext pvContext, Object pvKey, Object pvValue) { """ Get a ConversionContext and fire "after convert recursion" event. @param pvContext The ConversionContext. @param pvKey The key can be the key by the <code>Map</code> or the property name by a JavaBean. @param pvValue The value is the map-value or the value in a list or the property-value from a JavaBean. @return The ConversionContext with new or old keys and values. """ pvContext.key = pvKey; pvContext.value = pvValue; getConverterInterceptorHandler().fireAfterConvertRecursion(pvContext); return pvContext; }
java
private ConversionContext fireAfterConvertRecursion(final ConversionContext pvContext, Object pvKey, Object pvValue) { pvContext.key = pvKey; pvContext.value = pvValue; getConverterInterceptorHandler().fireAfterConvertRecursion(pvContext); return pvContext; }
[ "private", "ConversionContext", "fireAfterConvertRecursion", "(", "final", "ConversionContext", "pvContext", ",", "Object", "pvKey", ",", "Object", "pvValue", ")", "{", "pvContext", ".", "key", "=", "pvKey", ";", "pvContext", ".", "value", "=", "pvValue", ";", "...
Get a ConversionContext and fire "after convert recursion" event. @param pvContext The ConversionContext. @param pvKey The key can be the key by the <code>Map</code> or the property name by a JavaBean. @param pvValue The value is the map-value or the value in a list or the property-value from a JavaBean. @return The ConversionContext with new or old keys and values.
[ "Get", "a", "ConversionContext", "and", "fire", "after", "convert", "recursion", "event", "." ]
train
https://github.com/maddingo/sojo/blob/99e9e0a146b502deb7f507fe0623227402ed675b/src/main/java/net/sf/sojo/core/ConversionIterator.java#L160-L165
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java
Configurer.getImplementation
public final <T> T getImplementation(Class<T> type, String... path) { """ Get the class implementation from its name. Default constructor must be available. @param <T> The instance type. @param type The class type. @param path The node path. @return The typed class instance. @throws LionEngineException If invalid class. """ return getImplementation(getClass().getClassLoader(), type, path); }
java
public final <T> T getImplementation(Class<T> type, String... path) { return getImplementation(getClass().getClassLoader(), type, path); }
[ "public", "final", "<", "T", ">", "T", "getImplementation", "(", "Class", "<", "T", ">", "type", ",", "String", "...", "path", ")", "{", "return", "getImplementation", "(", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ",", "type", ",", "path"...
Get the class implementation from its name. Default constructor must be available. @param <T> The instance type. @param type The class type. @param path The node path. @return The typed class instance. @throws LionEngineException If invalid class.
[ "Get", "the", "class", "implementation", "from", "its", "name", ".", "Default", "constructor", "must", "be", "available", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Configurer.java#L295-L298
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/NetworkManagementClientImpl.java
NetworkManagementClientImpl.supportedSecurityProviders
public VirtualWanSecurityProvidersInner supportedSecurityProviders(String resourceGroupName, String virtualWANName) { """ Gives the supported security providers for the virtual wan. @param resourceGroupName The resource group name. @param virtualWANName The name of the VirtualWAN for which supported security providers are needed. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VirtualWanSecurityProvidersInner object if successful. """ return supportedSecurityProvidersWithServiceResponseAsync(resourceGroupName, virtualWANName).toBlocking().single().body(); }
java
public VirtualWanSecurityProvidersInner supportedSecurityProviders(String resourceGroupName, String virtualWANName) { return supportedSecurityProvidersWithServiceResponseAsync(resourceGroupName, virtualWANName).toBlocking().single().body(); }
[ "public", "VirtualWanSecurityProvidersInner", "supportedSecurityProviders", "(", "String", "resourceGroupName", ",", "String", "virtualWANName", ")", "{", "return", "supportedSecurityProvidersWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualWANName", ")", ".", ...
Gives the supported security providers for the virtual wan. @param resourceGroupName The resource group name. @param virtualWANName The name of the VirtualWAN for which supported security providers are needed. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VirtualWanSecurityProvidersInner object if successful.
[ "Gives", "the", "supported", "security", "providers", "for", "the", "virtual", "wan", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/NetworkManagementClientImpl.java#L1240-L1242
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/packet/Stanza.java
Stanza.overrideExtension
public ExtensionElement overrideExtension(ExtensionElement extension) { """ Add the given extension and override eventually existing extensions with the same name and namespace. @param extension the extension element to add. @return one of the removed extensions or <code>null</code> if there are none. @since 4.1.2 """ if (extension == null) return null; synchronized (packetExtensions) { // Note that we need to use removeExtension(String, String) here. If would use // removeExtension(ExtensionElement) then we would remove based on the equality of ExtensionElement, which // is not what we want in this case. ExtensionElement removedExtension = removeExtension(extension.getElementName(), extension.getNamespace()); addExtension(extension); return removedExtension; } }
java
public ExtensionElement overrideExtension(ExtensionElement extension) { if (extension == null) return null; synchronized (packetExtensions) { // Note that we need to use removeExtension(String, String) here. If would use // removeExtension(ExtensionElement) then we would remove based on the equality of ExtensionElement, which // is not what we want in this case. ExtensionElement removedExtension = removeExtension(extension.getElementName(), extension.getNamespace()); addExtension(extension); return removedExtension; } }
[ "public", "ExtensionElement", "overrideExtension", "(", "ExtensionElement", "extension", ")", "{", "if", "(", "extension", "==", "null", ")", "return", "null", ";", "synchronized", "(", "packetExtensions", ")", "{", "// Note that we need to use removeExtension(String, Str...
Add the given extension and override eventually existing extensions with the same name and namespace. @param extension the extension element to add. @return one of the removed extensions or <code>null</code> if there are none. @since 4.1.2
[ "Add", "the", "given", "extension", "and", "override", "eventually", "existing", "extensions", "with", "the", "same", "name", "and", "namespace", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/packet/Stanza.java#L394-L404
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/Workitem.java
Workitem.createEffort
public Effort createEffort(double value, Member member) { """ Log an effort record against this workitem with the current day and time and given member and value. @param member The subject of the Effort. @param value if the Effort. @return created Effort record. @throws IllegalStateException if Effort tracking is not enabled. """ return createEffort(value, member, DateTime.now()); }
java
public Effort createEffort(double value, Member member) { return createEffort(value, member, DateTime.now()); }
[ "public", "Effort", "createEffort", "(", "double", "value", ",", "Member", "member", ")", "{", "return", "createEffort", "(", "value", ",", "member", ",", "DateTime", ".", "now", "(", ")", ")", ";", "}" ]
Log an effort record against this workitem with the current day and time and given member and value. @param member The subject of the Effort. @param value if the Effort. @return created Effort record. @throws IllegalStateException if Effort tracking is not enabled.
[ "Log", "an", "effort", "record", "against", "this", "workitem", "with", "the", "current", "day", "and", "time", "and", "given", "member", "and", "value", "." ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/Workitem.java#L156-L158
Alluxio/alluxio
core/common/src/main/java/alluxio/concurrent/jsr/CompletableFuture.java
CompletableFuture.delayedExecutor
public static Executor delayedExecutor(long delay, TimeUnit unit) { """ Returns a new Executor that submits a task to the default executor after the given delay (or no delay if non-positive). Each delay commences upon invocation of the returned executor's {@code execute} method. @param delay how long to delay, in units of {@code unit} @param unit a {@code TimeUnit} determining how to interpret the {@code delay} parameter @return the new delayed executor @since 9 """ return new DelayedExecutor(delay, Objects.requireNonNull(unit), ASYNC_POOL); }
java
public static Executor delayedExecutor(long delay, TimeUnit unit) { return new DelayedExecutor(delay, Objects.requireNonNull(unit), ASYNC_POOL); }
[ "public", "static", "Executor", "delayedExecutor", "(", "long", "delay", ",", "TimeUnit", "unit", ")", "{", "return", "new", "DelayedExecutor", "(", "delay", ",", "Objects", ".", "requireNonNull", "(", "unit", ")", ",", "ASYNC_POOL", ")", ";", "}" ]
Returns a new Executor that submits a task to the default executor after the given delay (or no delay if non-positive). Each delay commences upon invocation of the returned executor's {@code execute} method. @param delay how long to delay, in units of {@code unit} @param unit a {@code TimeUnit} determining how to interpret the {@code delay} parameter @return the new delayed executor @since 9
[ "Returns", "a", "new", "Executor", "that", "submits", "a", "task", "to", "the", "default", "executor", "after", "the", "given", "delay", "(", "or", "no", "delay", "if", "non", "-", "positive", ")", ".", "Each", "delay", "commences", "upon", "invocation", ...
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/concurrent/jsr/CompletableFuture.java#L536-L538
motown-io/motown
operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/TransactionEventListener.java
TransactionEventListener.addMeterValueToTransaction
private void addMeterValueToTransaction(final Transaction transaction, final MeterValue meterValue) { """ Adds a single {@code MeterValue} to the {@code Transaction}. <p/> If a {@code MeterValue} cannot be added this method will skip adding it, won't throw an exception, and log that this occurred and why. @param transaction the {@code Transaction} to which to add the {@code MeterValue}. @param meterValue the {@code MeterValue} to add. """ if (meterValue.getUnit() == UnitOfMeasure.WATT_HOUR || meterValue.getUnit() == UnitOfMeasure.KILOWATT_HOUR) { try { transaction.getMeterValues().add(toOperatorApiMeterValue(meterValue)); } catch (Throwable t) { // Catching a Throwable here because we want to ensure other MeterValues are processed even if this one // fails (for whatever reason!). LOG.info(String.format("Skipping adding MeterValue [%s] to Transaction [%s] because an Exception was thrown", meterValue, transaction.getTransactionId()), t); } } else { LOG.info("Skipping adding MeterValue [{}] to Transaction [{}] because UnitOfMeasure is not WATT_HOUR or KILOWATT_HOUR", meterValue, transaction.getTransactionId()); } }
java
private void addMeterValueToTransaction(final Transaction transaction, final MeterValue meterValue) { if (meterValue.getUnit() == UnitOfMeasure.WATT_HOUR || meterValue.getUnit() == UnitOfMeasure.KILOWATT_HOUR) { try { transaction.getMeterValues().add(toOperatorApiMeterValue(meterValue)); } catch (Throwable t) { // Catching a Throwable here because we want to ensure other MeterValues are processed even if this one // fails (for whatever reason!). LOG.info(String.format("Skipping adding MeterValue [%s] to Transaction [%s] because an Exception was thrown", meterValue, transaction.getTransactionId()), t); } } else { LOG.info("Skipping adding MeterValue [{}] to Transaction [{}] because UnitOfMeasure is not WATT_HOUR or KILOWATT_HOUR", meterValue, transaction.getTransactionId()); } }
[ "private", "void", "addMeterValueToTransaction", "(", "final", "Transaction", "transaction", ",", "final", "MeterValue", "meterValue", ")", "{", "if", "(", "meterValue", ".", "getUnit", "(", ")", "==", "UnitOfMeasure", ".", "WATT_HOUR", "||", "meterValue", ".", ...
Adds a single {@code MeterValue} to the {@code Transaction}. <p/> If a {@code MeterValue} cannot be added this method will skip adding it, won't throw an exception, and log that this occurred and why. @param transaction the {@code Transaction} to which to add the {@code MeterValue}. @param meterValue the {@code MeterValue} to add.
[ "Adds", "a", "single", "{", "@code", "MeterValue", "}", "to", "the", "{", "@code", "Transaction", "}", ".", "<p", "/", ">", "If", "a", "{", "@code", "MeterValue", "}", "cannot", "be", "added", "this", "method", "will", "skip", "adding", "it", "won", ...
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/TransactionEventListener.java#L102-L114
awslabs/jsii
packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/Util.java
Util.extractResource
static String extractResource(final Class<?> klass, final String resourceName, final String outputDirectory) throws IOException { """ Extracts a resource file from the .jar and saves it into an output directory. @param url The URL of the resource @param outputDirectory The output directory (optional) @return The full path of the saved resource @throws IOException If there was an I/O error """ String directory = outputDirectory; if (directory == null) { directory = Files.createTempDirectory("jsii-java-runtime-resource").toString(); } Path target = Paths.get(directory, resourceName); // make sure directory tree is created, for the case of "@scoped/deps" Files.createDirectories(target.getParent()); try (InputStream inputStream = klass.getResourceAsStream(resourceName)) { Files.copy(inputStream, target); } return target.toAbsolutePath().toString(); }
java
static String extractResource(final Class<?> klass, final String resourceName, final String outputDirectory) throws IOException { String directory = outputDirectory; if (directory == null) { directory = Files.createTempDirectory("jsii-java-runtime-resource").toString(); } Path target = Paths.get(directory, resourceName); // make sure directory tree is created, for the case of "@scoped/deps" Files.createDirectories(target.getParent()); try (InputStream inputStream = klass.getResourceAsStream(resourceName)) { Files.copy(inputStream, target); } return target.toAbsolutePath().toString(); }
[ "static", "String", "extractResource", "(", "final", "Class", "<", "?", ">", "klass", ",", "final", "String", "resourceName", ",", "final", "String", "outputDirectory", ")", "throws", "IOException", "{", "String", "directory", "=", "outputDirectory", ";", "if", ...
Extracts a resource file from the .jar and saves it into an output directory. @param url The URL of the resource @param outputDirectory The output directory (optional) @return The full path of the saved resource @throws IOException If there was an I/O error
[ "Extracts", "a", "resource", "file", "from", "the", ".", "jar", "and", "saves", "it", "into", "an", "output", "directory", "." ]
train
https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/Util.java#L102-L118
morimekta/utils
diff-util/src/main/java/net/morimekta/diff/Diff.java
Diff.fromDelta
public static Diff fromDelta(String text1, String delta) throws IllegalArgumentException { """ Given the original text1, and an encoded string which describes the operations required to transform text1 into text2, compute the full diff. @param text1 Source string for the diff. @param delta Delta text. @return Diff object. @throws IllegalArgumentException If invalid input. """ return new Diff(changesFromDelta(text1, delta), DiffOptions.defaults()); }
java
public static Diff fromDelta(String text1, String delta) throws IllegalArgumentException { return new Diff(changesFromDelta(text1, delta), DiffOptions.defaults()); }
[ "public", "static", "Diff", "fromDelta", "(", "String", "text1", ",", "String", "delta", ")", "throws", "IllegalArgumentException", "{", "return", "new", "Diff", "(", "changesFromDelta", "(", "text1", ",", "delta", ")", ",", "DiffOptions", ".", "defaults", "("...
Given the original text1, and an encoded string which describes the operations required to transform text1 into text2, compute the full diff. @param text1 Source string for the diff. @param delta Delta text. @return Diff object. @throws IllegalArgumentException If invalid input.
[ "Given", "the", "original", "text1", "and", "an", "encoded", "string", "which", "describes", "the", "operations", "required", "to", "transform", "text1", "into", "text2", "compute", "the", "full", "diff", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/diff-util/src/main/java/net/morimekta/diff/Diff.java#L66-L69
rhuss/jolokia
agent/core/src/main/java/org/jolokia/converter/json/TabularDataExtractor.java
TabularDataExtractor.setObjectValue
public Object setObjectValue(StringToObjectConverter pConverter, Object pInner, String pAttribute, Object pValue) throws IllegalAccessException, InvocationTargetException { """ Throws always {@link IllegalArgumentException} since tabular data is immutable """ throw new IllegalArgumentException("TabularData cannot be written to"); }
java
public Object setObjectValue(StringToObjectConverter pConverter, Object pInner, String pAttribute, Object pValue) throws IllegalAccessException, InvocationTargetException { throw new IllegalArgumentException("TabularData cannot be written to"); }
[ "public", "Object", "setObjectValue", "(", "StringToObjectConverter", "pConverter", ",", "Object", "pInner", ",", "String", "pAttribute", ",", "Object", "pValue", ")", "throws", "IllegalAccessException", ",", "InvocationTargetException", "{", "throw", "new", "IllegalArg...
Throws always {@link IllegalArgumentException} since tabular data is immutable
[ "Throws", "always", "{" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/converter/json/TabularDataExtractor.java#L334-L337
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/ui/CmsAttributeValueView.java
CmsAttributeValueView.addChoice
public void addChoice(I_CmsWidgetService widgetService, final CmsChoiceMenuEntryBean menuEntry) { """ Adds a new choice choice selection menu.<p> @param widgetService the widget service to use for labels @param menuEntry the menu entry bean for the choice """ AsyncCallback<CmsChoiceMenuEntryBean> selectHandler = new AsyncCallback<CmsChoiceMenuEntryBean>() { public void onFailure(Throwable caught) { // will not be called } public void onSuccess(CmsChoiceMenuEntryBean selectedEntry) { m_attributeChoice.hide(); selectChoice(selectedEntry.getPath()); } }; m_attributeChoice.addChoice(widgetService, menuEntry, selectHandler); m_isChoice = true; }
java
public void addChoice(I_CmsWidgetService widgetService, final CmsChoiceMenuEntryBean menuEntry) { AsyncCallback<CmsChoiceMenuEntryBean> selectHandler = new AsyncCallback<CmsChoiceMenuEntryBean>() { public void onFailure(Throwable caught) { // will not be called } public void onSuccess(CmsChoiceMenuEntryBean selectedEntry) { m_attributeChoice.hide(); selectChoice(selectedEntry.getPath()); } }; m_attributeChoice.addChoice(widgetService, menuEntry, selectHandler); m_isChoice = true; }
[ "public", "void", "addChoice", "(", "I_CmsWidgetService", "widgetService", ",", "final", "CmsChoiceMenuEntryBean", "menuEntry", ")", "{", "AsyncCallback", "<", "CmsChoiceMenuEntryBean", ">", "selectHandler", "=", "new", "AsyncCallback", "<", "CmsChoiceMenuEntryBean", ">",...
Adds a new choice choice selection menu.<p> @param widgetService the widget service to use for labels @param menuEntry the menu entry bean for the choice
[ "Adds", "a", "new", "choice", "choice", "selection", "menu", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/ui/CmsAttributeValueView.java#L384-L403
alkacon/opencms-core
src/org/opencms/ui/favorites/CmsFavoriteDialog.java
CmsFavoriteDialog.createFavInfo
private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException { """ Creates a favorite widget for a favorite entry. @param entry the favorite entry @return the favorite widget @throws CmsException if something goes wrong """ String title = ""; String subtitle = ""; CmsFavInfo result = new CmsFavInfo(entry); CmsObject cms = A_CmsUI.getCmsObject(); String project = getProject(cms, entry); String site = getSite(cms, entry); try { CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId(); CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible()); CmsResourceUtil resutil = new CmsResourceUtil(cms, resource); switch (entry.getType()) { case explorerFolder: title = CmsStringUtil.isEmpty(resutil.getTitle()) ? CmsResource.getName(resource.getRootPath()) : resutil.getTitle(); break; case page: title = resutil.getTitle(); break; } subtitle = resource.getRootPath(); CmsResourceIcon icon = result.getResourceIcon(); icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } result.getTopLine().setValue(title); result.getBottomLine().setValue(subtitle); result.getProjectLabel().setValue(project); result.getSiteLabel().setValue(site); return result; }
java
private CmsFavInfo createFavInfo(CmsFavoriteEntry entry) throws CmsException { String title = ""; String subtitle = ""; CmsFavInfo result = new CmsFavInfo(entry); CmsObject cms = A_CmsUI.getCmsObject(); String project = getProject(cms, entry); String site = getSite(cms, entry); try { CmsUUID idToLoad = entry.getDetailId() != null ? entry.getDetailId() : entry.getStructureId(); CmsResource resource = cms.readResource(idToLoad, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible()); CmsResourceUtil resutil = new CmsResourceUtil(cms, resource); switch (entry.getType()) { case explorerFolder: title = CmsStringUtil.isEmpty(resutil.getTitle()) ? CmsResource.getName(resource.getRootPath()) : resutil.getTitle(); break; case page: title = resutil.getTitle(); break; } subtitle = resource.getRootPath(); CmsResourceIcon icon = result.getResourceIcon(); icon.initContent(resutil, CmsResource.STATE_UNCHANGED, false, false); } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } result.getTopLine().setValue(title); result.getBottomLine().setValue(subtitle); result.getProjectLabel().setValue(project); result.getSiteLabel().setValue(site); return result; }
[ "private", "CmsFavInfo", "createFavInfo", "(", "CmsFavoriteEntry", "entry", ")", "throws", "CmsException", "{", "String", "title", "=", "\"\"", ";", "String", "subtitle", "=", "\"\"", ";", "CmsFavInfo", "result", "=", "new", "CmsFavInfo", "(", "entry", ")", ";...
Creates a favorite widget for a favorite entry. @param entry the favorite entry @return the favorite widget @throws CmsException if something goes wrong
[ "Creates", "a", "favorite", "widget", "for", "a", "favorite", "entry", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/favorites/CmsFavoriteDialog.java#L314-L349
google/truth
core/src/main/java/com/google/common/truth/TableSubject.java
TableSubject.contains
public void contains(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { """ Fails if the table does not contain a mapping for the given row key and column key. """ if (!actual().contains(rowKey, columnKey)) { fail("contains mapping for row/column", rowKey, columnKey); } }
java
public void contains(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { if (!actual().contains(rowKey, columnKey)) { fail("contains mapping for row/column", rowKey, columnKey); } }
[ "public", "void", "contains", "(", "@", "NullableDecl", "Object", "rowKey", ",", "@", "NullableDecl", "Object", "columnKey", ")", "{", "if", "(", "!", "actual", "(", ")", ".", "contains", "(", "rowKey", ",", "columnKey", ")", ")", "{", "fail", "(", "\"...
Fails if the table does not contain a mapping for the given row key and column key.
[ "Fails", "if", "the", "table", "does", "not", "contain", "a", "mapping", "for", "the", "given", "row", "key", "and", "column", "key", "." ]
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/TableSubject.java#L58-L62
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.findAll
public static <T> Set<T> findAll(Set<T> self) { """ Finds the items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth). <p> Example: <pre class="groovyTestCase"> def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set assert items.findAll() == [1, 2, true, 'foo', [4, 5]] as Set </pre> @param self a Set @return a Set of the values found @since 2.4.0 @see Closure#IDENTITY """ return findAll(self, Closure.IDENTITY); }
java
public static <T> Set<T> findAll(Set<T> self) { return findAll(self, Closure.IDENTITY); }
[ "public", "static", "<", "T", ">", "Set", "<", "T", ">", "findAll", "(", "Set", "<", "T", ">", "self", ")", "{", "return", "findAll", "(", "self", ",", "Closure", ".", "IDENTITY", ")", ";", "}" ]
Finds the items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth). <p> Example: <pre class="groovyTestCase"> def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] as Set assert items.findAll() == [1, 2, true, 'foo', [4, 5]] as Set </pre> @param self a Set @return a Set of the values found @since 2.4.0 @see Closure#IDENTITY
[ "Finds", "the", "items", "matching", "the", "IDENTITY", "Closure", "(", "i", ".", "e", ".", "&#160", ";", "matching", "Groovy", "truth", ")", ".", "<p", ">", "Example", ":", "<pre", "class", "=", "groovyTestCase", ">", "def", "items", "=", "[", "1", ...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L4811-L4813
owetterau/neo4j-websockets
client/src/main/java/de/oliverwetterau/neo4j/websockets/client/web/WebSocketHandler.java
WebSocketHandler.handleTransportError
@Override public void handleTransportError(final WebSocketSession webSocketSession, final Throwable exception) throws Exception { """ Handles websocket transport errors @param webSocketSession websocket session where the error appeared @param exception exception that occured @throws Exception transport error exception """ if (exception != null) { logger.error("[handleTransportError]", exception); } }
java
@Override public void handleTransportError(final WebSocketSession webSocketSession, final Throwable exception) throws Exception { if (exception != null) { logger.error("[handleTransportError]", exception); } }
[ "@", "Override", "public", "void", "handleTransportError", "(", "final", "WebSocketSession", "webSocketSession", ",", "final", "Throwable", "exception", ")", "throws", "Exception", "{", "if", "(", "exception", "!=", "null", ")", "{", "logger", ".", "error", "(",...
Handles websocket transport errors @param webSocketSession websocket session where the error appeared @param exception exception that occured @throws Exception transport error exception
[ "Handles", "websocket", "transport", "errors" ]
train
https://github.com/owetterau/neo4j-websockets/blob/ca3481066819d01169873aeb145ab3bf5c736afe/client/src/main/java/de/oliverwetterau/neo4j/websockets/client/web/WebSocketHandler.java#L187-L192
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.Minkowski
public static double Minkowski(IntPoint p, IntPoint q, int r) { """ Gets the Minkowski distance between two points. @param p IntPoint with X and Y axis coordinates. @param q IntPoint with X and Y axis coordinates. @param r Order between two points. @return The Minkowski distance between x and y. """ return Minkowski(p.x, p.y, q.x, q.y, r); }
java
public static double Minkowski(IntPoint p, IntPoint q, int r) { return Minkowski(p.x, p.y, q.x, q.y, r); }
[ "public", "static", "double", "Minkowski", "(", "IntPoint", "p", ",", "IntPoint", "q", ",", "int", "r", ")", "{", "return", "Minkowski", "(", "p", ".", "x", ",", "p", ".", "y", ",", "q", ".", "x", ",", "q", ".", "y", ",", "r", ")", ";", "}" ]
Gets the Minkowski distance between two points. @param p IntPoint with X and Y axis coordinates. @param q IntPoint with X and Y axis coordinates. @param r Order between two points. @return The Minkowski distance between x and y.
[ "Gets", "the", "Minkowski", "distance", "between", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L745-L747
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/MeasureUnit.java
MeasureUnit.resolveUnitPerUnit
@Deprecated public static MeasureUnit resolveUnitPerUnit(MeasureUnit unit, MeasureUnit perUnit) { """ For ICU use only. @deprecated This API is ICU internal only. @hide original deprecated declaration @hide draft / provisional / internal are hidden on Android """ return unitPerUnitToSingleUnit.get(Pair.of(unit, perUnit)); }
java
@Deprecated public static MeasureUnit resolveUnitPerUnit(MeasureUnit unit, MeasureUnit perUnit) { return unitPerUnitToSingleUnit.get(Pair.of(unit, perUnit)); }
[ "@", "Deprecated", "public", "static", "MeasureUnit", "resolveUnitPerUnit", "(", "MeasureUnit", "unit", ",", "MeasureUnit", "perUnit", ")", "{", "return", "unitPerUnitToSingleUnit", ".", "get", "(", "Pair", ".", "of", "(", "unit", ",", "perUnit", ")", ")", ";"...
For ICU use only. @deprecated This API is ICU internal only. @hide original deprecated declaration @hide draft / provisional / internal are hidden on Android
[ "For", "ICU", "use", "only", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/MeasureUnit.java#L199-L202
casbin/jcasbin
src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java
BuiltInFunctions.keyMatch
public static boolean keyMatch(String key1, String key2) { """ keyMatch determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. For example, "/foo/bar" matches "/foo/*" @param key1 the first argument. @param key2 the second argument. @return whether key1 matches key2. """ int i = key2.indexOf('*'); if (i == -1) { return key1.equals(key2); } if (key1.length() > i) { return key1.substring(0, i).equals(key2.substring(0, i)); } return key1.equals(key2.substring(0, i)); }
java
public static boolean keyMatch(String key1, String key2) { int i = key2.indexOf('*'); if (i == -1) { return key1.equals(key2); } if (key1.length() > i) { return key1.substring(0, i).equals(key2.substring(0, i)); } return key1.equals(key2.substring(0, i)); }
[ "public", "static", "boolean", "keyMatch", "(", "String", "key1", ",", "String", "key2", ")", "{", "int", "i", "=", "key2", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "i", "==", "-", "1", ")", "{", "return", "key1", ".", "equals", "(", ...
keyMatch determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. For example, "/foo/bar" matches "/foo/*" @param key1 the first argument. @param key2 the second argument. @return whether key1 matches key2.
[ "keyMatch", "determines", "whether", "key1", "matches", "the", "pattern", "of", "key2", "(", "similar", "to", "RESTful", "path", ")", "key2", "can", "contain", "a", "*", ".", "For", "example", "/", "foo", "/", "bar", "matches", "/", "foo", "/", "*" ]
train
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/util/BuiltInFunctions.java#L39-L49
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/tuple/ArrayOfDoublesUnion.java
ArrayOfDoublesUnion.getResult
public ArrayOfDoublesCompactSketch getResult(final WritableMemory dstMem) { """ Returns the resulting union in the form of a compact sketch @param dstMem memory for the result (can be null) @return compact sketch representing the union (off-heap if memory is provided) """ if (sketch_.getRetainedEntries() > sketch_.getNominalEntries()) { theta_ = Math.min(theta_, sketch_.getNewTheta()); } if (dstMem == null) { return new HeapArrayOfDoublesCompactSketch(sketch_, theta_); } return new DirectArrayOfDoublesCompactSketch(sketch_, theta_, dstMem); }
java
public ArrayOfDoublesCompactSketch getResult(final WritableMemory dstMem) { if (sketch_.getRetainedEntries() > sketch_.getNominalEntries()) { theta_ = Math.min(theta_, sketch_.getNewTheta()); } if (dstMem == null) { return new HeapArrayOfDoublesCompactSketch(sketch_, theta_); } return new DirectArrayOfDoublesCompactSketch(sketch_, theta_, dstMem); }
[ "public", "ArrayOfDoublesCompactSketch", "getResult", "(", "final", "WritableMemory", "dstMem", ")", "{", "if", "(", "sketch_", ".", "getRetainedEntries", "(", ")", ">", "sketch_", ".", "getNominalEntries", "(", ")", ")", "{", "theta_", "=", "Math", ".", "min"...
Returns the resulting union in the form of a compact sketch @param dstMem memory for the result (can be null) @return compact sketch representing the union (off-heap if memory is provided)
[ "Returns", "the", "resulting", "union", "in", "the", "form", "of", "a", "compact", "sketch" ]
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/tuple/ArrayOfDoublesUnion.java#L137-L145
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/MappedParametrizedObjectEntry.java
MappedParametrizedObjectEntry.getParameterValue
public String getParameterValue(String name, String defaultValue) { """ Parse named parameter. @param name parameter name @param defaultValue default value @return String """ String value = defaultValue; SimpleParameterEntry p = parameters.get(name); if (p != null) { value = p.getValue(); } return value; }
java
public String getParameterValue(String name, String defaultValue) { String value = defaultValue; SimpleParameterEntry p = parameters.get(name); if (p != null) { value = p.getValue(); } return value; }
[ "public", "String", "getParameterValue", "(", "String", "name", ",", "String", "defaultValue", ")", "{", "String", "value", "=", "defaultValue", ";", "SimpleParameterEntry", "p", "=", "parameters", ".", "get", "(", "name", ")", ";", "if", "(", "p", "!=", "...
Parse named parameter. @param name parameter name @param defaultValue default value @return String
[ "Parse", "named", "parameter", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/MappedParametrizedObjectEntry.java#L103-L112
Whiley/WhileyCompiler
src/main/java/wyil/check/FlowTypeCheck.java
FlowTypeCheck.checkBlock
private Environment checkBlock(Stmt.Block block, Environment environment, EnclosingScope scope) { """ check type information in a flow-sensitive fashion through a block of statements, whilst type checking each statement and expression. @param block Block of statements to flow sensitively type check @param environment Determines the type of all variables immediately going into this block @return """ for (int i = 0; i != block.size(); ++i) { Stmt stmt = block.get(i); environment = checkStatement(stmt, environment, scope); } return environment; }
java
private Environment checkBlock(Stmt.Block block, Environment environment, EnclosingScope scope) { for (int i = 0; i != block.size(); ++i) { Stmt stmt = block.get(i); environment = checkStatement(stmt, environment, scope); } return environment; }
[ "private", "Environment", "checkBlock", "(", "Stmt", ".", "Block", "block", ",", "Environment", "environment", ",", "EnclosingScope", "scope", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "block", ".", "size", "(", ")", ";", "++", "i", ...
check type information in a flow-sensitive fashion through a block of statements, whilst type checking each statement and expression. @param block Block of statements to flow sensitively type check @param environment Determines the type of all variables immediately going into this block @return
[ "check", "type", "information", "in", "a", "flow", "-", "sensitive", "fashion", "through", "a", "block", "of", "statements", "whilst", "type", "checking", "each", "statement", "and", "expression", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L266-L272
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/effect/Effect.java
Effect.createBufferedImage
protected static BufferedImage createBufferedImage(int width, int height, boolean hasAlpha) { """ Create a buffered image of the given width and height, compatible with the alpha requirement. @param width the width of the new buffered image. @param height the height of the new buffered image. @param hasAlpha {@code true} if the new buffered image needs to support alpha transparency, {@code false} otherwise. @return the newly created buffered image. """ BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha) { transparency = Transparency.TRANSLUCENT; } // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(width, height, transparency); } catch (HeadlessException e) { // The system does not have a screen } if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; } bimage = new BufferedImage(width, height, type); } return bimage; }
java
protected static BufferedImage createBufferedImage(int width, int height, boolean hasAlpha) { BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha) { transparency = Transparency.TRANSLUCENT; } // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(width, height, transparency); } catch (HeadlessException e) { // The system does not have a screen } if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; } bimage = new BufferedImage(width, height, type); } return bimage; }
[ "protected", "static", "BufferedImage", "createBufferedImage", "(", "int", "width", ",", "int", "height", ",", "boolean", "hasAlpha", ")", "{", "BufferedImage", "bimage", "=", "null", ";", "GraphicsEnvironment", "ge", "=", "GraphicsEnvironment", ".", "getLocalGraphi...
Create a buffered image of the given width and height, compatible with the alpha requirement. @param width the width of the new buffered image. @param height the height of the new buffered image. @param hasAlpha {@code true} if the new buffered image needs to support alpha transparency, {@code false} otherwise. @return the newly created buffered image.
[ "Create", "a", "buffered", "image", "of", "the", "given", "width", "and", "height", "compatible", "with", "the", "alpha", "requirement", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/effect/Effect.java#L146-L181
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/InstanceClient.java
InstanceClient.setSchedulingInstance
@BetaApi public final Operation setSchedulingInstance(String instance, Scheduling schedulingResource) { """ Sets an instance's scheduling options. <p>Sample code: <pre><code> try (InstanceClient instanceClient = InstanceClient.create()) { ProjectZoneInstanceName instance = ProjectZoneInstanceName.of("[PROJECT]", "[ZONE]", "[INSTANCE]"); Scheduling schedulingResource = Scheduling.newBuilder().build(); Operation response = instanceClient.setSchedulingInstance(instance.toString(), schedulingResource); } </code></pre> @param instance Instance name for this request. @param schedulingResource Sets the scheduling options for an Instance. @throws com.google.api.gax.rpc.ApiException if the remote call fails """ SetSchedulingInstanceHttpRequest request = SetSchedulingInstanceHttpRequest.newBuilder() .setInstance(instance) .setSchedulingResource(schedulingResource) .build(); return setSchedulingInstance(request); }
java
@BetaApi public final Operation setSchedulingInstance(String instance, Scheduling schedulingResource) { SetSchedulingInstanceHttpRequest request = SetSchedulingInstanceHttpRequest.newBuilder() .setInstance(instance) .setSchedulingResource(schedulingResource) .build(); return setSchedulingInstance(request); }
[ "@", "BetaApi", "public", "final", "Operation", "setSchedulingInstance", "(", "String", "instance", ",", "Scheduling", "schedulingResource", ")", "{", "SetSchedulingInstanceHttpRequest", "request", "=", "SetSchedulingInstanceHttpRequest", ".", "newBuilder", "(", ")", ".",...
Sets an instance's scheduling options. <p>Sample code: <pre><code> try (InstanceClient instanceClient = InstanceClient.create()) { ProjectZoneInstanceName instance = ProjectZoneInstanceName.of("[PROJECT]", "[ZONE]", "[INSTANCE]"); Scheduling schedulingResource = Scheduling.newBuilder().build(); Operation response = instanceClient.setSchedulingInstance(instance.toString(), schedulingResource); } </code></pre> @param instance Instance name for this request. @param schedulingResource Sets the scheduling options for an Instance. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Sets", "an", "instance", "s", "scheduling", "options", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/InstanceClient.java#L2790-L2799
jhunters/jprotobuf
src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java
MiniTemplator.addBlock
public void addBlock(String blockName, boolean isOptional) throws BlockNotDefinedException { """ Adds an instance of a template block. <p> If the block contains variables, these variables must be set before the block is added. If the block contains subblocks (nested blocks), the subblocks must be added before this block is added. If multiple blocks exist with the specified name, an instance is added for each block occurrence. @param blockName the name of the block to be added. Case-insensitive. @param isOptional specifies whether an exception should be thrown when the block does not exist in the template. If <code>isOptional</code> is <code>false</code> and the block does not exist, an exception is thrown. @throws BlockNotDefinedException when no block with the specified name exists in the template and <code>isOptional</code> is <code>false</code>. """ int blockNo = mtp.lookupBlockName(blockName); if (blockNo == -1) { if (isOptional) { return; } throw new BlockNotDefinedException(blockName); } while (blockNo != -1) { addBlockByNo(blockNo); blockNo = mtp.blockTab[blockNo].nextWithSameName; } }
java
public void addBlock(String blockName, boolean isOptional) throws BlockNotDefinedException { int blockNo = mtp.lookupBlockName(blockName); if (blockNo == -1) { if (isOptional) { return; } throw new BlockNotDefinedException(blockName); } while (blockNo != -1) { addBlockByNo(blockNo); blockNo = mtp.blockTab[blockNo].nextWithSameName; } }
[ "public", "void", "addBlock", "(", "String", "blockName", ",", "boolean", "isOptional", ")", "throws", "BlockNotDefinedException", "{", "int", "blockNo", "=", "mtp", ".", "lookupBlockName", "(", "blockName", ")", ";", "if", "(", "blockNo", "==", "-", "1", ")...
Adds an instance of a template block. <p> If the block contains variables, these variables must be set before the block is added. If the block contains subblocks (nested blocks), the subblocks must be added before this block is added. If multiple blocks exist with the specified name, an instance is added for each block occurrence. @param blockName the name of the block to be added. Case-insensitive. @param isOptional specifies whether an exception should be thrown when the block does not exist in the template. If <code>isOptional</code> is <code>false</code> and the block does not exist, an exception is thrown. @throws BlockNotDefinedException when no block with the specified name exists in the template and <code>isOptional</code> is <code>false</code>.
[ "Adds", "an", "instance", "of", "a", "template", "block", ".", "<p", ">", "If", "the", "block", "contains", "variables", "these", "variables", "must", "be", "set", "before", "the", "block", "is", "added", ".", "If", "the", "block", "contains", "subblocks",...
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java#L521-L533
mpetazzoni/ttorrent
ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java
TrackerRequestProcessor.parseQuery
private HTTPAnnounceRequestMessage parseQuery(final String uri, final String hostAddress) throws IOException, MessageValidationException { """ Parse the query parameters using our defined BYTE_ENCODING. <p> <p> Because we're expecting byte-encoded strings as query parameters, we can't rely on SimpleHTTP's QueryParser which uses the wrong encoding for the job and returns us unparsable byte data. We thus have to implement our own little parsing method that uses BYTE_ENCODING to decode parameters from the URI. </p> <p> <p> <b>Note:</b> array parameters are not supported. If a key is present multiple times in the URI, the latest value prevails. We don't really need to implement this functionality as this never happens in the Tracker HTTP protocol. </p> @param uri @param hostAddress @return The {@link AnnounceRequestMessage} representing the client's announce request. """ Map<String, BEValue> params = new HashMap<String, BEValue>(); try { // String uri = request.getAddress().toString(); for (String pair : uri.split("[?]")[1].split("&")) { String[] keyval = pair.split("[=]", 2); if (keyval.length == 1) { this.recordParam(params, keyval[0], null); } else { this.recordParam(params, keyval[0], keyval[1]); } } } catch (ArrayIndexOutOfBoundsException e) { params.clear(); } // Make sure we have the peer IP, fallbacking on the request's source // address if the peer didn't provide it. if (params.get("ip") == null) { params.put("ip", new BEValue( hostAddress, Constants.BYTE_ENCODING)); } return HTTPAnnounceRequestMessage.parse(new BEValue(params)); }
java
private HTTPAnnounceRequestMessage parseQuery(final String uri, final String hostAddress) throws IOException, MessageValidationException { Map<String, BEValue> params = new HashMap<String, BEValue>(); try { // String uri = request.getAddress().toString(); for (String pair : uri.split("[?]")[1].split("&")) { String[] keyval = pair.split("[=]", 2); if (keyval.length == 1) { this.recordParam(params, keyval[0], null); } else { this.recordParam(params, keyval[0], keyval[1]); } } } catch (ArrayIndexOutOfBoundsException e) { params.clear(); } // Make sure we have the peer IP, fallbacking on the request's source // address if the peer didn't provide it. if (params.get("ip") == null) { params.put("ip", new BEValue( hostAddress, Constants.BYTE_ENCODING)); } return HTTPAnnounceRequestMessage.parse(new BEValue(params)); }
[ "private", "HTTPAnnounceRequestMessage", "parseQuery", "(", "final", "String", "uri", ",", "final", "String", "hostAddress", ")", "throws", "IOException", ",", "MessageValidationException", "{", "Map", "<", "String", ",", "BEValue", ">", "params", "=", "new", "Has...
Parse the query parameters using our defined BYTE_ENCODING. <p> <p> Because we're expecting byte-encoded strings as query parameters, we can't rely on SimpleHTTP's QueryParser which uses the wrong encoding for the job and returns us unparsable byte data. We thus have to implement our own little parsing method that uses BYTE_ENCODING to decode parameters from the URI. </p> <p> <p> <b>Note:</b> array parameters are not supported. If a key is present multiple times in the URI, the latest value prevails. We don't really need to implement this functionality as this never happens in the Tracker HTTP protocol. </p> @param uri @param hostAddress @return The {@link AnnounceRequestMessage} representing the client's announce request.
[ "Parse", "the", "query", "parameters", "using", "our", "defined", "BYTE_ENCODING", ".", "<p", ">", "<p", ">", "Because", "we", "re", "expecting", "byte", "-", "encoded", "strings", "as", "query", "parameters", "we", "can", "t", "rely", "on", "SimpleHTTP", ...
train
https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java#L237-L264
camunda/camunda-xml-model
src/main/java/org/camunda/bpm/model/xml/impl/util/IoUtil.java
IoUtil.writeDocumentToOutputStream
public static void writeDocumentToOutputStream(DomDocument document, OutputStream outputStream) { """ Writes a {@link DomDocument} to an {@link OutputStream} by transforming the DOM to XML. @param document the DOM document to write @param outputStream the {@link OutputStream} to write to """ StreamResult result = new StreamResult(outputStream); transformDocumentToXml(document, result); }
java
public static void writeDocumentToOutputStream(DomDocument document, OutputStream outputStream) { StreamResult result = new StreamResult(outputStream); transformDocumentToXml(document, result); }
[ "public", "static", "void", "writeDocumentToOutputStream", "(", "DomDocument", "document", ",", "OutputStream", "outputStream", ")", "{", "StreamResult", "result", "=", "new", "StreamResult", "(", "outputStream", ")", ";", "transformDocumentToXml", "(", "document", ",...
Writes a {@link DomDocument} to an {@link OutputStream} by transforming the DOM to XML. @param document the DOM document to write @param outputStream the {@link OutputStream} to write to
[ "Writes", "a", "{", "@link", "DomDocument", "}", "to", "an", "{", "@link", "OutputStream", "}", "by", "transforming", "the", "DOM", "to", "XML", "." ]
train
https://github.com/camunda/camunda-xml-model/blob/85b3f879e26d063f71c94cfd21ac17d9ff6baf4d/src/main/java/org/camunda/bpm/model/xml/impl/util/IoUtil.java#L113-L116
Impetus/Kundera
src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESFilterBuilder.java
ESFilterBuilder.populateLikeQuery
private QueryBuilder populateLikeQuery(LikeExpression likeExpression, EntityMetadata metadata) { """ Populate like query. @param likeExpression the like expression @param metadata the metadata @return the filter builder """ Expression patternValue = likeExpression.getPatternValue(); String field = likeExpression.getStringExpression().toString(); String likePattern = (patternValue instanceof InputParameter) ? kunderaQuery.getParametersMap() .get((patternValue).toParsedText()).toString() : patternValue.toParsedText().toString(); String jpaField = getField(field); log.debug("Pattern value for field " + field + " is: " + patternValue); QueryBuilder filterBuilder = getQueryBuilder(kunderaQuery.new FilterClause(jpaField, Expression.LIKE, likePattern, field), metadata); return filterBuilder; }
java
private QueryBuilder populateLikeQuery(LikeExpression likeExpression, EntityMetadata metadata) { Expression patternValue = likeExpression.getPatternValue(); String field = likeExpression.getStringExpression().toString(); String likePattern = (patternValue instanceof InputParameter) ? kunderaQuery.getParametersMap() .get((patternValue).toParsedText()).toString() : patternValue.toParsedText().toString(); String jpaField = getField(field); log.debug("Pattern value for field " + field + " is: " + patternValue); QueryBuilder filterBuilder = getQueryBuilder(kunderaQuery.new FilterClause(jpaField, Expression.LIKE, likePattern, field), metadata); return filterBuilder; }
[ "private", "QueryBuilder", "populateLikeQuery", "(", "LikeExpression", "likeExpression", ",", "EntityMetadata", "metadata", ")", "{", "Expression", "patternValue", "=", "likeExpression", ".", "getPatternValue", "(", ")", ";", "String", "field", "=", "likeExpression", ...
Populate like query. @param likeExpression the like expression @param metadata the metadata @return the filter builder
[ "Populate", "like", "query", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESFilterBuilder.java#L150-L164
jirkapinkas/jsitemapgenerator
src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractGenerator.java
AbstractGenerator.addPages
public <T> I addPages(Supplier<Collection<T>> webPagesSupplier, Function<T, WebPage> mapper) { """ Add collection of pages to sitemap @param <T> This is the type parameter @param webPagesSupplier Collection of pages supplier @param mapper Mapper function which transforms some object to WebPage @return this """ for (T element : webPagesSupplier.get()) { addPage(mapper.apply(element)); } return getThis(); }
java
public <T> I addPages(Supplier<Collection<T>> webPagesSupplier, Function<T, WebPage> mapper) { for (T element : webPagesSupplier.get()) { addPage(mapper.apply(element)); } return getThis(); }
[ "public", "<", "T", ">", "I", "addPages", "(", "Supplier", "<", "Collection", "<", "T", ">", ">", "webPagesSupplier", ",", "Function", "<", "T", ",", "WebPage", ">", "mapper", ")", "{", "for", "(", "T", "element", ":", "webPagesSupplier", ".", "get", ...
Add collection of pages to sitemap @param <T> This is the type parameter @param webPagesSupplier Collection of pages supplier @param mapper Mapper function which transforms some object to WebPage @return this
[ "Add", "collection", "of", "pages", "to", "sitemap" ]
train
https://github.com/jirkapinkas/jsitemapgenerator/blob/42e1f57bd936e21fe9df642e722726e71f667442/src/main/java/cz/jiripinkas/jsitemapgenerator/AbstractGenerator.java#L166-L171
amaembo/streamex
src/main/java/one/util/streamex/IntStreamEx.java
IntStreamEx.ofIndices
public static <T> IntStreamEx ofIndices(List<T> list, Predicate<T> predicate) { """ Returns a sequential ordered {@code IntStreamEx} containing all the indices of the supplied list elements which match given predicate. <p> The list elements are accessed using {@link List#get(int)}, so the list should provide fast random access. The list is assumed to be unmodifiable during the stream operations. @param <T> list element type @param list list to get the stream of its indices @param predicate a predicate to test list elements @return a sequential {@code IntStreamEx} of the matched list indices @since 0.1.1 """ return seq(IntStream.range(0, list.size()).filter(i -> predicate.test(list.get(i)))); }
java
public static <T> IntStreamEx ofIndices(List<T> list, Predicate<T> predicate) { return seq(IntStream.range(0, list.size()).filter(i -> predicate.test(list.get(i)))); }
[ "public", "static", "<", "T", ">", "IntStreamEx", "ofIndices", "(", "List", "<", "T", ">", "list", ",", "Predicate", "<", "T", ">", "predicate", ")", "{", "return", "seq", "(", "IntStream", ".", "range", "(", "0", ",", "list", ".", "size", "(", ")"...
Returns a sequential ordered {@code IntStreamEx} containing all the indices of the supplied list elements which match given predicate. <p> The list elements are accessed using {@link List#get(int)}, so the list should provide fast random access. The list is assumed to be unmodifiable during the stream operations. @param <T> list element type @param list list to get the stream of its indices @param predicate a predicate to test list elements @return a sequential {@code IntStreamEx} of the matched list indices @since 0.1.1
[ "Returns", "a", "sequential", "ordered", "{", "@code", "IntStreamEx", "}", "containing", "all", "the", "indices", "of", "the", "supplied", "list", "elements", "which", "match", "given", "predicate", "." ]
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/IntStreamEx.java#L2029-L2031
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.copyResource
public void copyResource(String source, String destination) throws CmsException, CmsIllegalArgumentException { """ Copies a resource.<p> The copied resource will always be locked to the current user after the copy operation.<p> Siblings will be treated according to the <code>{@link org.opencms.file.CmsResource#COPY_PRESERVE_SIBLING}</code> mode.<p> @param source the name of the resource to copy (full current site relative path) @param destination the name of the copy destination (full current site relative path) @throws CmsException if something goes wrong @throws CmsIllegalArgumentException if the <code>destination</code> argument is null or of length 0 @see #copyResource(String, String, CmsResource.CmsResourceCopyMode) """ copyResource(source, destination, CmsResource.COPY_PRESERVE_SIBLING); }
java
public void copyResource(String source, String destination) throws CmsException, CmsIllegalArgumentException { copyResource(source, destination, CmsResource.COPY_PRESERVE_SIBLING); }
[ "public", "void", "copyResource", "(", "String", "source", ",", "String", "destination", ")", "throws", "CmsException", ",", "CmsIllegalArgumentException", "{", "copyResource", "(", "source", ",", "destination", ",", "CmsResource", ".", "COPY_PRESERVE_SIBLING", ")", ...
Copies a resource.<p> The copied resource will always be locked to the current user after the copy operation.<p> Siblings will be treated according to the <code>{@link org.opencms.file.CmsResource#COPY_PRESERVE_SIBLING}</code> mode.<p> @param source the name of the resource to copy (full current site relative path) @param destination the name of the copy destination (full current site relative path) @throws CmsException if something goes wrong @throws CmsIllegalArgumentException if the <code>destination</code> argument is null or of length 0 @see #copyResource(String, String, CmsResource.CmsResourceCopyMode)
[ "Copies", "a", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L546-L549
GoogleCloudPlatform/appengine-pipelines
java/src/main/java/com/google/appengine/tools/pipeline/impl/backend/AppEngineBackEnd.java
AppEngineBackEnd.deletePipeline
@Override public void deletePipeline(Key rootJobKey, boolean force, boolean async) throws IllegalStateException { """ Delete all datastore entities corresponding to the given pipeline. @param rootJobKey The root job key identifying the pipeline @param force If this parameter is not {@code true} then this method will throw an {@link IllegalStateException} if the specified pipeline is not in the {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#FINALIZED} or {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#STOPPED} state. @param async If this parameter is {@code true} then instead of performing the delete operation synchronously, this method will enqueue a task to perform the operation. @throws IllegalStateException If {@code force = false} and the specified pipeline is not in the {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#FINALIZED} or {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#STOPPED} state. """ if (!force) { try { JobRecord rootJobRecord = queryJob(rootJobKey, JobRecord.InflationType.NONE); switch (rootJobRecord.getState()) { case FINALIZED: case STOPPED: break; default: throw new IllegalStateException("Pipeline is still running: " + rootJobRecord); } } catch (NoSuchObjectException ex) { // Consider missing rootJobRecord as a non-active job and allow further delete } } if (async) { // We do all the checks above before bothering to enqueue a task. // They will have to be done again when the task is processed. DeletePipelineTask task = new DeletePipelineTask(rootJobKey, force, new QueueSettings()); taskQueue.enqueue(task); return; } deleteAll(JobRecord.DATA_STORE_KIND, rootJobKey); deleteAll(Slot.DATA_STORE_KIND, rootJobKey); deleteAll(ShardedValue.DATA_STORE_KIND, rootJobKey); deleteAll(Barrier.DATA_STORE_KIND, rootJobKey); deleteAll(JobInstanceRecord.DATA_STORE_KIND, rootJobKey); deleteAll(FanoutTaskRecord.DATA_STORE_KIND, rootJobKey); }
java
@Override public void deletePipeline(Key rootJobKey, boolean force, boolean async) throws IllegalStateException { if (!force) { try { JobRecord rootJobRecord = queryJob(rootJobKey, JobRecord.InflationType.NONE); switch (rootJobRecord.getState()) { case FINALIZED: case STOPPED: break; default: throw new IllegalStateException("Pipeline is still running: " + rootJobRecord); } } catch (NoSuchObjectException ex) { // Consider missing rootJobRecord as a non-active job and allow further delete } } if (async) { // We do all the checks above before bothering to enqueue a task. // They will have to be done again when the task is processed. DeletePipelineTask task = new DeletePipelineTask(rootJobKey, force, new QueueSettings()); taskQueue.enqueue(task); return; } deleteAll(JobRecord.DATA_STORE_KIND, rootJobKey); deleteAll(Slot.DATA_STORE_KIND, rootJobKey); deleteAll(ShardedValue.DATA_STORE_KIND, rootJobKey); deleteAll(Barrier.DATA_STORE_KIND, rootJobKey); deleteAll(JobInstanceRecord.DATA_STORE_KIND, rootJobKey); deleteAll(FanoutTaskRecord.DATA_STORE_KIND, rootJobKey); }
[ "@", "Override", "public", "void", "deletePipeline", "(", "Key", "rootJobKey", ",", "boolean", "force", ",", "boolean", "async", ")", "throws", "IllegalStateException", "{", "if", "(", "!", "force", ")", "{", "try", "{", "JobRecord", "rootJobRecord", "=", "q...
Delete all datastore entities corresponding to the given pipeline. @param rootJobKey The root job key identifying the pipeline @param force If this parameter is not {@code true} then this method will throw an {@link IllegalStateException} if the specified pipeline is not in the {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#FINALIZED} or {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#STOPPED} state. @param async If this parameter is {@code true} then instead of performing the delete operation synchronously, this method will enqueue a task to perform the operation. @throws IllegalStateException If {@code force = false} and the specified pipeline is not in the {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#FINALIZED} or {@link com.google.appengine.tools.pipeline.impl.model.JobRecord.State#STOPPED} state.
[ "Delete", "all", "datastore", "entities", "corresponding", "to", "the", "given", "pipeline", "." ]
train
https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/java/src/main/java/com/google/appengine/tools/pipeline/impl/backend/AppEngineBackEnd.java#L603-L633
rterp/GMapsFX
GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/ArcBuilder.java
ArcBuilder.buildClosedArc
public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) { """ Builds the path for a closed arc, returning a PolygonOptions that can be further customised before use. @param center @param start @param end @param arcType Pass in either ArcType.CHORD or ArcType.ROUND @return PolygonOptions with the paths element populated. """ MVCArray res = buildArcPoints(center, start, end); if (ArcType.ROUND.equals(arcType)) { res.push(center); } return new PolygonOptions().paths(res); }
java
public static final PolygonOptions buildClosedArc(LatLong center, LatLong start, LatLong end, ArcType arcType) { MVCArray res = buildArcPoints(center, start, end); if (ArcType.ROUND.equals(arcType)) { res.push(center); } return new PolygonOptions().paths(res); }
[ "public", "static", "final", "PolygonOptions", "buildClosedArc", "(", "LatLong", "center", ",", "LatLong", "start", ",", "LatLong", "end", ",", "ArcType", "arcType", ")", "{", "MVCArray", "res", "=", "buildArcPoints", "(", "center", ",", "start", ",", "end", ...
Builds the path for a closed arc, returning a PolygonOptions that can be further customised before use. @param center @param start @param end @param arcType Pass in either ArcType.CHORD or ArcType.ROUND @return PolygonOptions with the paths element populated.
[ "Builds", "the", "path", "for", "a", "closed", "arc", "returning", "a", "PolygonOptions", "that", "can", "be", "further", "customised", "before", "use", "." ]
train
https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/shapes/ArcBuilder.java#L34-L40
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/rpc/CmsRpcPrefetcher.java
CmsRpcPrefetcher.getSerializedObjectFromString
public static Object getSerializedObjectFromString(Object asyncService, String serializedData) throws SerializationException { """ Deserializes the prefetched RPC data.<p> @param asyncService the RPC service instance @param serializedData the serialized object data @return the prefetched RPC data @throws SerializationException if the deserialization fails """ SerializationStreamFactory ssf = (SerializationStreamFactory)asyncService; return ssf.createStreamReader(serializedData).readObject(); }
java
public static Object getSerializedObjectFromString(Object asyncService, String serializedData) throws SerializationException { SerializationStreamFactory ssf = (SerializationStreamFactory)asyncService; return ssf.createStreamReader(serializedData).readObject(); }
[ "public", "static", "Object", "getSerializedObjectFromString", "(", "Object", "asyncService", ",", "String", "serializedData", ")", "throws", "SerializationException", "{", "SerializationStreamFactory", "ssf", "=", "(", "SerializationStreamFactory", ")", "asyncService", ";"...
Deserializes the prefetched RPC data.<p> @param asyncService the RPC service instance @param serializedData the serialized object data @return the prefetched RPC data @throws SerializationException if the deserialization fails
[ "Deserializes", "the", "prefetched", "RPC", "data", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/rpc/CmsRpcPrefetcher.java#L74-L79
Azure/azure-sdk-for-java
mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/LogFilesInner.java
LogFilesInner.listByServerAsync
public Observable<List<LogFileInner>> listByServerAsync(String resourceGroupName, String serverName) { """ List all the log files in a given server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;LogFileInner&gt; object """ return listByServerWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<List<LogFileInner>>, List<LogFileInner>>() { @Override public List<LogFileInner> call(ServiceResponse<List<LogFileInner>> response) { return response.body(); } }); }
java
public Observable<List<LogFileInner>> listByServerAsync(String resourceGroupName, String serverName) { return listByServerWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<List<LogFileInner>>, List<LogFileInner>>() { @Override public List<LogFileInner> call(ServiceResponse<List<LogFileInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "LogFileInner", ">", ">", "listByServerAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ")", "{", "return", "listByServerWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ")", ".",...
List all the log files in a given server. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;LogFileInner&gt; object
[ "List", "all", "the", "log", "files", "in", "a", "given", "server", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mysql/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/mysql/v2017_12_01/implementation/LogFilesInner.java#L96-L103
westnordost/osmapi
src/main/java/de/westnordost/osmapi/map/MapDataHistoryDao.java
MapDataHistoryDao.getWayHistory
public void getWayHistory(long id, Handler<Way> handler) { """ Feeds all versions of the given way to the handler. The elements are sorted by version, the oldest version is the first, the newest version is the last element.<br> If not logged in, the Changeset for each returned element will be null @throws OsmNotFoundException if the node has not been found. """ MapDataHandler mapDataHandler = new WrapperOsmElementHandler<>(Way.class, handler); boolean authenticate = osm.getOAuth() != null; osm.makeRequest(WAY + "/" + id + "/" + HISTORY, authenticate, new MapDataParser(mapDataHandler, factory)); }
java
public void getWayHistory(long id, Handler<Way> handler) { MapDataHandler mapDataHandler = new WrapperOsmElementHandler<>(Way.class, handler); boolean authenticate = osm.getOAuth() != null; osm.makeRequest(WAY + "/" + id + "/" + HISTORY, authenticate, new MapDataParser(mapDataHandler, factory)); }
[ "public", "void", "getWayHistory", "(", "long", "id", ",", "Handler", "<", "Way", ">", "handler", ")", "{", "MapDataHandler", "mapDataHandler", "=", "new", "WrapperOsmElementHandler", "<>", "(", "Way", ".", "class", ",", "handler", ")", ";", "boolean", "auth...
Feeds all versions of the given way to the handler. The elements are sorted by version, the oldest version is the first, the newest version is the last element.<br> If not logged in, the Changeset for each returned element will be null @throws OsmNotFoundException if the node has not been found.
[ "Feeds", "all", "versions", "of", "the", "given", "way", "to", "the", "handler", ".", "The", "elements", "are", "sorted", "by", "version", "the", "oldest", "version", "is", "the", "first", "the", "newest", "version", "is", "the", "last", "element", ".", ...
train
https://github.com/westnordost/osmapi/blob/dda6978fd12e117d0cf17812bc22037f61e22c4b/src/main/java/de/westnordost/osmapi/map/MapDataHistoryDao.java#L60-L66
ineunetOS/knife-commons
knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java
StringUtils.lastOrdinalIndexOf
public static int lastOrdinalIndexOf(String str, String searchStr, int ordinal) { """ <p>Finds the n-th last index within a String, handling <code>null</code>. This method uses {@link String#lastIndexOf(String)}.</p> <p>A <code>null</code> String will return <code>-1</code>.</p> <pre> StringUtils.lastOrdinalIndexOf(null, *, *) = -1 StringUtils.lastOrdinalIndexOf(*, null, *) = -1 StringUtils.lastOrdinalIndexOf("", "", *) = 0 StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7 StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6 StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5 StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2 StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4 StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1 StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8 StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8 </pre> <p>Note that 'tail(String str, int n)' may be implemented as: </p> <pre> str.substring(lastOrdinalIndexOf(str, "\n", n) + 1) </pre> @param str the String to check, may be null @param searchStr the String to find, may be null @param ordinal the n-th last <code>searchStr</code> to find @return the n-th last index of the search String, <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input @since 2.5 """ return ordinalIndexOf(str, searchStr, ordinal, true); }
java
public static int lastOrdinalIndexOf(String str, String searchStr, int ordinal) { return ordinalIndexOf(str, searchStr, ordinal, true); }
[ "public", "static", "int", "lastOrdinalIndexOf", "(", "String", "str", ",", "String", "searchStr", ",", "int", "ordinal", ")", "{", "return", "ordinalIndexOf", "(", "str", ",", "searchStr", ",", "ordinal", ",", "true", ")", ";", "}" ]
<p>Finds the n-th last index within a String, handling <code>null</code>. This method uses {@link String#lastIndexOf(String)}.</p> <p>A <code>null</code> String will return <code>-1</code>.</p> <pre> StringUtils.lastOrdinalIndexOf(null, *, *) = -1 StringUtils.lastOrdinalIndexOf(*, null, *) = -1 StringUtils.lastOrdinalIndexOf("", "", *) = 0 StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7 StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6 StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5 StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2 StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4 StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1 StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8 StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8 </pre> <p>Note that 'tail(String str, int n)' may be implemented as: </p> <pre> str.substring(lastOrdinalIndexOf(str, "\n", n) + 1) </pre> @param str the String to check, may be null @param searchStr the String to find, may be null @param ordinal the n-th last <code>searchStr</code> to find @return the n-th last index of the search String, <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input @since 2.5
[ "<p", ">", "Finds", "the", "n", "-", "th", "last", "index", "within", "a", "String", "handling", "<code", ">", "null<", "/", "code", ">", ".", "This", "method", "uses", "{", "@link", "String#lastIndexOf", "(", "String", ")", "}", ".", "<", "/", "p", ...
train
https://github.com/ineunetOS/knife-commons/blob/eae9e59afa020a00ae8977c10d43ac8ae46ae236/knife-commons-utils/src/main/java/com/ineunet/knife/util/StringUtils.java#L1068-L1070
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/meta/AlternateContentConfigProcessor.java
AlternateContentConfigProcessor.getAlternateContentDirectory
public File getAlternateContentDirectory(String userAgent) { """ Iterates through AlternateContent objects trying to match against their pre compiled pattern. @param userAgent The userAgent request header. @return the ContentDirectory of the matched AlternateContent instance or null if none are found. """ Configuration config = liveConfig; for(AlternateContent configuration: config.configs) { try { if(configuration.compiledPattern.matcher(userAgent).matches()) { return new File(config.metaDir, configuration.getContentDirectory()); } } catch(Exception e) { logger.warn("Failed to process config: "+ configuration.getPattern()+"->"+ configuration.getContentDirectory(), e); } } return null; }
java
public File getAlternateContentDirectory(String userAgent) { Configuration config = liveConfig; for(AlternateContent configuration: config.configs) { try { if(configuration.compiledPattern.matcher(userAgent).matches()) { return new File(config.metaDir, configuration.getContentDirectory()); } } catch(Exception e) { logger.warn("Failed to process config: "+ configuration.getPattern()+"->"+ configuration.getContentDirectory(), e); } } return null; }
[ "public", "File", "getAlternateContentDirectory", "(", "String", "userAgent", ")", "{", "Configuration", "config", "=", "liveConfig", ";", "for", "(", "AlternateContent", "configuration", ":", "config", ".", "configs", ")", "{", "try", "{", "if", "(", "configura...
Iterates through AlternateContent objects trying to match against their pre compiled pattern. @param userAgent The userAgent request header. @return the ContentDirectory of the matched AlternateContent instance or null if none are found.
[ "Iterates", "through", "AlternateContent", "objects", "trying", "to", "match", "against", "their", "pre", "compiled", "pattern", "." ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/meta/AlternateContentConfigProcessor.java#L75-L87
jqno/equalsverifier
src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/FactoryCache.java
FactoryCache.put
public <T> void put(Class<?> type, PrefabValueFactory<T> factory) { """ Adds the given factory to the cache and associates it with the given type. @param <T> The type of the factory. @param type The type to associate with the factory. @param factory The factory to associate with the type. """ if (type != null) { cache.put(type.getName(), factory); } }
java
public <T> void put(Class<?> type, PrefabValueFactory<T> factory) { if (type != null) { cache.put(type.getName(), factory); } }
[ "public", "<", "T", ">", "void", "put", "(", "Class", "<", "?", ">", "type", ",", "PrefabValueFactory", "<", "T", ">", "factory", ")", "{", "if", "(", "type", "!=", "null", ")", "{", "cache", ".", "put", "(", "type", ".", "getName", "(", ")", "...
Adds the given factory to the cache and associates it with the given type. @param <T> The type of the factory. @param type The type to associate with the factory. @param factory The factory to associate with the type.
[ "Adds", "the", "given", "factory", "to", "the", "cache", "and", "associates", "it", "with", "the", "given", "type", "." ]
train
https://github.com/jqno/equalsverifier/blob/25d73c9cb801c8b20b257d1d1283ac6e0585ef1d/src/main/java/nl/jqno/equalsverifier/internal/prefabvalues/FactoryCache.java#L27-L31
osiam/connector4java
src/main/java/org/osiam/client/OsiamConnector.java
OsiamConnector.refreshAccessToken
public AccessToken refreshAccessToken(AccessToken accessToken, Scope... scopes) { """ Provides a new and refreshed access token by getting the refresh token from the given access token. @param accessToken the access token to be refreshed @param scopes an optional parameter if the scope of the token should be changed. Otherwise the scopes of the old token are used. @return the new access token with the refreshed lifetime @throws IllegalArgumentException in case the accessToken has an empty refresh token @throws ConnectionInitializationException if the connection to the given OSIAM service could not be initialized @throws UnauthorizedException if the request could not be authorized. @throws IllegalStateException if OSIAM's endpoint(s) are not properly configured """ return getAuthService().refreshAccessToken(accessToken, scopes); }
java
public AccessToken refreshAccessToken(AccessToken accessToken, Scope... scopes) { return getAuthService().refreshAccessToken(accessToken, scopes); }
[ "public", "AccessToken", "refreshAccessToken", "(", "AccessToken", "accessToken", ",", "Scope", "...", "scopes", ")", "{", "return", "getAuthService", "(", ")", ".", "refreshAccessToken", "(", "accessToken", ",", "scopes", ")", ";", "}" ]
Provides a new and refreshed access token by getting the refresh token from the given access token. @param accessToken the access token to be refreshed @param scopes an optional parameter if the scope of the token should be changed. Otherwise the scopes of the old token are used. @return the new access token with the refreshed lifetime @throws IllegalArgumentException in case the accessToken has an empty refresh token @throws ConnectionInitializationException if the connection to the given OSIAM service could not be initialized @throws UnauthorizedException if the request could not be authorized. @throws IllegalStateException if OSIAM's endpoint(s) are not properly configured
[ "Provides", "a", "new", "and", "refreshed", "access", "token", "by", "getting", "the", "refresh", "token", "from", "the", "given", "access", "token", "." ]
train
https://github.com/osiam/connector4java/blob/a5e6ae1e706f4889d662a069fe2f3bf8e3848d12/src/main/java/org/osiam/client/OsiamConnector.java#L381-L383
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/AccountsImpl.java
AccountsImpl.listNodeAgentSkusNext
public PagedList<NodeAgentSku> listNodeAgentSkusNext(final String nextPageLink, final AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions) { """ Lists all node agent SKUs supported by the Azure Batch service. @param nextPageLink The NextLink from the previous successful call to List operation. @param accountListNodeAgentSkusNextOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PagedList&lt;NodeAgentSku&gt; object if successful. """ ServiceResponseWithHeaders<Page<NodeAgentSku>, AccountListNodeAgentSkusHeaders> response = listNodeAgentSkusNextSinglePageAsync(nextPageLink, accountListNodeAgentSkusNextOptions).toBlocking().single(); return new PagedList<NodeAgentSku>(response.body()) { @Override public Page<NodeAgentSku> nextPage(String nextPageLink) { return listNodeAgentSkusNextSinglePageAsync(nextPageLink, accountListNodeAgentSkusNextOptions).toBlocking().single().body(); } }; }
java
public PagedList<NodeAgentSku> listNodeAgentSkusNext(final String nextPageLink, final AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions) { ServiceResponseWithHeaders<Page<NodeAgentSku>, AccountListNodeAgentSkusHeaders> response = listNodeAgentSkusNextSinglePageAsync(nextPageLink, accountListNodeAgentSkusNextOptions).toBlocking().single(); return new PagedList<NodeAgentSku>(response.body()) { @Override public Page<NodeAgentSku> nextPage(String nextPageLink) { return listNodeAgentSkusNextSinglePageAsync(nextPageLink, accountListNodeAgentSkusNextOptions).toBlocking().single().body(); } }; }
[ "public", "PagedList", "<", "NodeAgentSku", ">", "listNodeAgentSkusNext", "(", "final", "String", "nextPageLink", ",", "final", "AccountListNodeAgentSkusNextOptions", "accountListNodeAgentSkusNextOptions", ")", "{", "ServiceResponseWithHeaders", "<", "Page", "<", "NodeAgentSk...
Lists all node agent SKUs supported by the Azure Batch service. @param nextPageLink The NextLink from the previous successful call to List operation. @param accountListNodeAgentSkusNextOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PagedList&lt;NodeAgentSku&gt; object if successful.
[ "Lists", "all", "node", "agent", "SKUs", "supported", "by", "the", "Azure", "Batch", "service", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/AccountsImpl.java#L759-L767
LearnLib/automatalib
visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/DOT.java
DOT.renderDOT
public static void renderDOT(Reader r, boolean modal) { """ Renders a GraphVIZ description and displays it in a Swing window. @param r the reader from which the description is obtained. @param modal whether or not the dialog should be modal. """ final DOTComponent cmp = createDOTComponent(r); if (cmp == null) { return; } final JDialog frame = new JDialog((Dialog) null, modal); JScrollPane scrollPane = new JScrollPane(cmp); frame.setContentPane(scrollPane); frame.setMaximumSize(new Dimension(MAX_WIDTH, MAX_HEIGHT)); frame.pack(); JMenu menu = new JMenu("File"); menu.add(cmp.getSavePngAction()); menu.add(cmp.getSaveDotAction()); menu.addSeparator(); menu.add(new AbstractAction("Close") { private static final long serialVersionUID = -1L; @Override public void actionPerformed(ActionEvent e) { frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); } }); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); frame.setJMenuBar(menuBar); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); frame.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ESCAPE) { frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); } } }); }
java
public static void renderDOT(Reader r, boolean modal) { final DOTComponent cmp = createDOTComponent(r); if (cmp == null) { return; } final JDialog frame = new JDialog((Dialog) null, modal); JScrollPane scrollPane = new JScrollPane(cmp); frame.setContentPane(scrollPane); frame.setMaximumSize(new Dimension(MAX_WIDTH, MAX_HEIGHT)); frame.pack(); JMenu menu = new JMenu("File"); menu.add(cmp.getSavePngAction()); menu.add(cmp.getSaveDotAction()); menu.addSeparator(); menu.add(new AbstractAction("Close") { private static final long serialVersionUID = -1L; @Override public void actionPerformed(ActionEvent e) { frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); } }); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); frame.setJMenuBar(menuBar); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); frame.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_ESCAPE) { frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); } } }); }
[ "public", "static", "void", "renderDOT", "(", "Reader", "r", ",", "boolean", "modal", ")", "{", "final", "DOTComponent", "cmp", "=", "createDOTComponent", "(", "r", ")", ";", "if", "(", "cmp", "==", "null", ")", "{", "return", ";", "}", "final", "JDial...
Renders a GraphVIZ description and displays it in a Swing window. @param r the reader from which the description is obtained. @param modal whether or not the dialog should be modal.
[ "Renders", "a", "GraphVIZ", "description", "and", "displays", "it", "in", "a", "Swing", "window", "." ]
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/DOT.java#L252-L290
Whiley/WhileyCompiler
src/main/java/wyc/io/WhileyFileParser.java
WhileyFileParser.tryAndMatch
private Token tryAndMatch(boolean terminated, Token.Kind... kinds) { """ Attempt to match a given token(s), whilst ignoring any whitespace in between. Note that, in the case it fails to match, then the index will be unchanged. This latter point is important, otherwise we could accidentally gobble up some important indentation. If more than one kind is provided then this will try to match any of them. @param terminated Indicates whether or not this function should be concerned with new lines. The terminated flag indicates whether or not the current construct being parsed is known to be terminated. If so, then we don't need to worry about newlines and can greedily consume them (i.e. since we'll eventually run into the terminating symbol). @param kinds @return """ // If the construct being parsed is know to be terminated, then we can // skip all whitespace. Otherwise, we can't skip newlines as these are // significant. int next = terminated ? skipWhiteSpace(index) : skipLineSpace(index); if (next < tokens.size()) { Token t = tokens.get(next); for (int i = 0; i != kinds.length; ++i) { if (t.kind == kinds[i]) { index = next + 1; return t; } } } return null; }
java
private Token tryAndMatch(boolean terminated, Token.Kind... kinds) { // If the construct being parsed is know to be terminated, then we can // skip all whitespace. Otherwise, we can't skip newlines as these are // significant. int next = terminated ? skipWhiteSpace(index) : skipLineSpace(index); if (next < tokens.size()) { Token t = tokens.get(next); for (int i = 0; i != kinds.length; ++i) { if (t.kind == kinds[i]) { index = next + 1; return t; } } } return null; }
[ "private", "Token", "tryAndMatch", "(", "boolean", "terminated", ",", "Token", ".", "Kind", "...", "kinds", ")", "{", "// If the construct being parsed is know to be terminated, then we can", "// skip all whitespace. Otherwise, we can't skip newlines as these are", "// significant.",...
Attempt to match a given token(s), whilst ignoring any whitespace in between. Note that, in the case it fails to match, then the index will be unchanged. This latter point is important, otherwise we could accidentally gobble up some important indentation. If more than one kind is provided then this will try to match any of them. @param terminated Indicates whether or not this function should be concerned with new lines. The terminated flag indicates whether or not the current construct being parsed is known to be terminated. If so, then we don't need to worry about newlines and can greedily consume them (i.e. since we'll eventually run into the terminating symbol). @param kinds @return
[ "Attempt", "to", "match", "a", "given", "token", "(", "s", ")", "whilst", "ignoring", "any", "whitespace", "in", "between", ".", "Note", "that", "in", "the", "case", "it", "fails", "to", "match", "then", "the", "index", "will", "be", "unchanged", ".", ...
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L4261-L4277
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java
Parameters.assertAtLeastOneDefined
public void assertAtLeastOneDefined(final String param1, final String... moreParams) { """ Throws a ParameterException if none of the supplied parameters are defined. """ if (!isPresent(param1)) { for (final String moreParam : moreParams) { if (isPresent(moreParam)) { return; } } final List<String> paramsForError = Lists.newArrayList(); paramsForError.add(param1); paramsForError.addAll(Arrays.asList(moreParams)); throw new ParameterException( String.format("At least one of %s must be defined.", StringUtils.CommaSpaceJoiner.join(paramsForError))); } }
java
public void assertAtLeastOneDefined(final String param1, final String... moreParams) { if (!isPresent(param1)) { for (final String moreParam : moreParams) { if (isPresent(moreParam)) { return; } } final List<String> paramsForError = Lists.newArrayList(); paramsForError.add(param1); paramsForError.addAll(Arrays.asList(moreParams)); throw new ParameterException( String.format("At least one of %s must be defined.", StringUtils.CommaSpaceJoiner.join(paramsForError))); } }
[ "public", "void", "assertAtLeastOneDefined", "(", "final", "String", "param1", ",", "final", "String", "...", "moreParams", ")", "{", "if", "(", "!", "isPresent", "(", "param1", ")", ")", "{", "for", "(", "final", "String", "moreParam", ":", "moreParams", ...
Throws a ParameterException if none of the supplied parameters are defined.
[ "Throws", "a", "ParameterException", "if", "none", "of", "the", "supplied", "parameters", "are", "defined", "." ]
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/parameters/Parameters.java#L1098-L1112
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.addClass
public Jar addClass(Class<?> clazz) throws IOException { """ Adds a class entry to this JAR. @param clazz the class to add to the JAR. @return {@code this} """ final String resource = clazz.getName().replace('.', '/') + ".class"; return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource)); }
java
public Jar addClass(Class<?> clazz) throws IOException { final String resource = clazz.getName().replace('.', '/') + ".class"; return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource)); }
[ "public", "Jar", "addClass", "(", "Class", "<", "?", ">", "clazz", ")", "throws", "IOException", "{", "final", "String", "resource", "=", "clazz", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\".class\"", ";", ...
Adds a class entry to this JAR. @param clazz the class to add to the JAR. @return {@code this}
[ "Adds", "a", "class", "entry", "to", "this", "JAR", "." ]
train
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L379-L382
looly/hutool
hutool-poi/src/main/java/cn/hutool/poi/excel/sax/ExcelSaxUtil.java
ExcelSaxUtil.getNumberValue
private static Number getNumberValue(String value, String numFmtString) { """ 获取数字类型值 @param value 值 @param numFmtString 格式 @return 数字,可以是Double、Long @since 4.1.0 """ if(StrUtil.isBlank(value)) { return null; } double numValue = Double.parseDouble(value); // 普通数字 if (null != numFmtString && numFmtString.indexOf(StrUtil.C_DOT) < 0) { final long longPart = (long) numValue; if (longPart == numValue) { // 对于无小数部分的数字类型,转为Long return longPart; } } return numValue; }
java
private static Number getNumberValue(String value, String numFmtString) { if(StrUtil.isBlank(value)) { return null; } double numValue = Double.parseDouble(value); // 普通数字 if (null != numFmtString && numFmtString.indexOf(StrUtil.C_DOT) < 0) { final long longPart = (long) numValue; if (longPart == numValue) { // 对于无小数部分的数字类型,转为Long return longPart; } } return numValue; }
[ "private", "static", "Number", "getNumberValue", "(", "String", "value", ",", "String", "numFmtString", ")", "{", "if", "(", "StrUtil", ".", "isBlank", "(", "value", ")", ")", "{", "return", "null", ";", "}", "double", "numValue", "=", "Double", ".", "pa...
获取数字类型值 @param value 值 @param numFmtString 格式 @return 数字,可以是Double、Long @since 4.1.0
[ "获取数字类型值" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/sax/ExcelSaxUtil.java#L140-L154
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/junit/JUnitXMLPerPageListener.java
JUnitXMLPerPageListener.writeResult
protected void writeResult(String testName, String resultXml) throws IOException { """ Writes XML result to disk. @param testName name of test. @param resultXml XML description of test outcome. @throws IOException if unable to write result. """ String finalPath = getXmlFileName(testName); Writer fw = null; try { fw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(finalPath), "UTF-8")); fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fw.write(resultXml); } finally { if (fw != null) { fw.close(); } } }
java
protected void writeResult(String testName, String resultXml) throws IOException { String finalPath = getXmlFileName(testName); Writer fw = null; try { fw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(finalPath), "UTF-8")); fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fw.write(resultXml); } finally { if (fw != null) { fw.close(); } } }
[ "protected", "void", "writeResult", "(", "String", "testName", ",", "String", "resultXml", ")", "throws", "IOException", "{", "String", "finalPath", "=", "getXmlFileName", "(", "testName", ")", ";", "Writer", "fw", "=", "null", ";", "try", "{", "fw", "=", ...
Writes XML result to disk. @param testName name of test. @param resultXml XML description of test outcome. @throws IOException if unable to write result.
[ "Writes", "XML", "result", "to", "disk", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/junit/JUnitXMLPerPageListener.java#L119-L134
apache/flink
flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/metric/directed/EdgeMetrics.java
EdgeMetrics.run
@Override public EdgeMetrics<K, VV, EV> run(Graph<K, VV, EV> input) throws Exception { """ /* Implementation notes: <p>Use aggregator to replace SumEdgeStats when aggregators are rewritten to use a hash-combineable hashable-reduce. <p>Use distinct to replace ReduceEdgeStats when the combiner can be disabled with a sorted-reduce forced. """ super.run(input); // s, t, (d(s), d(t)) DataSet<Edge<K, Tuple3<EV, Degrees, Degrees>>> edgeDegreesPair = input .run(new EdgeDegreesPair<K, VV, EV>() .setParallelism(parallelism)); // s, d(s), count of (u, v) where deg(u) < deg(v) or (deg(u) == deg(v) and u < v) DataSet<Tuple3<K, Degrees, LongValue>> edgeStats = edgeDegreesPair .flatMap(new EdgeStats<>()) .setParallelism(parallelism) .name("Edge stats") .groupBy(0, 1) .reduceGroup(new ReduceEdgeStats<>()) .setParallelism(parallelism) .name("Reduce edge stats") .groupBy(0) .reduce(new SumEdgeStats<>()) .setCombineHint(CombineHint.HASH) .setParallelism(parallelism) .name("Sum edge stats"); edgeMetricsHelper = new EdgeMetricsHelper<>(); edgeStats .output(edgeMetricsHelper) .setParallelism(parallelism) .name("Edge metrics"); return this; }
java
@Override public EdgeMetrics<K, VV, EV> run(Graph<K, VV, EV> input) throws Exception { super.run(input); // s, t, (d(s), d(t)) DataSet<Edge<K, Tuple3<EV, Degrees, Degrees>>> edgeDegreesPair = input .run(new EdgeDegreesPair<K, VV, EV>() .setParallelism(parallelism)); // s, d(s), count of (u, v) where deg(u) < deg(v) or (deg(u) == deg(v) and u < v) DataSet<Tuple3<K, Degrees, LongValue>> edgeStats = edgeDegreesPair .flatMap(new EdgeStats<>()) .setParallelism(parallelism) .name("Edge stats") .groupBy(0, 1) .reduceGroup(new ReduceEdgeStats<>()) .setParallelism(parallelism) .name("Reduce edge stats") .groupBy(0) .reduce(new SumEdgeStats<>()) .setCombineHint(CombineHint.HASH) .setParallelism(parallelism) .name("Sum edge stats"); edgeMetricsHelper = new EdgeMetricsHelper<>(); edgeStats .output(edgeMetricsHelper) .setParallelism(parallelism) .name("Edge metrics"); return this; }
[ "@", "Override", "public", "EdgeMetrics", "<", "K", ",", "VV", ",", "EV", ">", "run", "(", "Graph", "<", "K", ",", "VV", ",", "EV", ">", "input", ")", "throws", "Exception", "{", "super", ".", "run", "(", "input", ")", ";", "// s, t, (d(s), d(t))", ...
/* Implementation notes: <p>Use aggregator to replace SumEdgeStats when aggregators are rewritten to use a hash-combineable hashable-reduce. <p>Use distinct to replace ReduceEdgeStats when the combiner can be disabled with a sorted-reduce forced.
[ "/", "*", "Implementation", "notes", ":" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/metric/directed/EdgeMetrics.java#L83-L116
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java
MessageRetriever.getText
public String getText(String key, Object... args) throws MissingResourceException { """ Get and format message string from resource @param key selects message from resource @param args arguments to be replaced in the message. @throws MissingResourceException when the key does not exist in the properties file. """ if (messageRB == null) { try { messageRB = ResourceBundle.getBundle(resourcelocation); } catch (MissingResourceException e) { throw new Error("Fatal: Resource (" + resourcelocation + ") for javadoc doclets is missing."); } } String message = messageRB.getString(key); return MessageFormat.format(message, args); }
java
public String getText(String key, Object... args) throws MissingResourceException { if (messageRB == null) { try { messageRB = ResourceBundle.getBundle(resourcelocation); } catch (MissingResourceException e) { throw new Error("Fatal: Resource (" + resourcelocation + ") for javadoc doclets is missing."); } } String message = messageRB.getString(key); return MessageFormat.format(message, args); }
[ "public", "String", "getText", "(", "String", "key", ",", "Object", "...", "args", ")", "throws", "MissingResourceException", "{", "if", "(", "messageRB", "==", "null", ")", "{", "try", "{", "messageRB", "=", "ResourceBundle", ".", "getBundle", "(", "resourc...
Get and format message string from resource @param key selects message from resource @param args arguments to be replaced in the message. @throws MissingResourceException when the key does not exist in the properties file.
[ "Get", "and", "format", "message", "string", "from", "resource" ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/MessageRetriever.java#L93-L104
JOML-CI/JOML
src/org/joml/Intersectiond.java
Intersectiond.findClosestPointOnTriangle
public static int findClosestPointOnTriangle(Vector2dc v0, Vector2dc v1, Vector2dc v2, Vector2dc p, Vector2d result) { """ Determine the closest point on the triangle with the vertices <code>v0</code>, <code>v1</code>, <code>v2</code> between that triangle and the given point <code>p</code> and store that point into the given <code>result</code>. <p> Additionally, this method returns whether the closest point is a vertex ({@link #POINT_ON_TRIANGLE_VERTEX_0}, {@link #POINT_ON_TRIANGLE_VERTEX_1}, {@link #POINT_ON_TRIANGLE_VERTEX_2}) of the triangle, lies on an edge ({@link #POINT_ON_TRIANGLE_EDGE_01}, {@link #POINT_ON_TRIANGLE_EDGE_12}, {@link #POINT_ON_TRIANGLE_EDGE_20}) or on the {@link #POINT_ON_TRIANGLE_FACE face} of the triangle. <p> Reference: Book "Real-Time Collision Detection" chapter 5.1.5 "Closest Point on Triangle to Point" @param v0 the first vertex of the triangle @param v1 the second vertex of the triangle @param v2 the third vertex of the triangle @param p the point @param result will hold the closest point @return one of {@link #POINT_ON_TRIANGLE_VERTEX_0}, {@link #POINT_ON_TRIANGLE_VERTEX_1}, {@link #POINT_ON_TRIANGLE_VERTEX_2}, {@link #POINT_ON_TRIANGLE_EDGE_01}, {@link #POINT_ON_TRIANGLE_EDGE_12}, {@link #POINT_ON_TRIANGLE_EDGE_20} or {@link #POINT_ON_TRIANGLE_FACE} """ return findClosestPointOnTriangle(v0.x(), v0.y(), v1.x(), v1.y(), v2.x(), v2.y(), p.x(), p.y(), result); }
java
public static int findClosestPointOnTriangle(Vector2dc v0, Vector2dc v1, Vector2dc v2, Vector2dc p, Vector2d result) { return findClosestPointOnTriangle(v0.x(), v0.y(), v1.x(), v1.y(), v2.x(), v2.y(), p.x(), p.y(), result); }
[ "public", "static", "int", "findClosestPointOnTriangle", "(", "Vector2dc", "v0", ",", "Vector2dc", "v1", ",", "Vector2dc", "v2", ",", "Vector2dc", "p", ",", "Vector2d", "result", ")", "{", "return", "findClosestPointOnTriangle", "(", "v0", ".", "x", "(", ")", ...
Determine the closest point on the triangle with the vertices <code>v0</code>, <code>v1</code>, <code>v2</code> between that triangle and the given point <code>p</code> and store that point into the given <code>result</code>. <p> Additionally, this method returns whether the closest point is a vertex ({@link #POINT_ON_TRIANGLE_VERTEX_0}, {@link #POINT_ON_TRIANGLE_VERTEX_1}, {@link #POINT_ON_TRIANGLE_VERTEX_2}) of the triangle, lies on an edge ({@link #POINT_ON_TRIANGLE_EDGE_01}, {@link #POINT_ON_TRIANGLE_EDGE_12}, {@link #POINT_ON_TRIANGLE_EDGE_20}) or on the {@link #POINT_ON_TRIANGLE_FACE face} of the triangle. <p> Reference: Book "Real-Time Collision Detection" chapter 5.1.5 "Closest Point on Triangle to Point" @param v0 the first vertex of the triangle @param v1 the second vertex of the triangle @param v2 the third vertex of the triangle @param p the point @param result will hold the closest point @return one of {@link #POINT_ON_TRIANGLE_VERTEX_0}, {@link #POINT_ON_TRIANGLE_VERTEX_1}, {@link #POINT_ON_TRIANGLE_VERTEX_2}, {@link #POINT_ON_TRIANGLE_EDGE_01}, {@link #POINT_ON_TRIANGLE_EDGE_12}, {@link #POINT_ON_TRIANGLE_EDGE_20} or {@link #POINT_ON_TRIANGLE_FACE}
[ "Determine", "the", "closest", "point", "on", "the", "triangle", "with", "the", "vertices", "<code", ">", "v0<", "/", "code", ">", "<code", ">", "v1<", "/", "code", ">", "<code", ">", "v2<", "/", "code", ">", "between", "that", "triangle", "and", "the"...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectiond.java#L4192-L4194
JOML-CI/JOML
src/org/joml/Quaterniond.java
Quaterniond.setAngleAxis
public Quaterniond setAngleAxis(double angle, Vector3dc axis) { """ Set this quaternion to be a representation of the supplied axis and angle (in radians). @param angle the angle in radians @param axis the rotation axis @return this """ return setAngleAxis(angle, axis.x(), axis.y(), axis.z()); }
java
public Quaterniond setAngleAxis(double angle, Vector3dc axis) { return setAngleAxis(angle, axis.x(), axis.y(), axis.z()); }
[ "public", "Quaterniond", "setAngleAxis", "(", "double", "angle", ",", "Vector3dc", "axis", ")", "{", "return", "setAngleAxis", "(", "angle", ",", "axis", ".", "x", "(", ")", ",", "axis", ".", "y", "(", ")", ",", "axis", ".", "z", "(", ")", ")", ";"...
Set this quaternion to be a representation of the supplied axis and angle (in radians). @param angle the angle in radians @param axis the rotation axis @return this
[ "Set", "this", "quaternion", "to", "be", "a", "representation", "of", "the", "supplied", "axis", "and", "angle", "(", "in", "radians", ")", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaterniond.java#L418-L420
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/EmulatedFields.java
EmulatedFields.get
public char get(String name, char defaultValue) throws IllegalArgumentException { """ Finds and returns the char value of a given field named {@code name} in the receiver. If the field has not been assigned any value yet, the default value {@code defaultValue} is returned instead. @param name the name of the field to find. @param defaultValue return value in case the field has not been assigned to yet. @return the value of the given field if it has been assigned, the default value otherwise. @throws IllegalArgumentException if the corresponding field can not be found. """ ObjectSlot slot = findMandatorySlot(name, char.class); return slot.defaulted ? defaultValue : ((Character) slot.fieldValue).charValue(); }
java
public char get(String name, char defaultValue) throws IllegalArgumentException { ObjectSlot slot = findMandatorySlot(name, char.class); return slot.defaulted ? defaultValue : ((Character) slot.fieldValue).charValue(); }
[ "public", "char", "get", "(", "String", "name", ",", "char", "defaultValue", ")", "throws", "IllegalArgumentException", "{", "ObjectSlot", "slot", "=", "findMandatorySlot", "(", "name", ",", "char", ".", "class", ")", ";", "return", "slot", ".", "defaulted", ...
Finds and returns the char value of a given field named {@code name} in the receiver. If the field has not been assigned any value yet, the default value {@code defaultValue} is returned instead. @param name the name of the field to find. @param defaultValue return value in case the field has not been assigned to yet. @return the value of the given field if it has been assigned, the default value otherwise. @throws IllegalArgumentException if the corresponding field can not be found.
[ "Finds", "and", "returns", "the", "char", "value", "of", "a", "given", "field", "named", "{", "@code", "name", "}", "in", "the", "receiver", ".", "If", "the", "field", "has", "not", "been", "assigned", "any", "value", "yet", "the", "default", "value", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/EmulatedFields.java#L228-L231
OpenBEL/openbel-framework
org.openbel.framework.core/src/main/java/org/openbel/framework/core/protonetwork/ProtoNetworkBuilder.java
ProtoNetworkBuilder.handleParameter
protected int handleParameter(ProtoNetwork pn, Parameter p) { """ Builds the {@link ProtoNetwork} at the {@link Parameter} level. @param pn {@link ProtoNetwork}, the proto network @param p {@link Parameter}, the parameter to evaluate @return {@code int}, the parameter index in the {@link ParameterTable} """ ParameterTable pt = pn.getParameterTable(); Integer npidx; if (p.getNamespace() != null) { // add parameter with namespace TableNamespace ns = new TableNamespace(p.getNamespace()); npidx = pt.addTableParameter(new TableParameter(ns, p.getValue())); } else if (doc.getNamespaceGroup() != null && doc.getNamespaceGroup().getDefaultResourceLocation() != null) { // add parameter with user-defined default namespace TableNamespace ns = new TableNamespace(doc.getNamespaceGroup() .getDefaultResourceLocation()); npidx = pt.addTableParameter(new TableParameter(ns, p.getValue())); } else { // add parameter with TEXT namespace npidx = pt.addTableParameter(new TableParameter(p.getValue())); } return npidx; }
java
protected int handleParameter(ProtoNetwork pn, Parameter p) { ParameterTable pt = pn.getParameterTable(); Integer npidx; if (p.getNamespace() != null) { // add parameter with namespace TableNamespace ns = new TableNamespace(p.getNamespace()); npidx = pt.addTableParameter(new TableParameter(ns, p.getValue())); } else if (doc.getNamespaceGroup() != null && doc.getNamespaceGroup().getDefaultResourceLocation() != null) { // add parameter with user-defined default namespace TableNamespace ns = new TableNamespace(doc.getNamespaceGroup() .getDefaultResourceLocation()); npidx = pt.addTableParameter(new TableParameter(ns, p.getValue())); } else { // add parameter with TEXT namespace npidx = pt.addTableParameter(new TableParameter(p.getValue())); } return npidx; }
[ "protected", "int", "handleParameter", "(", "ProtoNetwork", "pn", ",", "Parameter", "p", ")", "{", "ParameterTable", "pt", "=", "pn", ".", "getParameterTable", "(", ")", ";", "Integer", "npidx", ";", "if", "(", "p", ".", "getNamespace", "(", ")", "!=", "...
Builds the {@link ProtoNetwork} at the {@link Parameter} level. @param pn {@link ProtoNetwork}, the proto network @param p {@link Parameter}, the parameter to evaluate @return {@code int}, the parameter index in the {@link ParameterTable}
[ "Builds", "the", "{", "@link", "ProtoNetwork", "}", "at", "the", "{", "@link", "Parameter", "}", "level", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/protonetwork/ProtoNetworkBuilder.java#L333-L353
phax/ph-commons
ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java
JAXBContextCache.getFromCache
@Nullable public JAXBContext getFromCache (@Nonnull final Class <?> aClass) { """ Get the {@link JAXBContext} from an existing {@link Class} object. If the class's owning package is a valid JAXB package, this method redirects to {@link #getFromCache(Package)} otherwise a new JAXB context is created and NOT cached. @param aClass The class for which the JAXB context is to be created. May not be <code>null</code>. @return May be <code>null</code>. """ return getFromCache (aClass, (ClassLoader) null); }
java
@Nullable public JAXBContext getFromCache (@Nonnull final Class <?> aClass) { return getFromCache (aClass, (ClassLoader) null); }
[ "@", "Nullable", "public", "JAXBContext", "getFromCache", "(", "@", "Nonnull", "final", "Class", "<", "?", ">", "aClass", ")", "{", "return", "getFromCache", "(", "aClass", ",", "(", "ClassLoader", ")", "null", ")", ";", "}" ]
Get the {@link JAXBContext} from an existing {@link Class} object. If the class's owning package is a valid JAXB package, this method redirects to {@link #getFromCache(Package)} otherwise a new JAXB context is created and NOT cached. @param aClass The class for which the JAXB context is to be created. May not be <code>null</code>. @return May be <code>null</code>.
[ "Get", "the", "{", "@link", "JAXBContext", "}", "from", "an", "existing", "{", "@link", "Class", "}", "object", ".", "If", "the", "class", "s", "owning", "package", "is", "a", "valid", "JAXB", "package", "this", "method", "redirects", "to", "{", "@link",...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-jaxb/src/main/java/com/helger/jaxb/JAXBContextCache.java#L149-L153