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 |
|---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java | ComputeNodesImpl.getAsync | public Observable<ComputeNode> getAsync(String poolId, String nodeId, ComputeNodeGetOptions computeNodeGetOptions) {
"""
Gets information about the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node that you want to get information about.
@param computeNodeGetOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ComputeNode object
"""
return getWithServiceResponseAsync(poolId, nodeId, computeNodeGetOptions).map(new Func1<ServiceResponseWithHeaders<ComputeNode, ComputeNodeGetHeaders>, ComputeNode>() {
@Override
public ComputeNode call(ServiceResponseWithHeaders<ComputeNode, ComputeNodeGetHeaders> response) {
return response.body();
}
});
} | java | public Observable<ComputeNode> getAsync(String poolId, String nodeId, ComputeNodeGetOptions computeNodeGetOptions) {
return getWithServiceResponseAsync(poolId, nodeId, computeNodeGetOptions).map(new Func1<ServiceResponseWithHeaders<ComputeNode, ComputeNodeGetHeaders>, ComputeNode>() {
@Override
public ComputeNode call(ServiceResponseWithHeaders<ComputeNode, ComputeNodeGetHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ComputeNode",
">",
"getAsync",
"(",
"String",
"poolId",
",",
"String",
"nodeId",
",",
"ComputeNodeGetOptions",
"computeNodeGetOptions",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"poolId",
",",
"nodeId",
",",
"computeNodeGetO... | Gets information about the specified compute node.
@param poolId The ID of the pool that contains the compute node.
@param nodeId The ID of the compute node that you want to get information about.
@param computeNodeGetOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ComputeNode object | [
"Gets",
"information",
"about",
"the",
"specified",
"compute",
"node",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java#L976-L983 |
netceteragroup/valdr-bean-validation | valdr-bean-validation/src/main/java/com/github/valdr/thirdparty/spring/AnnotationUtils.java | AnnotationUtils.getAnnotationAttributes | public static Map<String, Object> getAnnotationAttributes(Annotation annotation, boolean classValuesAsString) {
"""
Retrieve the given annotation's attributes as a Map. Equivalent to calling
{@link #getAnnotationAttributes(java.lang.annotation.Annotation, boolean, boolean)} with
the {@code nestedAnnotationsAsMap} parameter set to {@code false}.
<p>Note: As of Spring 3.1.1, the returned map is actually an
{@code org.springframework.core.annotation.AnnotationAttributes} instance, however the Map signature of this
methodhas
been preserved for binary compatibility.
@param annotation the annotation to retrieve the attributes for
@param classValuesAsString whether to turn Class references into Strings (for
compatibility with {@code org.springframework.core.type.AnnotationMetadata} or to
preserve them as Class references
@return the Map of annotation attributes, with attribute names as keys and
corresponding attribute values as values
"""
return getAnnotationAttributes(annotation, classValuesAsString, false);
} | java | public static Map<String, Object> getAnnotationAttributes(Annotation annotation, boolean classValuesAsString) {
return getAnnotationAttributes(annotation, classValuesAsString, false);
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"getAnnotationAttributes",
"(",
"Annotation",
"annotation",
",",
"boolean",
"classValuesAsString",
")",
"{",
"return",
"getAnnotationAttributes",
"(",
"annotation",
",",
"classValuesAsString",
",",
"false",... | Retrieve the given annotation's attributes as a Map. Equivalent to calling
{@link #getAnnotationAttributes(java.lang.annotation.Annotation, boolean, boolean)} with
the {@code nestedAnnotationsAsMap} parameter set to {@code false}.
<p>Note: As of Spring 3.1.1, the returned map is actually an
{@code org.springframework.core.annotation.AnnotationAttributes} instance, however the Map signature of this
methodhas
been preserved for binary compatibility.
@param annotation the annotation to retrieve the attributes for
@param classValuesAsString whether to turn Class references into Strings (for
compatibility with {@code org.springframework.core.type.AnnotationMetadata} or to
preserve them as Class references
@return the Map of annotation attributes, with attribute names as keys and
corresponding attribute values as values | [
"Retrieve",
"the",
"given",
"annotation",
"s",
"attributes",
"as",
"a",
"Map",
".",
"Equivalent",
"to",
"calling",
"{"
] | train | https://github.com/netceteragroup/valdr-bean-validation/blob/3f49f1357c575a11331be2de867cf47809a83823/valdr-bean-validation/src/main/java/com/github/valdr/thirdparty/spring/AnnotationUtils.java#L337-L339 |
drewnoakes/metadata-extractor | Source/com/drew/imaging/ImageMetadataReader.java | ImageMetadataReader.readMetadata | @NotNull
public static Metadata readMetadata(@NotNull final InputStream inputStream, final long streamLength, final FileType fileType) throws IOException, ImageProcessingException {
"""
Reads metadata from an {@link InputStream} of known length and file type.
@param inputStream a stream from which the file data may be read. The stream must be positioned at the
beginning of the file's data.
@param streamLength the length of the stream, if known, otherwise -1.
@param fileType the file type of the data stream.
@return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
@throws ImageProcessingException if the file type is unknown, or for general processing errors.
"""
switch (fileType) {
case Jpeg:
return JpegMetadataReader.readMetadata(inputStream);
case Tiff:
case Arw:
case Cr2:
case Nef:
case Orf:
case Rw2:
return TiffMetadataReader.readMetadata(new RandomAccessStreamReader(inputStream, RandomAccessStreamReader.DEFAULT_CHUNK_LENGTH, streamLength));
case Psd:
return PsdMetadataReader.readMetadata(inputStream);
case Png:
return PngMetadataReader.readMetadata(inputStream);
case Bmp:
return BmpMetadataReader.readMetadata(inputStream);
case Gif:
return GifMetadataReader.readMetadata(inputStream);
case Ico:
return IcoMetadataReader.readMetadata(inputStream);
case Pcx:
return PcxMetadataReader.readMetadata(inputStream);
case WebP:
return WebpMetadataReader.readMetadata(inputStream);
case Raf:
return RafMetadataReader.readMetadata(inputStream);
case Avi:
return AviMetadataReader.readMetadata(inputStream);
case Wav:
return WavMetadataReader.readMetadata(inputStream);
case Mov:
return QuickTimeMetadataReader.readMetadata(inputStream);
case Mp4:
return Mp4MetadataReader.readMetadata(inputStream);
case Mp3:
return Mp3MetadataReader.readMetadata(inputStream);
case Eps:
return EpsMetadataReader.readMetadata(inputStream);
case Heif:
return HeifMetadataReader.readMetadata(inputStream);
case Unknown:
throw new ImageProcessingException("File format could not be determined");
default:
return new Metadata();
}
} | java | @NotNull
public static Metadata readMetadata(@NotNull final InputStream inputStream, final long streamLength, final FileType fileType) throws IOException, ImageProcessingException
{
switch (fileType) {
case Jpeg:
return JpegMetadataReader.readMetadata(inputStream);
case Tiff:
case Arw:
case Cr2:
case Nef:
case Orf:
case Rw2:
return TiffMetadataReader.readMetadata(new RandomAccessStreamReader(inputStream, RandomAccessStreamReader.DEFAULT_CHUNK_LENGTH, streamLength));
case Psd:
return PsdMetadataReader.readMetadata(inputStream);
case Png:
return PngMetadataReader.readMetadata(inputStream);
case Bmp:
return BmpMetadataReader.readMetadata(inputStream);
case Gif:
return GifMetadataReader.readMetadata(inputStream);
case Ico:
return IcoMetadataReader.readMetadata(inputStream);
case Pcx:
return PcxMetadataReader.readMetadata(inputStream);
case WebP:
return WebpMetadataReader.readMetadata(inputStream);
case Raf:
return RafMetadataReader.readMetadata(inputStream);
case Avi:
return AviMetadataReader.readMetadata(inputStream);
case Wav:
return WavMetadataReader.readMetadata(inputStream);
case Mov:
return QuickTimeMetadataReader.readMetadata(inputStream);
case Mp4:
return Mp4MetadataReader.readMetadata(inputStream);
case Mp3:
return Mp3MetadataReader.readMetadata(inputStream);
case Eps:
return EpsMetadataReader.readMetadata(inputStream);
case Heif:
return HeifMetadataReader.readMetadata(inputStream);
case Unknown:
throw new ImageProcessingException("File format could not be determined");
default:
return new Metadata();
}
} | [
"@",
"NotNull",
"public",
"static",
"Metadata",
"readMetadata",
"(",
"@",
"NotNull",
"final",
"InputStream",
"inputStream",
",",
"final",
"long",
"streamLength",
",",
"final",
"FileType",
"fileType",
")",
"throws",
"IOException",
",",
"ImageProcessingException",
"{"... | Reads metadata from an {@link InputStream} of known length and file type.
@param inputStream a stream from which the file data may be read. The stream must be positioned at the
beginning of the file's data.
@param streamLength the length of the stream, if known, otherwise -1.
@param fileType the file type of the data stream.
@return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
@throws ImageProcessingException if the file type is unknown, or for general processing errors. | [
"Reads",
"metadata",
"from",
"an",
"{",
"@link",
"InputStream",
"}",
"of",
"known",
"length",
"and",
"file",
"type",
"."
] | train | https://github.com/drewnoakes/metadata-extractor/blob/a958e0b61b50e590731b3be1dca8df8e21ebd43c/Source/com/drew/imaging/ImageMetadataReader.java#L142-L190 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/RestSpec.java | RestSpec.sendRequest | @When("^I send a '(.+?)' request to '(.+?)'( with user and password '(.+:.+?)')? based on '([^:]+?)'( as '(json|string|gov)')? with:$")
public void sendRequest(String requestType, String endPoint, String foo, String loginInfo, String baseData, String baz, String type, DataTable modifications) throws Exception {
"""
Send a request of the type specified
@param requestType type of request to be sent. Possible values:
GET|DELETE|POST|PUT|CONNECT|PATCH|HEAD|OPTIONS|REQUEST|TRACE
@param endPoint end point to be used
@param foo parameter generated by cucumber because of the optional expression
@param baseData path to file containing the schema to be used
@param type element to read from file (element should contain a json)
@param modifications DataTable containing the modifications to be done to the
base schema element. Syntax will be:
{@code
| <key path> | <type of modification> | <new value> |
}
where:
key path: path to the key to be modified
type of modification: DELETE|ADD|UPDATE
new value: in case of UPDATE or ADD, new value to be used
for example:
if the element read is {"key1": "value1", "key2": {"key3": "value3"}}
and we want to modify the value in "key3" with "new value3"
the modification will be:
| key2.key3 | UPDATE | "new value3" |
being the result of the modification: {"key1": "value1", "key2": {"key3": "new value3"}}
@throws Exception
"""
// Retrieve data
String retrievedData = commonspec.retrieveData(baseData, type);
// Modify data
commonspec.getLogger().debug("Modifying data {} as {}", retrievedData, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString();
String user = null;
String password = null;
if (loginInfo != null) {
user = loginInfo.substring(0, loginInfo.indexOf(':'));
password = loginInfo.substring(loginInfo.indexOf(':') + 1, loginInfo.length());
}
commonspec.getLogger().debug("Generating request {} to {} with data {} as {}", requestType, endPoint, modifiedData, type);
Future<Response> response = commonspec.generateRequest(requestType, false, user, password, endPoint, modifiedData, type, "");
// Save response
commonspec.getLogger().debug("Saving response");
commonspec.setResponse(requestType, response.get());
} | java | @When("^I send a '(.+?)' request to '(.+?)'( with user and password '(.+:.+?)')? based on '([^:]+?)'( as '(json|string|gov)')? with:$")
public void sendRequest(String requestType, String endPoint, String foo, String loginInfo, String baseData, String baz, String type, DataTable modifications) throws Exception {
// Retrieve data
String retrievedData = commonspec.retrieveData(baseData, type);
// Modify data
commonspec.getLogger().debug("Modifying data {} as {}", retrievedData, type);
String modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString();
String user = null;
String password = null;
if (loginInfo != null) {
user = loginInfo.substring(0, loginInfo.indexOf(':'));
password = loginInfo.substring(loginInfo.indexOf(':') + 1, loginInfo.length());
}
commonspec.getLogger().debug("Generating request {} to {} with data {} as {}", requestType, endPoint, modifiedData, type);
Future<Response> response = commonspec.generateRequest(requestType, false, user, password, endPoint, modifiedData, type, "");
// Save response
commonspec.getLogger().debug("Saving response");
commonspec.setResponse(requestType, response.get());
} | [
"@",
"When",
"(",
"\"^I send a '(.+?)' request to '(.+?)'( with user and password '(.+:.+?)')? based on '([^:]+?)'( as '(json|string|gov)')? with:$\"",
")",
"public",
"void",
"sendRequest",
"(",
"String",
"requestType",
",",
"String",
"endPoint",
",",
"String",
"foo",
",",
"Strin... | Send a request of the type specified
@param requestType type of request to be sent. Possible values:
GET|DELETE|POST|PUT|CONNECT|PATCH|HEAD|OPTIONS|REQUEST|TRACE
@param endPoint end point to be used
@param foo parameter generated by cucumber because of the optional expression
@param baseData path to file containing the schema to be used
@param type element to read from file (element should contain a json)
@param modifications DataTable containing the modifications to be done to the
base schema element. Syntax will be:
{@code
| <key path> | <type of modification> | <new value> |
}
where:
key path: path to the key to be modified
type of modification: DELETE|ADD|UPDATE
new value: in case of UPDATE or ADD, new value to be used
for example:
if the element read is {"key1": "value1", "key2": {"key3": "value3"}}
and we want to modify the value in "key3" with "new value3"
the modification will be:
| key2.key3 | UPDATE | "new value3" |
being the result of the modification: {"key1": "value1", "key2": {"key3": "new value3"}}
@throws Exception | [
"Send",
"a",
"request",
"of",
"the",
"type",
"specified"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/RestSpec.java#L204-L227 |
sdl/Testy | src/main/java/com/sdl/selenium/utils/config/WebDriverConfig.java | WebDriverConfig.getWebDriver | public static WebDriver getWebDriver(String browserProperties, URL remoteUrl) throws IOException {
"""
Create and return new WebDriver or RemoteWebDriver based on properties file
@param browserProperties path to browser.properties
@param remoteUrl url
@return WebDriver
@throws IOException exception
"""
URL resource = Thread.currentThread().getContextClassLoader().getResource(browserProperties);
log.debug("File: {} " + (resource != null ? "exists" : "does not exist"), browserProperties);
if (resource != null) {
Browser browser = findBrowser(resource.openStream());
return getDriver(browser, resource.openStream(), remoteUrl);
}
return null;
} | java | public static WebDriver getWebDriver(String browserProperties, URL remoteUrl) throws IOException {
URL resource = Thread.currentThread().getContextClassLoader().getResource(browserProperties);
log.debug("File: {} " + (resource != null ? "exists" : "does not exist"), browserProperties);
if (resource != null) {
Browser browser = findBrowser(resource.openStream());
return getDriver(browser, resource.openStream(), remoteUrl);
}
return null;
} | [
"public",
"static",
"WebDriver",
"getWebDriver",
"(",
"String",
"browserProperties",
",",
"URL",
"remoteUrl",
")",
"throws",
"IOException",
"{",
"URL",
"resource",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
".",
"getRe... | Create and return new WebDriver or RemoteWebDriver based on properties file
@param browserProperties path to browser.properties
@param remoteUrl url
@return WebDriver
@throws IOException exception | [
"Create",
"and",
"return",
"new",
"WebDriver",
"or",
"RemoteWebDriver",
"based",
"on",
"properties",
"file"
] | train | https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/utils/config/WebDriverConfig.java#L173-L183 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/variable/dictionary/AbstractDataDictionary.java | AbstractDataDictionary.convertIfNecessary | protected <T> T convertIfNecessary(String value, T originalValue) {
"""
Convert to original value type if necessary.
@param value
@param originalValue
@param <T>
@return
"""
if (originalValue == null) {
return (T) value;
}
return TypeConversionUtils.convertIfNecessary(value, (Class<T>) originalValue.getClass());
} | java | protected <T> T convertIfNecessary(String value, T originalValue) {
if (originalValue == null) {
return (T) value;
}
return TypeConversionUtils.convertIfNecessary(value, (Class<T>) originalValue.getClass());
} | [
"protected",
"<",
"T",
">",
"T",
"convertIfNecessary",
"(",
"String",
"value",
",",
"T",
"originalValue",
")",
"{",
"if",
"(",
"originalValue",
"==",
"null",
")",
"{",
"return",
"(",
"T",
")",
"value",
";",
"}",
"return",
"TypeConversionUtils",
".",
"con... | Convert to original value type if necessary.
@param value
@param originalValue
@param <T>
@return | [
"Convert",
"to",
"original",
"value",
"type",
"if",
"necessary",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/variable/dictionary/AbstractDataDictionary.java#L62-L68 |
mongodb/stitch-android-sdk | core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/DataSynchronizer.java | DataSynchronizer.deleteOneFromRemote | @CheckReturnValue
@Nullable
private LocalSyncWriteModelContainer deleteOneFromRemote(
final NamespaceSynchronizationConfig nsConfig,
final BsonValue documentId
) {
"""
Deletes a single synchronized document by its given id. No deletion will occur if the _id is
not being synchronized.
@param nsConfig the namespace synchronization config of the namespace where the document
lives.
@param documentId the _id of the document.
"""
final MongoNamespace namespace = nsConfig.getNamespace();
final Lock lock = this.syncConfig.getNamespaceConfig(namespace).getLock().writeLock();
lock.lock();
final CoreDocumentSynchronizationConfig config;
try {
config = syncConfig.getSynchronizedDocument(namespace, documentId);
if (config == null) {
return null;
}
} finally {
lock.unlock();
}
eventDispatcher.emitEvent(nsConfig,
ChangeEvents.changeEventForLocalDelete(namespace, documentId, false));
return desyncDocumentsFromRemote(nsConfig, documentId);
} | java | @CheckReturnValue
@Nullable
private LocalSyncWriteModelContainer deleteOneFromRemote(
final NamespaceSynchronizationConfig nsConfig,
final BsonValue documentId
) {
final MongoNamespace namespace = nsConfig.getNamespace();
final Lock lock = this.syncConfig.getNamespaceConfig(namespace).getLock().writeLock();
lock.lock();
final CoreDocumentSynchronizationConfig config;
try {
config = syncConfig.getSynchronizedDocument(namespace, documentId);
if (config == null) {
return null;
}
} finally {
lock.unlock();
}
eventDispatcher.emitEvent(nsConfig,
ChangeEvents.changeEventForLocalDelete(namespace, documentId, false));
return desyncDocumentsFromRemote(nsConfig, documentId);
} | [
"@",
"CheckReturnValue",
"@",
"Nullable",
"private",
"LocalSyncWriteModelContainer",
"deleteOneFromRemote",
"(",
"final",
"NamespaceSynchronizationConfig",
"nsConfig",
",",
"final",
"BsonValue",
"documentId",
")",
"{",
"final",
"MongoNamespace",
"namespace",
"=",
"nsConfig"... | Deletes a single synchronized document by its given id. No deletion will occur if the _id is
not being synchronized.
@param nsConfig the namespace synchronization config of the namespace where the document
lives.
@param documentId the _id of the document. | [
"Deletes",
"a",
"single",
"synchronized",
"document",
"by",
"its",
"given",
"id",
".",
"No",
"deletion",
"will",
"occur",
"if",
"the",
"_id",
"is",
"not",
"being",
"synchronized",
"."
] | train | https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/DataSynchronizer.java#L2915-L2936 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/value/support/AbstractValueModel.java | AbstractValueModel.fireValueChange | protected void fireValueChange(Object oldValue, Object newValue) {
"""
Notifies all listeners that have registered interest for
notification on this event type. The event instance
is lazily created using the parameters passed into
the fire method.
@param oldValue the float value before the change
@param newValue the float value after the change
"""
if (hasValueChanged(oldValue, newValue)) {
fireValueChangeEvent(oldValue, newValue);
}
} | java | protected void fireValueChange(Object oldValue, Object newValue) {
if (hasValueChanged(oldValue, newValue)) {
fireValueChangeEvent(oldValue, newValue);
}
} | [
"protected",
"void",
"fireValueChange",
"(",
"Object",
"oldValue",
",",
"Object",
"newValue",
")",
"{",
"if",
"(",
"hasValueChanged",
"(",
"oldValue",
",",
"newValue",
")",
")",
"{",
"fireValueChangeEvent",
"(",
"oldValue",
",",
"newValue",
")",
";",
"}",
"}... | Notifies all listeners that have registered interest for
notification on this event type. The event instance
is lazily created using the parameters passed into
the fire method.
@param oldValue the float value before the change
@param newValue the float value after the change | [
"Notifies",
"all",
"listeners",
"that",
"have",
"registered",
"interest",
"for",
"notification",
"on",
"this",
"event",
"type",
".",
"The",
"event",
"instance",
"is",
"lazily",
"created",
"using",
"the",
"parameters",
"passed",
"into",
"the",
"fire",
"method",
... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/binding/value/support/AbstractValueModel.java#L143-L147 |
alkacon/opencms-core | src/org/opencms/jsp/util/CmsJspImageBean.java | CmsJspImageBean.addHiDpiImage | public void addHiDpiImage(String factor, CmsJspImageBean image) {
"""
adds a CmsJspImageBean as hi-DPI variant to this image
@param factor the variant multiplier, e.g. "2x" (the common retina multiplier)
@param image the image to be used for this variant
"""
if (m_hiDpiImages == null) {
m_hiDpiImages = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleHiDpiTransformer());
}
m_hiDpiImages.put(factor, image);
} | java | public void addHiDpiImage(String factor, CmsJspImageBean image) {
if (m_hiDpiImages == null) {
m_hiDpiImages = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleHiDpiTransformer());
}
m_hiDpiImages.put(factor, image);
} | [
"public",
"void",
"addHiDpiImage",
"(",
"String",
"factor",
",",
"CmsJspImageBean",
"image",
")",
"{",
"if",
"(",
"m_hiDpiImages",
"==",
"null",
")",
"{",
"m_hiDpiImages",
"=",
"CmsCollectionsGenericWrapper",
".",
"createLazyMap",
"(",
"new",
"CmsScaleHiDpiTransform... | adds a CmsJspImageBean as hi-DPI variant to this image
@param factor the variant multiplier, e.g. "2x" (the common retina multiplier)
@param image the image to be used for this variant | [
"adds",
"a",
"CmsJspImageBean",
"as",
"hi",
"-",
"DPI",
"variant",
"to",
"this",
"image"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspImageBean.java#L362-L368 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/event/RecordChangedHandler.java | RecordChangedHandler.setTemporaryKeyField | public void setTemporaryKeyField() {
"""
Set up/do the remote criteria.
@param strbFilter The SQL query string to add to.
@param bIncludeFileName Include the file name with this query?
@param vParamList The param list to add the raw data to (for prepared statements).
@return True if you should not skip this record (does a check on the local data).
"""
FieldDataScratchHandler fieldDataScratchHandler = (FieldDataScratchHandler)m_field.getListener(FieldDataScratchHandler.class);
Record record = this.getOwner();
KeyArea keyArea = record.getKeyArea(0);
if (keyArea.getKeyFields(false, true) == 1)
{
if (m_fakeKeyField == null)
{
m_fakeKeyField = new KeyField(keyArea, m_field, DBConstants.ASCENDING);
m_fakeKeyField.setIsTemporary(true);
}
else
keyArea.addKeyField(m_fakeKeyField);
}
BaseField paramField = m_fakeKeyField.getField(DBConstants.TEMP_KEY_AREA);
paramField.setData(fieldDataScratchHandler.getOriginalData());
Utility.getLogger().info("Set temp key field: " + paramField.toString());
} | java | public void setTemporaryKeyField()
{
FieldDataScratchHandler fieldDataScratchHandler = (FieldDataScratchHandler)m_field.getListener(FieldDataScratchHandler.class);
Record record = this.getOwner();
KeyArea keyArea = record.getKeyArea(0);
if (keyArea.getKeyFields(false, true) == 1)
{
if (m_fakeKeyField == null)
{
m_fakeKeyField = new KeyField(keyArea, m_field, DBConstants.ASCENDING);
m_fakeKeyField.setIsTemporary(true);
}
else
keyArea.addKeyField(m_fakeKeyField);
}
BaseField paramField = m_fakeKeyField.getField(DBConstants.TEMP_KEY_AREA);
paramField.setData(fieldDataScratchHandler.getOriginalData());
Utility.getLogger().info("Set temp key field: " + paramField.toString());
} | [
"public",
"void",
"setTemporaryKeyField",
"(",
")",
"{",
"FieldDataScratchHandler",
"fieldDataScratchHandler",
"=",
"(",
"FieldDataScratchHandler",
")",
"m_field",
".",
"getListener",
"(",
"FieldDataScratchHandler",
".",
"class",
")",
";",
"Record",
"record",
"=",
"th... | Set up/do the remote criteria.
@param strbFilter The SQL query string to add to.
@param bIncludeFileName Include the file name with this query?
@param vParamList The param list to add the raw data to (for prepared statements).
@return True if you should not skip this record (does a check on the local data). | [
"Set",
"up",
"/",
"do",
"the",
"remote",
"criteria",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/event/RecordChangedHandler.java#L195-L213 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IntegerExtensions.java | IntegerExtensions.operator_greaterThanDoubleDot | @Pure
@Inline(value="new $3($1, $2, false)", imported=ExclusiveRange.class, statementExpression=false)
public static ExclusiveRange operator_greaterThanDoubleDot(final int a, final int b) {
"""
The <code>>..</code> operator yields an {@link ExclusiveRange} that decrements from a
(exclusive) down to b.
@param a the start of the range (exclusive).
@param b the end of the range.
@return a decrementing {@link ExclusiveRange}. Never <code>null</code>.
@since 2.4
"""
return new ExclusiveRange(a, b, false);
} | java | @Pure
@Inline(value="new $3($1, $2, false)", imported=ExclusiveRange.class, statementExpression=false)
public static ExclusiveRange operator_greaterThanDoubleDot(final int a, final int b) {
return new ExclusiveRange(a, b, false);
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"new $3($1, $2, false)\"",
",",
"imported",
"=",
"ExclusiveRange",
".",
"class",
",",
"statementExpression",
"=",
"false",
")",
"public",
"static",
"ExclusiveRange",
"operator_greaterThanDoubleDot",
"(",
"final",
"int... | The <code>>..</code> operator yields an {@link ExclusiveRange} that decrements from a
(exclusive) down to b.
@param a the start of the range (exclusive).
@param b the end of the range.
@return a decrementing {@link ExclusiveRange}. Never <code>null</code>.
@since 2.4 | [
"The",
"<code",
">",
">",
";",
"..",
"<",
"/",
"code",
">",
"operator",
"yields",
"an",
"{",
"@link",
"ExclusiveRange",
"}",
"that",
"decrements",
"from",
"a",
"(",
"exclusive",
")",
"down",
"to",
"b",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IntegerExtensions.java#L61-L65 |
jbossas/jboss-vfs | src/main/java/org/jboss/vfs/VFSUtils.java | VFSUtils.writeFile | public static void writeFile(VirtualFile virtualFile, InputStream is) throws IOException {
"""
Write the content from the given {@link InputStream} to the given virtual file, replacing its current contents (if any) or creating a new file if
one does not exist.
@param virtualFile the virtual file to write
@param is the input stream
@throws IOException if an error occurs
"""
final File file = virtualFile.getPhysicalFile();
file.getParentFile().mkdirs();
final FileOutputStream fos = new FileOutputStream(file);
copyStreamAndClose(is, fos);
} | java | public static void writeFile(VirtualFile virtualFile, InputStream is) throws IOException {
final File file = virtualFile.getPhysicalFile();
file.getParentFile().mkdirs();
final FileOutputStream fos = new FileOutputStream(file);
copyStreamAndClose(is, fos);
} | [
"public",
"static",
"void",
"writeFile",
"(",
"VirtualFile",
"virtualFile",
",",
"InputStream",
"is",
")",
"throws",
"IOException",
"{",
"final",
"File",
"file",
"=",
"virtualFile",
".",
"getPhysicalFile",
"(",
")",
";",
"file",
".",
"getParentFile",
"(",
")",... | Write the content from the given {@link InputStream} to the given virtual file, replacing its current contents (if any) or creating a new file if
one does not exist.
@param virtualFile the virtual file to write
@param is the input stream
@throws IOException if an error occurs | [
"Write",
"the",
"content",
"from",
"the",
"given",
"{",
"@link",
"InputStream",
"}",
"to",
"the",
"given",
"virtual",
"file",
"replacing",
"its",
"current",
"contents",
"(",
"if",
"any",
")",
"or",
"creating",
"a",
"new",
"file",
"if",
"one",
"does",
"no... | train | https://github.com/jbossas/jboss-vfs/blob/420f4b896d6178ee5f6758f3421e9f350d2b8ab5/src/main/java/org/jboss/vfs/VFSUtils.java#L471-L476 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/TextBuilder.java | TextBuilder.parStyledContent | public TextBuilder parStyledContent(final String text, final TextStyle ts) {
"""
Create a new paragraph with a text content
@param text the text
@param ts the style
@return this for fluent style
"""
return this.par().styledSpan(text, ts);
} | java | public TextBuilder parStyledContent(final String text, final TextStyle ts) {
return this.par().styledSpan(text, ts);
} | [
"public",
"TextBuilder",
"parStyledContent",
"(",
"final",
"String",
"text",
",",
"final",
"TextStyle",
"ts",
")",
"{",
"return",
"this",
".",
"par",
"(",
")",
".",
"styledSpan",
"(",
"text",
",",
"ts",
")",
";",
"}"
] | Create a new paragraph with a text content
@param text the text
@param ts the style
@return this for fluent style | [
"Create",
"a",
"new",
"paragraph",
"with",
"a",
"text",
"content"
] | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/TextBuilder.java#L98-L100 |
ModeShape/modeshape | modeshape-common/src/main/java/org/modeshape/common/util/Reflection.java | Reflection.invokeGetterMethodOnTarget | public Object invokeGetterMethodOnTarget( String javaPropertyName,
Object target )
throws NoSuchMethodException, SecurityException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
"""
Find and execute the getter method on the target class for the supplied property name. If no such method is found, a
NoSuchMethodException is thrown.
@param javaPropertyName the name of the property whose getter is to be invoked, in the order they are to be tried
@param target the object on which the method is to be invoked
@return the property value (the result of the getter method call)
@throws NoSuchMethodException if a matching method is not found.
@throws SecurityException if access to the information is denied.
@throws InvocationTargetException
@throws IllegalAccessException
@throws IllegalArgumentException
"""
String[] methodNamesArray = findMethodNames("get" + javaPropertyName);
if (methodNamesArray.length <= 0) {
// Try 'is' getter ...
methodNamesArray = findMethodNames("is" + javaPropertyName);
}
if (methodNamesArray.length <= 0) {
// Try 'are' getter ...
methodNamesArray = findMethodNames("are" + javaPropertyName);
}
return invokeBestMethodOnTarget(methodNamesArray, target);
} | java | public Object invokeGetterMethodOnTarget( String javaPropertyName,
Object target )
throws NoSuchMethodException, SecurityException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
String[] methodNamesArray = findMethodNames("get" + javaPropertyName);
if (methodNamesArray.length <= 0) {
// Try 'is' getter ...
methodNamesArray = findMethodNames("is" + javaPropertyName);
}
if (methodNamesArray.length <= 0) {
// Try 'are' getter ...
methodNamesArray = findMethodNames("are" + javaPropertyName);
}
return invokeBestMethodOnTarget(methodNamesArray, target);
} | [
"public",
"Object",
"invokeGetterMethodOnTarget",
"(",
"String",
"javaPropertyName",
",",
"Object",
"target",
")",
"throws",
"NoSuchMethodException",
",",
"SecurityException",
",",
"IllegalArgumentException",
",",
"IllegalAccessException",
",",
"InvocationTargetException",
"{... | Find and execute the getter method on the target class for the supplied property name. If no such method is found, a
NoSuchMethodException is thrown.
@param javaPropertyName the name of the property whose getter is to be invoked, in the order they are to be tried
@param target the object on which the method is to be invoked
@return the property value (the result of the getter method call)
@throws NoSuchMethodException if a matching method is not found.
@throws SecurityException if access to the information is denied.
@throws InvocationTargetException
@throws IllegalAccessException
@throws IllegalArgumentException | [
"Find",
"and",
"execute",
"the",
"getter",
"method",
"on",
"the",
"target",
"class",
"for",
"the",
"supplied",
"property",
"name",
".",
"If",
"no",
"such",
"method",
"is",
"found",
"a",
"NoSuchMethodException",
"is",
"thrown",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/Reflection.java#L633-L647 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/Utils.java | Utils.getUriFromResource | public static Uri getUriFromResource(@NonNull Context context, @AnyRes int resId) throws Resources.NotFoundException {
"""
Get uri to any resource type
@param context - context
@param resId - resource id
@throws Resources.NotFoundException if the given ID does not exist.
@return - Uri to resource by given id
"""
/** Return a Resources instance for your application's package. */
Resources res = context.getResources();
/**
* Creates a Uri which parses the given encoded URI string.
* @param uriString an RFC 2396-compliant, encoded URI
* @throws NullPointerException if uriString is null
* @return Uri for this given uri string
*/
/** return uri */
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + res.getResourcePackageName(resId)
+ '/' + res.getResourceTypeName(resId)
+ '/' + res.getResourceEntryName(resId));
} | java | public static Uri getUriFromResource(@NonNull Context context, @AnyRes int resId) throws Resources.NotFoundException {
/** Return a Resources instance for your application's package. */
Resources res = context.getResources();
/**
* Creates a Uri which parses the given encoded URI string.
* @param uriString an RFC 2396-compliant, encoded URI
* @throws NullPointerException if uriString is null
* @return Uri for this given uri string
*/
/** return uri */
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + res.getResourcePackageName(resId)
+ '/' + res.getResourceTypeName(resId)
+ '/' + res.getResourceEntryName(resId));
} | [
"public",
"static",
"Uri",
"getUriFromResource",
"(",
"@",
"NonNull",
"Context",
"context",
",",
"@",
"AnyRes",
"int",
"resId",
")",
"throws",
"Resources",
".",
"NotFoundException",
"{",
"/** Return a Resources instance for your application's package. */",
"Resources",
"r... | Get uri to any resource type
@param context - context
@param resId - resource id
@throws Resources.NotFoundException if the given ID does not exist.
@return - Uri to resource by given id | [
"Get",
"uri",
"to",
"any",
"resource",
"type"
] | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/util/Utils.java#L101-L115 |
mygreen/excel-cellformatter | src/main/java/com/github/mygreen/cellformatter/ConditionFormatterFactory.java | ConditionFormatterFactory.setupConditionOperator | protected ConditionOperator setupConditionOperator(final ConditionFormatter formatter, final Token.Condition token) {
"""
{@literal '[<=1000]'}などの数値の条件を組み立てる
@param formatter 現在の組み立て中のフォーマッタのインスタンス。
@param token 条件式のトークン。
@return 演算子の条件式。
@throws IllegalArgumentException 処理対象の条件として一致しない場合
"""
final Matcher matcher = PATTERN_CONDITION_OPERATOR.matcher(token.getValue());
if(!matcher.matches()) {
throw new IllegalArgumentException("not match condition:" + token.getValue());
}
final String operator = matcher.group(1);
final String number = matcher.group(2);
final double condition = Double.valueOf(number);
final ConditionOperator conditionOperator;
switch(operator) {
case "=":
conditionOperator = new ConditionOperator.Equal(condition);
break;
case "<>":
conditionOperator = new ConditionOperator.NotEqual(condition);
break;
case ">":
conditionOperator = new ConditionOperator.GreaterThan(condition);
break;
case "<":
conditionOperator = new ConditionOperator.LessThan(condition);
break;
case ">=":
conditionOperator = new ConditionOperator.GreaterEqual(condition);
break;
case "<=":
conditionOperator = new ConditionOperator.LessEqual(condition);
break;
default:
logger.warn("unknown operator : {}", operator);
conditionOperator = ConditionOperator.ALL;
break;
}
formatter.setOperator(conditionOperator);
return conditionOperator;
} | java | protected ConditionOperator setupConditionOperator(final ConditionFormatter formatter, final Token.Condition token) {
final Matcher matcher = PATTERN_CONDITION_OPERATOR.matcher(token.getValue());
if(!matcher.matches()) {
throw new IllegalArgumentException("not match condition:" + token.getValue());
}
final String operator = matcher.group(1);
final String number = matcher.group(2);
final double condition = Double.valueOf(number);
final ConditionOperator conditionOperator;
switch(operator) {
case "=":
conditionOperator = new ConditionOperator.Equal(condition);
break;
case "<>":
conditionOperator = new ConditionOperator.NotEqual(condition);
break;
case ">":
conditionOperator = new ConditionOperator.GreaterThan(condition);
break;
case "<":
conditionOperator = new ConditionOperator.LessThan(condition);
break;
case ">=":
conditionOperator = new ConditionOperator.GreaterEqual(condition);
break;
case "<=":
conditionOperator = new ConditionOperator.LessEqual(condition);
break;
default:
logger.warn("unknown operator : {}", operator);
conditionOperator = ConditionOperator.ALL;
break;
}
formatter.setOperator(conditionOperator);
return conditionOperator;
} | [
"protected",
"ConditionOperator",
"setupConditionOperator",
"(",
"final",
"ConditionFormatter",
"formatter",
",",
"final",
"Token",
".",
"Condition",
"token",
")",
"{",
"final",
"Matcher",
"matcher",
"=",
"PATTERN_CONDITION_OPERATOR",
".",
"matcher",
"(",
"token",
"."... | {@literal '[<=1000]'}などの数値の条件を組み立てる
@param formatter 現在の組み立て中のフォーマッタのインスタンス。
@param token 条件式のトークン。
@return 演算子の条件式。
@throws IllegalArgumentException 処理対象の条件として一致しない場合 | [
"{"
] | train | https://github.com/mygreen/excel-cellformatter/blob/e802af273d49889500591e03799c9262cbf29185/src/main/java/com/github/mygreen/cellformatter/ConditionFormatterFactory.java#L122-L162 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/io/BufferUtils.java | BufferUtils.writeBufferToFile | public static void writeBufferToFile(String path, byte[] buffer) throws IOException {
"""
Writes buffer to the given file path.
@param path file path to write the data
@param buffer raw data
"""
try (FileOutputStream os = new FileOutputStream(path)) {
os.write(buffer);
}
} | java | public static void writeBufferToFile(String path, byte[] buffer) throws IOException {
try (FileOutputStream os = new FileOutputStream(path)) {
os.write(buffer);
}
} | [
"public",
"static",
"void",
"writeBufferToFile",
"(",
"String",
"path",
",",
"byte",
"[",
"]",
"buffer",
")",
"throws",
"IOException",
"{",
"try",
"(",
"FileOutputStream",
"os",
"=",
"new",
"FileOutputStream",
"(",
"path",
")",
")",
"{",
"os",
".",
"write"... | Writes buffer to the given file path.
@param path file path to write the data
@param buffer raw data | [
"Writes",
"buffer",
"to",
"the",
"given",
"file",
"path",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/BufferUtils.java#L273-L277 |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java | JCudnn.cudnnBatchNormalizationBackward | public static int cudnnBatchNormalizationBackward(
cudnnHandle handle,
int mode,
Pointer alphaDataDiff,
Pointer betaDataDiff,
Pointer alphaParamDiff,
Pointer betaParamDiff,
cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */
Pointer x,
cudnnTensorDescriptor dyDesc,
Pointer dy,
cudnnTensorDescriptor dxDesc,
Pointer dx,
/** Shared tensor desc for the 4 tensors below */
cudnnTensorDescriptor dBnScaleBiasDesc,
Pointer bnScale, /** bnBias doesn't affect backpropagation */
/** scale and bias diff are not backpropagated below this layer */
Pointer dBnScaleResult,
Pointer dBnBiasResult,
/** Same epsilon as forward pass */
double epsilon,
/** Optionally cached intermediate results from
forward pass */
Pointer savedMean,
Pointer savedInvVariance) {
"""
Performs backward pass of Batch Normalization layer. Returns x gradient,
bnScale gradient and bnBias gradient
"""
return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));
} | java | public static int cudnnBatchNormalizationBackward(
cudnnHandle handle,
int mode,
Pointer alphaDataDiff,
Pointer betaDataDiff,
Pointer alphaParamDiff,
Pointer betaParamDiff,
cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */
Pointer x,
cudnnTensorDescriptor dyDesc,
Pointer dy,
cudnnTensorDescriptor dxDesc,
Pointer dx,
/** Shared tensor desc for the 4 tensors below */
cudnnTensorDescriptor dBnScaleBiasDesc,
Pointer bnScale, /** bnBias doesn't affect backpropagation */
/** scale and bias diff are not backpropagated below this layer */
Pointer dBnScaleResult,
Pointer dBnBiasResult,
/** Same epsilon as forward pass */
double epsilon,
/** Optionally cached intermediate results from
forward pass */
Pointer savedMean,
Pointer savedInvVariance)
{
return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));
} | [
"public",
"static",
"int",
"cudnnBatchNormalizationBackward",
"(",
"cudnnHandle",
"handle",
",",
"int",
"mode",
",",
"Pointer",
"alphaDataDiff",
",",
"Pointer",
"betaDataDiff",
",",
"Pointer",
"alphaParamDiff",
",",
"Pointer",
"betaParamDiff",
",",
"cudnnTensorDescripto... | Performs backward pass of Batch Normalization layer. Returns x gradient,
bnScale gradient and bnBias gradient | [
"Performs",
"backward",
"pass",
"of",
"Batch",
"Normalization",
"layer",
".",
"Returns",
"x",
"gradient",
"bnScale",
"gradient",
"and",
"bnBias",
"gradient"
] | train | https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2487-L2514 |
apache/incubator-atlas | notification/src/main/java/org/apache/atlas/notification/VersionedMessageDeserializer.java | VersionedMessageDeserializer.checkVersion | protected void checkVersion(VersionedMessage<T> versionedMessage, String messageJson) {
"""
Check the message version against the expected version.
@param versionedMessage the versioned message
@param messageJson the notification message json
@throws IncompatibleVersionException if the message version is incompatable with the expected version
"""
int comp = versionedMessage.compareVersion(expectedVersion);
// message has newer version
if (comp > 0) {
String msg =
String.format(VERSION_MISMATCH_MSG, expectedVersion, versionedMessage.getVersion(), messageJson);
notificationLogger.error(msg);
throw new IncompatibleVersionException(msg);
}
// message has older version
if (comp < 0) {
notificationLogger.info(String.format(VERSION_MISMATCH_MSG, expectedVersion, versionedMessage.getVersion(),
messageJson));
}
} | java | protected void checkVersion(VersionedMessage<T> versionedMessage, String messageJson) {
int comp = versionedMessage.compareVersion(expectedVersion);
// message has newer version
if (comp > 0) {
String msg =
String.format(VERSION_MISMATCH_MSG, expectedVersion, versionedMessage.getVersion(), messageJson);
notificationLogger.error(msg);
throw new IncompatibleVersionException(msg);
}
// message has older version
if (comp < 0) {
notificationLogger.info(String.format(VERSION_MISMATCH_MSG, expectedVersion, versionedMessage.getVersion(),
messageJson));
}
} | [
"protected",
"void",
"checkVersion",
"(",
"VersionedMessage",
"<",
"T",
">",
"versionedMessage",
",",
"String",
"messageJson",
")",
"{",
"int",
"comp",
"=",
"versionedMessage",
".",
"compareVersion",
"(",
"expectedVersion",
")",
";",
"// message has newer version",
... | Check the message version against the expected version.
@param versionedMessage the versioned message
@param messageJson the notification message json
@throws IncompatibleVersionException if the message version is incompatable with the expected version | [
"Check",
"the",
"message",
"version",
"against",
"the",
"expected",
"version",
"."
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/notification/src/main/java/org/apache/atlas/notification/VersionedMessageDeserializer.java#L88-L104 |
vvakame/JsonPullParser | jsonpullparser-apt/src/main/java/net/vvakame/apt/AptUtil.java | AptUtil.getPackageName | public static String getPackageName(Elements elementUtils, Element element) {
"""
Returns the package name of the given element.
NB: This method requires the given element has the kind of {@link ElementKind#CLASS}.
@param elementUtils
@param element
@return the package name
@author vvakame
"""
return elementUtils.getPackageOf(element).getQualifiedName().toString();
} | java | public static String getPackageName(Elements elementUtils, Element element) {
return elementUtils.getPackageOf(element).getQualifiedName().toString();
} | [
"public",
"static",
"String",
"getPackageName",
"(",
"Elements",
"elementUtils",
",",
"Element",
"element",
")",
"{",
"return",
"elementUtils",
".",
"getPackageOf",
"(",
"element",
")",
".",
"getQualifiedName",
"(",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Returns the package name of the given element.
NB: This method requires the given element has the kind of {@link ElementKind#CLASS}.
@param elementUtils
@param element
@return the package name
@author vvakame | [
"Returns",
"the",
"package",
"name",
"of",
"the",
"given",
"element",
".",
"NB",
":",
"This",
"method",
"requires",
"the",
"given",
"element",
"has",
"the",
"kind",
"of",
"{"
] | train | https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-apt/src/main/java/net/vvakame/apt/AptUtil.java#L187-L189 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/lang/Validator.java | Validator.validateBirthday | public static <T extends CharSequence> T validateBirthday(T value, String errorMsg) throws ValidateException {
"""
验证验证是否为生日
@param <T> 字符串类型
@param value 值
@param errorMsg 验证错误的信息
@return 验证后的值
@throws ValidateException 验证异常
"""
if (false == isBirthday(value)) {
throw new ValidateException(errorMsg);
}
return value;
} | java | public static <T extends CharSequence> T validateBirthday(T value, String errorMsg) throws ValidateException {
if (false == isBirthday(value)) {
throw new ValidateException(errorMsg);
}
return value;
} | [
"public",
"static",
"<",
"T",
"extends",
"CharSequence",
">",
"T",
"validateBirthday",
"(",
"T",
"value",
",",
"String",
"errorMsg",
")",
"throws",
"ValidateException",
"{",
"if",
"(",
"false",
"==",
"isBirthday",
"(",
"value",
")",
")",
"{",
"throw",
"new... | 验证验证是否为生日
@param <T> 字符串类型
@param value 值
@param errorMsg 验证错误的信息
@return 验证后的值
@throws ValidateException 验证异常 | [
"验证验证是否为生日"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Validator.java#L783-L788 |
tvesalainen/lpg | src/main/java/org/vesalainen/grammar/Grammar.java | Grammar.addRule | public void addRule(ExecutableElement reducer, String nonterminal, String document, boolean synthetic, List<String> rhs) {
"""
Adds new rule if the same rule doesn't exist already.
@param reducer Reducer method.
@param nonterminal Left hand side of the rule.
@param rhs Strings which are either nonterminal names, terminal names or
anonymous terminals. Anonymous terminals are regular expressions inside
apostrophes. E.g '[0-9]+'
"""
Grammar.R rule = new Grammar.R(nonterminal, rhs, reducer, document, synthetic);
if (!ruleSet.contains(rule))
{
rule.number = ruleNumber++;
ruleSet.add(rule);
lhsMap.add(nonterminal, rule);
if (!nonterminalMap.containsKey(nonterminal))
{
Grammar.NT nt = new Grammar.NT(nonterminal);
nonterminalMap.put(nonterminal, nt);
symbolMap.put(nonterminal, nt);
numberMap.put(nt.number, nt);
}
for (String s : rhs)
{
if (isAnonymousTerminal(s))
{
String expression = s.substring(1, s.length()-1);
addAnonymousTerminal(expression);
}
}
}
} | java | public void addRule(ExecutableElement reducer, String nonterminal, String document, boolean synthetic, List<String> rhs)
{
Grammar.R rule = new Grammar.R(nonterminal, rhs, reducer, document, synthetic);
if (!ruleSet.contains(rule))
{
rule.number = ruleNumber++;
ruleSet.add(rule);
lhsMap.add(nonterminal, rule);
if (!nonterminalMap.containsKey(nonterminal))
{
Grammar.NT nt = new Grammar.NT(nonterminal);
nonterminalMap.put(nonterminal, nt);
symbolMap.put(nonterminal, nt);
numberMap.put(nt.number, nt);
}
for (String s : rhs)
{
if (isAnonymousTerminal(s))
{
String expression = s.substring(1, s.length()-1);
addAnonymousTerminal(expression);
}
}
}
} | [
"public",
"void",
"addRule",
"(",
"ExecutableElement",
"reducer",
",",
"String",
"nonterminal",
",",
"String",
"document",
",",
"boolean",
"synthetic",
",",
"List",
"<",
"String",
">",
"rhs",
")",
"{",
"Grammar",
".",
"R",
"rule",
"=",
"new",
"Grammar",
".... | Adds new rule if the same rule doesn't exist already.
@param reducer Reducer method.
@param nonterminal Left hand side of the rule.
@param rhs Strings which are either nonterminal names, terminal names or
anonymous terminals. Anonymous terminals are regular expressions inside
apostrophes. E.g '[0-9]+' | [
"Adds",
"new",
"rule",
"if",
"the",
"same",
"rule",
"doesn",
"t",
"exist",
"already",
"."
] | train | https://github.com/tvesalainen/lpg/blob/0917b8d295e9772b9f8a0affc258a08530cd567a/src/main/java/org/vesalainen/grammar/Grammar.java#L295-L319 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/res/XPATHErrorResources.java | XPATHErrorResources.loadResourceBundle | public static final XPATHErrorResources loadResourceBundle(String className)
throws MissingResourceException {
"""
Return a named ResourceBundle for a particular locale. This method mimics the behavior
of ResourceBundle.getBundle().
@param className Name of local-specific subclass.
@return the ResourceBundle
@throws MissingResourceException
"""
Locale locale = Locale.getDefault();
String suffix = getResourceSuffix(locale);
try
{
// first try with the given locale
return (XPATHErrorResources) ResourceBundle.getBundle(className
+ suffix, locale);
}
catch (MissingResourceException e)
{
try // try to fall back to en_US if we can't load
{
// Since we can't find the localized property file,
// fall back to en_US.
return (XPATHErrorResources) ResourceBundle.getBundle(className,
new Locale("en", "US"));
}
catch (MissingResourceException e2)
{
// Now we are really in trouble.
// very bad, definitely very bad...not going to get very far
throw new MissingResourceException(
"Could not load any resource bundles.", className, "");
}
}
} | java | public static final XPATHErrorResources loadResourceBundle(String className)
throws MissingResourceException
{
Locale locale = Locale.getDefault();
String suffix = getResourceSuffix(locale);
try
{
// first try with the given locale
return (XPATHErrorResources) ResourceBundle.getBundle(className
+ suffix, locale);
}
catch (MissingResourceException e)
{
try // try to fall back to en_US if we can't load
{
// Since we can't find the localized property file,
// fall back to en_US.
return (XPATHErrorResources) ResourceBundle.getBundle(className,
new Locale("en", "US"));
}
catch (MissingResourceException e2)
{
// Now we are really in trouble.
// very bad, definitely very bad...not going to get very far
throw new MissingResourceException(
"Could not load any resource bundles.", className, "");
}
}
} | [
"public",
"static",
"final",
"XPATHErrorResources",
"loadResourceBundle",
"(",
"String",
"className",
")",
"throws",
"MissingResourceException",
"{",
"Locale",
"locale",
"=",
"Locale",
".",
"getDefault",
"(",
")",
";",
"String",
"suffix",
"=",
"getResourceSuffix",
"... | Return a named ResourceBundle for a particular locale. This method mimics the behavior
of ResourceBundle.getBundle().
@param className Name of local-specific subclass.
@return the ResourceBundle
@throws MissingResourceException | [
"Return",
"a",
"named",
"ResourceBundle",
"for",
"a",
"particular",
"locale",
".",
"This",
"method",
"mimics",
"the",
"behavior",
"of",
"ResourceBundle",
".",
"getBundle",
"()",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/res/XPATHErrorResources.java#L944-L977 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java | TheMovieDbApi.getSessionTokenLogin | public TokenAuthorisation getSessionTokenLogin(TokenAuthorisation token, String username, String password) throws MovieDbException {
"""
This method is used to generate a session id for user based
authentication. User must provide their username and password
A session id is required in order to use any of the write methods.
@param token Session token
@param username User's username
@param password User's password
@return TokenAuthorisation
@throws MovieDbException exception
"""
return tmdbAuth.getSessionTokenLogin(token, username, password);
} | java | public TokenAuthorisation getSessionTokenLogin(TokenAuthorisation token, String username, String password) throws MovieDbException {
return tmdbAuth.getSessionTokenLogin(token, username, password);
} | [
"public",
"TokenAuthorisation",
"getSessionTokenLogin",
"(",
"TokenAuthorisation",
"token",
",",
"String",
"username",
",",
"String",
"password",
")",
"throws",
"MovieDbException",
"{",
"return",
"tmdbAuth",
".",
"getSessionTokenLogin",
"(",
"token",
",",
"username",
... | This method is used to generate a session id for user based
authentication. User must provide their username and password
A session id is required in order to use any of the write methods.
@param token Session token
@param username User's username
@param password User's password
@return TokenAuthorisation
@throws MovieDbException exception | [
"This",
"method",
"is",
"used",
"to",
"generate",
"a",
"session",
"id",
"for",
"user",
"based",
"authentication",
".",
"User",
"must",
"provide",
"their",
"username",
"and",
"password"
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L399-L401 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketImageExtensions.java | WicketImageExtensions.getNonCachingImage | public static NonCachingImage getNonCachingImage(final String wicketId,
final String contentType, final byte[] data) {
"""
Gets a non caching image from the given wicketId, contentType and the byte array data.
@param wicketId
the id from the image for the html template.
@param contentType
the content type of the image.
@param data
the data for the image as an byte array.
@return the non caching image
"""
return new NonCachingImage(wicketId, new DatabaseImageResource(contentType, data));
} | java | public static NonCachingImage getNonCachingImage(final String wicketId,
final String contentType, final byte[] data)
{
return new NonCachingImage(wicketId, new DatabaseImageResource(contentType, data));
} | [
"public",
"static",
"NonCachingImage",
"getNonCachingImage",
"(",
"final",
"String",
"wicketId",
",",
"final",
"String",
"contentType",
",",
"final",
"byte",
"[",
"]",
"data",
")",
"{",
"return",
"new",
"NonCachingImage",
"(",
"wicketId",
",",
"new",
"DatabaseIm... | Gets a non caching image from the given wicketId, contentType and the byte array data.
@param wicketId
the id from the image for the html template.
@param contentType
the content type of the image.
@param data
the data for the image as an byte array.
@return the non caching image | [
"Gets",
"a",
"non",
"caching",
"image",
"from",
"the",
"given",
"wicketId",
"contentType",
"and",
"the",
"byte",
"array",
"data",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketImageExtensions.java#L76-L80 |
oaqa/uima-ecd | src/main/java/edu/cmu/lti/oaqa/ecd/driver/SimplePipelineRev803.java | SimplePipelineRev803.runPipeline | public static void runPipeline(final CollectionReaderDescription readerDesc,
final AnalysisEngineDescription... descs) throws UIMAException, IOException {
"""
Run the CollectionReader and AnalysisEngines as a pipeline. After processing all CASes
provided by the reader, the method calls {@link AnalysisEngine#collectionProcessComplete()
collectionProcessComplete()} on the engines, {@link CollectionReader#close() close()} on the
reader and {@link Resource#destroy() destroy()} on the reader and all engines.
@param readerDesc
The CollectionReader that loads the documents into the CAS.
@param descs
Primitive AnalysisEngineDescriptions that process the CAS, in order. If you have a
mix of primitive and aggregate engines, then please create the AnalysisEngines
yourself and call the other runPipeline method.
@throws UIMAException
@throws IOException
"""
// Create the components
final CollectionReader reader = createCollectionReader(readerDesc);
try {
// Run the pipeline
runPipeline(reader, descs);
}
finally {
close(reader);
destroy(reader);
}
} | java | public static void runPipeline(final CollectionReaderDescription readerDesc,
final AnalysisEngineDescription... descs) throws UIMAException, IOException {
// Create the components
final CollectionReader reader = createCollectionReader(readerDesc);
try {
// Run the pipeline
runPipeline(reader, descs);
}
finally {
close(reader);
destroy(reader);
}
} | [
"public",
"static",
"void",
"runPipeline",
"(",
"final",
"CollectionReaderDescription",
"readerDesc",
",",
"final",
"AnalysisEngineDescription",
"...",
"descs",
")",
"throws",
"UIMAException",
",",
"IOException",
"{",
"// Create the components",
"final",
"CollectionReader",... | Run the CollectionReader and AnalysisEngines as a pipeline. After processing all CASes
provided by the reader, the method calls {@link AnalysisEngine#collectionProcessComplete()
collectionProcessComplete()} on the engines, {@link CollectionReader#close() close()} on the
reader and {@link Resource#destroy() destroy()} on the reader and all engines.
@param readerDesc
The CollectionReader that loads the documents into the CAS.
@param descs
Primitive AnalysisEngineDescriptions that process the CAS, in order. If you have a
mix of primitive and aggregate engines, then please create the AnalysisEngines
yourself and call the other runPipeline method.
@throws UIMAException
@throws IOException | [
"Run",
"the",
"CollectionReader",
"and",
"AnalysisEngines",
"as",
"a",
"pipeline",
".",
"After",
"processing",
"all",
"CASes",
"provided",
"by",
"the",
"reader",
"the",
"method",
"calls",
"{",
"@link",
"AnalysisEngine#collectionProcessComplete",
"()",
"collectionProce... | train | https://github.com/oaqa/uima-ecd/blob/09a0ae26647490b43affc36ab3a01100702b989f/src/main/java/edu/cmu/lti/oaqa/ecd/driver/SimplePipelineRev803.java#L117-L130 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/cache/impl/AbstractCacheService.java | AbstractCacheService.addInvalidationListener | @Override
public String addInvalidationListener(String cacheNameWithPrefix, CacheEventListener listener, boolean localOnly) {
"""
Registers and {@link com.hazelcast.cache.impl.CacheEventListener} for specified {@code cacheNameWithPrefix}
@param cacheNameWithPrefix the full name of the cache (including manager scope prefix)
that {@link com.hazelcast.cache.impl.CacheEventListener} will be registered for
@param listener the {@link com.hazelcast.cache.impl.CacheEventListener} to be registered
for specified {@code cacheNameWithPrefix}
@param localOnly true if only events originated from this member wants be listened, false if all
invalidation events in the cluster wants to be listened
@return the ID which is unique for current registration
"""
EventService eventService = nodeEngine.getEventService();
EventRegistration registration;
if (localOnly) {
registration = eventService.registerLocalListener(SERVICE_NAME, cacheNameWithPrefix, listener);
} else {
registration = eventService.registerListener(SERVICE_NAME, cacheNameWithPrefix, listener);
}
return registration.getId();
} | java | @Override
public String addInvalidationListener(String cacheNameWithPrefix, CacheEventListener listener, boolean localOnly) {
EventService eventService = nodeEngine.getEventService();
EventRegistration registration;
if (localOnly) {
registration = eventService.registerLocalListener(SERVICE_NAME, cacheNameWithPrefix, listener);
} else {
registration = eventService.registerListener(SERVICE_NAME, cacheNameWithPrefix, listener);
}
return registration.getId();
} | [
"@",
"Override",
"public",
"String",
"addInvalidationListener",
"(",
"String",
"cacheNameWithPrefix",
",",
"CacheEventListener",
"listener",
",",
"boolean",
"localOnly",
")",
"{",
"EventService",
"eventService",
"=",
"nodeEngine",
".",
"getEventService",
"(",
")",
";"... | Registers and {@link com.hazelcast.cache.impl.CacheEventListener} for specified {@code cacheNameWithPrefix}
@param cacheNameWithPrefix the full name of the cache (including manager scope prefix)
that {@link com.hazelcast.cache.impl.CacheEventListener} will be registered for
@param listener the {@link com.hazelcast.cache.impl.CacheEventListener} to be registered
for specified {@code cacheNameWithPrefix}
@param localOnly true if only events originated from this member wants be listened, false if all
invalidation events in the cluster wants to be listened
@return the ID which is unique for current registration | [
"Registers",
"and",
"{",
"@link",
"com",
".",
"hazelcast",
".",
"cache",
".",
"impl",
".",
"CacheEventListener",
"}",
"for",
"specified",
"{",
"@code",
"cacheNameWithPrefix",
"}"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cache/impl/AbstractCacheService.java#L798-L808 |
apache/predictionio-sdk-java | client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java | EventClient.setUser | public String setUser(String uid, Map<String, Object> properties, DateTime eventTime)
throws ExecutionException, InterruptedException, IOException {
"""
Sets properties of a user. Implicitly creates the user if it's not already there. Properties
could be empty.
@param uid ID of the user
@param properties a map of all the properties to be associated with the user, could be empty
@param eventTime timestamp of the event
@return ID of this event
"""
return createEvent(setUserAsFuture(uid, properties, eventTime));
} | java | public String setUser(String uid, Map<String, Object> properties, DateTime eventTime)
throws ExecutionException, InterruptedException, IOException {
return createEvent(setUserAsFuture(uid, properties, eventTime));
} | [
"public",
"String",
"setUser",
"(",
"String",
"uid",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
",",
"DateTime",
"eventTime",
")",
"throws",
"ExecutionException",
",",
"InterruptedException",
",",
"IOException",
"{",
"return",
"createEvent",
"(... | Sets properties of a user. Implicitly creates the user if it's not already there. Properties
could be empty.
@param uid ID of the user
@param properties a map of all the properties to be associated with the user, could be empty
@param eventTime timestamp of the event
@return ID of this event | [
"Sets",
"properties",
"of",
"a",
"user",
".",
"Implicitly",
"creates",
"the",
"user",
"if",
"it",
"s",
"not",
"already",
"there",
".",
"Properties",
"could",
"be",
"empty",
"."
] | train | https://github.com/apache/predictionio-sdk-java/blob/16052c96b136340c175c3f9c2692e720850df219/client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java#L324-L327 |
alkacon/opencms-core | src-gwt/org/opencms/ui/client/contextmenu/CmsContextMenuOverlay.java | CmsContextMenuOverlay.showAt | public void showAt(final int x, final int y) {
"""
Shows the overlay at the given position.<p>
@param x the client x position
@param y the client y position
"""
setPopupPositionAndShow(new PopupPanel.PositionCallback() {
@Override
public void setPosition(int offsetWidth, int offsetHeight) {
int left = x + Window.getScrollLeft();
int top = y + Window.getScrollTop();
int exceedingWidth = (offsetWidth + left) - (Window.getClientWidth() + Window.getScrollLeft());
if (exceedingWidth > 0) {
left -= exceedingWidth;
if (left < 0) {
left = 0;
}
}
int exceedingHeight = (offsetHeight + top) - (Window.getClientHeight() + Window.getScrollTop());
if (exceedingHeight > 0) {
top -= exceedingHeight;
if (top < 0) {
top = 0;
}
}
setPopupPosition(left, top);
}
});
} | java | public void showAt(final int x, final int y) {
setPopupPositionAndShow(new PopupPanel.PositionCallback() {
@Override
public void setPosition(int offsetWidth, int offsetHeight) {
int left = x + Window.getScrollLeft();
int top = y + Window.getScrollTop();
int exceedingWidth = (offsetWidth + left) - (Window.getClientWidth() + Window.getScrollLeft());
if (exceedingWidth > 0) {
left -= exceedingWidth;
if (left < 0) {
left = 0;
}
}
int exceedingHeight = (offsetHeight + top) - (Window.getClientHeight() + Window.getScrollTop());
if (exceedingHeight > 0) {
top -= exceedingHeight;
if (top < 0) {
top = 0;
}
}
setPopupPosition(left, top);
}
});
} | [
"public",
"void",
"showAt",
"(",
"final",
"int",
"x",
",",
"final",
"int",
"y",
")",
"{",
"setPopupPositionAndShow",
"(",
"new",
"PopupPanel",
".",
"PositionCallback",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"setPosition",
"(",
"int",
"offsetWidth"... | Shows the overlay at the given position.<p>
@param x the client x position
@param y the client y position | [
"Shows",
"the",
"overlay",
"at",
"the",
"given",
"position",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ui/client/contextmenu/CmsContextMenuOverlay.java#L234-L263 |
google/closure-templates | java/src/com/google/template/soy/soytree/TemplateNodeBuilder.java | TemplateNodeBuilder.setSoyDoc | public T setSoyDoc(String soyDoc, SourceLocation soyDocLocation) {
"""
Sets the SoyDoc for the node to be built.
@return This builder.
"""
Preconditions.checkState(this.soyDoc == null);
Preconditions.checkState(cmdText != null);
int paramOffset = soyDoc.indexOf("@param");
if (paramOffset != -1) {
errorReporter.report(
new RawTextNode(-1, soyDoc, soyDocLocation)
.substringLocation(paramOffset, paramOffset + "@param".length()),
SOYDOC_PARAM);
}
this.soyDoc = soyDoc;
Preconditions.checkArgument(soyDoc.startsWith("/**") && soyDoc.endsWith("*/"));
this.soyDocDesc = cleanSoyDocHelper(soyDoc);
return (T) this;
} | java | public T setSoyDoc(String soyDoc, SourceLocation soyDocLocation) {
Preconditions.checkState(this.soyDoc == null);
Preconditions.checkState(cmdText != null);
int paramOffset = soyDoc.indexOf("@param");
if (paramOffset != -1) {
errorReporter.report(
new RawTextNode(-1, soyDoc, soyDocLocation)
.substringLocation(paramOffset, paramOffset + "@param".length()),
SOYDOC_PARAM);
}
this.soyDoc = soyDoc;
Preconditions.checkArgument(soyDoc.startsWith("/**") && soyDoc.endsWith("*/"));
this.soyDocDesc = cleanSoyDocHelper(soyDoc);
return (T) this;
} | [
"public",
"T",
"setSoyDoc",
"(",
"String",
"soyDoc",
",",
"SourceLocation",
"soyDocLocation",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"this",
".",
"soyDoc",
"==",
"null",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"cmdText",
"!=",
"null",
... | Sets the SoyDoc for the node to be built.
@return This builder. | [
"Sets",
"the",
"SoyDoc",
"for",
"the",
"node",
"to",
"be",
"built",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/soytree/TemplateNodeBuilder.java#L193-L208 |
threerings/nenya | core/src/main/java/com/threerings/media/image/ImageUtil.java | ImageUtil.tileImageDown | public static void tileImageDown (Graphics2D gfx, Mirage image, int x, int y, int height) {
"""
Paints multiple copies of the supplied image using the supplied graphics context such that
the requested height is filled with the image.
"""
tileImage(gfx, image, x, y, image.getWidth(), height);
} | java | public static void tileImageDown (Graphics2D gfx, Mirage image, int x, int y, int height)
{
tileImage(gfx, image, x, y, image.getWidth(), height);
} | [
"public",
"static",
"void",
"tileImageDown",
"(",
"Graphics2D",
"gfx",
",",
"Mirage",
"image",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"height",
")",
"{",
"tileImage",
"(",
"gfx",
",",
"image",
",",
"x",
",",
"y",
",",
"image",
".",
"getWidth",... | Paints multiple copies of the supplied image using the supplied graphics context such that
the requested height is filled with the image. | [
"Paints",
"multiple",
"copies",
"of",
"the",
"supplied",
"image",
"using",
"the",
"supplied",
"graphics",
"context",
"such",
"that",
"the",
"requested",
"height",
"is",
"filled",
"with",
"the",
"image",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/image/ImageUtil.java#L225-L228 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/util/Assert.java | Assert.checkNull | public static void checkNull(Object o, Supplier<String> msg) {
"""
Equivalent to
assert (o == null) : msg.get();
Note: message string is computed lazily.
"""
if (o != null)
error(msg.get());
} | java | public static void checkNull(Object o, Supplier<String> msg) {
if (o != null)
error(msg.get());
} | [
"public",
"static",
"void",
"checkNull",
"(",
"Object",
"o",
",",
"Supplier",
"<",
"String",
">",
"msg",
")",
"{",
"if",
"(",
"o",
"!=",
"null",
")",
"error",
"(",
"msg",
".",
"get",
"(",
")",
")",
";",
"}"
] | Equivalent to
assert (o == null) : msg.get();
Note: message string is computed lazily. | [
"Equivalent",
"to",
"assert",
"(",
"o",
"==",
"null",
")",
":",
"msg",
".",
"get",
"()",
";",
"Note",
":",
"message",
"string",
"is",
"computed",
"lazily",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Assert.java#L127-L130 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java | PackageSummaryBuilder.buildAnnotationTypeSummary | public void buildAnnotationTypeSummary(XMLNode node, Content summaryContentTree) {
"""
Build the summary for the annotation type in this package.
@param node the XML element that specifies which components to document
@param summaryContentTree the summary tree to which the annotation type
summary will be added
"""
String annotationtypeTableSummary =
configuration.getText("doclet.Member_Table_Summary",
configuration.getText("doclet.Annotation_Types_Summary"),
configuration.getText("doclet.annotationtypes"));
List<String> annotationtypeTableHeader = Arrays.asList(
configuration.getText("doclet.AnnotationType"),
configuration.getText("doclet.Description"));
SortedSet<TypeElement> iannotationTypes =
utils.isSpecified(packageElement)
? utils.getTypeElementsAsSortedSet(utils.getAnnotationTypes(packageElement))
: configuration.typeElementCatalog.annotationTypes(packageElement);
SortedSet<TypeElement> annotationTypes = utils.filterOutPrivateClasses(iannotationTypes,
configuration.javafx);
if (!annotationTypes.isEmpty()) {
packageWriter.addClassesSummary(annotationTypes,
configuration.getText("doclet.Annotation_Types_Summary"),
annotationtypeTableSummary, annotationtypeTableHeader,
summaryContentTree);
}
} | java | public void buildAnnotationTypeSummary(XMLNode node, Content summaryContentTree) {
String annotationtypeTableSummary =
configuration.getText("doclet.Member_Table_Summary",
configuration.getText("doclet.Annotation_Types_Summary"),
configuration.getText("doclet.annotationtypes"));
List<String> annotationtypeTableHeader = Arrays.asList(
configuration.getText("doclet.AnnotationType"),
configuration.getText("doclet.Description"));
SortedSet<TypeElement> iannotationTypes =
utils.isSpecified(packageElement)
? utils.getTypeElementsAsSortedSet(utils.getAnnotationTypes(packageElement))
: configuration.typeElementCatalog.annotationTypes(packageElement);
SortedSet<TypeElement> annotationTypes = utils.filterOutPrivateClasses(iannotationTypes,
configuration.javafx);
if (!annotationTypes.isEmpty()) {
packageWriter.addClassesSummary(annotationTypes,
configuration.getText("doclet.Annotation_Types_Summary"),
annotationtypeTableSummary, annotationtypeTableHeader,
summaryContentTree);
}
} | [
"public",
"void",
"buildAnnotationTypeSummary",
"(",
"XMLNode",
"node",
",",
"Content",
"summaryContentTree",
")",
"{",
"String",
"annotationtypeTableSummary",
"=",
"configuration",
".",
"getText",
"(",
"\"doclet.Member_Table_Summary\"",
",",
"configuration",
".",
"getTex... | Build the summary for the annotation type in this package.
@param node the XML element that specifies which components to document
@param summaryContentTree the summary tree to which the annotation type
summary will be added | [
"Build",
"the",
"summary",
"for",
"the",
"annotation",
"type",
"in",
"this",
"package",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/PackageSummaryBuilder.java#L305-L325 |
gallandarakhneorg/afc | core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/astar/AStar.java | AStar.newAStarNode | @Pure
protected AStarNode<ST, PT> newAStarNode(PT node, double cost, double estimatedCost, ST arrival) {
"""
Create a instance of {@link AStarNode A* node}.
@param node is the node of the graph to put in the A* node.
@param cost is the cost to reach the node.
@param estimatedCost is the estimated cost to reach the target.
@param arrival is the segment, which permits to arrive at the node.
@return the A* node.
"""
return new Candidate(arrival, node, cost, estimatedCost);
} | java | @Pure
protected AStarNode<ST, PT> newAStarNode(PT node, double cost, double estimatedCost, ST arrival) {
return new Candidate(arrival, node, cost, estimatedCost);
} | [
"@",
"Pure",
"protected",
"AStarNode",
"<",
"ST",
",",
"PT",
">",
"newAStarNode",
"(",
"PT",
"node",
",",
"double",
"cost",
",",
"double",
"estimatedCost",
",",
"ST",
"arrival",
")",
"{",
"return",
"new",
"Candidate",
"(",
"arrival",
",",
"node",
",",
... | Create a instance of {@link AStarNode A* node}.
@param node is the node of the graph to put in the A* node.
@param cost is the cost to reach the node.
@param estimatedCost is the estimated cost to reach the target.
@param arrival is the segment, which permits to arrive at the node.
@return the A* node. | [
"Create",
"a",
"instance",
"of",
"{",
"@link",
"AStarNode",
"A",
"*",
"node",
"}",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/astar/AStar.java#L482-L485 |
apache/groovy | subprojects/groovy-xml/src/main/java/groovy/xml/XmlUtil.java | XmlUtil.newSAXParser | public static SAXParser newSAXParser(String schemaLanguage, Source... schemas) throws SAXException, ParserConfigurationException {
"""
Factory method to create a SAXParser configured to validate according to a particular schema language and
optionally providing the schema sources to validate with.
The created SAXParser will be namespace-aware and not validate against DTDs.
@param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants)
@param schemas the schemas to validate against
@return the created SAXParser
@throws SAXException
@throws ParserConfigurationException
@see #newSAXParser(String, boolean, boolean, Source...)
@since 1.8.7
"""
return newSAXParser(schemaLanguage, true, false, schemas);
} | java | public static SAXParser newSAXParser(String schemaLanguage, Source... schemas) throws SAXException, ParserConfigurationException {
return newSAXParser(schemaLanguage, true, false, schemas);
} | [
"public",
"static",
"SAXParser",
"newSAXParser",
"(",
"String",
"schemaLanguage",
",",
"Source",
"...",
"schemas",
")",
"throws",
"SAXException",
",",
"ParserConfigurationException",
"{",
"return",
"newSAXParser",
"(",
"schemaLanguage",
",",
"true",
",",
"false",
",... | Factory method to create a SAXParser configured to validate according to a particular schema language and
optionally providing the schema sources to validate with.
The created SAXParser will be namespace-aware and not validate against DTDs.
@param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants)
@param schemas the schemas to validate against
@return the created SAXParser
@throws SAXException
@throws ParserConfigurationException
@see #newSAXParser(String, boolean, boolean, Source...)
@since 1.8.7 | [
"Factory",
"method",
"to",
"create",
"a",
"SAXParser",
"configured",
"to",
"validate",
"according",
"to",
"a",
"particular",
"schema",
"language",
"and",
"optionally",
"providing",
"the",
"schema",
"sources",
"to",
"validate",
"with",
".",
"The",
"created",
"SAX... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-xml/src/main/java/groovy/xml/XmlUtil.java#L229-L231 |
Azure/azure-sdk-for-java | batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/WorkspacesInner.java | WorkspacesInner.beginCreate | public WorkspaceInner beginCreate(String resourceGroupName, String workspaceName, WorkspaceCreateParameters parameters) {
"""
Creates a Workspace.
@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 parameters Workspace creation parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the WorkspaceInner object if successful.
"""
return beginCreateWithServiceResponseAsync(resourceGroupName, workspaceName, parameters).toBlocking().single().body();
} | java | public WorkspaceInner beginCreate(String resourceGroupName, String workspaceName, WorkspaceCreateParameters parameters) {
return beginCreateWithServiceResponseAsync(resourceGroupName, workspaceName, parameters).toBlocking().single().body();
} | [
"public",
"WorkspaceInner",
"beginCreate",
"(",
"String",
"resourceGroupName",
",",
"String",
"workspaceName",
",",
"WorkspaceCreateParameters",
"parameters",
")",
"{",
"return",
"beginCreateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"workspaceName",
",",
"pa... | Creates a Workspace.
@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 parameters Workspace creation parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the WorkspaceInner object if successful. | [
"Creates",
"a",
"Workspace",
"."
] | 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/WorkspacesInner.java#L650-L652 |
groovy/groovy-core | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.newWriter | public static BufferedWriter newWriter(Path self, String charset, boolean append) throws IOException {
"""
Helper method to create a buffered writer for a file. If the given
charset is "UTF-16BE" or "UTF-16LE", the requisite byte order mark is
written to the stream before the writer is returned.
@param self a Path
@param charset the name of the encoding used to write in this file
@param append true if in append mode
@return a BufferedWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0
"""
if (append) {
return Files.newBufferedWriter(self, Charset.forName(charset), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.forName(charset));
} | java | public static BufferedWriter newWriter(Path self, String charset, boolean append) throws IOException {
if (append) {
return Files.newBufferedWriter(self, Charset.forName(charset), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.forName(charset));
} | [
"public",
"static",
"BufferedWriter",
"newWriter",
"(",
"Path",
"self",
",",
"String",
"charset",
",",
"boolean",
"append",
")",
"throws",
"IOException",
"{",
"if",
"(",
"append",
")",
"{",
"return",
"Files",
".",
"newBufferedWriter",
"(",
"self",
",",
"Char... | Helper method to create a buffered writer for a file. If the given
charset is "UTF-16BE" or "UTF-16LE", the requisite byte order mark is
written to the stream before the writer is returned.
@param self a Path
@param charset the name of the encoding used to write in this file
@param append true if in append mode
@return a BufferedWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0 | [
"Helper",
"method",
"to",
"create",
"a",
"buffered",
"writer",
"for",
"a",
"file",
".",
"If",
"the",
"given",
"charset",
"is",
"UTF",
"-",
"16BE",
"or",
"UTF",
"-",
"16LE",
"the",
"requisite",
"byte",
"order",
"mark",
"is",
"written",
"to",
"the",
"str... | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1480-L1485 |
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/MapAddon.java | MapAddon.setMapSize | public void setMapSize(int mapWidth, int mapHeight) {
"""
Apply a new width and height for the map onto whom this add-on is drawn. This method is triggered automatically
when the map resizes.
@param mapWidth
The map's new width.
@param mapHeight
The map's new height.
"""
double x = horizontalMargin;
double y = verticalMargin;
// Calculate horizontal position:
switch (alignment) {
case LEFT:
break;
case CENTER:
x = Math.round((mapWidth - width) / 2);
break;
case RIGHT:
x = mapWidth - width - horizontalMargin;
}
// Calculate vertical position:
switch (verticalAlignment) {
case TOP:
break;
case CENTER:
y = Math.round((mapHeight - height) / 2);
break;
case BOTTOM:
y = mapHeight - height - verticalMargin;
}
upperLeftCorner = new Coordinate(x, y);
} | java | public void setMapSize(int mapWidth, int mapHeight) {
double x = horizontalMargin;
double y = verticalMargin;
// Calculate horizontal position:
switch (alignment) {
case LEFT:
break;
case CENTER:
x = Math.round((mapWidth - width) / 2);
break;
case RIGHT:
x = mapWidth - width - horizontalMargin;
}
// Calculate vertical position:
switch (verticalAlignment) {
case TOP:
break;
case CENTER:
y = Math.round((mapHeight - height) / 2);
break;
case BOTTOM:
y = mapHeight - height - verticalMargin;
}
upperLeftCorner = new Coordinate(x, y);
} | [
"public",
"void",
"setMapSize",
"(",
"int",
"mapWidth",
",",
"int",
"mapHeight",
")",
"{",
"double",
"x",
"=",
"horizontalMargin",
";",
"double",
"y",
"=",
"verticalMargin",
";",
"// Calculate horizontal position:",
"switch",
"(",
"alignment",
")",
"{",
"case",
... | Apply a new width and height for the map onto whom this add-on is drawn. This method is triggered automatically
when the map resizes.
@param mapWidth
The map's new width.
@param mapHeight
The map's new height. | [
"Apply",
"a",
"new",
"width",
"and",
"height",
"for",
"the",
"map",
"onto",
"whom",
"this",
"add",
"-",
"on",
"is",
"drawn",
".",
"This",
"method",
"is",
"triggered",
"automatically",
"when",
"the",
"map",
"resizes",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/MapAddon.java#L99-L126 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.waitForLogMessage | public boolean waitForLogMessage(String logMessage, int timeout) {
"""
Waits for the specified log message to appear.
Requires read logs permission (android.permission.READ_LOGS) in AndroidManifest.xml of the application under test.
@param logMessage the log message to wait for
@param timeout the amount of time in milliseconds to wait
@return {@code true} if log message appears and {@code false} if it does not appear before the timeout
@see #clearLog()
"""
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForLogMessage(\""+logMessage+"\", "+timeout+")");
}
return waiter.waitForLogMessage(logMessage, timeout);
} | java | public boolean waitForLogMessage(String logMessage, int timeout){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForLogMessage(\""+logMessage+"\", "+timeout+")");
}
return waiter.waitForLogMessage(logMessage, timeout);
} | [
"public",
"boolean",
"waitForLogMessage",
"(",
"String",
"logMessage",
",",
"int",
"timeout",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"waitForLogMessage(\\\"\"",
"+",
"log... | Waits for the specified log message to appear.
Requires read logs permission (android.permission.READ_LOGS) in AndroidManifest.xml of the application under test.
@param logMessage the log message to wait for
@param timeout the amount of time in milliseconds to wait
@return {@code true} if log message appears and {@code false} if it does not appear before the timeout
@see #clearLog() | [
"Waits",
"for",
"the",
"specified",
"log",
"message",
"to",
"appear",
".",
"Requires",
"read",
"logs",
"permission",
"(",
"android",
".",
"permission",
".",
"READ_LOGS",
")",
"in",
"AndroidManifest",
".",
"xml",
"of",
"the",
"application",
"under",
"test",
"... | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L3746-L3752 |
Whiley/WhileyCompiler | src/main/java/wyil/type/util/ConcreteTypeExtractor.java | ConcreteTypeExtractor.apply | private Type apply(SemanticType.Array type, LifetimeRelation lifetimes) {
"""
Extracting a concrete type from a semantic array is relatively easy. We just
recursively extract the concrete element type. Example of how this can arise:
<pre>
function f() -> (int[] r):
return [1,2,null]
</pre>
The type generated for <code>[1,2,null]</code> will be a semantic array type
<code>(int|null)[]</code>.
@param type
@return
"""
return new Type.Array(apply(type.getElement(), lifetimes));
} | java | private Type apply(SemanticType.Array type, LifetimeRelation lifetimes) {
return new Type.Array(apply(type.getElement(), lifetimes));
} | [
"private",
"Type",
"apply",
"(",
"SemanticType",
".",
"Array",
"type",
",",
"LifetimeRelation",
"lifetimes",
")",
"{",
"return",
"new",
"Type",
".",
"Array",
"(",
"apply",
"(",
"type",
".",
"getElement",
"(",
")",
",",
"lifetimes",
")",
")",
";",
"}"
] | Extracting a concrete type from a semantic array is relatively easy. We just
recursively extract the concrete element type. Example of how this can arise:
<pre>
function f() -> (int[] r):
return [1,2,null]
</pre>
The type generated for <code>[1,2,null]</code> will be a semantic array type
<code>(int|null)[]</code>.
@param type
@return | [
"Extracting",
"a",
"concrete",
"type",
"from",
"a",
"semantic",
"array",
"is",
"relatively",
"easy",
".",
"We",
"just",
"recursively",
"extract",
"the",
"concrete",
"element",
"type",
".",
"Example",
"of",
"how",
"this",
"can",
"arise",
":"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/type/util/ConcreteTypeExtractor.java#L120-L122 |
tvesalainen/util | vfs/src/main/java/org/vesalainen/vfs/Env.java | Env.getDefaultDirectoryFileAttributes | public static final FileAttribute<?>[] getDefaultDirectoryFileAttributes(Map<String, ?> env) {
"""
Return default attributes for new directory. Either from env or default
values.
@param env
@return
"""
FileAttribute<?>[] attrs = (FileAttribute<?>[]) env.get(DEFAULT_DIRECTORY_FILE_ATTRIBUTES);
if (attrs == null)
{
attrs = new FileAttribute<?>[]{
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x")),
new FileAttributeImpl(OWNER, new UnixUser("root", 0)),
new FileAttributeImpl(GROUP, new UnixGroup("root", 0)),
};
}
return attrs;
} | java | public static final FileAttribute<?>[] getDefaultDirectoryFileAttributes(Map<String, ?> env)
{
FileAttribute<?>[] attrs = (FileAttribute<?>[]) env.get(DEFAULT_DIRECTORY_FILE_ATTRIBUTES);
if (attrs == null)
{
attrs = new FileAttribute<?>[]{
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x")),
new FileAttributeImpl(OWNER, new UnixUser("root", 0)),
new FileAttributeImpl(GROUP, new UnixGroup("root", 0)),
};
}
return attrs;
} | [
"public",
"static",
"final",
"FileAttribute",
"<",
"?",
">",
"[",
"]",
"getDefaultDirectoryFileAttributes",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"env",
")",
"{",
"FileAttribute",
"<",
"?",
">",
"[",
"]",
"attrs",
"=",
"(",
"FileAttribute",
"<",
"?",... | Return default attributes for new directory. Either from env or default
values.
@param env
@return | [
"Return",
"default",
"attributes",
"for",
"new",
"directory",
".",
"Either",
"from",
"env",
"or",
"default",
"values",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/vfs/src/main/java/org/vesalainen/vfs/Env.java#L139-L151 |
mapsforge/mapsforge | mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java | AndroidUtil.createTileCache | public static TileCache createTileCache(Context c, String id, int tileSize,
int width, int height, double overdraw, boolean persistent) {
"""
Utility function to create a two-level tile cache with the right size, using the size of the map view.
@param c the Android context
@param id name for the storage directory
@param tileSize tile size
@param width the width of the map view
@param height the height of the map view
@param overdraw overdraw allowance
@param persistent whether the cache should be persistent
@return a new cache created on the external storage
"""
int cacheSize = getMinimumCacheSize(tileSize, overdraw, width, height);
return createExternalStorageTileCache(c, id, cacheSize, tileSize, persistent);
} | java | public static TileCache createTileCache(Context c, String id, int tileSize,
int width, int height, double overdraw, boolean persistent) {
int cacheSize = getMinimumCacheSize(tileSize, overdraw, width, height);
return createExternalStorageTileCache(c, id, cacheSize, tileSize, persistent);
} | [
"public",
"static",
"TileCache",
"createTileCache",
"(",
"Context",
"c",
",",
"String",
"id",
",",
"int",
"tileSize",
",",
"int",
"width",
",",
"int",
"height",
",",
"double",
"overdraw",
",",
"boolean",
"persistent",
")",
"{",
"int",
"cacheSize",
"=",
"ge... | Utility function to create a two-level tile cache with the right size, using the size of the map view.
@param c the Android context
@param id name for the storage directory
@param tileSize tile size
@param width the width of the map view
@param height the height of the map view
@param overdraw overdraw allowance
@param persistent whether the cache should be persistent
@return a new cache created on the external storage | [
"Utility",
"function",
"to",
"create",
"a",
"two",
"-",
"level",
"tile",
"cache",
"with",
"the",
"right",
"size",
"using",
"the",
"size",
"of",
"the",
"map",
"view",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L204-L208 |
opentable/otj-jaxrs | client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java | JaxRsClientFactory.addFeatureMap | public synchronized JaxRsClientFactory addFeatureMap(SetMultimap<JaxRsFeatureGroup, Feature> map) {
"""
Register many features at once. Mostly a convenience for DI environments.
"""
return addFeatureMap(Multimaps.asMap(map));
} | java | public synchronized JaxRsClientFactory addFeatureMap(SetMultimap<JaxRsFeatureGroup, Feature> map) {
return addFeatureMap(Multimaps.asMap(map));
} | [
"public",
"synchronized",
"JaxRsClientFactory",
"addFeatureMap",
"(",
"SetMultimap",
"<",
"JaxRsFeatureGroup",
",",
"Feature",
">",
"map",
")",
"{",
"return",
"addFeatureMap",
"(",
"Multimaps",
".",
"asMap",
"(",
"map",
")",
")",
";",
"}"
] | Register many features at once. Mostly a convenience for DI environments. | [
"Register",
"many",
"features",
"at",
"once",
".",
"Mostly",
"a",
"convenience",
"for",
"DI",
"environments",
"."
] | train | https://github.com/opentable/otj-jaxrs/blob/384e7094fe5a56d41b2a9970bfd783fa85cbbcb8/client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java#L108-L110 |
geomajas/geomajas-project-client-gwt2 | server-extension/src/main/java/org/geomajas/gwt2/client/GeomajasServerExtension.java | GeomajasServerExtension.createLayer | protected ServerLayer<?> createLayer(MapConfiguration mapConfiguration, ClientLayerInfo layerInfo,
ViewPort viewPort, MapEventBus eventBus) {
"""
Create a new layer, based upon a server-side layer configuration object.
@param mapConfiguration The map configuration.
@param layerInfo The server-side configuration object.
@param viewPort The map viewport.
@param eventBus The map eventBus.
@return The new layer object. It has NOT been added to the map just yet.
"""
ServerLayer<?> layer = null;
switch (layerInfo.getLayerType()) {
case RASTER:
layer = new RasterServerLayerImpl(mapConfiguration, (ClientRasterLayerInfo) layerInfo, viewPort,
eventBus);
break;
default:
layer = new VectorServerLayerImpl(mapConfiguration, (ClientVectorLayerInfo) layerInfo, viewPort,
eventBus);
break;
}
return layer;
} | java | protected ServerLayer<?> createLayer(MapConfiguration mapConfiguration, ClientLayerInfo layerInfo,
ViewPort viewPort, MapEventBus eventBus) {
ServerLayer<?> layer = null;
switch (layerInfo.getLayerType()) {
case RASTER:
layer = new RasterServerLayerImpl(mapConfiguration, (ClientRasterLayerInfo) layerInfo, viewPort,
eventBus);
break;
default:
layer = new VectorServerLayerImpl(mapConfiguration, (ClientVectorLayerInfo) layerInfo, viewPort,
eventBus);
break;
}
return layer;
} | [
"protected",
"ServerLayer",
"<",
"?",
">",
"createLayer",
"(",
"MapConfiguration",
"mapConfiguration",
",",
"ClientLayerInfo",
"layerInfo",
",",
"ViewPort",
"viewPort",
",",
"MapEventBus",
"eventBus",
")",
"{",
"ServerLayer",
"<",
"?",
">",
"layer",
"=",
"null",
... | Create a new layer, based upon a server-side layer configuration object.
@param mapConfiguration The map configuration.
@param layerInfo The server-side configuration object.
@param viewPort The map viewport.
@param eventBus The map eventBus.
@return The new layer object. It has NOT been added to the map just yet. | [
"Create",
"a",
"new",
"layer",
"based",
"upon",
"a",
"server",
"-",
"side",
"layer",
"configuration",
"object",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/server-extension/src/main/java/org/geomajas/gwt2/client/GeomajasServerExtension.java#L220-L234 |
Whiley/WhileyCompiler | src/main/java/wyc/io/WhileyFileParser.java | WhileyFileParser.parseRecordInitialiser | private Expr parseRecordInitialiser(Identifier name, EnclosingScope scope, boolean terminated) {
"""
Parse a record initialiser, which is of the form:
<pre>
RecordExpr ::= '{' Identifier ':' Expr (',' Identifier ':' Expr)* '}'
</pre>
During parsing, we additionally check that each identifier is unique;
otherwise, an error is reported.
@param name
An optional name component for the record initialiser. If
null, then this is an anonymous record initialiser. Otherwise,
it is a named record initialiser.
@param scope
The enclosing scope for this statement, which determines the
set of visible (i.e. declared) variables and also the current
indentation level.
@param terminated
This indicates that the expression is known to be terminated
(or not). An expression that's known to be terminated is one
which is guaranteed to be followed by something. This is
important because it means that we can ignore any newline
characters encountered in parsing this expression, and that
we'll never overrun the end of the expression (i.e. because
there's guaranteed to be something which terminates this
expression). A classic situation where terminated is true is
when parsing an expression surrounded in braces. In such case,
we know the right-brace will always terminate this expression.
@return
"""
int start = index;
match(LeftCurly);
HashSet<String> keys = new HashSet<>();
ArrayList<Identifier> fields = new ArrayList<>();
ArrayList<Expr> operands = new ArrayList<>();
boolean firstTime = true;
while (eventuallyMatch(RightCurly) == null) {
if (!firstTime) {
match(Comma);
}
firstTime = false;
// Parse field name being constructed
Identifier field = parseIdentifier();
// Check field name is unique
if (keys.contains(field.get())) {
syntaxError("duplicate record key", field);
}
match(Colon);
// Parse expression being assigned to field
// NOTE: we require the following expression be a "non-tuple"
// expression. That is, it cannot be composed using ',' unless
// braces enclose the entire expression. This is because the outer
// record constructor expression is used ',' to distinguish fields.
// Also, expression is guaranteed to be terminated, either by '}' or
// ','.
Expr initialiser = parseExpression(scope, true);
fields.add(field);
operands.add(initialiser);
keys.add(field.get());
}
// handle naming
// FIXME: Need to support named record initialisers. The suggestion here
// is to support arbitrary named initialisers. The reason for this being
// we could then support named arrays and other types as well? Not sure
// what the real difference from a cast is though.
return annotateSourceLocation(new Expr.RecordInitialiser(Type.Void, new Tuple<>(fields), new Tuple<>(operands)),
start);
} | java | private Expr parseRecordInitialiser(Identifier name, EnclosingScope scope, boolean terminated) {
int start = index;
match(LeftCurly);
HashSet<String> keys = new HashSet<>();
ArrayList<Identifier> fields = new ArrayList<>();
ArrayList<Expr> operands = new ArrayList<>();
boolean firstTime = true;
while (eventuallyMatch(RightCurly) == null) {
if (!firstTime) {
match(Comma);
}
firstTime = false;
// Parse field name being constructed
Identifier field = parseIdentifier();
// Check field name is unique
if (keys.contains(field.get())) {
syntaxError("duplicate record key", field);
}
match(Colon);
// Parse expression being assigned to field
// NOTE: we require the following expression be a "non-tuple"
// expression. That is, it cannot be composed using ',' unless
// braces enclose the entire expression. This is because the outer
// record constructor expression is used ',' to distinguish fields.
// Also, expression is guaranteed to be terminated, either by '}' or
// ','.
Expr initialiser = parseExpression(scope, true);
fields.add(field);
operands.add(initialiser);
keys.add(field.get());
}
// handle naming
// FIXME: Need to support named record initialisers. The suggestion here
// is to support arbitrary named initialisers. The reason for this being
// we could then support named arrays and other types as well? Not sure
// what the real difference from a cast is though.
return annotateSourceLocation(new Expr.RecordInitialiser(Type.Void, new Tuple<>(fields), new Tuple<>(operands)),
start);
} | [
"private",
"Expr",
"parseRecordInitialiser",
"(",
"Identifier",
"name",
",",
"EnclosingScope",
"scope",
",",
"boolean",
"terminated",
")",
"{",
"int",
"start",
"=",
"index",
";",
"match",
"(",
"LeftCurly",
")",
";",
"HashSet",
"<",
"String",
">",
"keys",
"="... | Parse a record initialiser, which is of the form:
<pre>
RecordExpr ::= '{' Identifier ':' Expr (',' Identifier ':' Expr)* '}'
</pre>
During parsing, we additionally check that each identifier is unique;
otherwise, an error is reported.
@param name
An optional name component for the record initialiser. If
null, then this is an anonymous record initialiser. Otherwise,
it is a named record initialiser.
@param scope
The enclosing scope for this statement, which determines the
set of visible (i.e. declared) variables and also the current
indentation level.
@param terminated
This indicates that the expression is known to be terminated
(or not). An expression that's known to be terminated is one
which is guaranteed to be followed by something. This is
important because it means that we can ignore any newline
characters encountered in parsing this expression, and that
we'll never overrun the end of the expression (i.e. because
there's guaranteed to be something which terminates this
expression). A classic situation where terminated is true is
when parsing an expression surrounded in braces. In such case,
we know the right-brace will always terminate this expression.
@return | [
"Parse",
"a",
"record",
"initialiser",
"which",
"is",
"of",
"the",
"form",
":"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L2775-L2815 |
comapi/comapi-sdk-android | COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java | InternalService.updateConversation | public void updateConversation(@NonNull final String conversationId, @NonNull final ConversationUpdate request, @NonNull final String eTag, @Nullable Callback<ComapiResult<ConversationDetails>> callback) {
"""
Returns observable to update a conversation.
@param conversationId ID of a conversation to update.
@param request Request with conversation details to update.
@param eTag ETag for server to check if local version of the data is the same as the one the server side.
@param callback Callback to deliver new session instance.
"""
adapter.adapt(updateConversation(conversationId, request, eTag), callback);
} | java | public void updateConversation(@NonNull final String conversationId, @NonNull final ConversationUpdate request, @NonNull final String eTag, @Nullable Callback<ComapiResult<ConversationDetails>> callback) {
adapter.adapt(updateConversation(conversationId, request, eTag), callback);
} | [
"public",
"void",
"updateConversation",
"(",
"@",
"NonNull",
"final",
"String",
"conversationId",
",",
"@",
"NonNull",
"final",
"ConversationUpdate",
"request",
",",
"@",
"NonNull",
"final",
"String",
"eTag",
",",
"@",
"Nullable",
"Callback",
"<",
"ComapiResult",
... | Returns observable to update a conversation.
@param conversationId ID of a conversation to update.
@param request Request with conversation details to update.
@param eTag ETag for server to check if local version of the data is the same as the one the server side.
@param callback Callback to deliver new session instance. | [
"Returns",
"observable",
"to",
"update",
"a",
"conversation",
"."
] | train | https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L595-L597 |
kite-sdk/kite | kite-tools-parent/kite-tools/src/main/java/org/kitesdk/tools/JobClasspathHelper.java | JobClasspathHelper.createMd5SumFile | private void createMd5SumFile(FileSystem fs, String md5sum, Path remoteMd5Path) throws IOException {
"""
This method creates an file that contains a line with a MD5 sum
@param fs
FileSystem where to create the file.
@param md5sum
The string containing the MD5 sum.
@param remoteMd5Path
The path where to save the file.
@throws IOException
"""
FSDataOutputStream os = null;
try {
os = fs.create(remoteMd5Path, true);
os.writeBytes(md5sum);
os.flush();
} catch (Exception e) {
LOG.error("{}", e);
} finally {
if (os != null) {
os.close();
}
}
} | java | private void createMd5SumFile(FileSystem fs, String md5sum, Path remoteMd5Path) throws IOException {
FSDataOutputStream os = null;
try {
os = fs.create(remoteMd5Path, true);
os.writeBytes(md5sum);
os.flush();
} catch (Exception e) {
LOG.error("{}", e);
} finally {
if (os != null) {
os.close();
}
}
} | [
"private",
"void",
"createMd5SumFile",
"(",
"FileSystem",
"fs",
",",
"String",
"md5sum",
",",
"Path",
"remoteMd5Path",
")",
"throws",
"IOException",
"{",
"FSDataOutputStream",
"os",
"=",
"null",
";",
"try",
"{",
"os",
"=",
"fs",
".",
"create",
"(",
"remoteMd... | This method creates an file that contains a line with a MD5 sum
@param fs
FileSystem where to create the file.
@param md5sum
The string containing the MD5 sum.
@param remoteMd5Path
The path where to save the file.
@throws IOException | [
"This",
"method",
"creates",
"an",
"file",
"that",
"contains",
"a",
"line",
"with",
"a",
"MD5",
"sum"
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-tools-parent/kite-tools/src/main/java/org/kitesdk/tools/JobClasspathHelper.java#L231-L244 |
dbracewell/mango | src/main/java/com/davidbracewell/reflection/Reflect.java | Reflect.onObject | public static Reflect onObject(Object object) {
"""
Creates an instance of Reflect associated with an object
@param object The object for reflection
@return The Reflect object
"""
if (object == null) {
return new Reflect(null, null);
}
return new Reflect(object, object.getClass());
} | java | public static Reflect onObject(Object object) {
if (object == null) {
return new Reflect(null, null);
}
return new Reflect(object, object.getClass());
} | [
"public",
"static",
"Reflect",
"onObject",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"return",
"new",
"Reflect",
"(",
"null",
",",
"null",
")",
";",
"}",
"return",
"new",
"Reflect",
"(",
"object",
",",
"object",
... | Creates an instance of Reflect associated with an object
@param object The object for reflection
@return The Reflect object | [
"Creates",
"an",
"instance",
"of",
"Reflect",
"associated",
"with",
"an",
"object"
] | train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/reflection/Reflect.java#L66-L71 |
alkacon/opencms-core | src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsSerialDateView.java | CmsSerialDateView.createAndAddButton | private void createAndAddButton(PatternType pattern, String messageKey) {
"""
Creates a pattern choice radio button and adds it where necessary.
@param pattern the pattern that should be chosen by the button.
@param messageKey the message key for the button's label.
"""
CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));
btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());
btn.setGroup(m_groupPattern);
m_patternButtons.put(pattern, btn);
m_patternRadioButtonsPanel.add(btn);
} | java | private void createAndAddButton(PatternType pattern, String messageKey) {
CmsRadioButton btn = new CmsRadioButton(pattern.toString(), Messages.get().key(messageKey));
btn.addStyleName(I_CmsWidgetsLayoutBundle.INSTANCE.widgetCss().radioButtonlabel());
btn.setGroup(m_groupPattern);
m_patternButtons.put(pattern, btn);
m_patternRadioButtonsPanel.add(btn);
} | [
"private",
"void",
"createAndAddButton",
"(",
"PatternType",
"pattern",
",",
"String",
"messageKey",
")",
"{",
"CmsRadioButton",
"btn",
"=",
"new",
"CmsRadioButton",
"(",
"pattern",
".",
"toString",
"(",
")",
",",
"Messages",
".",
"get",
"(",
")",
".",
"key"... | Creates a pattern choice radio button and adds it where necessary.
@param pattern the pattern that should be chosen by the button.
@param messageKey the message key for the button's label. | [
"Creates",
"a",
"pattern",
"choice",
"radio",
"button",
"and",
"adds",
"it",
"where",
"necessary",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/widgets/serialdate/CmsSerialDateView.java#L552-L560 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterTokenServices.java | TwitterTokenServices.setCookies | protected void setCookies(HttpServletRequest request, HttpServletResponse response, String requestToken, String stateValue) {
"""
Sets cookies for the provided request token and the original request URL. These values can then be verified and used in
subsequent requests.
@param request
@param response
@param requestToken
@param stateValue
"""
ReferrerURLCookieHandler referrerURLCookieHandler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler();
// Create cookie for request token
Cookie requestTokenCookie = referrerURLCookieHandler.createCookie(TwitterConstants.COOKIE_NAME_REQUEST_TOKEN, requestToken, request);
response.addCookie(requestTokenCookie);
// Set original request URL in cookie
String cookieName = ClientConstants.COOKIE_NAME_REQ_URL_PREFIX + stateValue.hashCode();
Cookie c = referrerURLCookieHandler.createCookie(cookieName, webUtils.getRequestUrlWithEncodedQueryString(request), request);
response.addCookie(c);
} | java | protected void setCookies(HttpServletRequest request, HttpServletResponse response, String requestToken, String stateValue) {
ReferrerURLCookieHandler referrerURLCookieHandler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler();
// Create cookie for request token
Cookie requestTokenCookie = referrerURLCookieHandler.createCookie(TwitterConstants.COOKIE_NAME_REQUEST_TOKEN, requestToken, request);
response.addCookie(requestTokenCookie);
// Set original request URL in cookie
String cookieName = ClientConstants.COOKIE_NAME_REQ_URL_PREFIX + stateValue.hashCode();
Cookie c = referrerURLCookieHandler.createCookie(cookieName, webUtils.getRequestUrlWithEncodedQueryString(request), request);
response.addCookie(c);
} | [
"protected",
"void",
"setCookies",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"String",
"requestToken",
",",
"String",
"stateValue",
")",
"{",
"ReferrerURLCookieHandler",
"referrerURLCookieHandler",
"=",
"WebAppSecurityCollaboratorImpl"... | Sets cookies for the provided request token and the original request URL. These values can then be verified and used in
subsequent requests.
@param request
@param response
@param requestToken
@param stateValue | [
"Sets",
"cookies",
"for",
"the",
"provided",
"request",
"token",
"and",
"the",
"original",
"request",
"URL",
".",
"These",
"values",
"can",
"then",
"be",
"verified",
"and",
"used",
"in",
"subsequent",
"requests",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterTokenServices.java#L188-L200 |
killbilling/recurly-java-library | src/main/java/com/ning/billing/recurly/RecurlyClient.java | RecurlyClient.getAddOn | public AddOn getAddOn(final String planCode, final String addOnCode) {
"""
Get an AddOn's details
<p>
@param addOnCode recurly id of {@link AddOn}
@param planCode recurly id of {@link Plan}
@return the {@link AddOn} object as identified by the passed in plan and add-on IDs
"""
if (addOnCode == null || addOnCode.isEmpty())
throw new RuntimeException("addOnCode cannot be empty!");
return doGET(Plan.PLANS_RESOURCE +
"/" +
planCode +
AddOn.ADDONS_RESOURCE +
"/" +
addOnCode, AddOn.class);
} | java | public AddOn getAddOn(final String planCode, final String addOnCode) {
if (addOnCode == null || addOnCode.isEmpty())
throw new RuntimeException("addOnCode cannot be empty!");
return doGET(Plan.PLANS_RESOURCE +
"/" +
planCode +
AddOn.ADDONS_RESOURCE +
"/" +
addOnCode, AddOn.class);
} | [
"public",
"AddOn",
"getAddOn",
"(",
"final",
"String",
"planCode",
",",
"final",
"String",
"addOnCode",
")",
"{",
"if",
"(",
"addOnCode",
"==",
"null",
"||",
"addOnCode",
".",
"isEmpty",
"(",
")",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"addOnCode ca... | Get an AddOn's details
<p>
@param addOnCode recurly id of {@link AddOn}
@param planCode recurly id of {@link Plan}
@return the {@link AddOn} object as identified by the passed in plan and add-on IDs | [
"Get",
"an",
"AddOn",
"s",
"details",
"<p",
">"
] | train | https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L1454-L1464 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/batikutil/CloneInlineImages.java | CloneInlineImages.inlineThumbnail | protected Node inlineThumbnail(Document doc, ParsedURL urldata, Node eold) {
"""
Inline a referenced thumbnail.
@param doc Document (element factory)
@param urldata URL
@param eold Existing node
@return Replacement node, or {@code null}
"""
RenderableImage img = ThumbnailRegistryEntry.handleURL(urldata);
if(img == null) {
LoggingUtil.warning("Image not found in registry: " + urldata.toString());
return null;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
os.write(SVGSyntax.DATA_PROTOCOL_PNG_PREFIX.getBytes());
Base64EncoderStream encoder = new Base64EncoderStream(os);
ImageIO.write(img.createDefaultRendering(), "png", encoder);
encoder.close();
}
catch(IOException e) {
LoggingUtil.exception("Exception serializing image to png", e);
return null;
}
Element i = (Element) super.cloneNode(doc, eold);
i.setAttributeNS(SVGConstants.XLINK_NAMESPACE_URI, SVGConstants.XLINK_HREF_ATTRIBUTE, os.toString().replaceAll("\\s*[\\r\\n]+\\s*", ""));
return i;
} | java | protected Node inlineThumbnail(Document doc, ParsedURL urldata, Node eold) {
RenderableImage img = ThumbnailRegistryEntry.handleURL(urldata);
if(img == null) {
LoggingUtil.warning("Image not found in registry: " + urldata.toString());
return null;
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
os.write(SVGSyntax.DATA_PROTOCOL_PNG_PREFIX.getBytes());
Base64EncoderStream encoder = new Base64EncoderStream(os);
ImageIO.write(img.createDefaultRendering(), "png", encoder);
encoder.close();
}
catch(IOException e) {
LoggingUtil.exception("Exception serializing image to png", e);
return null;
}
Element i = (Element) super.cloneNode(doc, eold);
i.setAttributeNS(SVGConstants.XLINK_NAMESPACE_URI, SVGConstants.XLINK_HREF_ATTRIBUTE, os.toString().replaceAll("\\s*[\\r\\n]+\\s*", ""));
return i;
} | [
"protected",
"Node",
"inlineThumbnail",
"(",
"Document",
"doc",
",",
"ParsedURL",
"urldata",
",",
"Node",
"eold",
")",
"{",
"RenderableImage",
"img",
"=",
"ThumbnailRegistryEntry",
".",
"handleURL",
"(",
"urldata",
")",
";",
"if",
"(",
"img",
"==",
"null",
"... | Inline a referenced thumbnail.
@param doc Document (element factory)
@param urldata URL
@param eold Existing node
@return Replacement node, or {@code null} | [
"Inline",
"a",
"referenced",
"thumbnail",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/batikutil/CloneInlineImages.java#L81-L101 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java | AppServiceEnvironmentsInner.listMultiRoleMetricDefinitionsAsync | public Observable<Page<ResourceMetricDefinitionInner>> listMultiRoleMetricDefinitionsAsync(final String resourceGroupName, final String name) {
"""
Get metric definitions for a multi-role pool of an App Service Environment.
Get metric definitions for a multi-role pool of an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricDefinitionInner> object
"""
return listMultiRoleMetricDefinitionsWithServiceResponseAsync(resourceGroupName, name)
.map(new Func1<ServiceResponse<Page<ResourceMetricDefinitionInner>>, Page<ResourceMetricDefinitionInner>>() {
@Override
public Page<ResourceMetricDefinitionInner> call(ServiceResponse<Page<ResourceMetricDefinitionInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<ResourceMetricDefinitionInner>> listMultiRoleMetricDefinitionsAsync(final String resourceGroupName, final String name) {
return listMultiRoleMetricDefinitionsWithServiceResponseAsync(resourceGroupName, name)
.map(new Func1<ServiceResponse<Page<ResourceMetricDefinitionInner>>, Page<ResourceMetricDefinitionInner>>() {
@Override
public Page<ResourceMetricDefinitionInner> call(ServiceResponse<Page<ResourceMetricDefinitionInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"ResourceMetricDefinitionInner",
">",
">",
"listMultiRoleMetricDefinitionsAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"name",
")",
"{",
"return",
"listMultiRoleMetricDefinitionsWithServiceResponseAsync... | Get metric definitions for a multi-role pool of an App Service Environment.
Get metric definitions for a multi-role pool of an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceMetricDefinitionInner> object | [
"Get",
"metric",
"definitions",
"for",
"a",
"multi",
"-",
"role",
"pool",
"of",
"an",
"App",
"Service",
"Environment",
".",
"Get",
"metric",
"definitions",
"for",
"a",
"multi",
"-",
"role",
"pool",
"of",
"an",
"App",
"Service",
"Environment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L3005-L3013 |
demidenko05/beigesoft-orm | src/main/java/org/beigesoft/orm/holder/HldProcessorNames.java | HldProcessorNames.getFor | @Override
public final String getFor(final Class<?> pClass, final String pThingName) {
"""
<p>Get thing for given class and thing name.</p>
@param pClass a Class
@param pThingName Thing Name
@return a thing
"""
if ("list".equals(pThingName)) {
return PrcEntitiesPage.class.getSimpleName();
} else if ("about".equals(pThingName)) {
return PrcAbout.class.getSimpleName();
}
return null;
} | java | @Override
public final String getFor(final Class<?> pClass, final String pThingName) {
if ("list".equals(pThingName)) {
return PrcEntitiesPage.class.getSimpleName();
} else if ("about".equals(pThingName)) {
return PrcAbout.class.getSimpleName();
}
return null;
} | [
"@",
"Override",
"public",
"final",
"String",
"getFor",
"(",
"final",
"Class",
"<",
"?",
">",
"pClass",
",",
"final",
"String",
"pThingName",
")",
"{",
"if",
"(",
"\"list\"",
".",
"equals",
"(",
"pThingName",
")",
")",
"{",
"return",
"PrcEntitiesPage",
"... | <p>Get thing for given class and thing name.</p>
@param pClass a Class
@param pThingName Thing Name
@return a thing | [
"<p",
">",
"Get",
"thing",
"for",
"given",
"class",
"and",
"thing",
"name",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/demidenko05/beigesoft-orm/blob/f1b2c70701a111741a436911ca24ef9d38eba0b9/src/main/java/org/beigesoft/orm/holder/HldProcessorNames.java#L33-L41 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ExpressRouteCircuitConnectionsInner.java | ExpressRouteCircuitConnectionsInner.beginCreateOrUpdate | public ExpressRouteCircuitConnectionInner beginCreateOrUpdate(String resourceGroupName, String circuitName, String peeringName, String connectionName, ExpressRouteCircuitConnectionInner expressRouteCircuitConnectionParameters) {
"""
Creates or updates a Express Route Circuit Connection in the specified express route circuits.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the express route circuit.
@param peeringName The name of the peering.
@param connectionName The name of the express route circuit connection.
@param expressRouteCircuitConnectionParameters Parameters supplied to the create or update express route circuit circuit connection operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCircuitConnectionInner object if successful.
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters).toBlocking().single().body();
} | java | public ExpressRouteCircuitConnectionInner beginCreateOrUpdate(String resourceGroupName, String circuitName, String peeringName, String connectionName, ExpressRouteCircuitConnectionInner expressRouteCircuitConnectionParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, peeringName, connectionName, expressRouteCircuitConnectionParameters).toBlocking().single().body();
} | [
"public",
"ExpressRouteCircuitConnectionInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"circuitName",
",",
"String",
"peeringName",
",",
"String",
"connectionName",
",",
"ExpressRouteCircuitConnectionInner",
"expressRouteCircuitConnectionParameter... | Creates or updates a Express Route Circuit Connection in the specified express route circuits.
@param resourceGroupName The name of the resource group.
@param circuitName The name of the express route circuit.
@param peeringName The name of the peering.
@param connectionName The name of the express route circuit connection.
@param expressRouteCircuitConnectionParameters Parameters supplied to the create or update express route circuit circuit connection operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ExpressRouteCircuitConnectionInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"Express",
"Route",
"Circuit",
"Connection",
"in",
"the",
"specified",
"express",
"route",
"circuits",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ExpressRouteCircuitConnectionsInner.java#L459-L461 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/util/pathfinding/AStarPathFinder.java | AStarPathFinder.getHeuristicCost | public float getHeuristicCost(Mover mover, int x, int y, int tx, int ty) {
"""
Get the heuristic cost for the given location. This determines in which
order the locations are processed.
@param mover The entity that is being moved
@param x The x coordinate of the tile whose cost is being determined
@param y The y coordiante of the tile whose cost is being determined
@param tx The x coordinate of the target location
@param ty The y coordinate of the target location
@return The heuristic cost assigned to the tile
"""
return heuristic.getCost(map, mover, x, y, tx, ty);
} | java | public float getHeuristicCost(Mover mover, int x, int y, int tx, int ty) {
return heuristic.getCost(map, mover, x, y, tx, ty);
} | [
"public",
"float",
"getHeuristicCost",
"(",
"Mover",
"mover",
",",
"int",
"x",
",",
"int",
"y",
",",
"int",
"tx",
",",
"int",
"ty",
")",
"{",
"return",
"heuristic",
".",
"getCost",
"(",
"map",
",",
"mover",
",",
"x",
",",
"y",
",",
"tx",
",",
"ty... | Get the heuristic cost for the given location. This determines in which
order the locations are processed.
@param mover The entity that is being moved
@param x The x coordinate of the tile whose cost is being determined
@param y The y coordiante of the tile whose cost is being determined
@param tx The x coordinate of the target location
@param ty The y coordinate of the target location
@return The heuristic cost assigned to the tile | [
"Get",
"the",
"heuristic",
"cost",
"for",
"the",
"given",
"location",
".",
"This",
"determines",
"in",
"which",
"order",
"the",
"locations",
"are",
"processed",
"."
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/util/pathfinding/AStarPathFinder.java#L359-L361 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ExtendedServerBlobAuditingPoliciesInner.java | ExtendedServerBlobAuditingPoliciesInner.createOrUpdateAsync | public Observable<ExtendedServerBlobAuditingPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, ExtendedServerBlobAuditingPolicyInner parameters) {
"""
Creates or updates an extended server's blob auditing policy.
@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.
@param parameters Properties of extended blob auditing policy
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ExtendedServerBlobAuditingPolicyInner>, ExtendedServerBlobAuditingPolicyInner>() {
@Override
public ExtendedServerBlobAuditingPolicyInner call(ServiceResponse<ExtendedServerBlobAuditingPolicyInner> response) {
return response.body();
}
});
} | java | public Observable<ExtendedServerBlobAuditingPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, ExtendedServerBlobAuditingPolicyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ExtendedServerBlobAuditingPolicyInner>, ExtendedServerBlobAuditingPolicyInner>() {
@Override
public ExtendedServerBlobAuditingPolicyInner call(ServiceResponse<ExtendedServerBlobAuditingPolicyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ExtendedServerBlobAuditingPolicyInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"ExtendedServerBlobAuditingPolicyInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsy... | Creates or updates an extended server's blob auditing policy.
@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.
@param parameters Properties of extended blob auditing policy
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"an",
"extended",
"server",
"s",
"blob",
"auditing",
"policy",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ExtendedServerBlobAuditingPoliciesInner.java#L196-L203 |
threerings/nenya | core/src/main/java/com/threerings/resource/FileResourceBundle.java | FileResourceBundle.wipeBundle | public void wipeBundle (boolean deleteJar) {
"""
Clears out everything associated with this resource bundle in the hopes that we can
download it afresh and everything will work the next time around.
"""
// clear out our cache directory
if (_cache != null) {
FileUtil.recursiveClean(_cache);
}
// delete our unpack stamp file
if (_unpacked != null) {
_unpacked.delete();
}
// clear out any .jarv file that Getdown might be maintaining so
// that we ensure that it is revalidated
File vfile = new File(FileUtil.resuffix(_source, ".jar", ".jarv"));
if (vfile.exists() && !vfile.delete()) {
log.warning("Failed to delete vfile", "file", vfile);
}
// close and delete our source jar file
if (deleteJar && _source != null) {
closeJar();
if (!_source.delete()) {
log.warning("Failed to delete source",
"source", _source, "exists", _source.exists());
}
}
} | java | public void wipeBundle (boolean deleteJar)
{
// clear out our cache directory
if (_cache != null) {
FileUtil.recursiveClean(_cache);
}
// delete our unpack stamp file
if (_unpacked != null) {
_unpacked.delete();
}
// clear out any .jarv file that Getdown might be maintaining so
// that we ensure that it is revalidated
File vfile = new File(FileUtil.resuffix(_source, ".jar", ".jarv"));
if (vfile.exists() && !vfile.delete()) {
log.warning("Failed to delete vfile", "file", vfile);
}
// close and delete our source jar file
if (deleteJar && _source != null) {
closeJar();
if (!_source.delete()) {
log.warning("Failed to delete source",
"source", _source, "exists", _source.exists());
}
}
} | [
"public",
"void",
"wipeBundle",
"(",
"boolean",
"deleteJar",
")",
"{",
"// clear out our cache directory",
"if",
"(",
"_cache",
"!=",
"null",
")",
"{",
"FileUtil",
".",
"recursiveClean",
"(",
"_cache",
")",
";",
"}",
"// delete our unpack stamp file",
"if",
"(",
... | Clears out everything associated with this resource bundle in the hopes that we can
download it afresh and everything will work the next time around. | [
"Clears",
"out",
"everything",
"associated",
"with",
"this",
"resource",
"bundle",
"in",
"the",
"hopes",
"that",
"we",
"can",
"download",
"it",
"afresh",
"and",
"everything",
"will",
"work",
"the",
"next",
"time",
"around",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/resource/FileResourceBundle.java#L178-L205 |
wealthfront/magellan | magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java | Navigator.rewriteHistory | public void rewriteHistory(Activity activity, HistoryRewriter historyRewriter) {
"""
Change the elements of the back stack according to the implementation of the HistoryRewriter parameter.
<b>Note, this method cannot be called after calling {@link #onCreate(Activity, Bundle)} on this Navigator.</b> The
primary use case for this method is to change the back stack before the navigator is fully initialized (e.g.
showing a login screen if necessary). It is possible to manipulate the back stack with a {@link HistoryRewriter},
{@link #navigate(HistoryRewriter)}.
@param activity activity used to verify this Navigator is in an acceptable state when resetWithRoot is called
@param historyRewriter rewrites back stack to desired state
@throws IllegalStateException if {@link #onCreate(Activity, Bundle)} has already been called on this Navigator
"""
checkOnCreateNotYetCalled(activity, "rewriteHistory() must be called before onCreate()");
historyRewriter.rewriteHistory(backStack);
} | java | public void rewriteHistory(Activity activity, HistoryRewriter historyRewriter) {
checkOnCreateNotYetCalled(activity, "rewriteHistory() must be called before onCreate()");
historyRewriter.rewriteHistory(backStack);
} | [
"public",
"void",
"rewriteHistory",
"(",
"Activity",
"activity",
",",
"HistoryRewriter",
"historyRewriter",
")",
"{",
"checkOnCreateNotYetCalled",
"(",
"activity",
",",
"\"rewriteHistory() must be called before onCreate()\"",
")",
";",
"historyRewriter",
".",
"rewriteHistory"... | Change the elements of the back stack according to the implementation of the HistoryRewriter parameter.
<b>Note, this method cannot be called after calling {@link #onCreate(Activity, Bundle)} on this Navigator.</b> The
primary use case for this method is to change the back stack before the navigator is fully initialized (e.g.
showing a login screen if necessary). It is possible to manipulate the back stack with a {@link HistoryRewriter},
{@link #navigate(HistoryRewriter)}.
@param activity activity used to verify this Navigator is in an acceptable state when resetWithRoot is called
@param historyRewriter rewrites back stack to desired state
@throws IllegalStateException if {@link #onCreate(Activity, Bundle)} has already been called on this Navigator | [
"Change",
"the",
"elements",
"of",
"the",
"back",
"stack",
"according",
"to",
"the",
"implementation",
"of",
"the",
"HistoryRewriter",
"parameter",
".",
"<b",
">",
"Note",
"this",
"method",
"cannot",
"be",
"called",
"after",
"calling",
"{",
"@link",
"#onCreate... | train | https://github.com/wealthfront/magellan/blob/f690979161a97e40fb9d11dc9d7e3c8cf85ba312/magellan-library/src/main/java/com/wealthfront/magellan/Navigator.java#L270-L273 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VpnGatewaysInner.java | VpnGatewaysInner.beginCreateOrUpdateAsync | public Observable<VpnGatewayInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
"""
Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
@param resourceGroupName The resource group name of the VpnGateway.
@param gatewayName The name of the gateway.
@param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VpnGatewayInner object
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
} | java | public Observable<VpnGatewayInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VpnGatewayInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"gatewayName",
",",
"VpnGatewayInner",
"vpnGatewayParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resource... | Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
@param resourceGroupName The resource group name of the VpnGateway.
@param gatewayName The name of the gateway.
@param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VpnGatewayInner object | [
"Creates",
"a",
"virtual",
"wan",
"vpn",
"gateway",
"if",
"it",
"doesn",
"t",
"exist",
"else",
"updates",
"the",
"existing",
"gateway",
"."
] | 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/VpnGatewaysInner.java#L313-L320 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java | AmazonS3Client.addPartNumberIfNotNull | private void addPartNumberIfNotNull(Request<?> request, Integer partNumber) {
"""
Adds the part number to the specified request, if partNumber is not null.
@param request
The request to add the partNumber to.
@param partNumber
The part number to be added.
"""
if (partNumber != null) {
request.addParameter("partNumber", partNumber.toString());
}
} | java | private void addPartNumberIfNotNull(Request<?> request, Integer partNumber) {
if (partNumber != null) {
request.addParameter("partNumber", partNumber.toString());
}
} | [
"private",
"void",
"addPartNumberIfNotNull",
"(",
"Request",
"<",
"?",
">",
"request",
",",
"Integer",
"partNumber",
")",
"{",
"if",
"(",
"partNumber",
"!=",
"null",
")",
"{",
"request",
".",
"addParameter",
"(",
"\"partNumber\"",
",",
"partNumber",
".",
"to... | Adds the part number to the specified request, if partNumber is not null.
@param request
The request to add the partNumber to.
@param partNumber
The part number to be added. | [
"Adds",
"the",
"part",
"number",
"to",
"the",
"specified",
"request",
"if",
"partNumber",
"is",
"not",
"null",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java#L4420-L4424 |
languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/rules/patterns/CaseConversionHelper.java | CaseConversionHelper.convertCase | public static String convertCase(Match.CaseConversion conversion, String s, String sample, Language lang) {
"""
Converts case of the string token according to match element attributes.
@param s Token to be converted.
@param sample the sample string used to determine how the original string looks like (used only on case preservation)
@return Converted string.
"""
if (StringTools.isEmpty(s)) {
return s;
}
String token = s;
switch (conversion) {
case NONE:
break;
case PRESERVE:
if (StringTools.startsWithUppercase(sample)) {
if (StringTools.isAllUppercase(sample)) {
token = token.toUpperCase(Locale.ENGLISH);
} else {
token = StringTools.uppercaseFirstChar(token, lang);
}
}
break;
case STARTLOWER:
token = token.substring(0, 1).toLowerCase() + token.substring(1);
break;
case STARTUPPER:
token = StringTools.uppercaseFirstChar(token, lang);
break;
case ALLUPPER:
token = token.toUpperCase(Locale.ENGLISH);
break;
case ALLLOWER:
token = token.toLowerCase();
break;
default:
break;
}
return token;
} | java | public static String convertCase(Match.CaseConversion conversion, String s, String sample, Language lang) {
if (StringTools.isEmpty(s)) {
return s;
}
String token = s;
switch (conversion) {
case NONE:
break;
case PRESERVE:
if (StringTools.startsWithUppercase(sample)) {
if (StringTools.isAllUppercase(sample)) {
token = token.toUpperCase(Locale.ENGLISH);
} else {
token = StringTools.uppercaseFirstChar(token, lang);
}
}
break;
case STARTLOWER:
token = token.substring(0, 1).toLowerCase() + token.substring(1);
break;
case STARTUPPER:
token = StringTools.uppercaseFirstChar(token, lang);
break;
case ALLUPPER:
token = token.toUpperCase(Locale.ENGLISH);
break;
case ALLLOWER:
token = token.toLowerCase();
break;
default:
break;
}
return token;
} | [
"public",
"static",
"String",
"convertCase",
"(",
"Match",
".",
"CaseConversion",
"conversion",
",",
"String",
"s",
",",
"String",
"sample",
",",
"Language",
"lang",
")",
"{",
"if",
"(",
"StringTools",
".",
"isEmpty",
"(",
"s",
")",
")",
"{",
"return",
"... | Converts case of the string token according to match element attributes.
@param s Token to be converted.
@param sample the sample string used to determine how the original string looks like (used only on case preservation)
@return Converted string. | [
"Converts",
"case",
"of",
"the",
"string",
"token",
"according",
"to",
"match",
"element",
"attributes",
"."
] | train | https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/patterns/CaseConversionHelper.java#L40-L73 |
jmrozanec/cron-utils | src/main/java/com/cronutils/descriptor/CronDescriptor.java | CronDescriptor.describeYear | public String describeYear(final Map<CronFieldName, CronField> fields) {
"""
Provide description for a year.
@param fields - fields to describe;
@return description - String
"""
final String description =
DescriptionStrategyFactory.plainInstance(
resourceBundle,
fields.containsKey(CronFieldName.YEAR) ? fields.get(CronFieldName.YEAR).getExpression() : null
).describe();
return addExpressions(description, resourceBundle.getString("year"), resourceBundle.getString("years"));
} | java | public String describeYear(final Map<CronFieldName, CronField> fields) {
final String description =
DescriptionStrategyFactory.plainInstance(
resourceBundle,
fields.containsKey(CronFieldName.YEAR) ? fields.get(CronFieldName.YEAR).getExpression() : null
).describe();
return addExpressions(description, resourceBundle.getString("year"), resourceBundle.getString("years"));
} | [
"public",
"String",
"describeYear",
"(",
"final",
"Map",
"<",
"CronFieldName",
",",
"CronField",
">",
"fields",
")",
"{",
"final",
"String",
"description",
"=",
"DescriptionStrategyFactory",
".",
"plainInstance",
"(",
"resourceBundle",
",",
"fields",
".",
"contain... | Provide description for a year.
@param fields - fields to describe;
@return description - String | [
"Provide",
"description",
"for",
"a",
"year",
"."
] | train | https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/descriptor/CronDescriptor.java#L151-L158 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/impl/DefaultFaceletFactory.java | DefaultFaceletFactory._removeFirst | private String _removeFirst(String string, String toRemove) {
"""
Removes the first appearance of toRemove in string.
Works just like string.replaceFirst(toRemove, ""), except that toRemove
is not treated as a regex (which could cause problems with filenames).
@param string
@param toRemove
@return
"""
// do exactly what String.replaceFirst(toRemove, "") internally does,
// except treating the search as literal text and not as regex
return Pattern.compile(toRemove, Pattern.LITERAL).matcher(string).replaceFirst("");
} | java | private String _removeFirst(String string, String toRemove)
{
// do exactly what String.replaceFirst(toRemove, "") internally does,
// except treating the search as literal text and not as regex
return Pattern.compile(toRemove, Pattern.LITERAL).matcher(string).replaceFirst("");
} | [
"private",
"String",
"_removeFirst",
"(",
"String",
"string",
",",
"String",
"toRemove",
")",
"{",
"// do exactly what String.replaceFirst(toRemove, \"\") internally does,",
"// except treating the search as literal text and not as regex",
"return",
"Pattern",
".",
"compile",
"(",
... | Removes the first appearance of toRemove in string.
Works just like string.replaceFirst(toRemove, ""), except that toRemove
is not treated as a regex (which could cause problems with filenames).
@param string
@param toRemove
@return | [
"Removes",
"the",
"first",
"appearance",
"of",
"toRemove",
"in",
"string",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/impl/DefaultFaceletFactory.java#L613-L619 |
couchbase/java-dcp-client | src/main/java/com/couchbase/client/dcp/state/SessionState.java | SessionState.setFromJson | public void setFromJson(final byte[] persisted) {
"""
Recovers the session state from persisted JSON.
@param persisted the persisted JSON format.
"""
try {
SessionState decoded = JACKSON.readValue(persisted, SessionState.class);
decoded.foreachPartition(new Action1<PartitionState>() {
int i = 0;
@Override
public void call(PartitionState dps) {
partitionStates.set(i++, dps);
}
});
} catch (Exception ex) {
throw new RuntimeException("Could not decode SessionState from JSON.", ex);
}
} | java | public void setFromJson(final byte[] persisted) {
try {
SessionState decoded = JACKSON.readValue(persisted, SessionState.class);
decoded.foreachPartition(new Action1<PartitionState>() {
int i = 0;
@Override
public void call(PartitionState dps) {
partitionStates.set(i++, dps);
}
});
} catch (Exception ex) {
throw new RuntimeException("Could not decode SessionState from JSON.", ex);
}
} | [
"public",
"void",
"setFromJson",
"(",
"final",
"byte",
"[",
"]",
"persisted",
")",
"{",
"try",
"{",
"SessionState",
"decoded",
"=",
"JACKSON",
".",
"readValue",
"(",
"persisted",
",",
"SessionState",
".",
"class",
")",
";",
"decoded",
".",
"foreachPartition"... | Recovers the session state from persisted JSON.
@param persisted the persisted JSON format. | [
"Recovers",
"the",
"session",
"state",
"from",
"persisted",
"JSON",
"."
] | train | https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/state/SessionState.java#L103-L117 |
beanshell/beanshell | src/main/java/bsh/NameSpace.java | NameSpace.createVariable | protected Variable createVariable(final String name, final Class<?> type,
final LHS lhs) throws UtilEvalError {
"""
Creates the variable.
@param name the name
@param type the type
@param lhs the lhs
@return the variable
@throws UtilEvalError the util eval error
"""
return new Variable(name, type, lhs);
} | java | protected Variable createVariable(final String name, final Class<?> type,
final LHS lhs) throws UtilEvalError {
return new Variable(name, type, lhs);
} | [
"protected",
"Variable",
"createVariable",
"(",
"final",
"String",
"name",
",",
"final",
"Class",
"<",
"?",
">",
"type",
",",
"final",
"LHS",
"lhs",
")",
"throws",
"UtilEvalError",
"{",
"return",
"new",
"Variable",
"(",
"name",
",",
"type",
",",
"lhs",
"... | Creates the variable.
@param name the name
@param type the type
@param lhs the lhs
@return the variable
@throws UtilEvalError the util eval error | [
"Creates",
"the",
"variable",
"."
] | train | https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/NameSpace.java#L427-L430 |
aws/aws-sdk-java | jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java | JmesPathEvaluationVisitor.visit | @Override
public JsonNode visit(JmesPathField fieldNode, JsonNode input) {
"""
Retrieves the value of the field node
@param fieldNode JmesPath field type
@param input Input json node whose value is
retrieved
@return Value of the input json node
"""
if (input.isObject()) {
//TODO : CamelCase will need to change at some point
return input.get(CamelCaseUtils.toCamelCase(fieldNode.getValue()));
}
return NullNode.getInstance();
} | java | @Override
public JsonNode visit(JmesPathField fieldNode, JsonNode input) {
if (input.isObject()) {
//TODO : CamelCase will need to change at some point
return input.get(CamelCaseUtils.toCamelCase(fieldNode.getValue()));
}
return NullNode.getInstance();
} | [
"@",
"Override",
"public",
"JsonNode",
"visit",
"(",
"JmesPathField",
"fieldNode",
",",
"JsonNode",
"input",
")",
"{",
"if",
"(",
"input",
".",
"isObject",
"(",
")",
")",
"{",
"//TODO : CamelCase will need to change at some point",
"return",
"input",
".",
"get",
... | Retrieves the value of the field node
@param fieldNode JmesPath field type
@param input Input json node whose value is
retrieved
@return Value of the input json node | [
"Retrieves",
"the",
"value",
"of",
"the",
"field",
"node"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/jmespath-java/src/main/java/com/amazonaws/jmespath/JmesPathEvaluationVisitor.java#L56-L63 |
alkacon/opencms-core | src/org/opencms/search/CmsSearchIndex.java | CmsSearchIndex.appendPathFilter | protected BooleanQuery.Builder appendPathFilter(CmsObject cms, BooleanQuery.Builder filter, List<String> roots) {
"""
Appends the a VFS path filter to the given filter clause that matches all given root paths.<p>
In case the provided List is null or empty, the current request context site root is appended.<p>
The original filter parameter is extended and also provided as return value.<p>
@param cms the current OpenCms search context
@param filter the filter to extend
@param roots the VFS root paths that will compose the filter
@return the extended filter clause
"""
// complete the search root
List<Term> terms = new ArrayList<Term>();
if ((roots != null) && (roots.size() > 0)) {
// add the all configured search roots with will request context
for (int i = 0; i < roots.size(); i++) {
String searchRoot = cms.getRequestContext().addSiteRoot(roots.get(i));
extendPathFilter(terms, searchRoot);
}
} else {
// use the current site root as the search root
extendPathFilter(terms, cms.getRequestContext().getSiteRoot());
// also add the shared folder (v 8.0)
if (OpenCms.getSiteManager().getSharedFolder() != null) {
extendPathFilter(terms, OpenCms.getSiteManager().getSharedFolder());
}
}
// add the calculated path filter for the root path
BooleanQuery.Builder build = new BooleanQuery.Builder();
terms.forEach(term -> build.add(new TermQuery(term), Occur.SHOULD));
filter.add(new BooleanClause(build.build(), BooleanClause.Occur.MUST));
return filter;
} | java | protected BooleanQuery.Builder appendPathFilter(CmsObject cms, BooleanQuery.Builder filter, List<String> roots) {
// complete the search root
List<Term> terms = new ArrayList<Term>();
if ((roots != null) && (roots.size() > 0)) {
// add the all configured search roots with will request context
for (int i = 0; i < roots.size(); i++) {
String searchRoot = cms.getRequestContext().addSiteRoot(roots.get(i));
extendPathFilter(terms, searchRoot);
}
} else {
// use the current site root as the search root
extendPathFilter(terms, cms.getRequestContext().getSiteRoot());
// also add the shared folder (v 8.0)
if (OpenCms.getSiteManager().getSharedFolder() != null) {
extendPathFilter(terms, OpenCms.getSiteManager().getSharedFolder());
}
}
// add the calculated path filter for the root path
BooleanQuery.Builder build = new BooleanQuery.Builder();
terms.forEach(term -> build.add(new TermQuery(term), Occur.SHOULD));
filter.add(new BooleanClause(build.build(), BooleanClause.Occur.MUST));
return filter;
} | [
"protected",
"BooleanQuery",
".",
"Builder",
"appendPathFilter",
"(",
"CmsObject",
"cms",
",",
"BooleanQuery",
".",
"Builder",
"filter",
",",
"List",
"<",
"String",
">",
"roots",
")",
"{",
"// complete the search root",
"List",
"<",
"Term",
">",
"terms",
"=",
... | Appends the a VFS path filter to the given filter clause that matches all given root paths.<p>
In case the provided List is null or empty, the current request context site root is appended.<p>
The original filter parameter is extended and also provided as return value.<p>
@param cms the current OpenCms search context
@param filter the filter to extend
@param roots the VFS root paths that will compose the filter
@return the extended filter clause | [
"Appends",
"the",
"a",
"VFS",
"path",
"filter",
"to",
"the",
"given",
"filter",
"clause",
"that",
"matches",
"all",
"given",
"root",
"paths",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchIndex.java#L1365-L1389 |
m-szalik/rest-client | src/main/java/org/jsoftware/restclient/plugins/GetMethodCachePlugin.java | GetMethodCachePlugin.headerEq | private boolean headerEq(HttpRequestBase request, String headerName, String headerValue) {
"""
Check if request contains header with value
@param request request
@param headerName header name
@param headerValue header value to check
"""
Header[] headers = request.getAllHeaders();
if (headers != null) {
for(Header h : headers) {
if (headerName.equalsIgnoreCase(h.getName()) && headerValue.equalsIgnoreCase(h.getValue())) {
return true;
}
}
}
return false;
} | java | private boolean headerEq(HttpRequestBase request, String headerName, String headerValue) {
Header[] headers = request.getAllHeaders();
if (headers != null) {
for(Header h : headers) {
if (headerName.equalsIgnoreCase(h.getName()) && headerValue.equalsIgnoreCase(h.getValue())) {
return true;
}
}
}
return false;
} | [
"private",
"boolean",
"headerEq",
"(",
"HttpRequestBase",
"request",
",",
"String",
"headerName",
",",
"String",
"headerValue",
")",
"{",
"Header",
"[",
"]",
"headers",
"=",
"request",
".",
"getAllHeaders",
"(",
")",
";",
"if",
"(",
"headers",
"!=",
"null",
... | Check if request contains header with value
@param request request
@param headerName header name
@param headerValue header value to check | [
"Check",
"if",
"request",
"contains",
"header",
"with",
"value"
] | train | https://github.com/m-szalik/rest-client/blob/14a0ab6a19b97183282bac71f3a3b237e45a5bf3/src/main/java/org/jsoftware/restclient/plugins/GetMethodCachePlugin.java#L102-L112 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.ipOrganisation_organisationId_GET | public OvhIpv4Org ipOrganisation_organisationId_GET(String organisationId) throws IOException {
"""
Get this object properties
REST: GET /me/ipOrganisation/{organisationId}
@param organisationId [required]
"""
String qPath = "/me/ipOrganisation/{organisationId}";
StringBuilder sb = path(qPath, organisationId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhIpv4Org.class);
} | java | public OvhIpv4Org ipOrganisation_organisationId_GET(String organisationId) throws IOException {
String qPath = "/me/ipOrganisation/{organisationId}";
StringBuilder sb = path(qPath, organisationId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhIpv4Org.class);
} | [
"public",
"OvhIpv4Org",
"ipOrganisation_organisationId_GET",
"(",
"String",
"organisationId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/ipOrganisation/{organisationId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"organisationId"... | Get this object properties
REST: GET /me/ipOrganisation/{organisationId}
@param organisationId [required] | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L2196-L2201 |
googleads/googleads-java-lib | examples/adwords_axis/src/main/java/adwords/axis/v201809/advancedoperations/AddUniversalAppCampaign.java | AddUniversalAppCampaign.createBudget | private static Long createBudget(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws RemoteException, ApiException {
"""
Creates the budget for the campaign.
@return the new budget.
"""
// Get the BudgetService.
BudgetServiceInterface budgetService =
adWordsServices.get(session, BudgetServiceInterface.class);
// Create the campaign budget.
Budget budget = new Budget();
budget.setName("Interplanetary Cruise App Budget #" + System.currentTimeMillis());
Money budgetAmount = new Money();
budgetAmount.setMicroAmount(50000000L);
budget.setAmount(budgetAmount);
budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);
// Universal app campaigns don't support shared budgets.
budget.setIsExplicitlyShared(false);
BudgetOperation budgetOperation = new BudgetOperation();
budgetOperation.setOperand(budget);
budgetOperation.setOperator(Operator.ADD);
// Add the budget
Budget addedBudget = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0);
System.out.printf(
"Budget with name '%s' and ID %d was created.%n",
addedBudget.getName(), addedBudget.getBudgetId());
return addedBudget.getBudgetId();
} | java | private static Long createBudget(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws RemoteException, ApiException {
// Get the BudgetService.
BudgetServiceInterface budgetService =
adWordsServices.get(session, BudgetServiceInterface.class);
// Create the campaign budget.
Budget budget = new Budget();
budget.setName("Interplanetary Cruise App Budget #" + System.currentTimeMillis());
Money budgetAmount = new Money();
budgetAmount.setMicroAmount(50000000L);
budget.setAmount(budgetAmount);
budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);
// Universal app campaigns don't support shared budgets.
budget.setIsExplicitlyShared(false);
BudgetOperation budgetOperation = new BudgetOperation();
budgetOperation.setOperand(budget);
budgetOperation.setOperator(Operator.ADD);
// Add the budget
Budget addedBudget = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0);
System.out.printf(
"Budget with name '%s' and ID %d was created.%n",
addedBudget.getName(), addedBudget.getBudgetId());
return addedBudget.getBudgetId();
} | [
"private",
"static",
"Long",
"createBudget",
"(",
"AdWordsServicesInterface",
"adWordsServices",
",",
"AdWordsSession",
"session",
")",
"throws",
"RemoteException",
",",
"ApiException",
"{",
"// Get the BudgetService.",
"BudgetServiceInterface",
"budgetService",
"=",
"adWords... | Creates the budget for the campaign.
@return the new budget. | [
"Creates",
"the",
"budget",
"for",
"the",
"campaign",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/adwords_axis/src/main/java/adwords/axis/v201809/advancedoperations/AddUniversalAppCampaign.java#L246-L272 |
marklogic/marklogic-sesame | marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClient.java | MarkLogicClient.sendAdd | public void sendAdd(File file, String baseURI, RDFFormat dataFormat, Resource... contexts) throws RDFParseException {
"""
add triples from file
@param file
@param baseURI
@param dataFormat
@param contexts
@throws RDFParseException
"""
getClient().performAdd(file, baseURI, dataFormat, this.tx, contexts);
} | java | public void sendAdd(File file, String baseURI, RDFFormat dataFormat, Resource... contexts) throws RDFParseException {
getClient().performAdd(file, baseURI, dataFormat, this.tx, contexts);
} | [
"public",
"void",
"sendAdd",
"(",
"File",
"file",
",",
"String",
"baseURI",
",",
"RDFFormat",
"dataFormat",
",",
"Resource",
"...",
"contexts",
")",
"throws",
"RDFParseException",
"{",
"getClient",
"(",
")",
".",
"performAdd",
"(",
"file",
",",
"baseURI",
",... | add triples from file
@param file
@param baseURI
@param dataFormat
@param contexts
@throws RDFParseException | [
"add",
"triples",
"from",
"file"
] | train | https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClient.java#L302-L304 |
google/closure-compiler | src/com/google/javascript/jscomp/MinimizeExitPoints.java | MinimizeExitPoints.matchingExitNode | private static boolean matchingExitNode(Node n, Token type, @Nullable String labelName) {
"""
Determines if n matches the type and name for the following types of
"exits":
- return without values
- continues and breaks with or without names.
@param n The node to inspect.
@param type The Token type to look for.
@param labelName The name that must be associated with the exit type.
non-null only for breaks associated with labels.
@return Whether the node matches the specified block-exit type.
"""
if (n.getToken() == type) {
if (type == Token.RETURN) {
// only returns without expressions.
return !n.hasChildren();
} else {
if (labelName == null) {
return !n.hasChildren();
} else {
return n.hasChildren()
&& labelName.equals(n.getFirstChild().getString());
}
}
}
return false;
} | java | private static boolean matchingExitNode(Node n, Token type, @Nullable String labelName) {
if (n.getToken() == type) {
if (type == Token.RETURN) {
// only returns without expressions.
return !n.hasChildren();
} else {
if (labelName == null) {
return !n.hasChildren();
} else {
return n.hasChildren()
&& labelName.equals(n.getFirstChild().getString());
}
}
}
return false;
} | [
"private",
"static",
"boolean",
"matchingExitNode",
"(",
"Node",
"n",
",",
"Token",
"type",
",",
"@",
"Nullable",
"String",
"labelName",
")",
"{",
"if",
"(",
"n",
".",
"getToken",
"(",
")",
"==",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"Token",
".... | Determines if n matches the type and name for the following types of
"exits":
- return without values
- continues and breaks with or without names.
@param n The node to inspect.
@param type The Token type to look for.
@param labelName The name that must be associated with the exit type.
non-null only for breaks associated with labels.
@return Whether the node matches the specified block-exit type. | [
"Determines",
"if",
"n",
"matches",
"the",
"type",
"and",
"name",
"for",
"the",
"following",
"types",
"of",
"exits",
":",
"-",
"return",
"without",
"values",
"-",
"continues",
"and",
"breaks",
"with",
"or",
"without",
"names",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MinimizeExitPoints.java#L321-L336 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/net/MessagingService.java | MessagingService.sendOneWay | public void sendOneWay(MessageOut message, int id, InetAddress to) {
"""
Send a message to a given endpoint. This method adheres to the fire and forget
style messaging.
@param message messages to be sent.
@param to endpoint to which the message needs to be sent
"""
if (logger.isTraceEnabled())
logger.trace(FBUtilities.getBroadcastAddress() + " sending " + message.verb + " to " + id + "@" + to);
if (to.equals(FBUtilities.getBroadcastAddress()))
logger.trace("Message-to-self {} going over MessagingService", message);
// message sinks are a testing hook
MessageOut processedMessage = SinkManager.processOutboundMessage(message, id, to);
if (processedMessage == null)
{
return;
}
// get pooled connection (really, connection queue)
OutboundTcpConnection connection = getConnection(to, processedMessage);
// write it
connection.enqueue(processedMessage, id);
} | java | public void sendOneWay(MessageOut message, int id, InetAddress to)
{
if (logger.isTraceEnabled())
logger.trace(FBUtilities.getBroadcastAddress() + " sending " + message.verb + " to " + id + "@" + to);
if (to.equals(FBUtilities.getBroadcastAddress()))
logger.trace("Message-to-self {} going over MessagingService", message);
// message sinks are a testing hook
MessageOut processedMessage = SinkManager.processOutboundMessage(message, id, to);
if (processedMessage == null)
{
return;
}
// get pooled connection (really, connection queue)
OutboundTcpConnection connection = getConnection(to, processedMessage);
// write it
connection.enqueue(processedMessage, id);
} | [
"public",
"void",
"sendOneWay",
"(",
"MessageOut",
"message",
",",
"int",
"id",
",",
"InetAddress",
"to",
")",
"{",
"if",
"(",
"logger",
".",
"isTraceEnabled",
"(",
")",
")",
"logger",
".",
"trace",
"(",
"FBUtilities",
".",
"getBroadcastAddress",
"(",
")",... | Send a message to a given endpoint. This method adheres to the fire and forget
style messaging.
@param message messages to be sent.
@param to endpoint to which the message needs to be sent | [
"Send",
"a",
"message",
"to",
"a",
"given",
"endpoint",
".",
"This",
"method",
"adheres",
"to",
"the",
"fire",
"and",
"forget",
"style",
"messaging",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/net/MessagingService.java#L663-L683 |
OpenLiberty/open-liberty | dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/component/_ArrayMap.java | _ArrayMap.put | static public Object[] put(Object[] array, Object key, Object value) {
"""
Adds the key/value pair to the array, returning a
new array if necessary.
"""
if (array != null)
{
int length = array.length;
for (int i = 0; i < length; i += 2)
{
Object curKey = array[i];
if (((curKey != null) && (curKey.equals(key)))
|| (curKey == key))
{
array[i + 1] = value;
return array;
}
}
}
return _addToArray(array, key, value, 1);
} | java | static public Object[] put(Object[] array, Object key, Object value)
{
if (array != null)
{
int length = array.length;
for (int i = 0; i < length; i += 2)
{
Object curKey = array[i];
if (((curKey != null) && (curKey.equals(key)))
|| (curKey == key))
{
array[i + 1] = value;
return array;
}
}
}
return _addToArray(array, key, value, 1);
} | [
"static",
"public",
"Object",
"[",
"]",
"put",
"(",
"Object",
"[",
"]",
"array",
",",
"Object",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"array",
"!=",
"null",
")",
"{",
"int",
"length",
"=",
"array",
".",
"length",
";",
"for",
"(",
"i... | Adds the key/value pair to the array, returning a
new array if necessary. | [
"Adds",
"the",
"key",
"/",
"value",
"pair",
"to",
"the",
"array",
"returning",
"a",
"new",
"array",
"if",
"necessary",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/component/_ArrayMap.java#L198-L218 |
JDBDT/jdbdt | src/main/java/org/jdbdt/JDBDT.java | JDBDT.deleteAllWhere | @SafeVarargs
public static int deleteAllWhere(Table table, String where, Object... args) {
"""
Delete all data from a table, subject to a <code>WHERE</code>
clause.
@param table Table.
@param where <code>WHERE</code> clause
@param args <code>WHERE</code> clause arguments, if any.
@return Number of deleted entries.
@see #deleteAll(Table)
@see #truncate(Table)
"""
return DBSetup.deleteAll(CallInfo.create(), table, where, args);
} | java | @SafeVarargs
public static int deleteAllWhere(Table table, String where, Object... args) {
return DBSetup.deleteAll(CallInfo.create(), table, where, args);
} | [
"@",
"SafeVarargs",
"public",
"static",
"int",
"deleteAllWhere",
"(",
"Table",
"table",
",",
"String",
"where",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"DBSetup",
".",
"deleteAll",
"(",
"CallInfo",
".",
"create",
"(",
")",
",",
"table",
",",
"w... | Delete all data from a table, subject to a <code>WHERE</code>
clause.
@param table Table.
@param where <code>WHERE</code> clause
@param args <code>WHERE</code> clause arguments, if any.
@return Number of deleted entries.
@see #deleteAll(Table)
@see #truncate(Table) | [
"Delete",
"all",
"data",
"from",
"a",
"table",
"subject",
"to",
"a",
"<code",
">",
"WHERE<",
"/",
"code",
">",
"clause",
"."
] | train | https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L1145-L1148 |
craterdog/java-security-framework | java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java | CertificateManager.retrievePrivateKey | public final PrivateKey retrievePrivateKey(KeyStore keyStore, String keyName, char[] password) {
"""
This method retrieves a private key from a key store.
@param keyStore The key store containing the private key.
@param keyName The name (alias) of the private key.
@param password The password used to encrypt the private key.
@return The decrypted private key.
"""
try {
logger.entry();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyName, password);
logger.exit();
return privateKey;
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a private key.", e);
logger.error(exception.toString());
throw exception;
}
} | java | public final PrivateKey retrievePrivateKey(KeyStore keyStore, String keyName, char[] password) {
try {
logger.entry();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyName, password);
logger.exit();
return privateKey;
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a private key.", e);
logger.error(exception.toString());
throw exception;
}
} | [
"public",
"final",
"PrivateKey",
"retrievePrivateKey",
"(",
"KeyStore",
"keyStore",
",",
"String",
"keyName",
",",
"char",
"[",
"]",
"password",
")",
"{",
"try",
"{",
"logger",
".",
"entry",
"(",
")",
";",
"PrivateKey",
"privateKey",
"=",
"(",
"PrivateKey",
... | This method retrieves a private key from a key store.
@param keyStore The key store containing the private key.
@param keyName The name (alias) of the private key.
@param password The password used to encrypt the private key.
@return The decrypted private key. | [
"This",
"method",
"retrieves",
"a",
"private",
"key",
"from",
"a",
"key",
"store",
"."
] | train | https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java#L109-L120 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_vpnicaconnection.java | ns_vpnicaconnection.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception {
"""
<pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre>
"""
ns_vpnicaconnection_responses result = (ns_vpnicaconnection_responses) service.get_payload_formatter().string_to_resource(ns_vpnicaconnection_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_vpnicaconnection_response_array);
}
ns_vpnicaconnection[] result_ns_vpnicaconnection = new ns_vpnicaconnection[result.ns_vpnicaconnection_response_array.length];
for(int i = 0; i < result.ns_vpnicaconnection_response_array.length; i++)
{
result_ns_vpnicaconnection[i] = result.ns_vpnicaconnection_response_array[i].ns_vpnicaconnection[0];
}
return result_ns_vpnicaconnection;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
ns_vpnicaconnection_responses result = (ns_vpnicaconnection_responses) service.get_payload_formatter().string_to_resource(ns_vpnicaconnection_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.ns_vpnicaconnection_response_array);
}
ns_vpnicaconnection[] result_ns_vpnicaconnection = new ns_vpnicaconnection[result.ns_vpnicaconnection_response_array.length];
for(int i = 0; i < result.ns_vpnicaconnection_response_array.length; i++)
{
result_ns_vpnicaconnection[i] = result.ns_vpnicaconnection_response_array[i].ns_vpnicaconnection[0];
}
return result_ns_vpnicaconnection;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"ns_vpnicaconnection_responses",
"result",
"=",
"(",
"ns_vpnicaconnection_responses",
")",
"service",
".",
"ge... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/ns_vpnicaconnection.java#L236-L253 |
JodaOrg/joda-time | src/main/java/org/joda/time/Years.java | Years.yearsBetween | public static Years yearsBetween(ReadableInstant start, ReadableInstant end) {
"""
Creates a <code>Years</code> representing the number of whole years
between the two specified datetimes. This method correctly handles
any daylight savings time changes that may occur during the interval.
@param start the start instant, must not be null
@param end the end instant, must not be null
@return the period in years
@throws IllegalArgumentException if the instants are null or invalid
"""
int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.years());
return Years.years(amount);
} | java | public static Years yearsBetween(ReadableInstant start, ReadableInstant end) {
int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.years());
return Years.years(amount);
} | [
"public",
"static",
"Years",
"yearsBetween",
"(",
"ReadableInstant",
"start",
",",
"ReadableInstant",
"end",
")",
"{",
"int",
"amount",
"=",
"BaseSingleFieldPeriod",
".",
"between",
"(",
"start",
",",
"end",
",",
"DurationFieldType",
".",
"years",
"(",
")",
")... | Creates a <code>Years</code> representing the number of whole years
between the two specified datetimes. This method correctly handles
any daylight savings time changes that may occur during the interval.
@param start the start instant, must not be null
@param end the end instant, must not be null
@return the period in years
@throws IllegalArgumentException if the instants are null or invalid | [
"Creates",
"a",
"<code",
">",
"Years<",
"/",
"code",
">",
"representing",
"the",
"number",
"of",
"whole",
"years",
"between",
"the",
"two",
"specified",
"datetimes",
".",
"This",
"method",
"correctly",
"handles",
"any",
"daylight",
"savings",
"time",
"changes"... | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Years.java#L101-L104 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketComponentExtensions.java | WicketComponentExtensions.getHeaderContributorForFavicon | public static Behavior getHeaderContributorForFavicon() {
"""
Gets the header contributor for favicon.
@return the header contributor for favicon
"""
return new Behavior()
{
private static final long serialVersionUID = 1L;
@Override
public void renderHead(final Component component, final IHeaderResponse response)
{
super.renderHead(component, response);
response.render(new StringHeaderItem(
"<link type=\"image/x-icon\" rel=\"shortcut icon\" href=\"favicon.ico\" />"));
}
};
} | java | public static Behavior getHeaderContributorForFavicon()
{
return new Behavior()
{
private static final long serialVersionUID = 1L;
@Override
public void renderHead(final Component component, final IHeaderResponse response)
{
super.renderHead(component, response);
response.render(new StringHeaderItem(
"<link type=\"image/x-icon\" rel=\"shortcut icon\" href=\"favicon.ico\" />"));
}
};
} | [
"public",
"static",
"Behavior",
"getHeaderContributorForFavicon",
"(",
")",
"{",
"return",
"new",
"Behavior",
"(",
")",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"1L",
";",
"@",
"Override",
"public",
"void",
"renderHead",
"(",
"final",
... | Gets the header contributor for favicon.
@return the header contributor for favicon | [
"Gets",
"the",
"header",
"contributor",
"for",
"favicon",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketComponentExtensions.java#L98-L112 |
derari/cthul | objects/src/main/java/org/cthul/objects/reflection/Signatures.java | Signatures.bestMethod | public static Method bestMethod(Class<?> clazz, String name, Object[] args) throws AmbiguousMethodMatchException {
"""
Finds the best method for the given arguments.
@param clazz
@param name
@param args
@return method
@throws AmbiguousSignatureMatchException if multiple methods match equally
"""
return bestMethod(collectMethods(clazz, name), args);
} | java | public static Method bestMethod(Class<?> clazz, String name, Object[] args) throws AmbiguousMethodMatchException {
return bestMethod(collectMethods(clazz, name), args);
} | [
"public",
"static",
"Method",
"bestMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"name",
",",
"Object",
"[",
"]",
"args",
")",
"throws",
"AmbiguousMethodMatchException",
"{",
"return",
"bestMethod",
"(",
"collectMethods",
"(",
"clazz",
",",
"... | Finds the best method for the given arguments.
@param clazz
@param name
@param args
@return method
@throws AmbiguousSignatureMatchException if multiple methods match equally | [
"Finds",
"the",
"best",
"method",
"for",
"the",
"given",
"arguments",
"."
] | train | https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/reflection/Signatures.java#L127-L129 |
stephenc/java-iso-tools | iso9660-writer/src/main/java/com/github/stephenc/javaisotools/iso9660/impl/ISO9660Config.java | ISO9660Config.setInterchangeLevel | public void setInterchangeLevel(int level) throws ConfigException {
"""
Set Interchange Level<br> 1: Filenames 8+3, directories 8 characters<br> 2: Filenames 30, directories 31
characters<br> 3: multiple File Sections (files > 2 GB)
@param level 1, 2 or 3
@throws com.github.stephenc.javaisotools.iso9660.ConfigException Invalid or unsupported Interchange Level
"""
if (level < 1 || level > 3) {
throw new ConfigException(this, "Invalid ISO9660 Interchange Level: " + level);
}
if (level == 3) {
throw new ConfigException(this,
"Interchange Level 3 (multiple File Sections per file) is not (yet) supported by this implementation.");
}
ISO9660NamingConventions.INTERCHANGE_LEVEL = level;
} | java | public void setInterchangeLevel(int level) throws ConfigException {
if (level < 1 || level > 3) {
throw new ConfigException(this, "Invalid ISO9660 Interchange Level: " + level);
}
if (level == 3) {
throw new ConfigException(this,
"Interchange Level 3 (multiple File Sections per file) is not (yet) supported by this implementation.");
}
ISO9660NamingConventions.INTERCHANGE_LEVEL = level;
} | [
"public",
"void",
"setInterchangeLevel",
"(",
"int",
"level",
")",
"throws",
"ConfigException",
"{",
"if",
"(",
"level",
"<",
"1",
"||",
"level",
">",
"3",
")",
"{",
"throw",
"new",
"ConfigException",
"(",
"this",
",",
"\"Invalid ISO9660 Interchange Level: \"",
... | Set Interchange Level<br> 1: Filenames 8+3, directories 8 characters<br> 2: Filenames 30, directories 31
characters<br> 3: multiple File Sections (files > 2 GB)
@param level 1, 2 or 3
@throws com.github.stephenc.javaisotools.iso9660.ConfigException Invalid or unsupported Interchange Level | [
"Set",
"Interchange",
"Level<br",
">",
"1",
":",
"Filenames",
"8",
"+",
"3",
"directories",
"8",
"characters<br",
">",
"2",
":",
"Filenames",
"30",
"directories",
"31",
"characters<br",
">",
"3",
":",
"multiple",
"File",
"Sections",
"(",
"files",
">",
"2",... | train | https://github.com/stephenc/java-iso-tools/blob/828c50b02eb311a14dde0dab43462a0d0c9dfb06/iso9660-writer/src/main/java/com/github/stephenc/javaisotools/iso9660/impl/ISO9660Config.java#L45-L54 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseShortObj | @Nullable
public static Short parseShortObj (@Nullable final String sStr) {
"""
Parse the given {@link String} as {@link Short} with radix
{@value #DEFAULT_RADIX}.
@param sStr
The string to parse. May be <code>null</code>.
@return <code>null</code> if the string does not represent a valid value.
"""
return parseShortObj (sStr, DEFAULT_RADIX, null);
} | java | @Nullable
public static Short parseShortObj (@Nullable final String sStr)
{
return parseShortObj (sStr, DEFAULT_RADIX, null);
} | [
"@",
"Nullable",
"public",
"static",
"Short",
"parseShortObj",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
")",
"{",
"return",
"parseShortObj",
"(",
"sStr",
",",
"DEFAULT_RADIX",
",",
"null",
")",
";",
"}"
] | Parse the given {@link String} as {@link Short} with radix
{@value #DEFAULT_RADIX}.
@param sStr
The string to parse. May be <code>null</code>.
@return <code>null</code> if the string does not represent a valid value. | [
"Parse",
"the",
"given",
"{",
"@link",
"String",
"}",
"as",
"{",
"@link",
"Short",
"}",
"with",
"radix",
"{",
"@value",
"#DEFAULT_RADIX",
"}",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L1317-L1321 |
line/armeria | saml/src/main/java/com/linecorp/armeria/server/saml/SamlUtil.java | SamlUtil.getNameId | public static Optional<NameID> getNameId(Response response, SamlNameIdFormat expectedFormat) {
"""
Returns a {@link NameID} that its name format equals to the specified {@code expectedFormat},
from the {@link Response}.
"""
return getNameId(response, nameId -> nameId.getFormat().equals(expectedFormat.urn()));
} | java | public static Optional<NameID> getNameId(Response response, SamlNameIdFormat expectedFormat) {
return getNameId(response, nameId -> nameId.getFormat().equals(expectedFormat.urn()));
} | [
"public",
"static",
"Optional",
"<",
"NameID",
">",
"getNameId",
"(",
"Response",
"response",
",",
"SamlNameIdFormat",
"expectedFormat",
")",
"{",
"return",
"getNameId",
"(",
"response",
",",
"nameId",
"->",
"nameId",
".",
"getFormat",
"(",
")",
".",
"equals",... | Returns a {@link NameID} that its name format equals to the specified {@code expectedFormat},
from the {@link Response}. | [
"Returns",
"a",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/saml/src/main/java/com/linecorp/armeria/server/saml/SamlUtil.java#L33-L35 |
Esri/geometry-api-java | src/main/java/com/esri/core/geometry/MultiPath.java | MultiPath.insertPoint | public void insertPoint(int pathIndex, int beforePointIndex, Point pt) {
"""
Inserts a point.
@param pathIndex
The path index in this class to insert the point to. Must
correspond to an existing path.
@param beforePointIndex
The point index in the given path of this multipath. This
value must be between 0 and GetPathSize(pathIndex), or -1 to
insert the point at the end of the given path.
@param pt
The point to be inserted.
"""
m_impl.insertPoint(pathIndex, beforePointIndex, pt);
} | java | public void insertPoint(int pathIndex, int beforePointIndex, Point pt) {
m_impl.insertPoint(pathIndex, beforePointIndex, pt);
} | [
"public",
"void",
"insertPoint",
"(",
"int",
"pathIndex",
",",
"int",
"beforePointIndex",
",",
"Point",
"pt",
")",
"{",
"m_impl",
".",
"insertPoint",
"(",
"pathIndex",
",",
"beforePointIndex",
",",
"pt",
")",
";",
"}"
] | Inserts a point.
@param pathIndex
The path index in this class to insert the point to. Must
correspond to an existing path.
@param beforePointIndex
The point index in the given path of this multipath. This
value must be between 0 and GetPathSize(pathIndex), or -1 to
insert the point at the end of the given path.
@param pt
The point to be inserted. | [
"Inserts",
"a",
"point",
"."
] | train | https://github.com/Esri/geometry-api-java/blob/494da8ec953d76e7c6072afbc081abfe48ff07cf/src/main/java/com/esri/core/geometry/MultiPath.java#L480-L482 |
jenkinsci/java-client-api | jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java | JenkinsServer.updateJob | public JenkinsServer updateJob(String jobName, String jobXml) throws IOException {
"""
Update the xml description of an existing job
@param jobName name of the job to be updated.
@param jobXml the configuration to be used for updating.
@throws IOException in case of an error.
"""
return this.updateJob(jobName, jobXml, true);
} | java | public JenkinsServer updateJob(String jobName, String jobXml) throws IOException {
return this.updateJob(jobName, jobXml, true);
} | [
"public",
"JenkinsServer",
"updateJob",
"(",
"String",
"jobName",
",",
"String",
"jobXml",
")",
"throws",
"IOException",
"{",
"return",
"this",
".",
"updateJob",
"(",
"jobName",
",",
"jobXml",
",",
"true",
")",
";",
"}"
] | Update the xml description of an existing job
@param jobName name of the job to be updated.
@param jobXml the configuration to be used for updating.
@throws IOException in case of an error. | [
"Update",
"the",
"xml",
"description",
"of",
"an",
"existing",
"job"
] | train | https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L608-L610 |
YahooArchive/samoa | samoa-api/src/main/java/com/yahoo/labs/samoa/learners/classifiers/trees/SplitNode.java | SplitNode.setChild | void setChild(int index, Node child) {
"""
Method to set the children in a specific index of the SplitNode with the appropriate child
@param index Index of the child in the SplitNode
@param child The child node
"""
if ((this.splitTest.maxBranches() >= 0)
&& (index >= this.splitTest.maxBranches())) {
throw new IndexOutOfBoundsException();
}
this.children.set(index, child);
} | java | void setChild(int index, Node child){
if ((this.splitTest.maxBranches() >= 0)
&& (index >= this.splitTest.maxBranches())) {
throw new IndexOutOfBoundsException();
}
this.children.set(index, child);
} | [
"void",
"setChild",
"(",
"int",
"index",
",",
"Node",
"child",
")",
"{",
"if",
"(",
"(",
"this",
".",
"splitTest",
".",
"maxBranches",
"(",
")",
">=",
"0",
")",
"&&",
"(",
"index",
">=",
"this",
".",
"splitTest",
".",
"maxBranches",
"(",
")",
")",
... | Method to set the children in a specific index of the SplitNode with the appropriate child
@param index Index of the child in the SplitNode
@param child The child node | [
"Method",
"to",
"set",
"the",
"children",
"in",
"a",
"specific",
"index",
"of",
"the",
"SplitNode",
"with",
"the",
"appropriate",
"child"
] | train | https://github.com/YahooArchive/samoa/blob/540a2c30167ac85c432b593baabd5ca97e7e8a0f/samoa-api/src/main/java/com/yahoo/labs/samoa/learners/classifiers/trees/SplitNode.java#L83-L89 |
apereo/cas | support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/WsFederationHelper.java | WsFederationHelper.validateSignature | public boolean validateSignature(final Pair<Assertion, WsFederationConfiguration> resultPair) {
"""
validateSignature checks to see if the signature on an assertion is valid.
@param resultPair a provided assertion
@return true if the assertion's signature is valid, otherwise false
"""
if (resultPair == null) {
LOGGER.warn("No assertion or its configuration was provided to validate signatures");
return false;
}
val configuration = resultPair.getValue();
val assertion = resultPair.getKey();
if (assertion == null || configuration == null) {
LOGGER.warn("No signature or configuration was provided to validate signatures");
return false;
}
val signature = assertion.getSignature();
if (signature == null) {
LOGGER.warn("No signature is attached to the assertion to validate");
return false;
}
try {
LOGGER.debug("Validating the signature...");
val validator = new SAMLSignatureProfileValidator();
validator.validate(signature);
val criteriaSet = new CriteriaSet();
criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS));
criteriaSet.add(new EntityIdCriterion(configuration.getIdentityProviderIdentifier()));
try {
val engine = buildSignatureTrustEngine(configuration);
LOGGER.debug("Validating signature via trust engine for [{}]", configuration.getIdentityProviderIdentifier());
return engine.validate(signature, criteriaSet);
} catch (final SecurityException e) {
LOGGER.warn(e.getMessage(), e);
}
} catch (final SignatureException e) {
LOGGER.error("Failed to validate assertion signature", e);
}
SamlUtils.logSamlObject(this.configBean, assertion);
LOGGER.error("Signature doesn't match any signing credential and cannot be validated.");
return false;
} | java | public boolean validateSignature(final Pair<Assertion, WsFederationConfiguration> resultPair) {
if (resultPair == null) {
LOGGER.warn("No assertion or its configuration was provided to validate signatures");
return false;
}
val configuration = resultPair.getValue();
val assertion = resultPair.getKey();
if (assertion == null || configuration == null) {
LOGGER.warn("No signature or configuration was provided to validate signatures");
return false;
}
val signature = assertion.getSignature();
if (signature == null) {
LOGGER.warn("No signature is attached to the assertion to validate");
return false;
}
try {
LOGGER.debug("Validating the signature...");
val validator = new SAMLSignatureProfileValidator();
validator.validate(signature);
val criteriaSet = new CriteriaSet();
criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS));
criteriaSet.add(new EntityIdCriterion(configuration.getIdentityProviderIdentifier()));
try {
val engine = buildSignatureTrustEngine(configuration);
LOGGER.debug("Validating signature via trust engine for [{}]", configuration.getIdentityProviderIdentifier());
return engine.validate(signature, criteriaSet);
} catch (final SecurityException e) {
LOGGER.warn(e.getMessage(), e);
}
} catch (final SignatureException e) {
LOGGER.error("Failed to validate assertion signature", e);
}
SamlUtils.logSamlObject(this.configBean, assertion);
LOGGER.error("Signature doesn't match any signing credential and cannot be validated.");
return false;
} | [
"public",
"boolean",
"validateSignature",
"(",
"final",
"Pair",
"<",
"Assertion",
",",
"WsFederationConfiguration",
">",
"resultPair",
")",
"{",
"if",
"(",
"resultPair",
"==",
"null",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"No assertion or its configuration was pro... | validateSignature checks to see if the signature on an assertion is valid.
@param resultPair a provided assertion
@return true if the assertion's signature is valid, otherwise false | [
"validateSignature",
"checks",
"to",
"see",
"if",
"the",
"signature",
"on",
"an",
"assertion",
"is",
"valid",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/WsFederationHelper.java#L312-L355 |
jboss/jboss-jsf-api_spec | src/main/java/javax/faces/view/facelets/MetaTagHandler.java | MetaTagHandler.setAttributes | protected void setAttributes(FaceletContext ctx, Object instance) {
"""
Invoking/extending this method will cause the results of the created
MetaRuleset to auto-wire state to the passed instance.
@param ctx
@param instance
"""
if (instance != null) {
Class type = instance.getClass();
if (mapper == null || !this.lastType.equals(type)) {
this.lastType = type;
this.mapper = this.createMetaRuleset(type).finish();
}
this.mapper.applyMetadata(ctx, instance);
}
} | java | protected void setAttributes(FaceletContext ctx, Object instance) {
if (instance != null) {
Class type = instance.getClass();
if (mapper == null || !this.lastType.equals(type)) {
this.lastType = type;
this.mapper = this.createMetaRuleset(type).finish();
}
this.mapper.applyMetadata(ctx, instance);
}
} | [
"protected",
"void",
"setAttributes",
"(",
"FaceletContext",
"ctx",
",",
"Object",
"instance",
")",
"{",
"if",
"(",
"instance",
"!=",
"null",
")",
"{",
"Class",
"type",
"=",
"instance",
".",
"getClass",
"(",
")",
";",
"if",
"(",
"mapper",
"==",
"null",
... | Invoking/extending this method will cause the results of the created
MetaRuleset to auto-wire state to the passed instance.
@param ctx
@param instance | [
"Invoking",
"/",
"extending",
"this",
"method",
"will",
"cause",
"the",
"results",
"of",
"the",
"created",
"MetaRuleset",
"to",
"auto",
"-",
"wire",
"state",
"to",
"the",
"passed",
"instance",
"."
] | train | https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/view/facelets/MetaTagHandler.java#L122-L131 |
lastaflute/lastaflute | src/main/java/org/lastaflute/core/mail/LaTypicalPostcard.java | LaTypicalPostcard.forcedlyDirect | public void forcedlyDirect(String subject, String plainBody) {
"""
Set subject and plain body as forcedly-direct. <br>
It ignores body file settings. (conversely can keep them)
@param subject The subject to be sent plainly. (NotNull)
@param plainBody The plain body to be sent plainly. (NotNull)
"""
postcard.useDirectBody(plainBody).useWholeFixedText().forcedlyDirect(subject);
} | java | public void forcedlyDirect(String subject, String plainBody) {
postcard.useDirectBody(plainBody).useWholeFixedText().forcedlyDirect(subject);
} | [
"public",
"void",
"forcedlyDirect",
"(",
"String",
"subject",
",",
"String",
"plainBody",
")",
"{",
"postcard",
".",
"useDirectBody",
"(",
"plainBody",
")",
".",
"useWholeFixedText",
"(",
")",
".",
"forcedlyDirect",
"(",
"subject",
")",
";",
"}"
] | Set subject and plain body as forcedly-direct. <br>
It ignores body file settings. (conversely can keep them)
@param subject The subject to be sent plainly. (NotNull)
@param plainBody The plain body to be sent plainly. (NotNull) | [
"Set",
"subject",
"and",
"plain",
"body",
"as",
"forcedly",
"-",
"direct",
".",
"<br",
">",
"It",
"ignores",
"body",
"file",
"settings",
".",
"(",
"conversely",
"can",
"keep",
"them",
")"
] | train | https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/core/mail/LaTypicalPostcard.java#L247-L249 |
zaproxy/zaproxy | src/org/parosproxy/paros/core/scanner/HostProcess.java | HostProcess.pluginSkipped | public void pluginSkipped(Plugin plugin, String reason) {
"""
Skips the given {@code plugin} with the given {@code reason}.
<p>
Ideally the {@code reason} should be internationalised as it is shown in the GUI.
@param plugin the plugin that will be skipped, must not be {@code null}
@param reason the reason why the plugin was skipped, might be {@code null}
@since 2.6.0
"""
if (isStop()) {
return;
}
PluginStats pluginStats = mapPluginStats.get(plugin.getId());
if (pluginStats == null || pluginStats.isSkipped() || pluginFactory.getCompleted().contains(plugin)) {
return;
}
pluginStats.skip();
pluginStats.setSkippedReason(reason);
for (Plugin dependent : pluginFactory.getDependentPlugins(plugin)) {
pluginStats = mapPluginStats.get(dependent.getId());
if (pluginStats != null && !pluginStats.isSkipped() && !pluginFactory.getCompleted().contains(dependent)) {
pluginStats.skip();
pluginStats.setSkippedReason(
Constant.messages.getString(
"ascan.progress.label.skipped.reason.dependency"));
}
}
} | java | public void pluginSkipped(Plugin plugin, String reason) {
if (isStop()) {
return;
}
PluginStats pluginStats = mapPluginStats.get(plugin.getId());
if (pluginStats == null || pluginStats.isSkipped() || pluginFactory.getCompleted().contains(plugin)) {
return;
}
pluginStats.skip();
pluginStats.setSkippedReason(reason);
for (Plugin dependent : pluginFactory.getDependentPlugins(plugin)) {
pluginStats = mapPluginStats.get(dependent.getId());
if (pluginStats != null && !pluginStats.isSkipped() && !pluginFactory.getCompleted().contains(dependent)) {
pluginStats.skip();
pluginStats.setSkippedReason(
Constant.messages.getString(
"ascan.progress.label.skipped.reason.dependency"));
}
}
} | [
"public",
"void",
"pluginSkipped",
"(",
"Plugin",
"plugin",
",",
"String",
"reason",
")",
"{",
"if",
"(",
"isStop",
"(",
")",
")",
"{",
"return",
";",
"}",
"PluginStats",
"pluginStats",
"=",
"mapPluginStats",
".",
"get",
"(",
"plugin",
".",
"getId",
"(",... | Skips the given {@code plugin} with the given {@code reason}.
<p>
Ideally the {@code reason} should be internationalised as it is shown in the GUI.
@param plugin the plugin that will be skipped, must not be {@code null}
@param reason the reason why the plugin was skipped, might be {@code null}
@since 2.6.0 | [
"Skips",
"the",
"given",
"{",
"@code",
"plugin",
"}",
"with",
"the",
"given",
"{",
"@code",
"reason",
"}",
".",
"<p",
">",
"Ideally",
"the",
"{",
"@code",
"reason",
"}",
"should",
"be",
"internationalised",
"as",
"it",
"is",
"shown",
"in",
"the",
"GUI"... | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/scanner/HostProcess.java#L881-L903 |
Alluxio/alluxio | core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java | InodeTreePersistentState.applyAndJournal | public void applyAndJournal(Supplier<JournalContext> context, UpdateInodeEntry entry) {
"""
Updates an inode's state. This is used for state common to both files and directories.
@param context journal context supplier
@param entry update inode entry
"""
try {
applyUpdateInode(entry);
context.get().append(JournalEntry.newBuilder().setUpdateInode(entry).build());
} catch (Throwable t) {
ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry);
throw t; // fatalError will usually system.exit
}
} | java | public void applyAndJournal(Supplier<JournalContext> context, UpdateInodeEntry entry) {
try {
applyUpdateInode(entry);
context.get().append(JournalEntry.newBuilder().setUpdateInode(entry).build());
} catch (Throwable t) {
ProcessUtils.fatalError(LOG, t, "Failed to apply %s", entry);
throw t; // fatalError will usually system.exit
}
} | [
"public",
"void",
"applyAndJournal",
"(",
"Supplier",
"<",
"JournalContext",
">",
"context",
",",
"UpdateInodeEntry",
"entry",
")",
"{",
"try",
"{",
"applyUpdateInode",
"(",
"entry",
")",
";",
"context",
".",
"get",
"(",
")",
".",
"append",
"(",
"JournalEntr... | Updates an inode's state. This is used for state common to both files and directories.
@param context journal context supplier
@param entry update inode entry | [
"Updates",
"an",
"inode",
"s",
"state",
".",
"This",
"is",
"used",
"for",
"state",
"common",
"to",
"both",
"files",
"and",
"directories",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTreePersistentState.java#L234-L242 |
hawkular/hawkular-apm | client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java | OpenTracingManager.sanitizePaths | public String sanitizePaths(String baseUri, String resourcePath) {
"""
Helper to remove duplicate slashes
@param baseUri the base URI, usually in the format "/context/restapp/"
@param resourcePath the resource path, usually in the format "/resource/method/record"
@return The two parameters joined, with the double slash between them removed, like "/context/restapp/resource/method/record"
"""
if (baseUri.endsWith("/") && resourcePath.startsWith("/")) {
return baseUri.substring(0, baseUri.length()-1) + resourcePath;
}
if ((!baseUri.endsWith("/")) && (!resourcePath.startsWith("/"))) {
return baseUri + "/" + resourcePath;
}
return baseUri + resourcePath;
} | java | public String sanitizePaths(String baseUri, String resourcePath) {
if (baseUri.endsWith("/") && resourcePath.startsWith("/")) {
return baseUri.substring(0, baseUri.length()-1) + resourcePath;
}
if ((!baseUri.endsWith("/")) && (!resourcePath.startsWith("/"))) {
return baseUri + "/" + resourcePath;
}
return baseUri + resourcePath;
} | [
"public",
"String",
"sanitizePaths",
"(",
"String",
"baseUri",
",",
"String",
"resourcePath",
")",
"{",
"if",
"(",
"baseUri",
".",
"endsWith",
"(",
"\"/\"",
")",
"&&",
"resourcePath",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"return",
"baseUri",
"."... | Helper to remove duplicate slashes
@param baseUri the base URI, usually in the format "/context/restapp/"
@param resourcePath the resource path, usually in the format "/resource/method/record"
@return The two parameters joined, with the double slash between them removed, like "/context/restapp/resource/method/record" | [
"Helper",
"to",
"remove",
"duplicate",
"slashes"
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/agent-opentracing/src/main/java/org/hawkular/apm/agent/opentracing/OpenTracingManager.java#L543-L552 |
wildfly/wildfly-core | server/src/main/java/org/jboss/as/server/ServerEnvironment.java | ServerEnvironment.getFileFromProperty | private File getFileFromProperty(final String name, final Properties props) {
"""
Get a File from configuration.
@param name the name of the property
@param props the set of configuration properties
@return the CanonicalFile form for the given name.
"""
return getFileFromPath(props.getProperty(name));
} | java | private File getFileFromProperty(final String name, final Properties props) {
return getFileFromPath(props.getProperty(name));
} | [
"private",
"File",
"getFileFromProperty",
"(",
"final",
"String",
"name",
",",
"final",
"Properties",
"props",
")",
"{",
"return",
"getFileFromPath",
"(",
"props",
".",
"getProperty",
"(",
"name",
")",
")",
";",
"}"
] | Get a File from configuration.
@param name the name of the property
@param props the set of configuration properties
@return the CanonicalFile form for the given name. | [
"Get",
"a",
"File",
"from",
"configuration",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/ServerEnvironment.java#L1179-L1181 |
strator-dev/greenpepper | greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/rpc/runner/XmlRpcRemoteRunner.java | XmlRpcRemoteRunner.runReference | public Reference runReference(SystemUnderTest sut, Specification specification, Requirement requirement, String locale)
throws GreenPepperServerException {
"""
<p>runReference.</p>
@param sut a {@link com.greenpepper.server.domain.SystemUnderTest} object.
@param specification a {@link com.greenpepper.server.domain.Specification} object.
@param requirement a {@link com.greenpepper.server.domain.Requirement} object.
@param locale a {@link java.lang.String} object.
@return a {@link com.greenpepper.server.domain.Reference} object.
@throws com.greenpepper.server.GreenPepperServerException if any.
"""
if (sut.getProject() == null)
{
throw new IllegalArgumentException("Missing Project in SystemUnderTest");
}
if (specification.getRepository() == null)
{
throw new IllegalArgumentException("Missing Repository in Specification");
}
if (requirement.getRepository() == null)
{
throw new IllegalArgumentException("Missing Repository in Requirement");
}
Reference reference = Reference.newInstance(requirement, specification, sut);
return runReference(reference, locale);
} | java | public Reference runReference(SystemUnderTest sut, Specification specification, Requirement requirement, String locale)
throws GreenPepperServerException
{
if (sut.getProject() == null)
{
throw new IllegalArgumentException("Missing Project in SystemUnderTest");
}
if (specification.getRepository() == null)
{
throw new IllegalArgumentException("Missing Repository in Specification");
}
if (requirement.getRepository() == null)
{
throw new IllegalArgumentException("Missing Repository in Requirement");
}
Reference reference = Reference.newInstance(requirement, specification, sut);
return runReference(reference, locale);
} | [
"public",
"Reference",
"runReference",
"(",
"SystemUnderTest",
"sut",
",",
"Specification",
"specification",
",",
"Requirement",
"requirement",
",",
"String",
"locale",
")",
"throws",
"GreenPepperServerException",
"{",
"if",
"(",
"sut",
".",
"getProject",
"(",
")",
... | <p>runReference.</p>
@param sut a {@link com.greenpepper.server.domain.SystemUnderTest} object.
@param specification a {@link com.greenpepper.server.domain.Specification} object.
@param requirement a {@link com.greenpepper.server.domain.Requirement} object.
@param locale a {@link java.lang.String} object.
@return a {@link com.greenpepper.server.domain.Reference} object.
@throws com.greenpepper.server.GreenPepperServerException if any. | [
"<p",
">",
"runReference",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/rpc/runner/XmlRpcRemoteRunner.java#L198-L219 |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java | ArrayBackedSortedColumns.maybeAppendColumn | public void maybeAppendColumn(Cell cell, DeletionInfo.InOrderTester tester, int gcBefore) {
"""
Adds a cell, assuming that:
- it's non-gc-able (if a tombstone) or not a tombstone
- it has a more recent timestamp than any partition/range tombstone shadowing it
- it sorts *strictly after* the current-last cell in the array.
"""
if (cell.getLocalDeletionTime() >= gcBefore && !tester.isDeleted(cell))
{
internalAdd(cell);
sortedSize++;
}
} | java | public void maybeAppendColumn(Cell cell, DeletionInfo.InOrderTester tester, int gcBefore)
{
if (cell.getLocalDeletionTime() >= gcBefore && !tester.isDeleted(cell))
{
internalAdd(cell);
sortedSize++;
}
} | [
"public",
"void",
"maybeAppendColumn",
"(",
"Cell",
"cell",
",",
"DeletionInfo",
".",
"InOrderTester",
"tester",
",",
"int",
"gcBefore",
")",
"{",
"if",
"(",
"cell",
".",
"getLocalDeletionTime",
"(",
")",
">=",
"gcBefore",
"&&",
"!",
"tester",
".",
"isDelete... | Adds a cell, assuming that:
- it's non-gc-able (if a tombstone) or not a tombstone
- it has a more recent timestamp than any partition/range tombstone shadowing it
- it sorts *strictly after* the current-last cell in the array. | [
"Adds",
"a",
"cell",
"assuming",
"that",
":",
"-",
"it",
"s",
"non",
"-",
"gc",
"-",
"able",
"(",
"if",
"a",
"tombstone",
")",
"or",
"not",
"a",
"tombstone",
"-",
"it",
"has",
"a",
"more",
"recent",
"timestamp",
"than",
"any",
"partition",
"/",
"ra... | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/ArrayBackedSortedColumns.java#L282-L289 |
apereo/cas | support/cas-server-support-hazelcast-core/src/main/java/org/apereo/cas/hz/HazelcastConfigurationFactory.java | HazelcastConfigurationFactory.buildMapConfig | public MapConfig buildMapConfig(final BaseHazelcastProperties hz, final String mapName, final long timeoutSeconds) {
"""
Build map config map config.
@param hz the hz
@param mapName the storage name
@param timeoutSeconds the timeoutSeconds
@return the map config
"""
val cluster = hz.getCluster();
val evictionPolicy = EvictionPolicy.valueOf(cluster.getEvictionPolicy());
LOGGER.trace("Creating Hazelcast map configuration for [{}] with idle timeoutSeconds [{}] second(s)", mapName, timeoutSeconds);
val maxSizeConfig = new MaxSizeConfig()
.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.valueOf(cluster.getMaxSizePolicy()))
.setSize(cluster.getMaxHeapSizePercentage());
val mergePolicyConfig = new MergePolicyConfig();
if (StringUtils.hasText(cluster.getMapMergePolicy())) {
mergePolicyConfig.setPolicy(cluster.getMapMergePolicy());
}
return new MapConfig()
.setName(mapName)
.setMergePolicyConfig(mergePolicyConfig)
.setMaxIdleSeconds((int) timeoutSeconds)
.setBackupCount(cluster.getBackupCount())
.setAsyncBackupCount(cluster.getAsyncBackupCount())
.setEvictionPolicy(evictionPolicy)
.setMaxSizeConfig(maxSizeConfig);
} | java | public MapConfig buildMapConfig(final BaseHazelcastProperties hz, final String mapName, final long timeoutSeconds) {
val cluster = hz.getCluster();
val evictionPolicy = EvictionPolicy.valueOf(cluster.getEvictionPolicy());
LOGGER.trace("Creating Hazelcast map configuration for [{}] with idle timeoutSeconds [{}] second(s)", mapName, timeoutSeconds);
val maxSizeConfig = new MaxSizeConfig()
.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.valueOf(cluster.getMaxSizePolicy()))
.setSize(cluster.getMaxHeapSizePercentage());
val mergePolicyConfig = new MergePolicyConfig();
if (StringUtils.hasText(cluster.getMapMergePolicy())) {
mergePolicyConfig.setPolicy(cluster.getMapMergePolicy());
}
return new MapConfig()
.setName(mapName)
.setMergePolicyConfig(mergePolicyConfig)
.setMaxIdleSeconds((int) timeoutSeconds)
.setBackupCount(cluster.getBackupCount())
.setAsyncBackupCount(cluster.getAsyncBackupCount())
.setEvictionPolicy(evictionPolicy)
.setMaxSizeConfig(maxSizeConfig);
} | [
"public",
"MapConfig",
"buildMapConfig",
"(",
"final",
"BaseHazelcastProperties",
"hz",
",",
"final",
"String",
"mapName",
",",
"final",
"long",
"timeoutSeconds",
")",
"{",
"val",
"cluster",
"=",
"hz",
".",
"getCluster",
"(",
")",
";",
"val",
"evictionPolicy",
... | Build map config map config.
@param hz the hz
@param mapName the storage name
@param timeoutSeconds the timeoutSeconds
@return the map config | [
"Build",
"map",
"config",
"map",
"config",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-hazelcast-core/src/main/java/org/apereo/cas/hz/HazelcastConfigurationFactory.java#L49-L71 |
motown-io/motown | ocpp/soap-utils/src/main/java/io/motown/ocpp/utils/soap/async/StartTransactionFutureEventCallback.java | StartTransactionFutureEventCallback.onEvent | @Override
public boolean onEvent(EventMessage<?> event) {
"""
Handles the {@code AuthorizationResultEvent} (other events will directly result in 'false' return value). In the
flow of handling a start transaction message the first step is to authorize the identification used to start
the transaction. This method handles that event and uses the domain service to start the transaction and sets the
result of the start transaction using 'setResult'. The continuation, if it exists, is resumed.
@param event Authorizaton result event.
@return true if the event has been handled, false if the event was the wrong type.
"""
AuthorizationResultEvent resultEvent;
if (!(event.getPayload() instanceof AuthorizationResultEvent)) {
// not the right type of event... not 'handled'
return false;
}
resultEvent = (AuthorizationResultEvent) event.getPayload();
Transaction transaction = domainService.createTransaction(startTransaction.getEvseId());
NumberedTransactionId transactionId = new NumberedTransactionId(chargingStationId, protocolIdentifier, transaction.getId().intValue());
IdentifyingToken identifyingToken = resultEvent.getIdentifyingToken();
StartTransactionInfo extendedStartTransactionInfo = new StartTransactionInfo(startTransaction.getEvseId(), startTransaction.getMeterStart(), startTransaction.getTimestamp(), identifyingToken, startTransaction.getAttributes());
domainService.startTransactionNoAuthorize(chargingStationId, transactionId, extendedStartTransactionInfo, addOnIdentity);
StartTransactionFutureResult futureResult = new StartTransactionFutureResult();
futureResult.setAuthorizationResultStatus(resultEvent.getAuthenticationStatus());
futureResult.setTransactionId(transactionId.getNumber());
this.setResult(futureResult);
this.countDownLatch();
if (continuation != null) {
// no need to wait for the continuation timeout, resume it now
continuation.resume();
}
return true;
} | java | @Override
public boolean onEvent(EventMessage<?> event) {
AuthorizationResultEvent resultEvent;
if (!(event.getPayload() instanceof AuthorizationResultEvent)) {
// not the right type of event... not 'handled'
return false;
}
resultEvent = (AuthorizationResultEvent) event.getPayload();
Transaction transaction = domainService.createTransaction(startTransaction.getEvseId());
NumberedTransactionId transactionId = new NumberedTransactionId(chargingStationId, protocolIdentifier, transaction.getId().intValue());
IdentifyingToken identifyingToken = resultEvent.getIdentifyingToken();
StartTransactionInfo extendedStartTransactionInfo = new StartTransactionInfo(startTransaction.getEvseId(), startTransaction.getMeterStart(), startTransaction.getTimestamp(), identifyingToken, startTransaction.getAttributes());
domainService.startTransactionNoAuthorize(chargingStationId, transactionId, extendedStartTransactionInfo, addOnIdentity);
StartTransactionFutureResult futureResult = new StartTransactionFutureResult();
futureResult.setAuthorizationResultStatus(resultEvent.getAuthenticationStatus());
futureResult.setTransactionId(transactionId.getNumber());
this.setResult(futureResult);
this.countDownLatch();
if (continuation != null) {
// no need to wait for the continuation timeout, resume it now
continuation.resume();
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"onEvent",
"(",
"EventMessage",
"<",
"?",
">",
"event",
")",
"{",
"AuthorizationResultEvent",
"resultEvent",
";",
"if",
"(",
"!",
"(",
"event",
".",
"getPayload",
"(",
")",
"instanceof",
"AuthorizationResultEvent",
")",
")... | Handles the {@code AuthorizationResultEvent} (other events will directly result in 'false' return value). In the
flow of handling a start transaction message the first step is to authorize the identification used to start
the transaction. This method handles that event and uses the domain service to start the transaction and sets the
result of the start transaction using 'setResult'. The continuation, if it exists, is resumed.
@param event Authorizaton result event.
@return true if the event has been handled, false if the event was the wrong type. | [
"Handles",
"the",
"{",
"@code",
"AuthorizationResultEvent",
"}",
"(",
"other",
"events",
"will",
"directly",
"result",
"in",
"false",
"return",
"value",
")",
".",
"In",
"the",
"flow",
"of",
"handling",
"a",
"start",
"transaction",
"message",
"the",
"first",
... | train | https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/soap-utils/src/main/java/io/motown/ocpp/utils/soap/async/StartTransactionFutureEventCallback.java#L67-L100 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java | ExtractJobConfiguration.of | public static ExtractJobConfiguration of(TableId sourceTable, String destinationUri) {
"""
Returns a BigQuery Extract Job configuration for the given source table and destination URI.
"""
return newBuilder(sourceTable, destinationUri).build();
} | java | public static ExtractJobConfiguration of(TableId sourceTable, String destinationUri) {
return newBuilder(sourceTable, destinationUri).build();
} | [
"public",
"static",
"ExtractJobConfiguration",
"of",
"(",
"TableId",
"sourceTable",
",",
"String",
"destinationUri",
")",
"{",
"return",
"newBuilder",
"(",
"sourceTable",
",",
"destinationUri",
")",
".",
"build",
"(",
")",
";",
"}"
] | Returns a BigQuery Extract Job configuration for the given source table and destination URI. | [
"Returns",
"a",
"BigQuery",
"Extract",
"Job",
"configuration",
"for",
"the",
"given",
"source",
"table",
"and",
"destination",
"URI",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java#L257-L259 |
hawkular/hawkular-apm | api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java | AbstractAnalyticsService.buildTree | protected static void buildTree(EndpointPart parent, String[] parts, int index, String endpointType) {
"""
This method builds a tree.
@param parent The current parent node
@param parts The parts of the URI being processed
@param index The current index into the parts array
@param endpointType The endpoint type
"""
// Check if operation qualifier is part of last element
String name = parts[index];
String qualifier = null;
if (index == parts.length - 1) {
qualifier = EndpointUtil.decodeEndpointOperation(parts[index], false);
name = EndpointUtil.decodeEndpointURI(parts[index]);
}
// Check if part is defined in the parent
EndpointPart child = parent.addChild(name);
if (index < parts.length - 1) {
buildTree(child, parts, index + 1, endpointType);
} else {
// Check if part has an operation qualifier
if (qualifier != null) {
child = child.addChild(qualifier);
child.setQualifier(true);
}
child.setEndpointType(endpointType);
}
} | java | protected static void buildTree(EndpointPart parent, String[] parts, int index, String endpointType) {
// Check if operation qualifier is part of last element
String name = parts[index];
String qualifier = null;
if (index == parts.length - 1) {
qualifier = EndpointUtil.decodeEndpointOperation(parts[index], false);
name = EndpointUtil.decodeEndpointURI(parts[index]);
}
// Check if part is defined in the parent
EndpointPart child = parent.addChild(name);
if (index < parts.length - 1) {
buildTree(child, parts, index + 1, endpointType);
} else {
// Check if part has an operation qualifier
if (qualifier != null) {
child = child.addChild(qualifier);
child.setQualifier(true);
}
child.setEndpointType(endpointType);
}
} | [
"protected",
"static",
"void",
"buildTree",
"(",
"EndpointPart",
"parent",
",",
"String",
"[",
"]",
"parts",
",",
"int",
"index",
",",
"String",
"endpointType",
")",
"{",
"// Check if operation qualifier is part of last element",
"String",
"name",
"=",
"parts",
"[",... | This method builds a tree.
@param parent The current parent node
@param parts The parts of the URI being processed
@param index The current index into the parts array
@param endpointType The endpoint type | [
"This",
"method",
"builds",
"a",
"tree",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L182-L205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.