repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
inferred/FreeBuilder | src/main/java/org/inferred/freebuilder/processor/model/ModelUtils.java | ModelUtils.needsSafeVarargs | public static boolean needsSafeVarargs(TypeMirror elementType) {
return elementType.accept(new SimpleTypeVisitor8<Boolean, Void>() {
@Override
public Boolean visitDeclared(DeclaredType t, Void p) {
// Set<?>... does not need @SafeVarargs; Set<Integer>... or Set<? extends Number> does.
for (TypeMirror typeArgument : t.getTypeArguments()) {
if (!isPlainWildcard(typeArgument)) {
return true;
}
}
return false;
}
@Override
public Boolean visitTypeVariable(TypeVariable t, Void p) {
return true;
}
@Override
protected Boolean defaultAction(TypeMirror e, Void p) {
return false;
}
@Override
public Boolean visitUnknown(TypeMirror t, Void p) {
return false;
}
}, null);
} | java | public static boolean needsSafeVarargs(TypeMirror elementType) {
return elementType.accept(new SimpleTypeVisitor8<Boolean, Void>() {
@Override
public Boolean visitDeclared(DeclaredType t, Void p) {
// Set<?>... does not need @SafeVarargs; Set<Integer>... or Set<? extends Number> does.
for (TypeMirror typeArgument : t.getTypeArguments()) {
if (!isPlainWildcard(typeArgument)) {
return true;
}
}
return false;
}
@Override
public Boolean visitTypeVariable(TypeVariable t, Void p) {
return true;
}
@Override
protected Boolean defaultAction(TypeMirror e, Void p) {
return false;
}
@Override
public Boolean visitUnknown(TypeMirror t, Void p) {
return false;
}
}, null);
} | [
"public",
"static",
"boolean",
"needsSafeVarargs",
"(",
"TypeMirror",
"elementType",
")",
"{",
"return",
"elementType",
".",
"accept",
"(",
"new",
"SimpleTypeVisitor8",
"<",
"Boolean",
",",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Boolean",
"vis... | Returns true if a method with a variable number of {@code elementType} arguments needs a
{@code @SafeVarargs} annotation to avoid compiler warnings in Java 7+. | [
"Returns",
"true",
"if",
"a",
"method",
"with",
"a",
"variable",
"number",
"of",
"{"
] | train | https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/model/ModelUtils.java#L169-L197 |
knowm/Datasets | datasets-hja-birdsong/src/main/java/com/musicg/wave/SpectrogramRender.java | SpectrogramRender.renderSpectrogram | public BufferedImage renderSpectrogram(Spectrogram spectrogram) {
double[][] spectrogramData = spectrogram.getNormalizedSpectrogramData();
int width = spectrogramData.length;
int height = spectrogramData[0].length;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int value;
value = (int) (spectrogramData[i][j] * 255);
bufferedImage.setRGB(i, j, value << 16 | value << 8 | value);
}
}
return bufferedImage;
} | java | public BufferedImage renderSpectrogram(Spectrogram spectrogram) {
double[][] spectrogramData = spectrogram.getNormalizedSpectrogramData();
int width = spectrogramData.length;
int height = spectrogramData[0].length;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int value;
value = (int) (spectrogramData[i][j] * 255);
bufferedImage.setRGB(i, j, value << 16 | value << 8 | value);
}
}
return bufferedImage;
} | [
"public",
"BufferedImage",
"renderSpectrogram",
"(",
"Spectrogram",
"spectrogram",
")",
"{",
"double",
"[",
"]",
"[",
"]",
"spectrogramData",
"=",
"spectrogram",
".",
"getNormalizedSpectrogramData",
"(",
")",
";",
"int",
"width",
"=",
"spectrogramData",
".",
"leng... | Render a spectrogram of a wave file
@param spectrogram spectrogram object | [
"Render",
"a",
"spectrogram",
"of",
"a",
"wave",
"file"
] | train | https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-hja-birdsong/src/main/java/com/musicg/wave/SpectrogramRender.java#L32-L50 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/TerminalTextUtils.java | TerminalTextUtils.getStringCharacterIndex | public static int getStringCharacterIndex(String s, int columnIndex) {
int index = 0;
int counter = 0;
while(counter < columnIndex) {
if(isCharCJK(s.charAt(index++))) {
counter++;
if(counter == columnIndex) {
return index - 1;
}
}
counter++;
}
return index;
} | java | public static int getStringCharacterIndex(String s, int columnIndex) {
int index = 0;
int counter = 0;
while(counter < columnIndex) {
if(isCharCJK(s.charAt(index++))) {
counter++;
if(counter == columnIndex) {
return index - 1;
}
}
counter++;
}
return index;
} | [
"public",
"static",
"int",
"getStringCharacterIndex",
"(",
"String",
"s",
",",
"int",
"columnIndex",
")",
"{",
"int",
"index",
"=",
"0",
";",
"int",
"counter",
"=",
"0",
";",
"while",
"(",
"counter",
"<",
"columnIndex",
")",
"{",
"if",
"(",
"isCharCJK",
... | This method does the reverse of getColumnIndex, given a String and imagining it has been printed out to the
top-left corner of a terminal, in the column specified by {@code columnIndex}, what is the index of that
character in the string. If the string contains no CJK characters, this will always be the same as
{@code columnIndex}. If the index specified is the right column of a CJK character, the index is the same as if
the column was the left column. So calling {@code getStringCharacterIndex("英", 0)} and
{@code getStringCharacterIndex("英", 1)} will both return 0.
@param s String to translate the index to
@param columnIndex Column index of the string written to a terminal
@return The index in the string of the character in terminal column {@code columnIndex} | [
"This",
"method",
"does",
"the",
"reverse",
"of",
"getColumnIndex",
"given",
"a",
"String",
"and",
"imagining",
"it",
"has",
"been",
"printed",
"out",
"to",
"the",
"top",
"-",
"left",
"corner",
"of",
"a",
"terminal",
"in",
"the",
"column",
"specified",
"by... | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/TerminalTextUtils.java#L226-L239 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/routing/bindings/Request.java | Request.addAttribute | public void addAttribute(String key, Object value) {
Objects.requireNonNull(key, Required.KEY.toString());
this.attributes.put(key, value);
} | java | public void addAttribute(String key, Object value) {
Objects.requireNonNull(key, Required.KEY.toString());
this.attributes.put(key, value);
} | [
"public",
"void",
"addAttribute",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"key",
",",
"Required",
".",
"KEY",
".",
"toString",
"(",
")",
")",
";",
"this",
".",
"attributes",
".",
"put",
"(",
"key",... | Adds an attribute to the internal attributes map
@param key The key to store the attribute
@param value The value to store | [
"Adds",
"an",
"attribute",
"to",
"the",
"internal",
"attributes",
"map"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Request.java#L242-L245 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/PluralRanges.java | PluralRanges.get | @Deprecated
public StandardPlural get(StandardPlural start, StandardPlural end) {
StandardPlural result = matrix.get(start, end);
return result == null ? end : result;
} | java | @Deprecated
public StandardPlural get(StandardPlural start, StandardPlural end) {
StandardPlural result = matrix.get(start, end);
return result == null ? end : result;
} | [
"@",
"Deprecated",
"public",
"StandardPlural",
"get",
"(",
"StandardPlural",
"start",
",",
"StandardPlural",
"end",
")",
"{",
"StandardPlural",
"result",
"=",
"matrix",
".",
"get",
"(",
"start",
",",
"end",
")",
";",
"return",
"result",
"==",
"null",
"?",
... | Returns the appropriate plural category for a range from start to end. If there is no available data, then
'end' is returned as an implicit value. (Such an implicit value can be tested for with {@link #isExplicit}.)
@param start
plural category for the start of the range
@param end
plural category for the end of the range
@return the resulting plural category, or 'end' if there is no data.
@deprecated This API is ICU internal only.
@hide draft / provisional / internal are hidden on Android | [
"Returns",
"the",
"appropriate",
"plural",
"category",
"for",
"a",
"range",
"from",
"start",
"to",
"end",
".",
"If",
"there",
"is",
"no",
"available",
"data",
"then",
"end",
"is",
"returned",
"as",
"an",
"implicit",
"value",
".",
"(",
"Such",
"an",
"impl... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/PluralRanges.java#L244-L248 |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/helpers/CustomStickyRecyclerHeadersDecoration.java | CustomStickyRecyclerHeadersDecoration.setItemOffsetsForHeader | private void setItemOffsetsForHeader(Rect itemOffsets, View header, int orientation) {
mDimensionCalculator.initMargins(mTempRect, header);
if (orientation == LinearLayoutManager.VERTICAL) {
itemOffsets.top = header.getHeight() + mTempRect.top + mTempRect.bottom;
} else {
itemOffsets.left = header.getWidth() + mTempRect.left + mTempRect.right;
}
} | java | private void setItemOffsetsForHeader(Rect itemOffsets, View header, int orientation) {
mDimensionCalculator.initMargins(mTempRect, header);
if (orientation == LinearLayoutManager.VERTICAL) {
itemOffsets.top = header.getHeight() + mTempRect.top + mTempRect.bottom;
} else {
itemOffsets.left = header.getWidth() + mTempRect.left + mTempRect.right;
}
} | [
"private",
"void",
"setItemOffsetsForHeader",
"(",
"Rect",
"itemOffsets",
",",
"View",
"header",
",",
"int",
"orientation",
")",
"{",
"mDimensionCalculator",
".",
"initMargins",
"(",
"mTempRect",
",",
"header",
")",
";",
"if",
"(",
"orientation",
"==",
"LinearLa... | Sets the offsets for the first item in a section to make room for the header view
@param itemOffsets rectangle to define offsets for the item
@param header view used to calculate offset for the item
@param orientation used to calculate offset for the item | [
"Sets",
"the",
"offsets",
"for",
"the",
"first",
"item",
"in",
"a",
"section",
"to",
"make",
"room",
"for",
"the",
"header",
"view"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/app/src/main/java/com/mikepenz/fastadapter/app/helpers/CustomStickyRecyclerHeadersDecoration.java#L87-L94 |
looly/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/WorkbookUtil.java | WorkbookUtil.writeBook | public static void writeBook(Workbook book, OutputStream out) throws IORuntimeException {
try {
book.write(out);
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | java | public static void writeBook(Workbook book, OutputStream out) throws IORuntimeException {
try {
book.write(out);
} catch (IOException e) {
throw new IORuntimeException(e);
}
} | [
"public",
"static",
"void",
"writeBook",
"(",
"Workbook",
"book",
",",
"OutputStream",
"out",
")",
"throws",
"IORuntimeException",
"{",
"try",
"{",
"book",
".",
"write",
"(",
"out",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new... | 将Excel Workbook刷出到输出流,不关闭流
@param book {@link Workbook}
@param out 输出流
@throws IORuntimeException IO异常
@since 3.2.0 | [
"将Excel",
"Workbook刷出到输出流,不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/WorkbookUtil.java#L203-L209 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/gen/CodeBuilderUtil.java | CodeBuilderUtil.throwConcatException | public static void throwConcatException(CodeBuilder b, Class type, String... messages) {
if (messages == null || messages.length == 0) {
throwException(b, type, null);
return;
}
if (messages.length == 1) {
throwException(b, type, messages[0]);
return;
}
TypeDesc desc = TypeDesc.forClass(type);
b.newObject(desc);
b.dup();
TypeDesc[] params = new TypeDesc[] {TypeDesc.STRING};
for (int i=0; i<messages.length; i++) {
b.loadConstant(String.valueOf(messages[i]));
if (i > 0) {
b.invokeVirtual(TypeDesc.STRING, "concat", TypeDesc.STRING, params);
}
}
b.invokeConstructor(desc, params);
b.throwObject();
} | java | public static void throwConcatException(CodeBuilder b, Class type, String... messages) {
if (messages == null || messages.length == 0) {
throwException(b, type, null);
return;
}
if (messages.length == 1) {
throwException(b, type, messages[0]);
return;
}
TypeDesc desc = TypeDesc.forClass(type);
b.newObject(desc);
b.dup();
TypeDesc[] params = new TypeDesc[] {TypeDesc.STRING};
for (int i=0; i<messages.length; i++) {
b.loadConstant(String.valueOf(messages[i]));
if (i > 0) {
b.invokeVirtual(TypeDesc.STRING, "concat", TypeDesc.STRING, params);
}
}
b.invokeConstructor(desc, params);
b.throwObject();
} | [
"public",
"static",
"void",
"throwConcatException",
"(",
"CodeBuilder",
"b",
",",
"Class",
"type",
",",
"String",
"...",
"messages",
")",
"{",
"if",
"(",
"messages",
"==",
"null",
"||",
"messages",
".",
"length",
"==",
"0",
")",
"{",
"throwException",
"(",... | Generate code to throw an exception with a message concatenated at runtime.
@param b {@link CodeBuilder} to which to add code
@param type type of the object to throw
@param messages messages to concat at runtime | [
"Generate",
"code",
"to",
"throw",
"an",
"exception",
"with",
"a",
"message",
"concatenated",
"at",
"runtime",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/gen/CodeBuilderUtil.java#L109-L134 |
aws/aws-sdk-java | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/UpdateEventConfigurationsRequest.java | UpdateEventConfigurationsRequest.withEventConfigurations | public UpdateEventConfigurationsRequest withEventConfigurations(java.util.Map<String, Configuration> eventConfigurations) {
setEventConfigurations(eventConfigurations);
return this;
} | java | public UpdateEventConfigurationsRequest withEventConfigurations(java.util.Map<String, Configuration> eventConfigurations) {
setEventConfigurations(eventConfigurations);
return this;
} | [
"public",
"UpdateEventConfigurationsRequest",
"withEventConfigurations",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"Configuration",
">",
"eventConfigurations",
")",
"{",
"setEventConfigurations",
"(",
"eventConfigurations",
")",
";",
"return",
"this",
... | <p>
The new event configuration values.
</p>
@param eventConfigurations
The new event configuration values.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"new",
"event",
"configuration",
"values",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/UpdateEventConfigurationsRequest.java#L65-L68 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/SegmentMetadataUpdateTransaction.java | SegmentMetadataUpdateTransaction.preProcessAsSourceSegment | void preProcessAsSourceSegment(MergeSegmentOperation operation) throws StreamSegmentNotSealedException,
StreamSegmentMergedException, StreamSegmentTruncatedException {
Exceptions.checkArgument(this.id == operation.getSourceSegmentId(),
"operation", "Invalid Operation Source Segment Id.");
if (this.merged) {
throw new StreamSegmentMergedException(this.name);
}
if (!this.sealed) {
throw new StreamSegmentNotSealedException(this.name);
}
if (this.startOffset > 0) {
throw new StreamSegmentTruncatedException(this.name, "Segment cannot be merged because it is truncated.", null);
}
if (!this.recoveryMode) {
operation.setLength(this.length);
}
} | java | void preProcessAsSourceSegment(MergeSegmentOperation operation) throws StreamSegmentNotSealedException,
StreamSegmentMergedException, StreamSegmentTruncatedException {
Exceptions.checkArgument(this.id == operation.getSourceSegmentId(),
"operation", "Invalid Operation Source Segment Id.");
if (this.merged) {
throw new StreamSegmentMergedException(this.name);
}
if (!this.sealed) {
throw new StreamSegmentNotSealedException(this.name);
}
if (this.startOffset > 0) {
throw new StreamSegmentTruncatedException(this.name, "Segment cannot be merged because it is truncated.", null);
}
if (!this.recoveryMode) {
operation.setLength(this.length);
}
} | [
"void",
"preProcessAsSourceSegment",
"(",
"MergeSegmentOperation",
"operation",
")",
"throws",
"StreamSegmentNotSealedException",
",",
"StreamSegmentMergedException",
",",
"StreamSegmentTruncatedException",
"{",
"Exceptions",
".",
"checkArgument",
"(",
"this",
".",
"id",
"=="... | Pre-processes the given operation as a Source Segment.
@param operation The operation.
@throws IllegalArgumentException If the operation is for a different Segment.
@throws StreamSegmentNotSealedException If the Segment is not sealed.
@throws StreamSegmentMergedException If the Segment is already merged.
@throws StreamSegmentTruncatedException If the Segment is truncated. | [
"Pre",
"-",
"processes",
"the",
"given",
"operation",
"as",
"a",
"Source",
"Segment",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/SegmentMetadataUpdateTransaction.java#L401-L421 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jaxws.common/src/com/ibm/ws/jaxws/client/LibertyServiceImpl.java | LibertyServiceImpl.prepareProperties | private void prepareProperties(QName portQName, Map<String, String> serviceRefProps, Map<String, String> portProps) throws IOException {
// Merge the properties form port and service.
Map<String, String> allProperties = new HashMap<String, String>();
if (null != serviceRefProps) {
allProperties.putAll(serviceRefProps);
}
if (null != portProps) {
allProperties.putAll(portProps);
}
for (Map.Entry<String, String> entry : servicePidToPropertyPrefixMap.entrySet()) {
String serviceFactoryPid = entry.getKey();
String prefix = entry.getValue();
// Extract the properties according to different property prefix,
// update the extracted properties by corresponding factory service.
Map<String, String> extractProps = extract(prefix, allProperties);
// Put the port QName and the properties into the servicePropertiesMap
ConfigProperties configProps = new ConfigProperties(serviceFactoryPid, extractProps);
Set<ConfigProperties> configSet = servicePropertiesMap.get(portQName);
if (null == configSet) {
configSet = new HashSet<ConfigProperties>();
servicePropertiesMap.put(portQName, configSet);
}
if (configSet.contains(configProps)) {
// re-add the config props
configSet.remove(configProps);
configSet.add(configProps);
} else {
configSet.add(configProps);
}
}
} | java | private void prepareProperties(QName portQName, Map<String, String> serviceRefProps, Map<String, String> portProps) throws IOException {
// Merge the properties form port and service.
Map<String, String> allProperties = new HashMap<String, String>();
if (null != serviceRefProps) {
allProperties.putAll(serviceRefProps);
}
if (null != portProps) {
allProperties.putAll(portProps);
}
for (Map.Entry<String, String> entry : servicePidToPropertyPrefixMap.entrySet()) {
String serviceFactoryPid = entry.getKey();
String prefix = entry.getValue();
// Extract the properties according to different property prefix,
// update the extracted properties by corresponding factory service.
Map<String, String> extractProps = extract(prefix, allProperties);
// Put the port QName and the properties into the servicePropertiesMap
ConfigProperties configProps = new ConfigProperties(serviceFactoryPid, extractProps);
Set<ConfigProperties> configSet = servicePropertiesMap.get(portQName);
if (null == configSet) {
configSet = new HashSet<ConfigProperties>();
servicePropertiesMap.put(portQName, configSet);
}
if (configSet.contains(configProps)) {
// re-add the config props
configSet.remove(configProps);
configSet.add(configProps);
} else {
configSet.add(configProps);
}
}
} | [
"private",
"void",
"prepareProperties",
"(",
"QName",
"portQName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"serviceRefProps",
",",
"Map",
"<",
"String",
",",
"String",
">",
"portProps",
")",
"throws",
"IOException",
"{",
"// Merge the properties form port a... | merge the serviceRef properties and port properties, and update the merged properties in the configAdmin service.
@param configAdmin
@param serviceRefProps
@param portProps
@return
@throws IOException | [
"merge",
"the",
"serviceRef",
"properties",
"and",
"port",
"properties",
"and",
"update",
"the",
"merged",
"properties",
"in",
"the",
"configAdmin",
"service",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxws.common/src/com/ibm/ws/jaxws/client/LibertyServiceImpl.java#L233-L269 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java | SnowflakeAzureClient.setupAzureClient | private void setupAzureClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat)
throws IllegalArgumentException, SnowflakeSQLException
{
// Save the client creation parameters so that we can reuse them,
// to reset the Azure client.
this.stageInfo = stage;
this.encMat = encMat;
logger.debug("Setting up the Azure client ");
try
{
URI storageEndpoint = buildAzureStorageEndpointURI(stage.getEndPoint(), stage.getStorageAccount());
StorageCredentials azCreds;
String sasToken = (String) stage.getCredentials().get("AZURE_SAS_TOKEN");
if (sasToken != null)
{
// We are authenticated with a shared access token.
azCreds = new StorageCredentialsSharedAccessSignature(sasToken);
}
else
{
// Use anonymous authentication.
azCreds = StorageCredentialsAnonymous.ANONYMOUS;
}
if (encMat != null)
{
byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey());
encryptionKeySize = decodedKey.length * 8;
if (encryptionKeySize != 128 &&
encryptionKeySize != 192 &&
encryptionKeySize != 256)
{
throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
"unsupported key size", encryptionKeySize);
}
}
this.azStorageClient = new CloudBlobClient(storageEndpoint, azCreds);
}
catch (URISyntaxException ex)
{
throw new IllegalArgumentException("invalid_azure_credentials");
}
} | java | private void setupAzureClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat)
throws IllegalArgumentException, SnowflakeSQLException
{
// Save the client creation parameters so that we can reuse them,
// to reset the Azure client.
this.stageInfo = stage;
this.encMat = encMat;
logger.debug("Setting up the Azure client ");
try
{
URI storageEndpoint = buildAzureStorageEndpointURI(stage.getEndPoint(), stage.getStorageAccount());
StorageCredentials azCreds;
String sasToken = (String) stage.getCredentials().get("AZURE_SAS_TOKEN");
if (sasToken != null)
{
// We are authenticated with a shared access token.
azCreds = new StorageCredentialsSharedAccessSignature(sasToken);
}
else
{
// Use anonymous authentication.
azCreds = StorageCredentialsAnonymous.ANONYMOUS;
}
if (encMat != null)
{
byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey());
encryptionKeySize = decodedKey.length * 8;
if (encryptionKeySize != 128 &&
encryptionKeySize != 192 &&
encryptionKeySize != 256)
{
throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
"unsupported key size", encryptionKeySize);
}
}
this.azStorageClient = new CloudBlobClient(storageEndpoint, azCreds);
}
catch (URISyntaxException ex)
{
throw new IllegalArgumentException("invalid_azure_credentials");
}
} | [
"private",
"void",
"setupAzureClient",
"(",
"StageInfo",
"stage",
",",
"RemoteStoreFileEncryptionMaterial",
"encMat",
")",
"throws",
"IllegalArgumentException",
",",
"SnowflakeSQLException",
"{",
"// Save the client creation parameters so that we can reuse them,",
"// to reset the Az... | /*
Initializes the Azure client
This method is used during the object contruction, but also to
reset/recreate the encapsulated CloudBlobClient object with new
credentials (after SAS token expiration)
@param stage The stage information that the client will operate on
@param encMat The encryption material
required to decrypt/encrypt content in stage
@throws IllegalArgumentException when invalid credentials are used | [
"/",
"*",
"Initializes",
"the",
"Azure",
"client",
"This",
"method",
"is",
"used",
"during",
"the",
"object",
"contruction",
"but",
"also",
"to",
"reset",
"/",
"recreate",
"the",
"encapsulated",
"CloudBlobClient",
"object",
"with",
"new",
"credentials",
"(",
"... | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeAzureClient.java#L111-L158 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jEntityQueries.java | BaseNeo4jEntityQueries.initFindEntityQuery | private static String initFindEntityQuery(EntityKeyMetadata entityKeyMetadata, boolean includeEmbedded) {
StringBuilder queryBuilder = new StringBuilder();
appendMatchOwnerEntityNode( queryBuilder, entityKeyMetadata );
appendGetEmbeddedNodesIfNeeded( includeEmbedded, queryBuilder );
return queryBuilder.toString();
} | java | private static String initFindEntityQuery(EntityKeyMetadata entityKeyMetadata, boolean includeEmbedded) {
StringBuilder queryBuilder = new StringBuilder();
appendMatchOwnerEntityNode( queryBuilder, entityKeyMetadata );
appendGetEmbeddedNodesIfNeeded( includeEmbedded, queryBuilder );
return queryBuilder.toString();
} | [
"private",
"static",
"String",
"initFindEntityQuery",
"(",
"EntityKeyMetadata",
"entityKeyMetadata",
",",
"boolean",
"includeEmbedded",
")",
"{",
"StringBuilder",
"queryBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"appendMatchOwnerEntityNode",
"(",
"queryBuilder"... | /*
Example: MATCH (owner:ENTITY:table {id: {0}}) RETURN owner | [
"/",
"*",
"Example",
":",
"MATCH",
"(",
"owner",
":",
"ENTITY",
":",
"table",
"{",
"id",
":",
"{",
"0",
"}}",
")",
"RETURN",
"owner"
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jEntityQueries.java#L433-L438 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java | ValueMap.withBoolean | public ValueMap withBoolean(String key, boolean val) {
super.put(key, Boolean.valueOf(val));
return this;
} | java | public ValueMap withBoolean(String key, boolean val) {
super.put(key, Boolean.valueOf(val));
return this;
} | [
"public",
"ValueMap",
"withBoolean",
"(",
"String",
"key",
",",
"boolean",
"val",
")",
"{",
"super",
".",
"put",
"(",
"key",
",",
"Boolean",
".",
"valueOf",
"(",
"val",
")",
")",
";",
"return",
"this",
";",
"}"
] | Sets the value of the specified key in the current ValueMap to the
boolean value. | [
"Sets",
"the",
"value",
"of",
"the",
"specified",
"key",
"in",
"the",
"current",
"ValueMap",
"to",
"the",
"boolean",
"value",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java#L186-L189 |
gallandarakhneorg/afc | core/vmutils/src/main/java/org/arakhne/afc/vmutil/FileSystem.java | FileSystem.makeAbsolute | @Pure
public static File makeAbsolute(File filename, File current) {
if (filename == null) {
return null;
}
if (current != null && !filename.isAbsolute()) {
try {
return new File(current.getCanonicalFile(), filename.getPath());
} catch (IOException exception) {
return new File(current.getAbsoluteFile(), filename.getPath());
}
}
return filename;
} | java | @Pure
public static File makeAbsolute(File filename, File current) {
if (filename == null) {
return null;
}
if (current != null && !filename.isAbsolute()) {
try {
return new File(current.getCanonicalFile(), filename.getPath());
} catch (IOException exception) {
return new File(current.getAbsoluteFile(), filename.getPath());
}
}
return filename;
} | [
"@",
"Pure",
"public",
"static",
"File",
"makeAbsolute",
"(",
"File",
"filename",
",",
"File",
"current",
")",
"{",
"if",
"(",
"filename",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"current",
"!=",
"null",
"&&",
"!",
"filename",
... | Make the given filename absolute from the given root if it is not already absolute.
<table border="1" width="100%" summary="Cases">
<thead>
<tr>
<td>{@code filename}</td><td>{@code current}</td><td>Result</td>
</tr>
</thead>
<tr>
<td><code>null</code></td>
<td><code>null</code></td>
<td><code>null</code></td>
</tr>
<tr>
<td><code>null</code></td>
<td><code>/myroot</code></td>
<td><code>null</code></td>
</tr>
<tr>
<td><code>/path/to/file</code></td>
<td><code>null</code></td>
<td><code>/path/to/file</code></td>
</tr>
<tr>
<td><code>path/to/file</code></td>
<td><code>null</code></td>
<td><code>path/to/file</code></td>
</tr>
<tr>
<td><code>/path/to/file</code></td>
<td><code>/myroot</code></td>
<td><code>/path/to/file</code></td>
</tr>
<tr>
<td><code>path/to/file</code></td>
<td><code>/myroot</code></td>
<td><code>/myroot/path/to/file</code></td>
</tr>
</table>
@param filename is the name to make absolute.
@param current is the current directory which permits to make absolute.
@return an absolute filename. | [
"Make",
"the",
"given",
"filename",
"absolute",
"from",
"the",
"given",
"root",
"if",
"it",
"is",
"not",
"already",
"absolute",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/FileSystem.java#L2165-L2178 |
google/error-prone | check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java | ErrorProneScanner.handleError | @Override
protected void handleError(Suppressible s, Throwable t) {
if (t instanceof ErrorProneError) {
throw (ErrorProneError) t;
}
if (t instanceof CompletionFailure) {
throw (CompletionFailure) t;
}
TreePath path = getCurrentPath();
throw new ErrorProneError(
s.canonicalName(),
t,
(DiagnosticPosition) path.getLeaf(),
path.getCompilationUnit().getSourceFile());
} | java | @Override
protected void handleError(Suppressible s, Throwable t) {
if (t instanceof ErrorProneError) {
throw (ErrorProneError) t;
}
if (t instanceof CompletionFailure) {
throw (CompletionFailure) t;
}
TreePath path = getCurrentPath();
throw new ErrorProneError(
s.canonicalName(),
t,
(DiagnosticPosition) path.getLeaf(),
path.getCompilationUnit().getSourceFile());
} | [
"@",
"Override",
"protected",
"void",
"handleError",
"(",
"Suppressible",
"s",
",",
"Throwable",
"t",
")",
"{",
"if",
"(",
"t",
"instanceof",
"ErrorProneError",
")",
"{",
"throw",
"(",
"ErrorProneError",
")",
"t",
";",
"}",
"if",
"(",
"t",
"instanceof",
... | Handles an exception thrown by an individual BugPattern. By default, wraps the exception in an
{@link ErrorProneError} and rethrows. May be overridden by subclasses, for example to log the
error and continue. | [
"Handles",
"an",
"exception",
"thrown",
"by",
"an",
"individual",
"BugPattern",
".",
"By",
"default",
"wraps",
"the",
"exception",
"in",
"an",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java#L894-L908 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java | CacheConfigurationBuilder.withExpiry | @Deprecated
public CacheConfigurationBuilder<K, V> withExpiry(org.ehcache.expiry.Expiry<? super K, ? super V> expiry) {
return withExpiry(convertToExpiryPolicy(requireNonNull(expiry, "Null expiry")));
} | java | @Deprecated
public CacheConfigurationBuilder<K, V> withExpiry(org.ehcache.expiry.Expiry<? super K, ? super V> expiry) {
return withExpiry(convertToExpiryPolicy(requireNonNull(expiry, "Null expiry")));
} | [
"@",
"Deprecated",
"public",
"CacheConfigurationBuilder",
"<",
"K",
",",
"V",
">",
"withExpiry",
"(",
"org",
".",
"ehcache",
".",
"expiry",
".",
"Expiry",
"<",
"?",
"super",
"K",
",",
"?",
"super",
"V",
">",
"expiry",
")",
"{",
"return",
"withExpiry",
... | Adds {@link org.ehcache.expiry.Expiry} configuration to the returned builder.
<p>
{@code Expiry} is what controls data freshness in a cache.
@param expiry the expiry to use
@return a new builder with the added expiry
@deprecated Use {@link #withExpiry(ExpiryPolicy)} instead | [
"Adds",
"{",
"@link",
"org",
".",
"ehcache",
".",
"expiry",
".",
"Expiry",
"}",
"configuration",
"to",
"the",
"returned",
"builder",
".",
"<p",
">",
"{",
"@code",
"Expiry",
"}",
"is",
"what",
"controls",
"data",
"freshness",
"in",
"a",
"cache",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java#L298-L301 |
facebookarchive/hadoop-20 | src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/bookkeeper/zk/ZkUtil.java | ZkUtil.keeperException | public static void keeperException(String msg, KeeperException e)
throws IOException {
LOG.error(msg, e);
throw new IOException(msg, e);
} | java | public static void keeperException(String msg, KeeperException e)
throws IOException {
LOG.error(msg, e);
throw new IOException(msg, e);
} | [
"public",
"static",
"void",
"keeperException",
"(",
"String",
"msg",
",",
"KeeperException",
"e",
")",
"throws",
"IOException",
"{",
"LOG",
".",
"error",
"(",
"msg",
",",
"e",
")",
";",
"throw",
"new",
"IOException",
"(",
"msg",
",",
"e",
")",
";",
"}"... | Like {@link #interruptedException(String, InterruptedException)} but
handles KeeperException and will not interrupt the thread. | [
"Like",
"{"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/highavailability/src/java/org/apache/hadoop/hdfs/server/namenode/bookkeeper/zk/ZkUtil.java#L91-L95 |
carewebframework/carewebframework-core | org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutService.java | LayoutService.renameLayout | @Override
public void renameLayout(LayoutIdentifier layout, String newName) {
String text = getLayoutContent(layout);
saveLayout(new LayoutIdentifier(newName, layout.shared), text);
deleteLayout(layout);
} | java | @Override
public void renameLayout(LayoutIdentifier layout, String newName) {
String text = getLayoutContent(layout);
saveLayout(new LayoutIdentifier(newName, layout.shared), text);
deleteLayout(layout);
} | [
"@",
"Override",
"public",
"void",
"renameLayout",
"(",
"LayoutIdentifier",
"layout",
",",
"String",
"newName",
")",
"{",
"String",
"text",
"=",
"getLayoutContent",
"(",
"layout",
")",
";",
"saveLayout",
"(",
"new",
"LayoutIdentifier",
"(",
"newName",
",",
"la... | Rename a layout.
@param layout The original layout identifier.
@param newName The new layout name. | [
"Rename",
"a",
"layout",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutService.java#L90-L95 |
datumbox/datumbox-framework | datumbox-framework-common/src/main/java/com/datumbox/framework/common/ConfigurableFactory.java | ConfigurableFactory.getConfiguration | public static <C extends Configurable> C getConfiguration(Class<C> klass) {
String defaultPropertyFile = "datumbox." + klass.getSimpleName().toLowerCase(Locale.ENGLISH) + DEFAULT_POSTFIX + ".properties";
Properties properties = new Properties();
ClassLoader cl = klass.getClassLoader();
//Load default properties from jar
try (InputStream in = cl.getResourceAsStream(defaultPropertyFile)) {
properties.load(in);
}
catch(IOException ex) {
throw new UncheckedIOException(ex);
}
//Look for user defined properties
String propertyFile = defaultPropertyFile.replaceFirst(DEFAULT_POSTFIX, "");
if(cl.getResource(propertyFile)!=null) {
//Override the default if they exist
try (InputStream in = cl.getResourceAsStream(propertyFile)) {
properties.load(in);
}
catch(IOException ex) {
throw new UncheckedIOException(ex);
}
logger.trace("Loading properties file {}: {}", propertyFile, properties);
}
else {
logger.warn("Using default properties file {}: {}", defaultPropertyFile, properties);
}
return getConfiguration(klass, properties);
} | java | public static <C extends Configurable> C getConfiguration(Class<C> klass) {
String defaultPropertyFile = "datumbox." + klass.getSimpleName().toLowerCase(Locale.ENGLISH) + DEFAULT_POSTFIX + ".properties";
Properties properties = new Properties();
ClassLoader cl = klass.getClassLoader();
//Load default properties from jar
try (InputStream in = cl.getResourceAsStream(defaultPropertyFile)) {
properties.load(in);
}
catch(IOException ex) {
throw new UncheckedIOException(ex);
}
//Look for user defined properties
String propertyFile = defaultPropertyFile.replaceFirst(DEFAULT_POSTFIX, "");
if(cl.getResource(propertyFile)!=null) {
//Override the default if they exist
try (InputStream in = cl.getResourceAsStream(propertyFile)) {
properties.load(in);
}
catch(IOException ex) {
throw new UncheckedIOException(ex);
}
logger.trace("Loading properties file {}: {}", propertyFile, properties);
}
else {
logger.warn("Using default properties file {}: {}", defaultPropertyFile, properties);
}
return getConfiguration(klass, properties);
} | [
"public",
"static",
"<",
"C",
"extends",
"Configurable",
">",
"C",
"getConfiguration",
"(",
"Class",
"<",
"C",
">",
"klass",
")",
"{",
"String",
"defaultPropertyFile",
"=",
"\"datumbox.\"",
"+",
"klass",
".",
"getSimpleName",
"(",
")",
".",
"toLowerCase",
"(... | Initializes the Configuration Object based on the configuration file.
@param <C>
@param klass
@return | [
"Initializes",
"the",
"Configuration",
"Object",
"based",
"on",
"the",
"configuration",
"file",
"."
] | train | https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-common/src/main/java/com/datumbox/framework/common/ConfigurableFactory.java#L48-L80 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/RegistrationsApi.java | RegistrationsApi.confirmUserAsync | public com.squareup.okhttp.Call confirmUserAsync(DeviceRegConfirmUserRequest registrationInfo, final ApiCallback<DeviceRegConfirmUserResponseEnvelope> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = confirmUserValidateBeforeCall(registrationInfo, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<DeviceRegConfirmUserResponseEnvelope>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | java | public com.squareup.okhttp.Call confirmUserAsync(DeviceRegConfirmUserRequest registrationInfo, final ApiCallback<DeviceRegConfirmUserResponseEnvelope> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = confirmUserValidateBeforeCall(registrationInfo, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<DeviceRegConfirmUserResponseEnvelope>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"confirmUserAsync",
"(",
"DeviceRegConfirmUserRequest",
"registrationInfo",
",",
"final",
"ApiCallback",
"<",
"DeviceRegConfirmUserResponseEnvelope",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"Prog... | Confirm User (asynchronously)
This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device.
@param registrationInfo Device Registration information. (required)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Confirm",
"User",
"(",
"asynchronously",
")",
"This",
"call",
"updates",
"the",
"registration",
"request",
"issued",
"earlier",
"by",
"associating",
"it",
"with",
"an",
"authenticated",
"user",
"and",
"captures",
"all",
"additional",
"information",
"required",
"t... | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/RegistrationsApi.java#L152-L177 |
apache/incubator-druid | core/src/main/java/org/apache/druid/java/util/common/StringUtils.java | StringUtils.nonStrictFormat | public static String nonStrictFormat(String message, Object... formatArgs)
{
if (formatArgs == null || formatArgs.length == 0) {
return message;
}
try {
return String.format(Locale.ENGLISH, message, formatArgs);
}
catch (IllegalFormatException e) {
StringBuilder bob = new StringBuilder(message);
for (Object formatArg : formatArgs) {
bob.append("; ").append(formatArg);
}
return bob.toString();
}
} | java | public static String nonStrictFormat(String message, Object... formatArgs)
{
if (formatArgs == null || formatArgs.length == 0) {
return message;
}
try {
return String.format(Locale.ENGLISH, message, formatArgs);
}
catch (IllegalFormatException e) {
StringBuilder bob = new StringBuilder(message);
for (Object formatArg : formatArgs) {
bob.append("; ").append(formatArg);
}
return bob.toString();
}
} | [
"public",
"static",
"String",
"nonStrictFormat",
"(",
"String",
"message",
",",
"Object",
"...",
"formatArgs",
")",
"{",
"if",
"(",
"formatArgs",
"==",
"null",
"||",
"formatArgs",
".",
"length",
"==",
"0",
")",
"{",
"return",
"message",
";",
"}",
"try",
... | Formats the string as {@link #format(String, Object...)}, but instead of failing on illegal format, returns the
concatenated format string and format arguments. Should be used for unimportant formatting like logging,
exception messages, typically not directly. | [
"Formats",
"the",
"string",
"as",
"{"
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/core/src/main/java/org/apache/druid/java/util/common/StringUtils.java#L132-L147 |
alibaba/transmittable-thread-local | src/main/java/com/alibaba/ttl/TtlRunnable.java | TtlRunnable.get | @Nullable
public static TtlRunnable get(@Nullable Runnable runnable) {
return get(runnable, false, false);
} | java | @Nullable
public static TtlRunnable get(@Nullable Runnable runnable) {
return get(runnable, false, false);
} | [
"@",
"Nullable",
"public",
"static",
"TtlRunnable",
"get",
"(",
"@",
"Nullable",
"Runnable",
"runnable",
")",
"{",
"return",
"get",
"(",
"runnable",
",",
"false",
",",
"false",
")",
";",
"}"
] | Factory method, wrap input {@link Runnable} to {@link TtlRunnable}.
@param runnable input {@link Runnable}. if input is {@code null}, return {@code null}.
@return Wrapped {@link Runnable}
@throws IllegalStateException when input is {@link TtlRunnable} already. | [
"Factory",
"method",
"wrap",
"input",
"{",
"@link",
"Runnable",
"}",
"to",
"{",
"@link",
"TtlRunnable",
"}",
"."
] | train | https://github.com/alibaba/transmittable-thread-local/blob/30b4d99cdb7064b4c1797d2e40bfa07adce8e7f9/src/main/java/com/alibaba/ttl/TtlRunnable.java#L92-L95 |
apache/groovy | subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java | NioGroovyMethods.newWriter | public static BufferedWriter newWriter(Path self, boolean append) throws IOException {
if (append) {
return Files.newBufferedWriter(self, Charset.defaultCharset(), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.defaultCharset());
} | java | public static BufferedWriter newWriter(Path self, boolean append) throws IOException {
if (append) {
return Files.newBufferedWriter(self, Charset.defaultCharset(), CREATE, APPEND);
}
return Files.newBufferedWriter(self, Charset.defaultCharset());
} | [
"public",
"static",
"BufferedWriter",
"newWriter",
"(",
"Path",
"self",
",",
"boolean",
"append",
")",
"throws",
"IOException",
"{",
"if",
"(",
"append",
")",
"{",
"return",
"Files",
".",
"newBufferedWriter",
"(",
"self",
",",
"Charset",
".",
"defaultCharset",... | Creates a buffered writer for this file, optionally appending to the
existing file content.
@param self a Path
@param append true if data should be appended to the file
@return a BufferedWriter
@throws java.io.IOException if an IOException occurs.
@since 2.3.0 | [
"Creates",
"a",
"buffered",
"writer",
"for",
"this",
"file",
"optionally",
"appending",
"to",
"the",
"existing",
"file",
"content",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1556-L1561 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java | VirtualMachineScaleSetsInner.getByResourceGroup | public VirtualMachineScaleSetInner getByResourceGroup(String resourceGroupName, String vmScaleSetName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, vmScaleSetName).toBlocking().single().body();
} | java | public VirtualMachineScaleSetInner getByResourceGroup(String resourceGroupName, String vmScaleSetName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, vmScaleSetName).toBlocking().single().body();
} | [
"public",
"VirtualMachineScaleSetInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"vmScaleSetName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"vmScaleSetName",
")",
".",
"toBlocking",
"(",
... | Display information about a virtual machine scale set.
@param resourceGroupName The name of the resource group.
@param vmScaleSetName The name of the VM scale set.
@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 VirtualMachineScaleSetInner object if successful. | [
"Display",
"information",
"about",
"a",
"virtual",
"machine",
"scale",
"set",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java#L704-L706 |
Whiley/WhileyCompiler | src/main/java/wyil/transform/VerificationConditionGenerator.java | VerificationConditionGenerator.translateAssign | private Context translateAssign(WyilFile.Stmt.Assign stmt, Context context) {
Tuple<WyilFile.LVal> lhs = stmt.getLeftHandSide();
Tuple<WyilFile.Expr> rhs = stmt.getRightHandSide();
WyilFile.LVal[][] lvals = new LVal[rhs.size()][];
Expr[][] rvals = new Expr[rhs.size()][];
// First, generate bundles
for (int i = 0, j = 0; i != rhs.size(); ++i) {
WyilFile.Expr rval = rhs.get(i);
lvals[i] = generateEmptyLValBundle(rval.getTypes(), lhs, j);
j += lvals[i].length;
Pair<Expr[], Context> p = generateRValBundle(rval, context);
rvals[i] = p.first();
context = p.second();
}
// Second, apply the bundles to implement assignments.
for (int i = 0; i != rhs.size(); ++i) {
context = translateAssign(lvals[i], rvals[i], context);
}
// Done
return context;
} | java | private Context translateAssign(WyilFile.Stmt.Assign stmt, Context context) {
Tuple<WyilFile.LVal> lhs = stmt.getLeftHandSide();
Tuple<WyilFile.Expr> rhs = stmt.getRightHandSide();
WyilFile.LVal[][] lvals = new LVal[rhs.size()][];
Expr[][] rvals = new Expr[rhs.size()][];
// First, generate bundles
for (int i = 0, j = 0; i != rhs.size(); ++i) {
WyilFile.Expr rval = rhs.get(i);
lvals[i] = generateEmptyLValBundle(rval.getTypes(), lhs, j);
j += lvals[i].length;
Pair<Expr[], Context> p = generateRValBundle(rval, context);
rvals[i] = p.first();
context = p.second();
}
// Second, apply the bundles to implement assignments.
for (int i = 0; i != rhs.size(); ++i) {
context = translateAssign(lvals[i], rvals[i], context);
}
// Done
return context;
} | [
"private",
"Context",
"translateAssign",
"(",
"WyilFile",
".",
"Stmt",
".",
"Assign",
"stmt",
",",
"Context",
"context",
")",
"{",
"Tuple",
"<",
"WyilFile",
".",
"LVal",
">",
"lhs",
"=",
"stmt",
".",
"getLeftHandSide",
"(",
")",
";",
"Tuple",
"<",
"WyilF... | Translate an assign statement. This updates the version number of the
underlying assigned variable.
@param stmt
@param wyalFile
@throws ResolutionError | [
"Translate",
"an",
"assign",
"statement",
".",
"This",
"updates",
"the",
"version",
"number",
"of",
"the",
"underlying",
"assigned",
"variable",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L494-L514 |
pierre/serialization | smile/src/main/java/com/ning/metrics/serialization/smile/SmileEnvelopeEventDeserializer.java | SmileEnvelopeEventDeserializer.extractEvents | public static List<SmileEnvelopeEvent> extractEvents(final InputStream in) throws IOException
{
final PushbackInputStream pbIn = new PushbackInputStream(in);
final byte firstByte = (byte) pbIn.read();
// EOF?
if (firstByte == -1) {
return null;
}
pbIn.unread(firstByte);
SmileEnvelopeEventDeserializer deser = (firstByte == SMILE_MARKER) ?
new SmileEnvelopeEventDeserializer(pbIn, false) :
new SmileEnvelopeEventDeserializer(pbIn, true);
final List<SmileEnvelopeEvent> events = new LinkedList<SmileEnvelopeEvent>();
while (deser.hasNextEvent()) {
SmileEnvelopeEvent event = deser.getNextEvent();
if (event == null) {
// TODO: this is NOT expected, should warn
break;
}
events.add(event);
}
return events;
} | java | public static List<SmileEnvelopeEvent> extractEvents(final InputStream in) throws IOException
{
final PushbackInputStream pbIn = new PushbackInputStream(in);
final byte firstByte = (byte) pbIn.read();
// EOF?
if (firstByte == -1) {
return null;
}
pbIn.unread(firstByte);
SmileEnvelopeEventDeserializer deser = (firstByte == SMILE_MARKER) ?
new SmileEnvelopeEventDeserializer(pbIn, false) :
new SmileEnvelopeEventDeserializer(pbIn, true);
final List<SmileEnvelopeEvent> events = new LinkedList<SmileEnvelopeEvent>();
while (deser.hasNextEvent()) {
SmileEnvelopeEvent event = deser.getNextEvent();
if (event == null) {
// TODO: this is NOT expected, should warn
break;
}
events.add(event);
}
return events;
} | [
"public",
"static",
"List",
"<",
"SmileEnvelopeEvent",
">",
"extractEvents",
"(",
"final",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"final",
"PushbackInputStream",
"pbIn",
"=",
"new",
"PushbackInputStream",
"(",
"in",
")",
";",
"final",
"byte",
"f... | Extracts all events in the stream
Note: Stream must be formatted as an array of (serialized) SmileEnvelopeEvents.
@param in InputStream containing events
@return A list of SmileEnvelopeEvents
@throws IOException generic I/O exception | [
"Extracts",
"all",
"events",
"in",
"the",
"stream",
"Note",
":",
"Stream",
"must",
"be",
"formatted",
"as",
"an",
"array",
"of",
"(",
"serialized",
")",
"SmileEnvelopeEvents",
"."
] | train | https://github.com/pierre/serialization/blob/b15b7c749ba78bfe94dce8fc22f31b30b2e6830b/smile/src/main/java/com/ning/metrics/serialization/smile/SmileEnvelopeEventDeserializer.java#L164-L191 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java | DatabasesInner.importMethodAsync | public Observable<ImportExportResponseInner> importMethodAsync(String resourceGroupName, String serverName, ImportRequest parameters) {
return importMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ImportExportResponseInner>, ImportExportResponseInner>() {
@Override
public ImportExportResponseInner call(ServiceResponse<ImportExportResponseInner> response) {
return response.body();
}
});
} | java | public Observable<ImportExportResponseInner> importMethodAsync(String resourceGroupName, String serverName, ImportRequest parameters) {
return importMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ImportExportResponseInner>, ImportExportResponseInner>() {
@Override
public ImportExportResponseInner call(ServiceResponse<ImportExportResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ImportExportResponseInner",
">",
"importMethodAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"ImportRequest",
"parameters",
")",
"{",
"return",
"importMethodWithServiceResponseAsync",
"(",
"resourceGroupName",
","... | Imports a bacpac into a new database.
@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 The required parameters for importing a Bacpac into a database.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Imports",
"a",
"bacpac",
"into",
"a",
"new",
"database",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabasesInner.java#L1764-L1771 |
craftercms/deployer | src/main/java/org/craftercms/deployer/utils/ConfigUtils.java | ConfigUtils.getStringProperty | public static String getStringProperty(Configuration config, String key) throws DeployerConfigurationException {
return getStringProperty(config, key, null);
} | java | public static String getStringProperty(Configuration config, String key) throws DeployerConfigurationException {
return getStringProperty(config, key, null);
} | [
"public",
"static",
"String",
"getStringProperty",
"(",
"Configuration",
"config",
",",
"String",
"key",
")",
"throws",
"DeployerConfigurationException",
"{",
"return",
"getStringProperty",
"(",
"config",
",",
"key",
",",
"null",
")",
";",
"}"
] | Returns the specified String property from the configuration
@param config the configuration
@param key the key of the property
@return the String value of the property, or null if not found
@throws DeployerConfigurationException if an error occurred | [
"Returns",
"the",
"specified",
"String",
"property",
"from",
"the",
"configuration"
] | train | https://github.com/craftercms/deployer/blob/3ed446e3cc8af1055de2de6f871907f90ef27f63/src/main/java/org/craftercms/deployer/utils/ConfigUtils.java#L90-L92 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/filemgr/FileManagerImpl.java | FileManagerImpl.add_block_to_freelist | private void add_block_to_freelist(Block block, int ql_index)
{
block.next = ql_heads[ql_index].first_block;
ql_heads[ql_index].first_block = block;
ql_heads[ql_index].length++;
if (ql_heads[ql_index].length == 1) {
nonempty_lists++;
}
} | java | private void add_block_to_freelist(Block block, int ql_index)
{
block.next = ql_heads[ql_index].first_block;
ql_heads[ql_index].first_block = block;
ql_heads[ql_index].length++;
if (ql_heads[ql_index].length == 1) {
nonempty_lists++;
}
} | [
"private",
"void",
"add_block_to_freelist",
"(",
"Block",
"block",
",",
"int",
"ql_index",
")",
"{",
"block",
".",
"next",
"=",
"ql_heads",
"[",
"ql_index",
"]",
".",
"first_block",
";",
"ql_heads",
"[",
"ql_index",
"]",
".",
"first_block",
"=",
"block",
"... | /* Add a new block to the beginning of a free list data structure | [
"/",
"*",
"Add",
"a",
"new",
"block",
"to",
"the",
"beginning",
"of",
"a",
"free",
"list",
"data",
"structure"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/filemgr/FileManagerImpl.java#L1127-L1135 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/script/common/ImplicitObjectUtil.java | ImplicitObjectUtil.loadPageFlow | public static void loadPageFlow(ServletRequest request, PageFlowController pageFlow) {
if(pageFlow != null)
request.setAttribute(PAGE_FLOW_IMPLICIT_OBJECT_KEY, pageFlow);
Map map = InternalUtils.getPageInputMap(request);
request.setAttribute(PAGE_INPUT_IMPLICIT_OBJECT_KEY, map != null ? map : Collections.EMPTY_MAP);
} | java | public static void loadPageFlow(ServletRequest request, PageFlowController pageFlow) {
if(pageFlow != null)
request.setAttribute(PAGE_FLOW_IMPLICIT_OBJECT_KEY, pageFlow);
Map map = InternalUtils.getPageInputMap(request);
request.setAttribute(PAGE_INPUT_IMPLICIT_OBJECT_KEY, map != null ? map : Collections.EMPTY_MAP);
} | [
"public",
"static",
"void",
"loadPageFlow",
"(",
"ServletRequest",
"request",
",",
"PageFlowController",
"pageFlow",
")",
"{",
"if",
"(",
"pageFlow",
"!=",
"null",
")",
"request",
".",
"setAttribute",
"(",
"PAGE_FLOW_IMPLICIT_OBJECT_KEY",
",",
"pageFlow",
")",
";"... | Load Page Flow related implicit objects into the request. This method will set the
Page Flow itself and any available page inputs into the request.
@param request the request
@param pageFlow the current page flow | [
"Load",
"Page",
"Flow",
"related",
"implicit",
"objects",
"into",
"the",
"request",
".",
"This",
"method",
"will",
"set",
"the",
"Page",
"Flow",
"itself",
"and",
"any",
"available",
"page",
"inputs",
"into",
"the",
"request",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/script/common/ImplicitObjectUtil.java#L105-L111 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/helper/AuthenticateUserHelper.java | AuthenticateUserHelper.authenticateUser | public Subject authenticateUser(AuthenticationService authenticationService, String userName,
String jaasEntryName) throws AuthenticationException
{
return authenticateUser(authenticationService, userName, jaasEntryName, null);
} | java | public Subject authenticateUser(AuthenticationService authenticationService, String userName,
String jaasEntryName) throws AuthenticationException
{
return authenticateUser(authenticationService, userName, jaasEntryName, null);
} | [
"public",
"Subject",
"authenticateUser",
"(",
"AuthenticationService",
"authenticationService",
",",
"String",
"userName",
",",
"String",
"jaasEntryName",
")",
"throws",
"AuthenticationException",
"{",
"return",
"authenticateUser",
"(",
"authenticationService",
",",
"userNa... | Authenticate the given user and return an authenticated Subject.
@param authenticationService service to authenticate a user, must not be null
@param userName the user to authenticate, must not be null
@param jaasEntryName the optional JAAS configuration entry name. The system.DEFAULT JAAS entry name will be used if null or empty String is passed
@return the authenticated subject
@throws AuthenticationException if there was a problem authenticating the user, or if the userName or authenticationService is null | [
"Authenticate",
"the",
"given",
"user",
"and",
"return",
"an",
"authenticated",
"Subject",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/helper/AuthenticateUserHelper.java#L37-L41 |
LearnLib/learnlib | commons/acex/src/main/java/de/learnlib/acex/analyzers/AcexAnalysisAlgorithms.java | AcexAnalysisAlgorithms.linearSearchFwd | public static <E> int linearSearchFwd(AbstractCounterexample<E> acex, int low, int high) {
assert !acex.testEffects(low, high);
E effPrev = acex.effect(low);
for (int i = low + 1; i <= high; i++) {
E eff = acex.effect(i);
if (!acex.checkEffects(effPrev, eff)) {
return i - 1;
}
effPrev = eff;
}
throw new IllegalArgumentException();
} | java | public static <E> int linearSearchFwd(AbstractCounterexample<E> acex, int low, int high) {
assert !acex.testEffects(low, high);
E effPrev = acex.effect(low);
for (int i = low + 1; i <= high; i++) {
E eff = acex.effect(i);
if (!acex.checkEffects(effPrev, eff)) {
return i - 1;
}
effPrev = eff;
}
throw new IllegalArgumentException();
} | [
"public",
"static",
"<",
"E",
">",
"int",
"linearSearchFwd",
"(",
"AbstractCounterexample",
"<",
"E",
">",
"acex",
",",
"int",
"low",
",",
"int",
"high",
")",
"{",
"assert",
"!",
"acex",
".",
"testEffects",
"(",
"low",
",",
"high",
")",
";",
"E",
"ef... | Scan linearly through the counterexample in ascending order.
@param acex
the abstract counterexample
@param low
the lower bound of the search range
@param high
the upper bound of the search range
@return an index <code>i</code> such that <code>acex.testEffect(i) != acex.testEffect(i+1)</code> | [
"Scan",
"linearly",
"through",
"the",
"counterexample",
"in",
"ascending",
"order",
"."
] | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/commons/acex/src/main/java/de/learnlib/acex/analyzers/AcexAnalysisAlgorithms.java#L38-L50 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/MLLibUtil.java | MLLibUtil.fromLabeledPoint | public static JavaRDD<DataSet> fromLabeledPoint(JavaRDD<LabeledPoint> data, final long numPossibleLabels,
long batchSize) {
JavaRDD<DataSet> mappedData = data.map(new Function<LabeledPoint, DataSet>() {
@Override
public DataSet call(LabeledPoint lp) {
return fromLabeledPoint(lp, numPossibleLabels);
}
});
return mappedData.repartition((int) (mappedData.count() / batchSize));
} | java | public static JavaRDD<DataSet> fromLabeledPoint(JavaRDD<LabeledPoint> data, final long numPossibleLabels,
long batchSize) {
JavaRDD<DataSet> mappedData = data.map(new Function<LabeledPoint, DataSet>() {
@Override
public DataSet call(LabeledPoint lp) {
return fromLabeledPoint(lp, numPossibleLabels);
}
});
return mappedData.repartition((int) (mappedData.count() / batchSize));
} | [
"public",
"static",
"JavaRDD",
"<",
"DataSet",
">",
"fromLabeledPoint",
"(",
"JavaRDD",
"<",
"LabeledPoint",
">",
"data",
",",
"final",
"long",
"numPossibleLabels",
",",
"long",
"batchSize",
")",
"{",
"JavaRDD",
"<",
"DataSet",
">",
"mappedData",
"=",
"data",
... | Convert an rdd
of labeled point
based on the specified batch size
in to data set
@param data the data to convert
@param numPossibleLabels the number of possible labels
@param batchSize the batch size
@return the new rdd | [
"Convert",
"an",
"rdd",
"of",
"labeled",
"point",
"based",
"on",
"the",
"specified",
"batch",
"size",
"in",
"to",
"data",
"set"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/MLLibUtil.java#L211-L222 |
TheHortonMachine/hortonmachine | gears/src/main/java/oms3/Compound.java | Compound.in2in | public void in2in(String in, Object to, String to_in) {
controller.mapIn(in, to, to_in);
} | java | public void in2in(String in, Object to, String to_in) {
controller.mapIn(in, to, to_in);
} | [
"public",
"void",
"in2in",
"(",
"String",
"in",
",",
"Object",
"to",
",",
"String",
"to_in",
")",
"{",
"controller",
".",
"mapIn",
"(",
"in",
",",
"to",
",",
"to_in",
")",
";",
"}"
] | Maps a Compound Input field to a internal simple input field.
@param in Compound input field.
@param to internal Component
@param to_in Input field of the internal component | [
"Maps",
"a",
"Compound",
"Input",
"field",
"to",
"a",
"internal",
"simple",
"input",
"field",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/oms3/Compound.java#L145-L147 |
Azure/azure-sdk-for-java | iotcentral/resource-manager/v2017_07_01_privatepreview/src/main/java/com/microsoft/azure/management/iotcentral/v2017_07_01_privatepreview/implementation/AppsInner.java | AppsInner.beginDelete | public void beginDelete(String resourceGroupName, String resourceName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | java | public void beginDelete(String resourceGroupName, String resourceName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | [
"public",
"void",
"beginDelete",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
")",
"{",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"bod... | Delete an IoT Central application.
@param resourceGroupName The name of the resource group that contains the IoT Central application.
@param resourceName The ARM resource name of the IoT Central application.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorDetailsException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Delete",
"an",
"IoT",
"Central",
"application",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iotcentral/resource-manager/v2017_07_01_privatepreview/src/main/java/com/microsoft/azure/management/iotcentral/v2017_07_01_privatepreview/implementation/AppsInner.java#L629-L631 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java | Constraints.inGroup | public PropertyConstraint inGroup(String propertyName, Object[] group) {
return value(propertyName, new InGroup(group));
} | java | public PropertyConstraint inGroup(String propertyName, Object[] group) {
return value(propertyName, new InGroup(group));
} | [
"public",
"PropertyConstraint",
"inGroup",
"(",
"String",
"propertyName",
",",
"Object",
"[",
"]",
"group",
")",
"{",
"return",
"value",
"(",
"propertyName",
",",
"new",
"InGroup",
"(",
"group",
")",
")",
";",
"}"
] | Returns a 'in' group (or set) constraint appled to the provided property.
@param propertyName the property
@param group the group items
@return The InGroup constraint. | [
"Returns",
"a",
"in",
"group",
"(",
"or",
"set",
")",
"constraint",
"appled",
"to",
"the",
"provided",
"property",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/rules/constraint/Constraints.java#L619-L621 |
feedzai/pdb | src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java | AbstractDatabaseEngine.createPreparedStatement | private void createPreparedStatement(final String name, final String query, final int timeout, final boolean recovering) throws NameAlreadyExistsException, DatabaseEngineException {
if (!recovering) {
if (stmts.containsKey(name)) {
throw new NameAlreadyExistsException(String.format("There's already a PreparedStatement with the name '%s'", name));
}
try {
getConnection();
} catch (final Exception e) {
throw new DatabaseEngineException("Could not create prepared statement", e);
}
}
PreparedStatement ps;
try {
ps = conn.prepareStatement(query);
if (timeout > 0) {
ps.setQueryTimeout(timeout);
}
stmts.put(name, new PreparedStatementCapsule(query, ps, timeout));
} catch (final SQLException e) {
throw new DatabaseEngineException("Could not create prepared statement", e);
}
} | java | private void createPreparedStatement(final String name, final String query, final int timeout, final boolean recovering) throws NameAlreadyExistsException, DatabaseEngineException {
if (!recovering) {
if (stmts.containsKey(name)) {
throw new NameAlreadyExistsException(String.format("There's already a PreparedStatement with the name '%s'", name));
}
try {
getConnection();
} catch (final Exception e) {
throw new DatabaseEngineException("Could not create prepared statement", e);
}
}
PreparedStatement ps;
try {
ps = conn.prepareStatement(query);
if (timeout > 0) {
ps.setQueryTimeout(timeout);
}
stmts.put(name, new PreparedStatementCapsule(query, ps, timeout));
} catch (final SQLException e) {
throw new DatabaseEngineException("Could not create prepared statement", e);
}
} | [
"private",
"void",
"createPreparedStatement",
"(",
"final",
"String",
"name",
",",
"final",
"String",
"query",
",",
"final",
"int",
"timeout",
",",
"final",
"boolean",
"recovering",
")",
"throws",
"NameAlreadyExistsException",
",",
"DatabaseEngineException",
"{",
"i... | Creates a prepared statement.
@param name The name of the prepared statement.
@param query The query.
@param timeout The timeout (in seconds) if applicable. Only applicable if > 0.
@param recovering True if calling from recovering, false otherwise.
@throws NameAlreadyExistsException If the name already exists.
@throws DatabaseEngineException If something goes wrong creating the statement. | [
"Creates",
"a",
"prepared",
"statement",
"."
] | train | https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/engine/AbstractDatabaseEngine.java#L1837-L1860 |
google/closure-templates | java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java | GenJsCodeVisitor.addCodeToProvideSoyNamespace | private static void addCodeToProvideSoyNamespace(StringBuilder header, SoyFileNode soyFile) {
header.append("goog.provide('").append(soyFile.getNamespace()).append("');\n");
} | java | private static void addCodeToProvideSoyNamespace(StringBuilder header, SoyFileNode soyFile) {
header.append("goog.provide('").append(soyFile.getNamespace()).append("');\n");
} | [
"private",
"static",
"void",
"addCodeToProvideSoyNamespace",
"(",
"StringBuilder",
"header",
",",
"SoyFileNode",
"soyFile",
")",
"{",
"header",
".",
"append",
"(",
"\"goog.provide('\"",
")",
".",
"append",
"(",
"soyFile",
".",
"getNamespace",
"(",
")",
")",
".",... | Helper for visitSoyFileNode(SoyFileNode) to add code to provide Soy namespaces.
@param header
@param soyFile The node we're visiting. | [
"Helper",
"for",
"visitSoyFileNode",
"(",
"SoyFileNode",
")",
"to",
"add",
"code",
"to",
"provide",
"Soy",
"namespaces",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/internal/GenJsCodeVisitor.java#L508-L510 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/ArabicShaping.java | ArabicShaping.shiftArray | private static void shiftArray(char [] dest,int start, int e, char subChar){
int w = e;
int r = e;
while (--r >= start) {
char ch = dest[r];
if (ch != subChar) {
--w;
if (w != r) {
dest[w] = ch;
}
}
}
} | java | private static void shiftArray(char [] dest,int start, int e, char subChar){
int w = e;
int r = e;
while (--r >= start) {
char ch = dest[r];
if (ch != subChar) {
--w;
if (w != r) {
dest[w] = ch;
}
}
}
} | [
"private",
"static",
"void",
"shiftArray",
"(",
"char",
"[",
"]",
"dest",
",",
"int",
"start",
",",
"int",
"e",
",",
"char",
"subChar",
")",
"{",
"int",
"w",
"=",
"e",
";",
"int",
"r",
"=",
"e",
";",
"while",
"(",
"--",
"r",
">=",
"start",
")",... | /*
Name : shiftArray
Function: Shifts characters to replace space sub characters | [
"/",
"*",
"Name",
":",
"shiftArray",
"Function",
":",
"Shifts",
"characters",
"to",
"replace",
"space",
"sub",
"characters"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/ArabicShaping.java#L1165-L1177 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_health_interface.java | xen_health_interface.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_interface_responses result = (xen_health_interface_responses) service.get_payload_formatter().string_to_resource(xen_health_interface_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.xen_health_interface_response_array);
}
xen_health_interface[] result_xen_health_interface = new xen_health_interface[result.xen_health_interface_response_array.length];
for(int i = 0; i < result.xen_health_interface_response_array.length; i++)
{
result_xen_health_interface[i] = result.xen_health_interface_response_array[i].xen_health_interface[0];
}
return result_xen_health_interface;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_interface_responses result = (xen_health_interface_responses) service.get_payload_formatter().string_to_resource(xen_health_interface_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.xen_health_interface_response_array);
}
xen_health_interface[] result_xen_health_interface = new xen_health_interface[result.xen_health_interface_response_array.length];
for(int i = 0; i < result.xen_health_interface_response_array.length; i++)
{
result_xen_health_interface[i] = result.xen_health_interface_response_array[i].xen_health_interface[0];
}
return result_xen_health_interface;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"xen_health_interface_responses",
"result",
"=",
"(",
"xen_health_interface_responses",
")",
"service",
".",
"... | <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/xen/xen_health_interface.java#L430-L447 |
icode/ameba | src/main/java/ameba/websocket/internal/EndpointMeta.java | EndpointMeta.onError | public void onError(Session session, Throwable thr) {
if (getOnErrorHandle() != null) {
callMethod(getOnErrorHandle(), getOnErrorParameters(), session, false, thr);
} else {
logger.error(Messages.get("web.socket.error"), thr);
}
} | java | public void onError(Session session, Throwable thr) {
if (getOnErrorHandle() != null) {
callMethod(getOnErrorHandle(), getOnErrorParameters(), session, false, thr);
} else {
logger.error(Messages.get("web.socket.error"), thr);
}
} | [
"public",
"void",
"onError",
"(",
"Session",
"session",
",",
"Throwable",
"thr",
")",
"{",
"if",
"(",
"getOnErrorHandle",
"(",
")",
"!=",
"null",
")",
"{",
"callMethod",
"(",
"getOnErrorHandle",
"(",
")",
",",
"getOnErrorParameters",
"(",
")",
",",
"sessio... | <p>onError.</p>
@param session a {@link javax.websocket.Session} object.
@param thr a {@link java.lang.Throwable} object. | [
"<p",
">",
"onError",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/websocket/internal/EndpointMeta.java#L207-L213 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/CollectionLiteralsTypeComputer.java | CollectionLiteralsTypeComputer.createCollectionTypeReference | protected LightweightTypeReference createCollectionTypeReference(JvmGenericType collectionType, LightweightTypeReference elementType, LightweightTypeReference expectedType, ITypeReferenceOwner owner) {
ParameterizedTypeReference result = new ParameterizedTypeReference(owner, collectionType);
result.addTypeArgument(elementType);
if (isIterableExpectation(expectedType) && !expectedType.isAssignableFrom(result)) {
// avoid to assign a set literal to a list and viceversa:
// at least the raw types must be assignable
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=498779
if (expectedType.getRawTypeReference().isAssignableFrom(result.getRawTypeReference())) {
LightweightTypeReference expectedElementType = getElementOrComponentType(expectedType, owner);
if (matchesExpectation(elementType, expectedElementType)) {
return expectedType;
}
}
}
return result;
} | java | protected LightweightTypeReference createCollectionTypeReference(JvmGenericType collectionType, LightweightTypeReference elementType, LightweightTypeReference expectedType, ITypeReferenceOwner owner) {
ParameterizedTypeReference result = new ParameterizedTypeReference(owner, collectionType);
result.addTypeArgument(elementType);
if (isIterableExpectation(expectedType) && !expectedType.isAssignableFrom(result)) {
// avoid to assign a set literal to a list and viceversa:
// at least the raw types must be assignable
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=498779
if (expectedType.getRawTypeReference().isAssignableFrom(result.getRawTypeReference())) {
LightweightTypeReference expectedElementType = getElementOrComponentType(expectedType, owner);
if (matchesExpectation(elementType, expectedElementType)) {
return expectedType;
}
}
}
return result;
} | [
"protected",
"LightweightTypeReference",
"createCollectionTypeReference",
"(",
"JvmGenericType",
"collectionType",
",",
"LightweightTypeReference",
"elementType",
",",
"LightweightTypeReference",
"expectedType",
",",
"ITypeReferenceOwner",
"owner",
")",
"{",
"ParameterizedTypeRefer... | Creates a collection type reference that comes as close as possible / necessary to its expected type. | [
"Creates",
"a",
"collection",
"type",
"reference",
"that",
"comes",
"as",
"close",
"as",
"possible",
"/",
"necessary",
"to",
"its",
"expected",
"type",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/CollectionLiteralsTypeComputer.java#L241-L256 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/helper/JMFiles.java | JMFiles.buildBufferedAppendWriter | public static Writer buildBufferedAppendWriter(Path path, Charset charset) {
try {
if (JMPath.notExists(path))
JMPathOperation.createFileWithParentDirectories(path);
return Files.newBufferedWriter(path, charset, StandardOpenOption
.APPEND);
} catch (IOException e) {
return JMExceptionManager.handleExceptionAndReturnNull(log, e,
"buildBufferedAppendWriter", path, charset);
}
} | java | public static Writer buildBufferedAppendWriter(Path path, Charset charset) {
try {
if (JMPath.notExists(path))
JMPathOperation.createFileWithParentDirectories(path);
return Files.newBufferedWriter(path, charset, StandardOpenOption
.APPEND);
} catch (IOException e) {
return JMExceptionManager.handleExceptionAndReturnNull(log, e,
"buildBufferedAppendWriter", path, charset);
}
} | [
"public",
"static",
"Writer",
"buildBufferedAppendWriter",
"(",
"Path",
"path",
",",
"Charset",
"charset",
")",
"{",
"try",
"{",
"if",
"(",
"JMPath",
".",
"notExists",
"(",
"path",
")",
")",
"JMPathOperation",
".",
"createFileWithParentDirectories",
"(",
"path",... | Build buffered append writer writer.
@param path the path
@param charset the charset
@return the writer | [
"Build",
"buffered",
"append",
"writer",
"writer",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMFiles.java#L72-L82 |
sebastiangraf/jSCSI | bundles/target/src/main/java/org/jscsi/target/scsi/sense/senseDataDescriptor/SenseDataDescriptor.java | SenseDataDescriptor.serializeCommonFields | private final void serializeCommonFields (final ByteBuffer byteBuffer, final int index) {
byteBuffer.position(index);
byteBuffer.put(descriptorType.getValue());
byteBuffer.put((byte) additionalLength);
} | java | private final void serializeCommonFields (final ByteBuffer byteBuffer, final int index) {
byteBuffer.position(index);
byteBuffer.put(descriptorType.getValue());
byteBuffer.put((byte) additionalLength);
} | [
"private",
"final",
"void",
"serializeCommonFields",
"(",
"final",
"ByteBuffer",
"byteBuffer",
",",
"final",
"int",
"index",
")",
"{",
"byteBuffer",
".",
"position",
"(",
"index",
")",
";",
"byteBuffer",
".",
"put",
"(",
"descriptorType",
".",
"getValue",
"(",... | Serializes the fields common to all sense data descriptors.
@param byteBuffer where the serialized fields will be stored
@param index the position of the first byte of the sense data descriptor in the {@link ByteBuffer} | [
"Serializes",
"the",
"fields",
"common",
"to",
"all",
"sense",
"data",
"descriptors",
"."
] | train | https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/target/src/main/java/org/jscsi/target/scsi/sense/senseDataDescriptor/SenseDataDescriptor.java#L54-L58 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/BundleRepositoryRegistry.java | BundleRepositoryRegistry.initializeDefaults | public static synchronized void initializeDefaults(String serverName, boolean useMsgs) {
allUseMsgs = useMsgs;
cacheServerName = serverName;
addBundleRepository(Utils.getInstallDir().getAbsolutePath(), ExtensionConstants.CORE_EXTENSION);
addBundleRepository(new File(Utils.getUserDir(), "/extension/").getAbsolutePath(), ExtensionConstants.USER_EXTENSION);
} | java | public static synchronized void initializeDefaults(String serverName, boolean useMsgs) {
allUseMsgs = useMsgs;
cacheServerName = serverName;
addBundleRepository(Utils.getInstallDir().getAbsolutePath(), ExtensionConstants.CORE_EXTENSION);
addBundleRepository(new File(Utils.getUserDir(), "/extension/").getAbsolutePath(), ExtensionConstants.USER_EXTENSION);
} | [
"public",
"static",
"synchronized",
"void",
"initializeDefaults",
"(",
"String",
"serverName",
",",
"boolean",
"useMsgs",
")",
"{",
"allUseMsgs",
"=",
"useMsgs",
";",
"cacheServerName",
"=",
"serverName",
";",
"addBundleRepository",
"(",
"Utils",
".",
"getInstallDir... | Add the default repositories for the product
@param serverName If set to a serverName, a cache will be created in that server's workarea. A null value disables caching.
@param useMsgs This setting is passed on to the held ContentLocalBundleRepositories. | [
"Add",
"the",
"default",
"repositories",
"for",
"the",
"product"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/BundleRepositoryRegistry.java#L42-L47 |
Azure/azure-sdk-for-java | cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java | DatabaseAccountsInner.listReadOnlyKeysAsync | public Observable<DatabaseAccountListReadOnlyKeysResultInner> listReadOnlyKeysAsync(String resourceGroupName, String accountName) {
return listReadOnlyKeysWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<DatabaseAccountListReadOnlyKeysResultInner>, DatabaseAccountListReadOnlyKeysResultInner>() {
@Override
public DatabaseAccountListReadOnlyKeysResultInner call(ServiceResponse<DatabaseAccountListReadOnlyKeysResultInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseAccountListReadOnlyKeysResultInner> listReadOnlyKeysAsync(String resourceGroupName, String accountName) {
return listReadOnlyKeysWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<DatabaseAccountListReadOnlyKeysResultInner>, DatabaseAccountListReadOnlyKeysResultInner>() {
@Override
public DatabaseAccountListReadOnlyKeysResultInner call(ServiceResponse<DatabaseAccountListReadOnlyKeysResultInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseAccountListReadOnlyKeysResultInner",
">",
"listReadOnlyKeysAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
")",
"{",
"return",
"listReadOnlyKeysWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName... | Lists the read-only access keys for the specified Azure Cosmos DB database account.
@param resourceGroupName Name of an Azure resource group.
@param accountName Cosmos DB database account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseAccountListReadOnlyKeysResultInner object | [
"Lists",
"the",
"read",
"-",
"only",
"access",
"keys",
"for",
"the",
"specified",
"Azure",
"Cosmos",
"DB",
"database",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L1739-L1746 |
Jasig/uPortal | uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java | VersionUtils.parseVersion | public static Version parseVersion(String versionString) {
final Matcher versionMatcher = VERSION_PATTERN.matcher(versionString);
if (!versionMatcher.matches()) {
return null;
}
final int major = Integer.parseInt(versionMatcher.group(1));
final int minor = Integer.parseInt(versionMatcher.group(2));
final int patch = Integer.parseInt(versionMatcher.group(3));
final String local = versionMatcher.group(4);
if (local != null) {
return new SimpleVersion(major, minor, patch, Integer.valueOf(local));
}
return new SimpleVersion(major, minor, patch);
} | java | public static Version parseVersion(String versionString) {
final Matcher versionMatcher = VERSION_PATTERN.matcher(versionString);
if (!versionMatcher.matches()) {
return null;
}
final int major = Integer.parseInt(versionMatcher.group(1));
final int minor = Integer.parseInt(versionMatcher.group(2));
final int patch = Integer.parseInt(versionMatcher.group(3));
final String local = versionMatcher.group(4);
if (local != null) {
return new SimpleVersion(major, minor, patch, Integer.valueOf(local));
}
return new SimpleVersion(major, minor, patch);
} | [
"public",
"static",
"Version",
"parseVersion",
"(",
"String",
"versionString",
")",
"{",
"final",
"Matcher",
"versionMatcher",
"=",
"VERSION_PATTERN",
".",
"matcher",
"(",
"versionString",
")",
";",
"if",
"(",
"!",
"versionMatcher",
".",
"matches",
"(",
")",
"... | Parse a version string into a Version object, if the string doesn't match the pattern null is
returned.
<p>The regular expression used in parsing is: ^(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:[\.-].*)?$
<p>Examples that match correctly:
<ul>
<li>4.0.5
<li>4.0.5.123123
<li>4.0.5-SNAPSHOT
<ul>
Examples do NOT match correctly:
<ul>
<li>4.0
<li>4.0.5_123123
<ul> | [
"Parse",
"a",
"version",
"string",
"into",
"a",
"Version",
"object",
"if",
"the",
"string",
"doesn",
"t",
"match",
"the",
"pattern",
"null",
"is",
"returned",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-tools/src/main/java/org/apereo/portal/version/VersionUtils.java#L46-L61 |
AltBeacon/android-beacon-library | lib/src/main/java/org/altbeacon/beacon/Beacon.java | Beacon.calculateDistance | protected static Double calculateDistance(int txPower, double bestRssiAvailable) {
if (Beacon.getDistanceCalculator() != null) {
return Beacon.getDistanceCalculator().calculateDistance(txPower, bestRssiAvailable);
}
else {
LogManager.e(TAG, "Distance calculator not set. Distance will bet set to -1");
return -1.0;
}
} | java | protected static Double calculateDistance(int txPower, double bestRssiAvailable) {
if (Beacon.getDistanceCalculator() != null) {
return Beacon.getDistanceCalculator().calculateDistance(txPower, bestRssiAvailable);
}
else {
LogManager.e(TAG, "Distance calculator not set. Distance will bet set to -1");
return -1.0;
}
} | [
"protected",
"static",
"Double",
"calculateDistance",
"(",
"int",
"txPower",
",",
"double",
"bestRssiAvailable",
")",
"{",
"if",
"(",
"Beacon",
".",
"getDistanceCalculator",
"(",
")",
"!=",
"null",
")",
"{",
"return",
"Beacon",
".",
"getDistanceCalculator",
"(",... | Estimate the distance to the beacon using the DistanceCalculator set on this class. If no
DistanceCalculator has been set, return -1 as the distance.
@see org.altbeacon.beacon.distance.DistanceCalculator
@param txPower
@param bestRssiAvailable
@return | [
"Estimate",
"the",
"distance",
"to",
"the",
"beacon",
"using",
"the",
"DistanceCalculator",
"set",
"on",
"this",
"class",
".",
"If",
"no",
"DistanceCalculator",
"has",
"been",
"set",
"return",
"-",
"1",
"as",
"the",
"distance",
".",
"@see",
"org",
".",
"al... | train | https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/Beacon.java#L659-L667 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/common/ServiceSupport.java | ServiceSupport.setService | @Override
public void setService(final String name, final FrameworkSupportService service){
synchronized (services){
if(null==services.get(name) && null!=service) {
services.put(name, service);
}else if(null==service) {
services.remove(name);
}
}
} | java | @Override
public void setService(final String name, final FrameworkSupportService service){
synchronized (services){
if(null==services.get(name) && null!=service) {
services.put(name, service);
}else if(null==service) {
services.remove(name);
}
}
} | [
"@",
"Override",
"public",
"void",
"setService",
"(",
"final",
"String",
"name",
",",
"final",
"FrameworkSupportService",
"service",
")",
"{",
"synchronized",
"(",
"services",
")",
"{",
"if",
"(",
"null",
"==",
"services",
".",
"get",
"(",
"name",
")",
"&&... | Set a service by name
@param name name
@param service service | [
"Set",
"a",
"service",
"by",
"name"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/common/ServiceSupport.java#L85-L94 |
duracloud/snapshot | snapshot-service-impl/src/main/java/org/duracloud/snapshot/service/impl/StepExecutionSupport.java | StepExecutionSupport.addToLong | protected void addToLong(String key, long value) {
synchronized (this.stepExecution) {
long currentValue = getLongValue(key);
getExecutionContext().putLong(key, currentValue + value);
}
} | java | protected void addToLong(String key, long value) {
synchronized (this.stepExecution) {
long currentValue = getLongValue(key);
getExecutionContext().putLong(key, currentValue + value);
}
} | [
"protected",
"void",
"addToLong",
"(",
"String",
"key",
",",
"long",
"value",
")",
"{",
"synchronized",
"(",
"this",
".",
"stepExecution",
")",
"{",
"long",
"currentValue",
"=",
"getLongValue",
"(",
"key",
")",
";",
"getExecutionContext",
"(",
")",
".",
"p... | Adds the specified value to the existing key.
@param key
@param value | [
"Adds",
"the",
"specified",
"value",
"to",
"the",
"existing",
"key",
"."
] | train | https://github.com/duracloud/snapshot/blob/7cb387b22fd4a9425087f654276138727c2c0b73/snapshot-service-impl/src/main/java/org/duracloud/snapshot/service/impl/StepExecutionSupport.java#L141-L147 |
Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java | GoogleDriveUtils.downloadFile | public static DownloadResponse downloadFile(Drive drive, File file) throws IOException {
if (file == null) {
return null;
}
return downloadFile(drive, file.getId());
} | java | public static DownloadResponse downloadFile(Drive drive, File file) throws IOException {
if (file == null) {
return null;
}
return downloadFile(drive, file.getId());
} | [
"public",
"static",
"DownloadResponse",
"downloadFile",
"(",
"Drive",
"drive",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"downloadFile",
"(",
"drive",
",",
"file... | Downloads file from Google Drive
@param drive drive client
@param file file to be downloaded
@return file content
@throws IOException an IOException | [
"Downloads",
"file",
"from",
"Google",
"Drive"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java#L351-L357 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/BoundedOverlay.java | BoundedOverlay.hasTile | public boolean hasTile(int x, int y, int zoom) {
// Check if generating tiles for the zoom level and is within the bounding box
boolean hasTile = isWithinBounds(x, y, zoom);
if (hasTile) {
// Check if there is a tile to retrieve
hasTile = hasTileToRetrieve(x, y, zoom);
}
return hasTile;
} | java | public boolean hasTile(int x, int y, int zoom) {
// Check if generating tiles for the zoom level and is within the bounding box
boolean hasTile = isWithinBounds(x, y, zoom);
if (hasTile) {
// Check if there is a tile to retrieve
hasTile = hasTileToRetrieve(x, y, zoom);
}
return hasTile;
} | [
"public",
"boolean",
"hasTile",
"(",
"int",
"x",
",",
"int",
"y",
",",
"int",
"zoom",
")",
"{",
"// Check if generating tiles for the zoom level and is within the bounding box",
"boolean",
"hasTile",
"=",
"isWithinBounds",
"(",
"x",
",",
"y",
",",
"zoom",
")",
";"... | Determine if there is a tile for the x, y, and zoom
@param x x coordinate
@param y y coordinate
@param zoom zoom value
@return true if there is a tile
@since 1.2.6 | [
"Determine",
"if",
"there",
"is",
"a",
"tile",
"for",
"the",
"x",
"y",
"and",
"zoom"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/tiles/overlay/BoundedOverlay.java#L151-L161 |
JetBrains/xodus | entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java | PersistentEntityStoreImpl.getLinkId | public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) {
return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName);
} | java | public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) {
return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName);
} | [
"public",
"int",
"getLinkId",
"(",
"@",
"NotNull",
"final",
"PersistentStoreTransaction",
"txn",
",",
"@",
"NotNull",
"final",
"String",
"linkName",
",",
"final",
"boolean",
"allowCreate",
")",
"{",
"return",
"allowCreate",
"?",
"linkIds",
".",
"getOrAllocateId",
... | Gets id of a link and creates the new one if necessary.
@param linkName name of the link.
@param allowCreate if set to true and if there is no link named as linkName,
create the new id for the linkName.
@return < 0 if there is no such link and create=false, else id of the link | [
"Gets",
"id",
"of",
"a",
"link",
"and",
"creates",
"the",
"new",
"one",
"if",
"necessary",
"."
] | train | https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/entity-store/src/main/java/jetbrains/exodus/entitystore/PersistentEntityStoreImpl.java#L1751-L1753 |
lucee/Lucee | core/src/main/java/lucee/runtime/schedule/StorageUtil.java | StorageUtil.toDateTime | public DateTime toDateTime(Element el, String attributeName, DateTime defaultValue) {
String value = el.getAttribute(attributeName);
if (value == null) return defaultValue;
DateTime dtValue = Caster.toDate(value, false, null, null);
if (dtValue == null) return defaultValue;
return dtValue;
} | java | public DateTime toDateTime(Element el, String attributeName, DateTime defaultValue) {
String value = el.getAttribute(attributeName);
if (value == null) return defaultValue;
DateTime dtValue = Caster.toDate(value, false, null, null);
if (dtValue == null) return defaultValue;
return dtValue;
} | [
"public",
"DateTime",
"toDateTime",
"(",
"Element",
"el",
",",
"String",
"attributeName",
",",
"DateTime",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"el",
".",
"getAttribute",
"(",
"attributeName",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"... | reads a XML Element Attribute ans cast it to a DateTime
@param el XML Element to read Attribute from it
@param attributeName Name of the Attribute to read
@param defaultValue if attribute doesn't exist return default value
@return Attribute Value | [
"reads",
"a",
"XML",
"Element",
"Attribute",
"ans",
"cast",
"it",
"to",
"a",
"DateTime"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/StorageUtil.java#L257-L264 |
jronrun/benayn | benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java | Retryer.exponentialWait | public Retryer<R> exponentialWait(long multiplier, long maximumTime, TimeUnit maximumUnit) {
return exponentialWait(multiplier, checkNotNull(maximumUnit).toMillis(maximumTime));
} | java | public Retryer<R> exponentialWait(long multiplier, long maximumTime, TimeUnit maximumUnit) {
return exponentialWait(multiplier, checkNotNull(maximumUnit).toMillis(maximumTime));
} | [
"public",
"Retryer",
"<",
"R",
">",
"exponentialWait",
"(",
"long",
"multiplier",
",",
"long",
"maximumTime",
",",
"TimeUnit",
"maximumUnit",
")",
"{",
"return",
"exponentialWait",
"(",
"multiplier",
",",
"checkNotNull",
"(",
"maximumUnit",
")",
".",
"toMillis",... | Sets the wait strategy which sleeps for an exponential amount of time after the first failed attempt
@see Retryer#exponentialWait(long, long)
@param multiplier
@param maximumTime
@param maximumUnit
@return | [
"Sets",
"the",
"wait",
"strategy",
"which",
"sleeps",
"for",
"an",
"exponential",
"amount",
"of",
"time",
"after",
"the",
"first",
"failed",
"attempt"
] | train | https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Retryer.java#L492-L494 |
Cleveroad/AdaptiveTableLayout | library/src/main/java/com/cleveroad/adaptivetablelayout/BaseDataAdaptiveTableLayoutAdapter.java | BaseDataAdaptiveTableLayoutAdapter.switchTwoColumnHeaders | void switchTwoColumnHeaders(int columnIndex, int columnToIndex) {
Object cellData = getColumnHeaders()[columnToIndex];
getColumnHeaders()[columnToIndex] = getColumnHeaders()[columnIndex];
getColumnHeaders()[columnIndex] = cellData;
} | java | void switchTwoColumnHeaders(int columnIndex, int columnToIndex) {
Object cellData = getColumnHeaders()[columnToIndex];
getColumnHeaders()[columnToIndex] = getColumnHeaders()[columnIndex];
getColumnHeaders()[columnIndex] = cellData;
} | [
"void",
"switchTwoColumnHeaders",
"(",
"int",
"columnIndex",
",",
"int",
"columnToIndex",
")",
"{",
"Object",
"cellData",
"=",
"getColumnHeaders",
"(",
")",
"[",
"columnToIndex",
"]",
";",
"getColumnHeaders",
"(",
")",
"[",
"columnToIndex",
"]",
"=",
"getColumnH... | Switch 2 columns headers with data
@param columnIndex column header from
@param columnToIndex column header to | [
"Switch",
"2",
"columns",
"headers",
"with",
"data"
] | train | https://github.com/Cleveroad/AdaptiveTableLayout/blob/188213b35e05e635497b03fe741799782dde7208/library/src/main/java/com/cleveroad/adaptivetablelayout/BaseDataAdaptiveTableLayoutAdapter.java#L49-L53 |
maven-nar/nar-maven-plugin | src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java | PropertyListSerialization.serializeMap | private static void serializeMap(final Map map, final ContentHandler handler) throws SAXException {
final AttributesImpl attributes = new AttributesImpl();
handler.startElement(null, "dict", "dict", attributes);
if (map.size() > 0) {
//
// need to output with sorted keys to maintain
// reproducability
//
final Object[] keys = map.keySet().toArray();
Arrays.sort(keys);
for (final Object key2 : keys) {
final String key = String.valueOf(key2);
handler.startElement(null, "key", "key", attributes);
handler.characters(key.toCharArray(), 0, key.length());
handler.endElement(null, "key", "key");
serializeObject(map.get(key2), handler);
}
}
handler.endElement(null, "dict", "dict");
} | java | private static void serializeMap(final Map map, final ContentHandler handler) throws SAXException {
final AttributesImpl attributes = new AttributesImpl();
handler.startElement(null, "dict", "dict", attributes);
if (map.size() > 0) {
//
// need to output with sorted keys to maintain
// reproducability
//
final Object[] keys = map.keySet().toArray();
Arrays.sort(keys);
for (final Object key2 : keys) {
final String key = String.valueOf(key2);
handler.startElement(null, "key", "key", attributes);
handler.characters(key.toCharArray(), 0, key.length());
handler.endElement(null, "key", "key");
serializeObject(map.get(key2), handler);
}
}
handler.endElement(null, "dict", "dict");
} | [
"private",
"static",
"void",
"serializeMap",
"(",
"final",
"Map",
"map",
",",
"final",
"ContentHandler",
"handler",
")",
"throws",
"SAXException",
"{",
"final",
"AttributesImpl",
"attributes",
"=",
"new",
"AttributesImpl",
"(",
")",
";",
"handler",
".",
"startEl... | Serialize a map as a dict element.
@param map
map to serialize.
@param handler
destination of serialization events.
@throws SAXException
if exception during serialization. | [
"Serialize",
"a",
"map",
"as",
"a",
"dict",
"element",
"."
] | train | https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java#L164-L184 |
tango-controls/JTango | dao/src/main/java/fr/esrf/TangoDs/Logging.java | Logging.add_logging_target | public void add_logging_target (Logger logger, String ttype, String tname) throws DevFailed
{
add_logging_target(logger, ttype + LOGGING_SEPARATOR + tname);
} | java | public void add_logging_target (Logger logger, String ttype, String tname) throws DevFailed
{
add_logging_target(logger, ttype + LOGGING_SEPARATOR + tname);
} | [
"public",
"void",
"add_logging_target",
"(",
"Logger",
"logger",
",",
"String",
"ttype",
",",
"String",
"tname",
")",
"throws",
"DevFailed",
"{",
"add_logging_target",
"(",
"logger",
",",
"ttype",
"+",
"LOGGING_SEPARATOR",
"+",
"tname",
")",
";",
"}"
] | Adds a logging target to the specified logger (i.e. device).
@param logger A lo4j logger to which the target will be added
@param ttype The target type
@param tname The target name | [
"Adds",
"a",
"logging",
"target",
"to",
"the",
"specified",
"logger",
"(",
"i",
".",
"e",
".",
"device",
")",
"."
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/dao/src/main/java/fr/esrf/TangoDs/Logging.java#L345-L348 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsSqlManager.java | CmsSqlManager.setBytes | public void setBytes(PreparedStatement statement, int pos, byte[] content) throws SQLException {
if (content.length < 2000) {
statement.setBytes(pos, content);
} else {
statement.setBinaryStream(pos, new ByteArrayInputStream(content), content.length);
}
} | java | public void setBytes(PreparedStatement statement, int pos, byte[] content) throws SQLException {
if (content.length < 2000) {
statement.setBytes(pos, content);
} else {
statement.setBinaryStream(pos, new ByteArrayInputStream(content), content.length);
}
} | [
"public",
"void",
"setBytes",
"(",
"PreparedStatement",
"statement",
",",
"int",
"pos",
",",
"byte",
"[",
"]",
"content",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"content",
".",
"length",
"<",
"2000",
")",
"{",
"statement",
".",
"setBytes",
"(",
"... | Sets the designated parameter to the given Java array of bytes.<p>
The driver converts this to an SQL VARBINARY or LONGVARBINARY (depending on the argument's
size relative to the driver's limits on VARBINARY values) when it sends it to the database.
@param statement the PreparedStatement where the content is set
@param pos the first parameter is 1, the second is 2, ...
@param content the parameter value
@throws SQLException if a database access error occurs | [
"Sets",
"the",
"designated",
"parameter",
"to",
"the",
"given",
"Java",
"array",
"of",
"bytes",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsSqlManager.java#L403-L410 |
GerdHolz/TOVAL | src/de/invation/code/toval/misc/ListUtils.java | ListUtils.divideListSize | public static <T> List<List<T>> divideListSize(List<T> list, int listSize) {
if(list.size() <= listSize)
return new ArrayList<>(Arrays.asList(list));
int numLists = (int) Math.ceil(list.size() / (listSize + 0.0));
// System.out.println("num lists: " + numLists);
Integer[] positions = new Integer[numLists-1];
for(int i=0; i<numLists; i++){
int position = ((i+1)*listSize);
// System.out.println("position: " + position);
if(position < list.size()){
positions[i] = position;
// System.out.println("add position");
}
}
// System.out.println(Arrays.toString(positions));
return divideListPos(list, positions);
} | java | public static <T> List<List<T>> divideListSize(List<T> list, int listSize) {
if(list.size() <= listSize)
return new ArrayList<>(Arrays.asList(list));
int numLists = (int) Math.ceil(list.size() / (listSize + 0.0));
// System.out.println("num lists: " + numLists);
Integer[] positions = new Integer[numLists-1];
for(int i=0; i<numLists; i++){
int position = ((i+1)*listSize);
// System.out.println("position: " + position);
if(position < list.size()){
positions[i] = position;
// System.out.println("add position");
}
}
// System.out.println(Arrays.toString(positions));
return divideListPos(list, positions);
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"List",
"<",
"T",
">",
">",
"divideListSize",
"(",
"List",
"<",
"T",
">",
"list",
",",
"int",
"listSize",
")",
"{",
"if",
"(",
"list",
".",
"size",
"(",
")",
"<=",
"listSize",
")",
"return",
"new",
... | Divides the given list using the boundaries in <code>cuts</code>.<br>
Cuts are interpreted in an inclusive way, which means that a single cut
at position i divides the given list in 0...i-1 + i...n<br>
This method deals with both cut positions including and excluding start
and end-indexes<br>
@param <T>
Type of list elements
@param list
The list to divide
@param positions
Cut positions for divide operations
@return A list of sublists of <code>list</code> according to the given
cut positions | [
"Divides",
"the",
"given",
"list",
"using",
"the",
"boundaries",
"in",
"<code",
">",
"cuts<",
"/",
"code",
">",
".",
"<br",
">",
"Cuts",
"are",
"interpreted",
"in",
"an",
"inclusive",
"way",
"which",
"means",
"that",
"a",
"single",
"cut",
"at",
"position... | train | https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/misc/ListUtils.java#L218-L234 |
apache/groovy | src/main/groovy/groovy/lang/MetaClassImpl.java | MetaClassImpl.invokeStaticMissingProperty | protected Object invokeStaticMissingProperty(Object instance, String propertyName, Object optionalValue, boolean isGetter) {
MetaClass mc = instance instanceof Class ? registry.getMetaClass((Class) instance) : this;
if (isGetter) {
MetaMethod propertyMissing = mc.getMetaMethod(STATIC_PROPERTY_MISSING, GETTER_MISSING_ARGS);
if (propertyMissing != null) {
return propertyMissing.invoke(instance, new Object[]{propertyName});
}
} else {
MetaMethod propertyMissing = mc.getMetaMethod(STATIC_PROPERTY_MISSING, SETTER_MISSING_ARGS);
if (propertyMissing != null) {
return propertyMissing.invoke(instance, new Object[]{propertyName, optionalValue});
}
}
if (instance instanceof Class) {
throw new MissingPropertyException(propertyName, (Class) instance);
}
throw new MissingPropertyException(propertyName, theClass);
} | java | protected Object invokeStaticMissingProperty(Object instance, String propertyName, Object optionalValue, boolean isGetter) {
MetaClass mc = instance instanceof Class ? registry.getMetaClass((Class) instance) : this;
if (isGetter) {
MetaMethod propertyMissing = mc.getMetaMethod(STATIC_PROPERTY_MISSING, GETTER_MISSING_ARGS);
if (propertyMissing != null) {
return propertyMissing.invoke(instance, new Object[]{propertyName});
}
} else {
MetaMethod propertyMissing = mc.getMetaMethod(STATIC_PROPERTY_MISSING, SETTER_MISSING_ARGS);
if (propertyMissing != null) {
return propertyMissing.invoke(instance, new Object[]{propertyName, optionalValue});
}
}
if (instance instanceof Class) {
throw new MissingPropertyException(propertyName, (Class) instance);
}
throw new MissingPropertyException(propertyName, theClass);
} | [
"protected",
"Object",
"invokeStaticMissingProperty",
"(",
"Object",
"instance",
",",
"String",
"propertyName",
",",
"Object",
"optionalValue",
",",
"boolean",
"isGetter",
")",
"{",
"MetaClass",
"mc",
"=",
"instance",
"instanceof",
"Class",
"?",
"registry",
".",
"... | Hook to deal with the case of MissingProperty for static properties. The method will look attempt to look up
"propertyMissing" handlers and invoke them otherwise thrown a MissingPropertyException
@param instance The instance
@param propertyName The name of the property
@param optionalValue The value in the case of a setter
@param isGetter True if its a getter
@return The value in the case of a getter or a MissingPropertyException | [
"Hook",
"to",
"deal",
"with",
"the",
"case",
"of",
"MissingProperty",
"for",
"static",
"properties",
".",
"The",
"method",
"will",
"look",
"attempt",
"to",
"look",
"up",
"propertyMissing",
"handlers",
"and",
"invoke",
"them",
"otherwise",
"thrown",
"a",
"Missi... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/lang/MetaClassImpl.java#L1009-L1027 |
Bedework/bw-util | bw-util-security/src/main/java/org/bedework/util/security/pki/PKITools.java | PKITools.writeFile | private void writeFile(final String fileName,
final byte[] bs,
final boolean append) throws IOException {
FileOutputStream fstr = null;
try {
fstr = new FileOutputStream(fileName, append);
fstr.write(bs);
// Terminate key with newline
fstr.write('\n');
fstr.flush();
} finally {
if (fstr != null) {
fstr.close();
}
}
} | java | private void writeFile(final String fileName,
final byte[] bs,
final boolean append) throws IOException {
FileOutputStream fstr = null;
try {
fstr = new FileOutputStream(fileName, append);
fstr.write(bs);
// Terminate key with newline
fstr.write('\n');
fstr.flush();
} finally {
if (fstr != null) {
fstr.close();
}
}
} | [
"private",
"void",
"writeFile",
"(",
"final",
"String",
"fileName",
",",
"final",
"byte",
"[",
"]",
"bs",
",",
"final",
"boolean",
"append",
")",
"throws",
"IOException",
"{",
"FileOutputStream",
"fstr",
"=",
"null",
";",
"try",
"{",
"fstr",
"=",
"new",
... | Write a single string to a file. Used to write keys
@param fileName String file to write to
@param bs bytes to write
@param append true to add the key to the file.
@throws IOException | [
"Write",
"a",
"single",
"string",
"to",
"a",
"file",
".",
"Used",
"to",
"write",
"keys"
] | train | https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-security/src/main/java/org/bedework/util/security/pki/PKITools.java#L433-L451 |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java | GeneratedDUserDaoImpl.queryByPhoneNumber1 | public Iterable<DUser> queryByPhoneNumber1(java.lang.String phoneNumber1) {
return queryByField(null, DUserMapper.Field.PHONENUMBER1.getFieldName(), phoneNumber1);
} | java | public Iterable<DUser> queryByPhoneNumber1(java.lang.String phoneNumber1) {
return queryByField(null, DUserMapper.Field.PHONENUMBER1.getFieldName(), phoneNumber1);
} | [
"public",
"Iterable",
"<",
"DUser",
">",
"queryByPhoneNumber1",
"(",
"java",
".",
"lang",
".",
"String",
"phoneNumber1",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"DUserMapper",
".",
"Field",
".",
"PHONENUMBER1",
".",
"getFieldName",
"(",
")",
",... | query-by method for field phoneNumber1
@param phoneNumber1 the specified attribute
@return an Iterable of DUsers for the specified phoneNumber1 | [
"query",
"-",
"by",
"method",
"for",
"field",
"phoneNumber1"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java#L187-L189 |
joniles/mpxj | src/main/java/net/sf/mpxj/common/DateHelper.java | DateHelper.min | public static Date min(Date d1, Date d2)
{
Date result;
if (d1 == null)
{
result = d2;
}
else
if (d2 == null)
{
result = d1;
}
else
{
result = (d1.compareTo(d2) < 0) ? d1 : d2;
}
return result;
} | java | public static Date min(Date d1, Date d2)
{
Date result;
if (d1 == null)
{
result = d2;
}
else
if (d2 == null)
{
result = d1;
}
else
{
result = (d1.compareTo(d2) < 0) ? d1 : d2;
}
return result;
} | [
"public",
"static",
"Date",
"min",
"(",
"Date",
"d1",
",",
"Date",
"d2",
")",
"{",
"Date",
"result",
";",
"if",
"(",
"d1",
"==",
"null",
")",
"{",
"result",
"=",
"d2",
";",
"}",
"else",
"if",
"(",
"d2",
"==",
"null",
")",
"{",
"result",
"=",
... | Returns the earlier of two dates, handling null values. A non-null Date
is always considered to be earlier than a null Date.
@param d1 Date instance
@param d2 Date instance
@return Date earliest date | [
"Returns",
"the",
"earlier",
"of",
"two",
"dates",
"handling",
"null",
"values",
".",
"A",
"non",
"-",
"null",
"Date",
"is",
"always",
"considered",
"to",
"be",
"earlier",
"than",
"a",
"null",
"Date",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/common/DateHelper.java#L191-L208 |
molgenis/molgenis | molgenis-core-ui/src/main/java/org/molgenis/core/ui/MolgenisMenuController.java | MolgenisMenuController.forwardMenuDefaultPlugin | @SuppressWarnings("squid:S3752") // multiple methods required
@RequestMapping(
method = {RequestMethod.GET, RequestMethod.POST},
value = "/{menuId}")
public String forwardMenuDefaultPlugin(@Valid @NotNull @PathVariable String menuId, Model model) {
Menu filteredMenu =
menuReaderService
.getMenu()
.flatMap(menu -> menu.findMenu(menuId))
.orElseThrow(
() -> new RuntimeException("menu with id [" + menuId + "] does not exist"));
model.addAttribute(KEY_MENU_ID, menuId);
String pluginId = filteredMenu.firstItem().map(MenuItem::getId).orElse(VoidPluginController.ID);
String contextUri = URI + '/' + menuId + '/' + pluginId;
addModelAttributes(model, contextUri);
return getForwardPluginUri(pluginId);
} | java | @SuppressWarnings("squid:S3752") // multiple methods required
@RequestMapping(
method = {RequestMethod.GET, RequestMethod.POST},
value = "/{menuId}")
public String forwardMenuDefaultPlugin(@Valid @NotNull @PathVariable String menuId, Model model) {
Menu filteredMenu =
menuReaderService
.getMenu()
.flatMap(menu -> menu.findMenu(menuId))
.orElseThrow(
() -> new RuntimeException("menu with id [" + menuId + "] does not exist"));
model.addAttribute(KEY_MENU_ID, menuId);
String pluginId = filteredMenu.firstItem().map(MenuItem::getId).orElse(VoidPluginController.ID);
String contextUri = URI + '/' + menuId + '/' + pluginId;
addModelAttributes(model, contextUri);
return getForwardPluginUri(pluginId);
} | [
"@",
"SuppressWarnings",
"(",
"\"squid:S3752\"",
")",
"// multiple methods required",
"@",
"RequestMapping",
"(",
"method",
"=",
"{",
"RequestMethod",
".",
"GET",
",",
"RequestMethod",
".",
"POST",
"}",
",",
"value",
"=",
"\"/{menuId}\"",
")",
"public",
"String",
... | Forwards to the first menu item in the specified menu. Forwards to the void controller if the
user has no permissions to view anything in that menu, i.e. the menu is empty.
@param menuId ID of the menu or plugin | [
"Forwards",
"to",
"the",
"first",
"menu",
"item",
"in",
"the",
"specified",
"menu",
".",
"Forwards",
"to",
"the",
"void",
"controller",
"if",
"the",
"user",
"has",
"no",
"permissions",
"to",
"view",
"anything",
"in",
"that",
"menu",
"i",
".",
"e",
".",
... | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-core-ui/src/main/java/org/molgenis/core/ui/MolgenisMenuController.java#L120-L138 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/matching/MessageProcessorMatching.java | MessageProcessorMatching.removeConsumerDispatcherMatchTarget | public void removeConsumerDispatcherMatchTarget(ConsumerDispatcher consumerDispatcher, SelectionCriteria selectionCriteria)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"removeConsumerDispatcherMatchTarget",
new Object[] {consumerDispatcher, selectionCriteria});
// Remove the consumer point from the matchspace
// Set the CD and selection criteria into a wrapper that extends MatchTarget
MatchingConsumerDispatcherWithCriteira key = new MatchingConsumerDispatcherWithCriteira (consumerDispatcher,selectionCriteria);
// Reset the CD flag to indicate that this subscription is not in the MatchSpace.
consumerDispatcher.setIsInMatchSpace(false);
try
{
removeTarget(key);
}
catch (MatchingException e)
{
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching.removeConsumerDispatcherMatchTarget",
"1:1312:1.117.1.11",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeConsumerDispatcherMatchTarget", "SICoreException");
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:1323:1.117.1.11",
e });
throw new SIErrorException(
nls.getFormattedMessage(
"INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:1331:1.117.1.11",
e },
null),
e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeConsumerDispatcherMatchTarget");
} | java | public void removeConsumerDispatcherMatchTarget(ConsumerDispatcher consumerDispatcher, SelectionCriteria selectionCriteria)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"removeConsumerDispatcherMatchTarget",
new Object[] {consumerDispatcher, selectionCriteria});
// Remove the consumer point from the matchspace
// Set the CD and selection criteria into a wrapper that extends MatchTarget
MatchingConsumerDispatcherWithCriteira key = new MatchingConsumerDispatcherWithCriteira (consumerDispatcher,selectionCriteria);
// Reset the CD flag to indicate that this subscription is not in the MatchSpace.
consumerDispatcher.setIsInMatchSpace(false);
try
{
removeTarget(key);
}
catch (MatchingException e)
{
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching.removeConsumerDispatcherMatchTarget",
"1:1312:1.117.1.11",
this);
SibTr.exception(tc, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeConsumerDispatcherMatchTarget", "SICoreException");
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:1323:1.117.1.11",
e });
throw new SIErrorException(
nls.getFormattedMessage(
"INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.matching.MessageProcessorMatching",
"1:1331:1.117.1.11",
e },
null),
e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeConsumerDispatcherMatchTarget");
} | [
"public",
"void",
"removeConsumerDispatcherMatchTarget",
"(",
"ConsumerDispatcher",
"consumerDispatcher",
",",
"SelectionCriteria",
"selectionCriteria",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
... | Method removeConsumerDispatcherMatchTarget
Used to remove a ConsumerDispatcher from the MatchSpace.
@param consumerDispatcher The consumer dispatcher to remove | [
"Method",
"removeConsumerDispatcherMatchTarget",
"Used",
"to",
"remove",
"a",
"ConsumerDispatcher",
"from",
"the",
"MatchSpace",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/matching/MessageProcessorMatching.java#L1247-L1299 |
lucee/Lucee | core/src/main/java/lucee/runtime/op/Caster.java | Caster.toDate | public static DateTime toDate(String str, boolean alsoNumbers, TimeZone tz, DateTime defaultValue) {
return DateCaster.toDateAdvanced(str, alsoNumbers ? DateCaster.CONVERTING_TYPE_OFFSET : DateCaster.CONVERTING_TYPE_NONE, tz, defaultValue);
} | java | public static DateTime toDate(String str, boolean alsoNumbers, TimeZone tz, DateTime defaultValue) {
return DateCaster.toDateAdvanced(str, alsoNumbers ? DateCaster.CONVERTING_TYPE_OFFSET : DateCaster.CONVERTING_TYPE_NONE, tz, defaultValue);
} | [
"public",
"static",
"DateTime",
"toDate",
"(",
"String",
"str",
",",
"boolean",
"alsoNumbers",
",",
"TimeZone",
"tz",
",",
"DateTime",
"defaultValue",
")",
"{",
"return",
"DateCaster",
".",
"toDateAdvanced",
"(",
"str",
",",
"alsoNumbers",
"?",
"DateCaster",
"... | cast a Object to a DateTime Object
@param str String to cast
@param alsoNumbers define if also numbers will casted to a datetime value
@param tz
@param defaultValue
@return casted DateTime Object | [
"cast",
"a",
"Object",
"to",
"a",
"DateTime",
"Object"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L2924-L2926 |
Azure/azure-sdk-for-java | resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java | ResourcesInner.validateMoveResourcesAsync | public Observable<Void> validateMoveResourcesAsync(String sourceResourceGroupName, ResourcesMoveInfo parameters) {
return validateMoveResourcesWithServiceResponseAsync(sourceResourceGroupName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> validateMoveResourcesAsync(String sourceResourceGroupName, ResourcesMoveInfo parameters) {
return validateMoveResourcesWithServiceResponseAsync(sourceResourceGroupName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"validateMoveResourcesAsync",
"(",
"String",
"sourceResourceGroupName",
",",
"ResourcesMoveInfo",
"parameters",
")",
"{",
"return",
"validateMoveResourcesWithServiceResponseAsync",
"(",
"sourceResourceGroupName",
",",
"parameters",
")... | Validates whether resources can be moved from one resource group to another resource group.
This operation checks whether the specified resources can be moved to the target. The resources to move must be in the same source resource group. The target resource group may be in a different subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the Location header value to check the result of the long-running operation.
@param sourceResourceGroupName The name of the resource group containing the resources to validate for move.
@param parameters Parameters for moving resources.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Validates",
"whether",
"resources",
"can",
"be",
"moved",
"from",
"one",
"resource",
"group",
"to",
"another",
"resource",
"group",
".",
"This",
"operation",
"checks",
"whether",
"the",
"specified",
"resources",
"can",
"be",
"moved",
"to",
"the",
"target",
".... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L609-L616 |
landawn/AbacusUtil | src/com/landawn/abacus/util/stream/Stream.java | Stream.parallelConcatt | public static <T> Stream<T> parallelConcatt(final Collection<? extends Iterator<? extends T>> c) {
return parallelConcatt(c, DEFAULT_READING_THREAD_NUM);
} | java | public static <T> Stream<T> parallelConcatt(final Collection<? extends Iterator<? extends T>> c) {
return parallelConcatt(c, DEFAULT_READING_THREAD_NUM);
} | [
"public",
"static",
"<",
"T",
">",
"Stream",
"<",
"T",
">",
"parallelConcatt",
"(",
"final",
"Collection",
"<",
"?",
"extends",
"Iterator",
"<",
"?",
"extends",
"T",
">",
">",
"c",
")",
"{",
"return",
"parallelConcatt",
"(",
"c",
",",
"DEFAULT_READING_TH... | Put the stream in try-catch to stop the back-end reading thread if error happens
<br />
<code>
try (Stream<Integer> stream = Stream.parallelConcat(a,b, ...)) {
stream.forEach(N::println);
}
</code>
@param c
@return | [
"Put",
"the",
"stream",
"in",
"try",
"-",
"catch",
"to",
"stop",
"the",
"back",
"-",
"end",
"reading",
"thread",
"if",
"error",
"happens",
"<br",
"/",
">",
"<code",
">",
"try",
"(",
"Stream<Integer",
">",
"stream",
"=",
"Stream",
".",
"parallelConcat",
... | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/stream/Stream.java#L4391-L4393 |
julienledem/brennus | brennus-builder/src/main/java/brennus/ClassBuilder.java | ClassBuilder.startMethod | public MethodDeclarationBuilder startMethod(Protection protection, Type returnType, String methodName) {
return startMethod(protection, returnType, methodName, false);
} | java | public MethodDeclarationBuilder startMethod(Protection protection, Type returnType, String methodName) {
return startMethod(protection, returnType, methodName, false);
} | [
"public",
"MethodDeclarationBuilder",
"startMethod",
"(",
"Protection",
"protection",
",",
"Type",
"returnType",
",",
"String",
"methodName",
")",
"{",
"return",
"startMethod",
"(",
"protection",
",",
"returnType",
",",
"methodName",
",",
"false",
")",
";",
"}"
] | .startMethod(protection, return, name){statements}.endMethod()
@param protection public/package/protected/private
@param returnType
@param methodName
@return a MethodDeclarationBuilder | [
".",
"startMethod",
"(",
"protection",
"return",
"name",
")",
"{",
"statements",
"}",
".",
"endMethod",
"()"
] | train | https://github.com/julienledem/brennus/blob/0798fb565d95af19ddc5accd084e58c4e882dbd0/brennus-builder/src/main/java/brennus/ClassBuilder.java#L116-L118 |
kuali/ojb-1.0.4 | src/xdoclet/java/src/xdoclet/modules/ojb/constraints/ModelConstraints.java | ModelConstraints.checkCollectionForeignkeys | private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
ClassDescriptorDef classDef;
CollectionDescriptorDef collDef;
for (Iterator it = modelDef.getClasses(); it.hasNext();)
{
classDef = (ClassDescriptorDef)it.next();
for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)
{
collDef = (CollectionDescriptorDef)collIt.next();
if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))
{
checkIndirectionTable(modelDef, collDef);
}
else
{
checkCollectionForeignkeys(modelDef, collDef);
}
}
}
}
} | java | private void checkCollectionForeignkeys(ModelDef modelDef, String checkLevel) throws ConstraintException
{
if (CHECKLEVEL_NONE.equals(checkLevel))
{
return;
}
ClassDescriptorDef classDef;
CollectionDescriptorDef collDef;
for (Iterator it = modelDef.getClasses(); it.hasNext();)
{
classDef = (ClassDescriptorDef)it.next();
for (Iterator collIt = classDef.getCollections(); collIt.hasNext();)
{
collDef = (CollectionDescriptorDef)collIt.next();
if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false))
{
if (collDef.hasProperty(PropertyHelper.OJB_PROPERTY_INDIRECTION_TABLE))
{
checkIndirectionTable(modelDef, collDef);
}
else
{
checkCollectionForeignkeys(modelDef, collDef);
}
}
}
}
} | [
"private",
"void",
"checkCollectionForeignkeys",
"(",
"ModelDef",
"modelDef",
",",
"String",
"checkLevel",
")",
"throws",
"ConstraintException",
"{",
"if",
"(",
"CHECKLEVEL_NONE",
".",
"equals",
"(",
"checkLevel",
")",
")",
"{",
"return",
";",
"}",
"ClassDescripto... | Checks the foreignkeys of all collections in the model.
@param modelDef The model
@param checkLevel The current check level (this constraint is checked in basic and strict)
@exception ConstraintException If the value for foreignkey is invalid | [
"Checks",
"the",
"foreignkeys",
"of",
"all",
"collections",
"in",
"the",
"model",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/constraints/ModelConstraints.java#L368-L397 |
teatrove/teatrove | tea/src/main/java/org/teatrove/tea/util/StringCompilationProvider.java | StringCompilationProvider.setTemplateSource | public void setTemplateSource(String name, String source) {
mTemplateSources.put(name, new TemplateSource(name, source));
} | java | public void setTemplateSource(String name, String source) {
mTemplateSources.put(name, new TemplateSource(name, source));
} | [
"public",
"void",
"setTemplateSource",
"(",
"String",
"name",
",",
"String",
"source",
")",
"{",
"mTemplateSources",
".",
"put",
"(",
"name",
",",
"new",
"TemplateSource",
"(",
"name",
",",
"source",
")",
")",
";",
"}"
] | Add or overwrite an existing source for the given fully-qualified dot
format of the given template name.
@param name The name of the template
@param source The source code for the template | [
"Add",
"or",
"overwrite",
"an",
"existing",
"source",
"for",
"the",
"given",
"fully",
"-",
"qualified",
"dot",
"format",
"of",
"the",
"given",
"template",
"name",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/tea/src/main/java/org/teatrove/tea/util/StringCompilationProvider.java#L73-L75 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/DocPath.java | DocPath.forPackage | public static DocPath forPackage(Utils utils, TypeElement typeElement) {
return (typeElement == null) ? empty : forPackage(utils.containingPackage(typeElement));
} | java | public static DocPath forPackage(Utils utils, TypeElement typeElement) {
return (typeElement == null) ? empty : forPackage(utils.containingPackage(typeElement));
} | [
"public",
"static",
"DocPath",
"forPackage",
"(",
"Utils",
"utils",
",",
"TypeElement",
"typeElement",
")",
"{",
"return",
"(",
"typeElement",
"==",
"null",
")",
"?",
"empty",
":",
"forPackage",
"(",
"utils",
".",
"containingPackage",
"(",
"typeElement",
")",
... | Return the path for the package of a class.
For example, if the class is java.lang.Object,
the path is java/lang. | [
"Return",
"the",
"path",
"for",
"the",
"package",
"of",
"a",
"class",
".",
"For",
"example",
"if",
"the",
"class",
"is",
"java",
".",
"lang",
".",
"Object",
"the",
"path",
"is",
"java",
"/",
"lang",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/DocPath.java#L81-L83 |
EasyinnovaSL/Tiff-Library-4J | src/main/java/com/easyinnova/tiff/model/ValidationResult.java | ValidationResult.addWarning | public void addWarning(String desc, String value, String loc) {
iaddWarning(desc, value, loc);
} | java | public void addWarning(String desc, String value, String loc) {
iaddWarning(desc, value, loc);
} | [
"public",
"void",
"addWarning",
"(",
"String",
"desc",
",",
"String",
"value",
",",
"String",
"loc",
")",
"{",
"iaddWarning",
"(",
"desc",
",",
"value",
",",
"loc",
")",
";",
"}"
] | Adds an warning.
@param desc Warning description
@param value the String that caused the warning
@param loc the location | [
"Adds",
"an",
"warning",
"."
] | train | https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/model/ValidationResult.java#L161-L163 |
vincentk/joptimizer | src/main/java/com/joptimizer/functions/LogarithmicBarrier.java | LogarithmicBarrier.createPhase1BarrierFunction | @Override
public BarrierFunction createPhase1BarrierFunction(){
final int dimPh1 = dim +1;
ConvexMultivariateRealFunction[] inequalitiesPh1 = new ConvexMultivariateRealFunction[this.fi.length];
for(int i=0; i<inequalitiesPh1.length; i++){
final ConvexMultivariateRealFunction originalFi = this.fi[i];
ConvexMultivariateRealFunction fi = new ConvexMultivariateRealFunction() {
@Override
public double value(double[] Y) {
DoubleMatrix1D y = DoubleFactory1D.dense.make(Y);
DoubleMatrix1D X = y.viewPart(0, dim);
return originalFi.value(X.toArray()) - y.get(dimPh1-1);
}
@Override
public double[] gradient(double[] Y) {
DoubleMatrix1D y = DoubleFactory1D.dense.make(Y);
DoubleMatrix1D X = y.viewPart(0, dim);
DoubleMatrix1D origGrad = F1.make(originalFi.gradient(X.toArray()));
DoubleMatrix1D ret = F1.make(1, -1);
ret = F1.append(origGrad, ret);
return ret.toArray();
}
@Override
public double[][] hessian(double[] Y) {
DoubleMatrix1D y = DoubleFactory1D.dense.make(Y);
DoubleMatrix1D X = y.viewPart(0, dim);
DoubleMatrix2D origHess;
double[][] origFiHessX = originalFi.hessian(X.toArray());
if(origFiHessX == FunctionsUtils.ZEROES_2D_ARRAY_PLACEHOLDER){
return FunctionsUtils.ZEROES_2D_ARRAY_PLACEHOLDER;
}else{
origHess = F2.make(origFiHessX);
DoubleMatrix2D[][] parts = new DoubleMatrix2D[][]{{origHess, null},{null,F2.make(1, 1)}};
return F2.compose(parts).toArray();
}
}
@Override
public int getDim() {
return dimPh1;
}
};
inequalitiesPh1[i] = fi;
}
BarrierFunction bfPh1 = new LogarithmicBarrier(inequalitiesPh1, dimPh1);
return bfPh1;
} | java | @Override
public BarrierFunction createPhase1BarrierFunction(){
final int dimPh1 = dim +1;
ConvexMultivariateRealFunction[] inequalitiesPh1 = new ConvexMultivariateRealFunction[this.fi.length];
for(int i=0; i<inequalitiesPh1.length; i++){
final ConvexMultivariateRealFunction originalFi = this.fi[i];
ConvexMultivariateRealFunction fi = new ConvexMultivariateRealFunction() {
@Override
public double value(double[] Y) {
DoubleMatrix1D y = DoubleFactory1D.dense.make(Y);
DoubleMatrix1D X = y.viewPart(0, dim);
return originalFi.value(X.toArray()) - y.get(dimPh1-1);
}
@Override
public double[] gradient(double[] Y) {
DoubleMatrix1D y = DoubleFactory1D.dense.make(Y);
DoubleMatrix1D X = y.viewPart(0, dim);
DoubleMatrix1D origGrad = F1.make(originalFi.gradient(X.toArray()));
DoubleMatrix1D ret = F1.make(1, -1);
ret = F1.append(origGrad, ret);
return ret.toArray();
}
@Override
public double[][] hessian(double[] Y) {
DoubleMatrix1D y = DoubleFactory1D.dense.make(Y);
DoubleMatrix1D X = y.viewPart(0, dim);
DoubleMatrix2D origHess;
double[][] origFiHessX = originalFi.hessian(X.toArray());
if(origFiHessX == FunctionsUtils.ZEROES_2D_ARRAY_PLACEHOLDER){
return FunctionsUtils.ZEROES_2D_ARRAY_PLACEHOLDER;
}else{
origHess = F2.make(origFiHessX);
DoubleMatrix2D[][] parts = new DoubleMatrix2D[][]{{origHess, null},{null,F2.make(1, 1)}};
return F2.compose(parts).toArray();
}
}
@Override
public int getDim() {
return dimPh1;
}
};
inequalitiesPh1[i] = fi;
}
BarrierFunction bfPh1 = new LogarithmicBarrier(inequalitiesPh1, dimPh1);
return bfPh1;
} | [
"@",
"Override",
"public",
"BarrierFunction",
"createPhase1BarrierFunction",
"(",
")",
"{",
"final",
"int",
"dimPh1",
"=",
"dim",
"+",
"1",
";",
"ConvexMultivariateRealFunction",
"[",
"]",
"inequalitiesPh1",
"=",
"new",
"ConvexMultivariateRealFunction",
"[",
"this",
... | Create the barrier function for the Phase I.
It is a LogarithmicBarrier for the constraints:
<br>fi(X)-s, i=1,...,n | [
"Create",
"the",
"barrier",
"function",
"for",
"the",
"Phase",
"I",
".",
"It",
"is",
"a",
"LogarithmicBarrier",
"for",
"the",
"constraints",
":",
"<br",
">",
"fi",
"(",
"X",
")",
"-",
"s",
"i",
"=",
"1",
"...",
"n"
] | train | https://github.com/vincentk/joptimizer/blob/65064c1bb0b26c7261358021e4c93d06dd43564f/src/main/java/com/joptimizer/functions/LogarithmicBarrier.java#L108-L161 |
maestrano/maestrano-java | src/main/java/com/maestrano/net/MnoHttpClient.java | MnoHttpClient.delete | public String delete(String url) throws AuthenticationException, ApiException {
return performRequest(url, "DELETE", null, null, null);
} | java | public String delete(String url) throws AuthenticationException, ApiException {
return performRequest(url, "DELETE", null, null, null);
} | [
"public",
"String",
"delete",
"(",
"String",
"url",
")",
"throws",
"AuthenticationException",
",",
"ApiException",
"{",
"return",
"performRequest",
"(",
"url",
",",
"\"DELETE\"",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}"
] | Perform a PUT request on the specified endpoint
@param url
@param header
@param payload
@return response body
@throws ApiException
@throws AuthenticationException | [
"Perform",
"a",
"PUT",
"request",
"on",
"the",
"specified",
"endpoint"
] | train | https://github.com/maestrano/maestrano-java/blob/e71c6d3172d7645529d678d1cb3ea9e0a59de314/src/main/java/com/maestrano/net/MnoHttpClient.java#L145-L147 |
CleverTap/clevertap-android-sdk | clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/ActivityLifecycleCallback.java | ActivityLifecycleCallback.register | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static synchronized void register(android.app.Application application) {
if (application == null) {
Logger.i("Application instance is null/system API is too old");
return;
}
if (registered) {
Logger.v("Lifecycle callbacks have already been registered");
return;
}
registered = true;
application.registerActivityLifecycleCallbacks(
new android.app.Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
CleverTapAPI.onActivityCreated(activity);
}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {
CleverTapAPI.onActivityResumed(activity);
}
@Override
public void onActivityPaused(Activity activity) {
CleverTapAPI.onActivityPaused();
}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
}
);
Logger.i("Activity Lifecycle Callback successfully registered");
} | java | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static synchronized void register(android.app.Application application) {
if (application == null) {
Logger.i("Application instance is null/system API is too old");
return;
}
if (registered) {
Logger.v("Lifecycle callbacks have already been registered");
return;
}
registered = true;
application.registerActivityLifecycleCallbacks(
new android.app.Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
CleverTapAPI.onActivityCreated(activity);
}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {
CleverTapAPI.onActivityResumed(activity);
}
@Override
public void onActivityPaused(Activity activity) {
CleverTapAPI.onActivityPaused();
}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
}
);
Logger.i("Activity Lifecycle Callback successfully registered");
} | [
"@",
"TargetApi",
"(",
"Build",
".",
"VERSION_CODES",
".",
"ICE_CREAM_SANDWICH",
")",
"public",
"static",
"synchronized",
"void",
"register",
"(",
"android",
".",
"app",
".",
"Application",
"application",
")",
"{",
"if",
"(",
"application",
"==",
"null",
")",
... | Enables lifecycle callbacks for Android devices
@param application App's Application object | [
"Enables",
"lifecycle",
"callbacks",
"for",
"Android",
"devices"
] | train | https://github.com/CleverTap/clevertap-android-sdk/blob/be134c06a4f07494c398335ad9ff4976633743e1/clevertap-android-sdk/src/main/java/com/clevertap/android/sdk/ActivityLifecycleCallback.java#L19-L65 |
kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/proxy/AbstractProxyLogicHandler.java | AbstractProxyLogicHandler.writeData | protected WriteFuture writeData(final NextFilter nextFilter,
final IoBuffer data) {
// write net data
ProxyHandshakeIoBuffer writeBuffer = new ProxyHandshakeIoBuffer(data);
LOGGER.debug(" session write: {}", writeBuffer);
WriteFuture writeFuture = new DefaultWriteFuture(getSession());
getProxyFilter().writeData(nextFilter, getSession(),
new DefaultWriteRequest(writeBuffer, writeFuture), true);
return writeFuture;
} | java | protected WriteFuture writeData(final NextFilter nextFilter,
final IoBuffer data) {
// write net data
ProxyHandshakeIoBuffer writeBuffer = new ProxyHandshakeIoBuffer(data);
LOGGER.debug(" session write: {}", writeBuffer);
WriteFuture writeFuture = new DefaultWriteFuture(getSession());
getProxyFilter().writeData(nextFilter, getSession(),
new DefaultWriteRequest(writeBuffer, writeFuture), true);
return writeFuture;
} | [
"protected",
"WriteFuture",
"writeData",
"(",
"final",
"NextFilter",
"nextFilter",
",",
"final",
"IoBuffer",
"data",
")",
"{",
"// write net data",
"ProxyHandshakeIoBuffer",
"writeBuffer",
"=",
"new",
"ProxyHandshakeIoBuffer",
"(",
"data",
")",
";",
"LOGGER",
".",
"... | Writes data to the proxy server.
@param nextFilter the next filter
@param data Data buffer to be written. | [
"Writes",
"data",
"to",
"the",
"proxy",
"server",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/AbstractProxyLogicHandler.java#L99-L111 |
MenoData/Time4J | base/src/main/java/net/time4j/UnitPatterns.java | UnitPatterns.getListPattern | String getListPattern(
TextWidth width,
int size
) {
if (width == null) {
throw new NullPointerException("Missing width.");
}
if (
(size >= MIN_LIST_INDEX)
&& (size <= MAX_LIST_INDEX)
) {
return this.list.get(Integer.valueOf(size)).get(width);
}
return lookup(this.locale, width, size);
} | java | String getListPattern(
TextWidth width,
int size
) {
if (width == null) {
throw new NullPointerException("Missing width.");
}
if (
(size >= MIN_LIST_INDEX)
&& (size <= MAX_LIST_INDEX)
) {
return this.list.get(Integer.valueOf(size)).get(width);
}
return lookup(this.locale, width, size);
} | [
"String",
"getListPattern",
"(",
"TextWidth",
"width",
",",
"int",
"size",
")",
"{",
"if",
"(",
"width",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Missing width.\"",
")",
";",
"}",
"if",
"(",
"(",
"size",
">=",
"MIN_LIST_INDEX... | <p>Constructs a localized list pattern suitable for the use in
{@link java.text.MessageFormat#format(String, Object[])}. </p>
@param width text width (ABBREVIATED as synonym for SHORT)
@param size count of list items
@return message format pattern with placeholders {0}, {1}, ..., {x}, ...
@throws IllegalArgumentException if size is smaller than 2 | [
"<p",
">",
"Constructs",
"a",
"localized",
"list",
"pattern",
"suitable",
"for",
"the",
"use",
"in",
"{",
"@link",
"java",
".",
"text",
".",
"MessageFormat#format",
"(",
"String",
"Object",
"[]",
")",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/UnitPatterns.java#L409-L427 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java | ApiOvhDedicatednasha.serviceName_partition_partitionName_snapshot_POST | public OvhTask serviceName_partition_partitionName_snapshot_POST(String serviceName, String partitionName, OvhSnapshotEnum snapshotType) throws IOException {
String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot";
StringBuilder sb = path(qPath, serviceName, partitionName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "snapshotType", snapshotType);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_partition_partitionName_snapshot_POST(String serviceName, String partitionName, OvhSnapshotEnum snapshotType) throws IOException {
String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot";
StringBuilder sb = path(qPath, serviceName, partitionName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "snapshotType", snapshotType);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_partition_partitionName_snapshot_POST",
"(",
"String",
"serviceName",
",",
"String",
"partitionName",
",",
"OvhSnapshotEnum",
"snapshotType",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/nasha/{serviceName}/partition... | Schedule a new snapshot type
REST: POST /dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot
@param snapshotType [required] Snapshot interval to add
@param serviceName [required] The internal name of your storage
@param partitionName [required] the given name of partition | [
"Schedule",
"a",
"new",
"snapshot",
"type"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatednasha/src/main/java/net/minidev/ovh/api/ApiOvhDedicatednasha.java#L341-L348 |
graknlabs/grakn | server/src/server/kb/concept/ElementFactory.java | ElementFactory.buildRelation | RelationImpl buildRelation(VertexElement vertex, RelationType type) {
return getOrBuildConcept(vertex, (v) -> RelationImpl.create(buildRelationReified(v, type)));
} | java | RelationImpl buildRelation(VertexElement vertex, RelationType type) {
return getOrBuildConcept(vertex, (v) -> RelationImpl.create(buildRelationReified(v, type)));
} | [
"RelationImpl",
"buildRelation",
"(",
"VertexElement",
"vertex",
",",
"RelationType",
"type",
")",
"{",
"return",
"getOrBuildConcept",
"(",
"vertex",
",",
"(",
"v",
")",
"-",
">",
"RelationImpl",
".",
"create",
"(",
"buildRelationReified",
"(",
"v",
",",
"type... | Used by RelationTypeImpl to create a new instance of RelationImpl
first build a ReifiedRelation and then inject it to RelationImpl
@return | [
"Used",
"by",
"RelationTypeImpl",
"to",
"create",
"a",
"new",
"instance",
"of",
"RelationImpl",
"first",
"build",
"a",
"ReifiedRelation",
"and",
"then",
"inject",
"it",
"to",
"RelationImpl"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/ElementFactory.java#L131-L133 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.domain_account_accountName_PUT | public void domain_account_accountName_PUT(String domain, String accountName, OvhAccount body) throws IOException {
String qPath = "/email/domain/{domain}/account/{accountName}";
StringBuilder sb = path(qPath, domain, accountName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void domain_account_accountName_PUT(String domain, String accountName, OvhAccount body) throws IOException {
String qPath = "/email/domain/{domain}/account/{accountName}";
StringBuilder sb = path(qPath, domain, accountName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"domain_account_accountName_PUT",
"(",
"String",
"domain",
",",
"String",
"accountName",
",",
"OvhAccount",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/{domain}/account/{accountName}\"",
";",
"StringBuilder",
"sb",... | Alter this object properties
REST: PUT /email/domain/{domain}/account/{accountName}
@param body [required] New object properties
@param domain [required] Name of your domain name
@param accountName [required] Name of account | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L843-L847 |
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/DatabaseVulnerabilityAssessmentsInner.java | DatabaseVulnerabilityAssessmentsInner.getAsync | public Observable<DatabaseVulnerabilityAssessmentInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseVulnerabilityAssessmentInner>, DatabaseVulnerabilityAssessmentInner>() {
@Override
public DatabaseVulnerabilityAssessmentInner call(ServiceResponse<DatabaseVulnerabilityAssessmentInner> response) {
return response.body();
}
});
} | java | public Observable<DatabaseVulnerabilityAssessmentInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseVulnerabilityAssessmentInner>, DatabaseVulnerabilityAssessmentInner>() {
@Override
public DatabaseVulnerabilityAssessmentInner call(ServiceResponse<DatabaseVulnerabilityAssessmentInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DatabaseVulnerabilityAssessmentInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverN... | Gets the database's vulnerability assessment.
@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 databaseName The name of the database for which the vulnerability assessment is defined.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DatabaseVulnerabilityAssessmentInner object | [
"Gets",
"the",
"database",
"s",
"vulnerability",
"assessment",
"."
] | 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/DatabaseVulnerabilityAssessmentsInner.java#L124-L131 |
javalite/activejdbc | activejdbc/src/main/java/org/javalite/activejdbc/Model.java | Model.updateAll | public static int updateAll(String updates, Object ... params) {
return ModelDelegate.updateAll(modelClass(), updates, params);
} | java | public static int updateAll(String updates, Object ... params) {
return ModelDelegate.updateAll(modelClass(), updates, params);
} | [
"public",
"static",
"int",
"updateAll",
"(",
"String",
"updates",
",",
"Object",
"...",
"params",
")",
"{",
"return",
"ModelDelegate",
".",
"updateAll",
"(",
"modelClass",
"(",
")",
",",
"updates",
",",
"params",
")",
";",
"}"
] | Updates all records associated with this model.
This example :
<pre>
Employee.updateAll("bonus = ?", "10");
</pre>
In this example, all employees get a bonus of 10%.
@param updates - what needs to be updated.
@param params list of parameters for both updates and conditions. Applied in the same order as in the arguments,
updates first, then conditions.
@return number of updated records. | [
"Updates",
"all",
"records",
"associated",
"with",
"this",
"model",
"."
] | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L849-L851 |
mapsforge/mapsforge | mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/rule/RenderTheme.java | RenderTheme.scaleTextSize | public synchronized void scaleTextSize(float scaleFactor, byte zoomLevel) {
if (!textScales.containsKey(zoomLevel) || scaleFactor != textScales.get(zoomLevel)) {
for (int i = 0, n = this.rulesList.size(); i < n; ++i) {
Rule rule = this.rulesList.get(i);
if (rule.zoomMin <= zoomLevel && rule.zoomMax >= zoomLevel) {
rule.scaleTextSize(scaleFactor * this.baseTextSize, zoomLevel);
}
}
textScales.put(zoomLevel, scaleFactor);
}
} | java | public synchronized void scaleTextSize(float scaleFactor, byte zoomLevel) {
if (!textScales.containsKey(zoomLevel) || scaleFactor != textScales.get(zoomLevel)) {
for (int i = 0, n = this.rulesList.size(); i < n; ++i) {
Rule rule = this.rulesList.get(i);
if (rule.zoomMin <= zoomLevel && rule.zoomMax >= zoomLevel) {
rule.scaleTextSize(scaleFactor * this.baseTextSize, zoomLevel);
}
}
textScales.put(zoomLevel, scaleFactor);
}
} | [
"public",
"synchronized",
"void",
"scaleTextSize",
"(",
"float",
"scaleFactor",
",",
"byte",
"zoomLevel",
")",
"{",
"if",
"(",
"!",
"textScales",
".",
"containsKey",
"(",
"zoomLevel",
")",
"||",
"scaleFactor",
"!=",
"textScales",
".",
"get",
"(",
"zoomLevel",
... | Scales the text size of this RenderTheme by the given factor for a given zoom level.
@param scaleFactor the factor by which the text size should be scaled.
@param zoomLevel the zoom level to which this is applied. | [
"Scales",
"the",
"text",
"size",
"of",
"this",
"RenderTheme",
"by",
"the",
"given",
"factor",
"for",
"a",
"given",
"zoom",
"level",
"."
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/rule/RenderTheme.java#L178-L188 |
hector-client/hector | object-mapper/src/main/java/me/prettyprint/hom/ClassCacheMgr.java | ClassCacheMgr.findAnnotatedMethod | public Method findAnnotatedMethod(Class<?> clazz, Class<? extends Annotation> anno) {
for (Method meth : clazz.getMethods()) {
if (meth.isAnnotationPresent(anno)) {
return meth;
}
}
return null;
} | java | public Method findAnnotatedMethod(Class<?> clazz, Class<? extends Annotation> anno) {
for (Method meth : clazz.getMethods()) {
if (meth.isAnnotationPresent(anno)) {
return meth;
}
}
return null;
} | [
"public",
"Method",
"findAnnotatedMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"anno",
")",
"{",
"for",
"(",
"Method",
"meth",
":",
"clazz",
".",
"getMethods",
"(",
")",
")",
"{",
"if",
"(",
"me... | Find method annotated with the given annotation.
@param clazz
@param anno
@return returns Method if found, null otherwise | [
"Find",
"method",
"annotated",
"with",
"the",
"given",
"annotation",
"."
] | train | https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/object-mapper/src/main/java/me/prettyprint/hom/ClassCacheMgr.java#L373-L380 |
intellimate/Izou | src/main/java/org/intellimate/izou/events/EventDistributor.java | EventDistributor.registerEventFinishedListener | @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"})
public void registerEventFinishedListener(EventModel event, EventListenerModel eventListener) throws IllegalIDException {
registerEventFinishedListener(event.getAllInformations(), eventListener);
} | java | @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"})
public void registerEventFinishedListener(EventModel event, EventListenerModel eventListener) throws IllegalIDException {
registerEventFinishedListener(event.getAllInformations(), eventListener);
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"SynchronizationOnLocalVariableOrMethodParameter\"",
"}",
")",
"public",
"void",
"registerEventFinishedListener",
"(",
"EventModel",
"event",
",",
"EventListenerModel",
"eventListener",
")",
"throws",
"IllegalIDException",
"{",
"registerEv... | Adds an listener for events that gets called when the event finished processing.
<p>
Be careful with this method, it will register the listener for ALL the informations found in the Event. If your
event-type is a common event type, it will fire EACH time!.
It will also register for all Descriptors individually!
It will also ignore if this listener is already listening to an Event.
Method is thread-safe.
</p>
@param event the Event to listen to (it will listen to all descriptors individually!)
@param eventListener the ActivatorEventListener-interface for receiving activator events
@throws IllegalIDException not yet implemented | [
"Adds",
"an",
"listener",
"for",
"events",
"that",
"gets",
"called",
"when",
"the",
"event",
"finished",
"processing",
".",
"<p",
">",
"Be",
"careful",
"with",
"this",
"method",
"it",
"will",
"register",
"the",
"listener",
"for",
"ALL",
"the",
"informations"... | train | https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/events/EventDistributor.java#L204-L207 |
recommenders/rival | rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java | StrategyRunnerInfile.readScoredItems | public static List<Pair<Long, Double>> readScoredItems(final File userRecommendationFile, final Long user) throws IOException {
final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(userRecommendationFile), "UTF-8"));
try {
String line = null;
boolean foundUser = false;
// read recommendations: user \t item \t score
while ((line = in.readLine()) != null) {
String[] toks = line.split("\t");
String u = toks[0];
if (u.equals(user + "")) {
StrategyIO.readLine(line, mapUserRecommendations);
foundUser = true;
} else if (foundUser) {
// assuming a sorted file (at least, per user)
break;
}
}
} finally {
in.close();
}
return mapUserRecommendations.get(user);
} | java | public static List<Pair<Long, Double>> readScoredItems(final File userRecommendationFile, final Long user) throws IOException {
final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations = new HashMap<Long, List<Pair<Long, Double>>>();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(userRecommendationFile), "UTF-8"));
try {
String line = null;
boolean foundUser = false;
// read recommendations: user \t item \t score
while ((line = in.readLine()) != null) {
String[] toks = line.split("\t");
String u = toks[0];
if (u.equals(user + "")) {
StrategyIO.readLine(line, mapUserRecommendations);
foundUser = true;
} else if (foundUser) {
// assuming a sorted file (at least, per user)
break;
}
}
} finally {
in.close();
}
return mapUserRecommendations.get(user);
} | [
"public",
"static",
"List",
"<",
"Pair",
"<",
"Long",
",",
"Double",
">",
">",
"readScoredItems",
"(",
"final",
"File",
"userRecommendationFile",
",",
"final",
"Long",
"user",
")",
"throws",
"IOException",
"{",
"final",
"Map",
"<",
"Long",
",",
"List",
"<"... | Method that reads the scores given to items by a recommender only for a
given user (it ignores the rest).
@param userRecommendationFile The file with the recommendation scores
@param user The user
@return the pairs (item, score) contained in the file for that user
@throws IOException when the file cannot be opened
@see StrategyIO#readLine(java.lang.String, java.util.Map) | [
"Method",
"that",
"reads",
"the",
"scores",
"given",
"to",
"items",
"by",
"a",
"recommender",
"only",
"for",
"a",
"given",
"user",
"(",
"it",
"ignores",
"the",
"rest",
")",
"."
] | train | https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java#L243-L265 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java | ServletUtil.uploadFileItems | public static void uploadFileItems(final List<FileItem> fileItems, final Map<String, String[]> parameters,
final Map<String, FileItem[]> files) {
for (FileItem item : fileItems) {
String name = item.getFieldName();
boolean formField = item.isFormField();
if (LOG.isDebugEnabled()) {
LOG.debug(
"Uploading form " + (formField ? "field" : "attachment") + " \"" + name + "\"");
}
if (formField) {
String value;
try {
// Without specifying UTF-8, apache commons DiskFileItem defaults to ISO-8859-1.
value = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new SystemException("Encoding error on formField item", e);
}
RequestUtil.addParameter(parameters, name, value);
} else {
// Form attachment
RequestUtil.addFileItem(files, name, item);
String value = item.getName();
RequestUtil.addParameter(parameters, name, value);
}
}
} | java | public static void uploadFileItems(final List<FileItem> fileItems, final Map<String, String[]> parameters,
final Map<String, FileItem[]> files) {
for (FileItem item : fileItems) {
String name = item.getFieldName();
boolean formField = item.isFormField();
if (LOG.isDebugEnabled()) {
LOG.debug(
"Uploading form " + (formField ? "field" : "attachment") + " \"" + name + "\"");
}
if (formField) {
String value;
try {
// Without specifying UTF-8, apache commons DiskFileItem defaults to ISO-8859-1.
value = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new SystemException("Encoding error on formField item", e);
}
RequestUtil.addParameter(parameters, name, value);
} else {
// Form attachment
RequestUtil.addFileItem(files, name, item);
String value = item.getName();
RequestUtil.addParameter(parameters, name, value);
}
}
} | [
"public",
"static",
"void",
"uploadFileItems",
"(",
"final",
"List",
"<",
"FileItem",
">",
"fileItems",
",",
"final",
"Map",
"<",
"String",
",",
"String",
"[",
"]",
">",
"parameters",
",",
"final",
"Map",
"<",
"String",
",",
"FileItem",
"[",
"]",
">",
... | <p>
{@link FileItem} classes (if attachements) will be kept as part of the request. The default behaviour of the file
item is to store the upload in memory until it reaches a certain size, after which the content is streamed to a
temp file.</p>
<p>
If, in the future, performance of uploads becomes a focus we can instead look into using the Jakarta Commons
Streaming API. In this case, the content of the upload isn't stored anywhere. It will be up to the user to
read/store the content of the stream.</p>
@param fileItems a list of {@link FileItem}s corresponding to POSTed form data.
@param parameters the map to store non-file request parameters in.
@param files the map to store the uploaded file parameters in. | [
"<p",
">",
"{",
"@link",
"FileItem",
"}",
"classes",
"(",
"if",
"attachements",
")",
"will",
"be",
"kept",
"as",
"part",
"of",
"the",
"request",
".",
"The",
"default",
"behaviour",
"of",
"the",
"file",
"item",
"is",
"to",
"store",
"the",
"upload",
"in"... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/servlet/ServletUtil.java#L681-L710 |
cojen/Cojen | src/main/java/org/cojen/classfile/MethodInfo.java | MethodInfo.addInnerClass | public ClassFile addInnerClass(String innerClassName, String superClassName) {
ClassFile inner;
if (innerClassName == null) {
inner = mParent.addInnerClass(null, null, superClassName);
} else {
String fullInnerClassName = mParent.getClassName() + '$' +
(++mAnonymousInnerClassCount) + innerClassName;
inner = mParent.addInnerClass(fullInnerClassName, innerClassName, superClassName);
}
if (mParent.getMajorVersion() >= 49) {
inner.addAttribute(new EnclosingMethodAttr
(mCp, mCp.addConstantClass(mParent.getClassName()),
mCp.addConstantNameAndType(mNameConstant, mDescriptorConstant)));
}
return inner;
} | java | public ClassFile addInnerClass(String innerClassName, String superClassName) {
ClassFile inner;
if (innerClassName == null) {
inner = mParent.addInnerClass(null, null, superClassName);
} else {
String fullInnerClassName = mParent.getClassName() + '$' +
(++mAnonymousInnerClassCount) + innerClassName;
inner = mParent.addInnerClass(fullInnerClassName, innerClassName, superClassName);
}
if (mParent.getMajorVersion() >= 49) {
inner.addAttribute(new EnclosingMethodAttr
(mCp, mCp.addConstantClass(mParent.getClassName()),
mCp.addConstantNameAndType(mNameConstant, mDescriptorConstant)));
}
return inner;
} | [
"public",
"ClassFile",
"addInnerClass",
"(",
"String",
"innerClassName",
",",
"String",
"superClassName",
")",
"{",
"ClassFile",
"inner",
";",
"if",
"(",
"innerClassName",
"==",
"null",
")",
"{",
"inner",
"=",
"mParent",
".",
"addInnerClass",
"(",
"null",
",",... | Add an inner class to this method.
@param innerClassName Optional short inner class name.
@param superClassName Full super class name. | [
"Add",
"an",
"inner",
"class",
"to",
"this",
"method",
"."
] | train | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/MethodInfo.java#L341-L358 |
apache/incubator-atlas | common/src/main/java/org/apache/atlas/utils/ParamChecker.java | ParamChecker.notEmpty | public static String notEmpty(String value, String name, String info) {
if (value == null) {
throw new IllegalArgumentException(name + " cannot be null" + (info == null ? "" : ", " + info));
}
return notEmptyIfNotNull(value, name, info);
} | java | public static String notEmpty(String value, String name, String info) {
if (value == null) {
throw new IllegalArgumentException(name + " cannot be null" + (info == null ? "" : ", " + info));
}
return notEmptyIfNotNull(value, name, info);
} | [
"public",
"static",
"String",
"notEmpty",
"(",
"String",
"value",
",",
"String",
"name",
",",
"String",
"info",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"name",
"+",
"\" cannot be null\"",
"+",
... | Check that a string is not null and not empty. If null or emtpy throws an IllegalArgumentException.
@param value value.
@param name parameter name for the exception message.
@param info additional information to be printed with the exception message
@return the given value. | [
"Check",
"that",
"a",
"string",
"is",
"not",
"null",
"and",
"not",
"empty",
".",
"If",
"null",
"or",
"emtpy",
"throws",
"an",
"IllegalArgumentException",
"."
] | train | https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/common/src/main/java/org/apache/atlas/utils/ParamChecker.java#L134-L139 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/oauth/OAuthFlowImpl.java | OAuthFlowImpl.obtainNewToken | public Token obtainNewToken(AuthorizationResult authorizationResult) throws OAuthTokenException, JSONSerializerException, HttpClientException,
URISyntaxException, InvalidRequestException {
if(authorizationResult == null){
throw new IllegalArgumentException();
}
// Prepare the hash
String doHash = clientSecret + "|" + authorizationResult.getCode();
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Your JVM does not support SHA-256, which is required for OAuth with Smartsheet.", e);
}
byte[] digest;
try {
digest = md.digest(doHash.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
//String hash = javax.xml.bind.DatatypeConverter.printHexBinary(digest);
String hash = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
// create a Map of the parameters
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("grant_type", "authorization_code");
params.put("client_id", clientId);
params.put("code", authorizationResult.getCode());
params.put("redirect_uri",redirectURL);
params.put("hash", hash);
// Generate the URL and then get the token
return requestToken(QueryUtil.generateUrl(tokenURL, params));
} | java | public Token obtainNewToken(AuthorizationResult authorizationResult) throws OAuthTokenException, JSONSerializerException, HttpClientException,
URISyntaxException, InvalidRequestException {
if(authorizationResult == null){
throw new IllegalArgumentException();
}
// Prepare the hash
String doHash = clientSecret + "|" + authorizationResult.getCode();
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Your JVM does not support SHA-256, which is required for OAuth with Smartsheet.", e);
}
byte[] digest;
try {
digest = md.digest(doHash.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
//String hash = javax.xml.bind.DatatypeConverter.printHexBinary(digest);
String hash = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
// create a Map of the parameters
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("grant_type", "authorization_code");
params.put("client_id", clientId);
params.put("code", authorizationResult.getCode());
params.put("redirect_uri",redirectURL);
params.put("hash", hash);
// Generate the URL and then get the token
return requestToken(QueryUtil.generateUrl(tokenURL, params));
} | [
"public",
"Token",
"obtainNewToken",
"(",
"AuthorizationResult",
"authorizationResult",
")",
"throws",
"OAuthTokenException",
",",
"JSONSerializerException",
",",
"HttpClientException",
",",
"URISyntaxException",
",",
"InvalidRequestException",
"{",
"if",
"(",
"authorizationR... | Obtain a new token using AuthorizationResult.
Exceptions:
- IllegalArgumentException : if authorizationResult is null
- InvalidTokenRequestException : if the token request is invalid (note that this won't really happen in current implementation)
- InvalidOAuthClientException : if the client information is invalid
- InvalidOAuthGrantException : if the authorization code or refresh token is invalid or expired, the
redirect_uri does not match, or the hash value does not match the client secret and/or code
- UnsupportedOAuthGrantTypeException : if the grant type is invalid (note that this won't really happen in
current implementation)
- OAuthTokenException : if any other error occurred during the operation
@param authorizationResult the authorization result
@return the token
@throws NoSuchAlgorithmException the no such algorithm exception
@throws UnsupportedEncodingException the unsupported encoding exception
@throws OAuthTokenException the o auth token exception
@throws JSONSerializerException the JSON serializer exception
@throws HttpClientException the http client exception
@throws URISyntaxException the URI syntax exception
@throws InvalidRequestException the invalid request exception | [
"Obtain",
"a",
"new",
"token",
"using",
"AuthorizationResult",
"."
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/oauth/OAuthFlowImpl.java#L243-L278 |
Jasig/spring-portlet-contrib | spring-webmvc-portlet-contrib/src/main/java/org/jasig/springframework/web/portlet/context/PortletContextLoader.java | PortletContextLoader.configureAndRefreshPortletApplicationContext | protected void configureAndRefreshPortletApplicationContext(ConfigurablePortletApplicationContext pac, PortletContext pc) {
if (ObjectUtils.identityToString(pac).equals(pac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = pc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
pac.setId(idParam);
}
else {
// Generate default id...
pac.setId(ConfigurablePortletApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(pc.getPortletContextName()));
}
}
// Determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(pc);
pac.setParent(parent);
pac.setPortletContext(pc);
String initParameter = pc.getInitParameter(CONFIG_LOCATION_PARAM);
if (initParameter != null) {
pac.setConfigLocation(initParameter);
}
else {
try {
pac.setConfigLocation("/WEB-INF/portletApplicationContext.xml");
}
catch (UnsupportedOperationException e) {
//Ignore, may get triggered if the context doesn't support config locations
}
}
customizeContext(pc, pac);
pac.refresh();
} | java | protected void configureAndRefreshPortletApplicationContext(ConfigurablePortletApplicationContext pac, PortletContext pc) {
if (ObjectUtils.identityToString(pac).equals(pac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = pc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
pac.setId(idParam);
}
else {
// Generate default id...
pac.setId(ConfigurablePortletApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(pc.getPortletContextName()));
}
}
// Determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(pc);
pac.setParent(parent);
pac.setPortletContext(pc);
String initParameter = pc.getInitParameter(CONFIG_LOCATION_PARAM);
if (initParameter != null) {
pac.setConfigLocation(initParameter);
}
else {
try {
pac.setConfigLocation("/WEB-INF/portletApplicationContext.xml");
}
catch (UnsupportedOperationException e) {
//Ignore, may get triggered if the context doesn't support config locations
}
}
customizeContext(pc, pac);
pac.refresh();
} | [
"protected",
"void",
"configureAndRefreshPortletApplicationContext",
"(",
"ConfigurablePortletApplicationContext",
"pac",
",",
"PortletContext",
"pc",
")",
"{",
"if",
"(",
"ObjectUtils",
".",
"identityToString",
"(",
"pac",
")",
".",
"equals",
"(",
"pac",
".",
"getId"... | <p>configureAndRefreshPortletApplicationContext.</p>
@param pac a {@link org.springframework.web.portlet.context.ConfigurablePortletApplicationContext} object.
@param pc a {@link javax.portlet.PortletContext} object. | [
"<p",
">",
"configureAndRefreshPortletApplicationContext",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/Jasig/spring-portlet-contrib/blob/719240fa268ddc69900ce9775d9cad3b9c543c6b/spring-webmvc-portlet-contrib/src/main/java/org/jasig/springframework/web/portlet/context/PortletContextLoader.java#L280-L314 |
super-csv/super-csv | super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanReader.java | CsvDozerBeanReader.readIntoBean | private <T> T readIntoBean(final T bean, final Class<T> clazz, final CellProcessor[] processors) throws IOException {
if( readRow() ) {
if( processors == null ) {
// populate bean data with the raw String values
beanData.getColumns().clear();
beanData.getColumns().addAll(getColumns());
} else {
// populate bean data with the processed values
executeProcessors(beanData.getColumns(), processors);
}
if( bean != null ) {
// populate existing bean
dozerBeanMapper.map(beanData, bean);
return bean;
} else {
// let Dozer create a new bean
return dozerBeanMapper.map(beanData, clazz);
}
}
return null; // EOF
} | java | private <T> T readIntoBean(final T bean, final Class<T> clazz, final CellProcessor[] processors) throws IOException {
if( readRow() ) {
if( processors == null ) {
// populate bean data with the raw String values
beanData.getColumns().clear();
beanData.getColumns().addAll(getColumns());
} else {
// populate bean data with the processed values
executeProcessors(beanData.getColumns(), processors);
}
if( bean != null ) {
// populate existing bean
dozerBeanMapper.map(beanData, bean);
return bean;
} else {
// let Dozer create a new bean
return dozerBeanMapper.map(beanData, clazz);
}
}
return null; // EOF
} | [
"private",
"<",
"T",
">",
"T",
"readIntoBean",
"(",
"final",
"T",
"bean",
",",
"final",
"Class",
"<",
"T",
">",
"clazz",
",",
"final",
"CellProcessor",
"[",
"]",
"processors",
")",
"throws",
"IOException",
"{",
"if",
"(",
"readRow",
"(",
")",
")",
"{... | Reads a row of a CSV file and populates the a bean, using Dozer to map column values to the appropriate field. If
an existing bean is supplied, Dozer will populate that, otherwise Dozer will create an instance of type clazz
(only one of bean or clazz should be supplied). If processors are supplied then they are used, otherwise the raw
String values will be used.
@param bean
the bean to populate (if null, then clazz will be used instead)
@param clazz
the type to instantiate (only required if bean is null)
@param processors
the (optional) cell processors
@return the populated bean
@throws IOException
if an I/O error occurred | [
"Reads",
"a",
"row",
"of",
"a",
"CSV",
"file",
"and",
"populates",
"the",
"a",
"bean",
"using",
"Dozer",
"to",
"map",
"column",
"values",
"to",
"the",
"appropriate",
"field",
".",
"If",
"an",
"existing",
"bean",
"is",
"supplied",
"Dozer",
"will",
"popula... | train | https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv-dozer/src/main/java/org/supercsv/io/dozer/CsvDozerBeanReader.java#L203-L226 |
Erudika/para | para-server/src/main/java/com/erudika/para/queue/AWSQueueUtils.java | AWSQueueUtils.getClient | public static AmazonSQS getClient() {
if (sqsClient != null) {
return sqsClient;
}
if (Config.IN_PRODUCTION) {
sqsClient = AmazonSQSClientBuilder.standard().build();
} else {
sqsClient = AmazonSQSClientBuilder.standard().
withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "x"))).
withEndpointConfiguration(new EndpointConfiguration(LOCAL_ENDPOINT, "")).build();
}
Para.addDestroyListener(new DestroyListener() {
public void onDestroy() {
sqsClient.shutdown();
}
});
return sqsClient;
} | java | public static AmazonSQS getClient() {
if (sqsClient != null) {
return sqsClient;
}
if (Config.IN_PRODUCTION) {
sqsClient = AmazonSQSClientBuilder.standard().build();
} else {
sqsClient = AmazonSQSClientBuilder.standard().
withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "x"))).
withEndpointConfiguration(new EndpointConfiguration(LOCAL_ENDPOINT, "")).build();
}
Para.addDestroyListener(new DestroyListener() {
public void onDestroy() {
sqsClient.shutdown();
}
});
return sqsClient;
} | [
"public",
"static",
"AmazonSQS",
"getClient",
"(",
")",
"{",
"if",
"(",
"sqsClient",
"!=",
"null",
")",
"{",
"return",
"sqsClient",
";",
"}",
"if",
"(",
"Config",
".",
"IN_PRODUCTION",
")",
"{",
"sqsClient",
"=",
"AmazonSQSClientBuilder",
".",
"standard",
... | Returns a client instance for AWS SQS.
@return a client that talks to SQS | [
"Returns",
"a",
"client",
"instance",
"for",
"AWS",
"SQS",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/queue/AWSQueueUtils.java#L76-L94 |
landawn/AbacusUtil | src/com/landawn/abacus/util/CSVUtil.java | CSVUtil.importCSV | @SuppressWarnings("rawtypes")
public static <E extends Exception> long importCSV(final File file, final long offset, final long count, final boolean skipTitle,
final Try.Predicate<String[], E> filter, final PreparedStatement stmt, final int batchSize, final int batchInterval,
final List<? extends Type> columnTypeList) throws UncheckedSQLException, UncheckedIOException, E {
Reader reader = null;
try {
reader = new FileReader(file);
return importCSV(reader, offset, count, skipTitle, filter, stmt, batchSize, batchInterval, columnTypeList);
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
IOUtil.close(reader);
}
} | java | @SuppressWarnings("rawtypes")
public static <E extends Exception> long importCSV(final File file, final long offset, final long count, final boolean skipTitle,
final Try.Predicate<String[], E> filter, final PreparedStatement stmt, final int batchSize, final int batchInterval,
final List<? extends Type> columnTypeList) throws UncheckedSQLException, UncheckedIOException, E {
Reader reader = null;
try {
reader = new FileReader(file);
return importCSV(reader, offset, count, skipTitle, filter, stmt, batchSize, batchInterval, columnTypeList);
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
IOUtil.close(reader);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"static",
"<",
"E",
"extends",
"Exception",
">",
"long",
"importCSV",
"(",
"final",
"File",
"file",
",",
"final",
"long",
"offset",
",",
"final",
"long",
"count",
",",
"final",
"boolean",
"skipTitl... | Imports the data from CSV to database.
@param file
@param offset
@param count
@param skipTitle
@param filter
@param stmt the column order in the sql must be consistent with the column order in the CSV file.
@param batchSize
@param batchInterval
@param columnTypeList set the column type to null to skip the column in CSV.
@return | [
"Imports",
"the",
"data",
"from",
"CSV",
"to",
"database",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/CSVUtil.java#L1140-L1155 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java | SparkComputationGraph.fitMultiDataSet | public ComputationGraph fitMultiDataSet(String path) {
if (Nd4j.getExecutioner() instanceof GridExecutioner)
((GridExecutioner) Nd4j.getExecutioner()).flushQueue();
JavaRDD<String> paths;
try {
paths = SparkUtils.listPaths(sc, path);
} catch (IOException e) {
throw new RuntimeException("Error listing paths in directory", e);
}
return fitPathsMultiDataSet(paths);
} | java | public ComputationGraph fitMultiDataSet(String path) {
if (Nd4j.getExecutioner() instanceof GridExecutioner)
((GridExecutioner) Nd4j.getExecutioner()).flushQueue();
JavaRDD<String> paths;
try {
paths = SparkUtils.listPaths(sc, path);
} catch (IOException e) {
throw new RuntimeException("Error listing paths in directory", e);
}
return fitPathsMultiDataSet(paths);
} | [
"public",
"ComputationGraph",
"fitMultiDataSet",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"Nd4j",
".",
"getExecutioner",
"(",
")",
"instanceof",
"GridExecutioner",
")",
"(",
"(",
"GridExecutioner",
")",
"Nd4j",
".",
"getExecutioner",
"(",
")",
")",
".",
"... | Fit the SparkComputationGraph network using a directory of serialized MultiDataSet objects
The assumption here is that the directory contains a number of serialized {@link MultiDataSet} objects
@param path Path to the directory containing the serialized MultiDataSet objcets
@return The MultiLayerNetwork after training | [
"Fit",
"the",
"SparkComputationGraph",
"network",
"using",
"a",
"directory",
"of",
"serialized",
"MultiDataSet",
"objects",
"The",
"assumption",
"here",
"is",
"that",
"the",
"directory",
"contains",
"a",
"number",
"of",
"serialized",
"{",
"@link",
"MultiDataSet",
... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java#L303-L315 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/xmlutil/XmlInOut.java | XmlInOut.enableAllBehaviors | public static void enableAllBehaviors(Record record, boolean bEnableRecordBehaviors, boolean bEnableFieldBehaviors)
{
if (record == null)
return;
record.setEnableListeners(bEnableRecordBehaviors); // Disable all file behaviors
for (int iFieldSeq = 0; iFieldSeq < record.getFieldCount(); iFieldSeq++)
{
BaseField field = record.getField(iFieldSeq);
field.setEnableListeners(bEnableFieldBehaviors);
}
} | java | public static void enableAllBehaviors(Record record, boolean bEnableRecordBehaviors, boolean bEnableFieldBehaviors)
{
if (record == null)
return;
record.setEnableListeners(bEnableRecordBehaviors); // Disable all file behaviors
for (int iFieldSeq = 0; iFieldSeq < record.getFieldCount(); iFieldSeq++)
{
BaseField field = record.getField(iFieldSeq);
field.setEnableListeners(bEnableFieldBehaviors);
}
} | [
"public",
"static",
"void",
"enableAllBehaviors",
"(",
"Record",
"record",
",",
"boolean",
"bEnableRecordBehaviors",
",",
"boolean",
"bEnableFieldBehaviors",
")",
"{",
"if",
"(",
"record",
"==",
"null",
")",
"return",
";",
"record",
".",
"setEnableListeners",
"(",... | Enable or disable all the behaviors.
@param record The target record.
@param bEnableRecordBehaviors Enable/disable all the record behaviors.
@param bEnableFieldBehaviors Enable/disable all the field behaviors. | [
"Enable",
"or",
"disable",
"all",
"the",
"behaviors",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/xmlutil/XmlInOut.java#L624-L634 |
ngageoint/geopackage-android-map | geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java | GoogleMapShapeConverter.toPolyhedralSurface | public PolyhedralSurface toPolyhedralSurface(
List<com.google.android.gms.maps.model.Polygon> polygonList) {
return toPolyhedralSurface(polygonList, false, false);
} | java | public PolyhedralSurface toPolyhedralSurface(
List<com.google.android.gms.maps.model.Polygon> polygonList) {
return toPolyhedralSurface(polygonList, false, false);
} | [
"public",
"PolyhedralSurface",
"toPolyhedralSurface",
"(",
"List",
"<",
"com",
".",
"google",
".",
"android",
".",
"gms",
".",
"maps",
".",
"model",
".",
"Polygon",
">",
"polygonList",
")",
"{",
"return",
"toPolyhedralSurface",
"(",
"polygonList",
",",
"false"... | Convert a list of {@link Polygon} to a {@link PolyhedralSurface}
@param polygonList polygon list
@return polyhedral surface | [
"Convert",
"a",
"list",
"of",
"{",
"@link",
"Polygon",
"}",
"to",
"a",
"{",
"@link",
"PolyhedralSurface",
"}"
] | train | https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/geom/GoogleMapShapeConverter.java#L1207-L1210 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.