repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java | ServicesInner.beginCreateOrUpdate | public DataMigrationServiceInner beginCreateOrUpdate(String groupName, String serviceName, DataMigrationServiceInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(groupName, serviceName, parameters).toBlocking().single().body();
} | java | public DataMigrationServiceInner beginCreateOrUpdate(String groupName, String serviceName, DataMigrationServiceInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(groupName, serviceName, parameters).toBlocking().single().body();
} | [
"public",
"DataMigrationServiceInner",
"beginCreateOrUpdate",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
",",
"DataMigrationServiceInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
","... | Create or update DMS Instance.
The services resource is the top-level resource that represents the Data Migration Service. The PUT method creates a new service or updates an existing one. When a service is updated, existing child resources (i.e. tasks) are unaffected. Services currently support a single kind, "vm", which refers to a VM-based service, although other kinds may be added in the future. This method can change the kind, SKU, and network of the service, but if tasks are currently running (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). The provider will reply when successful with 200 OK or 201 Created. Long-running operations use the provisioningState property.
@param groupName Name of the resource group
@param serviceName Name of the service
@param parameters Information about the service
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DataMigrationServiceInner object if successful. | [
"Create",
"or",
"update",
"DMS",
"Instance",
".",
"The",
"services",
"resource",
"is",
"the",
"top",
"-",
"level",
"resource",
"that",
"represents",
"the",
"Data",
"Migration",
"Service",
".",
"The",
"PUT",
"method",
"creates",
"a",
"new",
"service",
"or",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L245-L247 |
structurizr/java | structurizr-core/src/com/structurizr/documentation/DocumentationTemplate.java | DocumentationTemplate.addSection | public Section addSection(String title, File... files) throws IOException {
return add(null, title, files);
} | java | public Section addSection(String title, File... files) throws IOException {
return add(null, title, files);
} | [
"public",
"Section",
"addSection",
"(",
"String",
"title",
",",
"File",
"...",
"files",
")",
"throws",
"IOException",
"{",
"return",
"add",
"(",
"null",
",",
"title",
",",
"files",
")",
";",
"}"
] | Adds a custom section from one or more files, that isn't related to any element in the model.
@param title the section title
@param files one or more File objects that point to the documentation content
@return a documentation {@link Section}
@throws IOException if there is an error reading the files | [
"Adds",
"a",
"custom",
"section",
"from",
"one",
"or",
"more",
"files",
"that",
"isn",
"t",
"related",
"to",
"any",
"element",
"in",
"the",
"model",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/DocumentationTemplate.java#L47-L49 |
aalmiray/Json-lib | src/main/java/net/sf/json/JSONObject.java | JSONObject.optInt | public int optInt( String key, int defaultValue ) {
verifyIsNull();
try{
return getInt( key );
}catch( Exception e ){
return defaultValue;
}
} | java | public int optInt( String key, int defaultValue ) {
verifyIsNull();
try{
return getInt( key );
}catch( Exception e ){
return defaultValue;
}
} | [
"public",
"int",
"optInt",
"(",
"String",
"key",
",",
"int",
"defaultValue",
")",
"{",
"verifyIsNull",
"(",
")",
";",
"try",
"{",
"return",
"getInt",
"(",
"key",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"defaultValue",
";",
... | Get an optional int value associated with a key, or the default if there
is no such key or if the value is not a number. If the value is a string,
an attempt will be made to evaluate it as a number.
@param key A key string.
@param defaultValue The default.
@return An object which is the value. | [
"Get",
"an",
"optional",
"int",
"value",
"associated",
"with",
"a",
"key",
"or",
"the",
"default",
"if",
"there",
"is",
"no",
"such",
"key",
"or",
"if",
"the",
"value",
"is",
"not",
"a",
"number",
".",
"If",
"the",
"value",
"is",
"a",
"string",
"an",... | train | https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONObject.java#L2202-L2209 |
micronaut-projects/micronaut-core | core/src/main/java/io/micronaut/core/util/StringUtils.java | StringUtils.convertDotToUnderscore | public static String convertDotToUnderscore(String dottedProperty, boolean uppercase) {
if (dottedProperty == null) {
return dottedProperty;
}
Optional<String> converted = Optional.of(dottedProperty)
.map(value -> value.replace('.', '_'))
.map(value -> uppercase ? value.toUpperCase() : value);
return converted.get();
} | java | public static String convertDotToUnderscore(String dottedProperty, boolean uppercase) {
if (dottedProperty == null) {
return dottedProperty;
}
Optional<String> converted = Optional.of(dottedProperty)
.map(value -> value.replace('.', '_'))
.map(value -> uppercase ? value.toUpperCase() : value);
return converted.get();
} | [
"public",
"static",
"String",
"convertDotToUnderscore",
"(",
"String",
"dottedProperty",
",",
"boolean",
"uppercase",
")",
"{",
"if",
"(",
"dottedProperty",
"==",
"null",
")",
"{",
"return",
"dottedProperty",
";",
"}",
"Optional",
"<",
"String",
">",
"converted"... | Replace the dots in the property with underscore and
transform to uppercase based on given flag.
@param dottedProperty The property with dots, example - a.b.c
@param uppercase To transform to uppercase string
@return The converted value | [
"Replace",
"the",
"dots",
"in",
"the",
"property",
"with",
"underscore",
"and",
"transform",
"to",
"uppercase",
"based",
"on",
"given",
"flag",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/util/StringUtils.java#L234-L242 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/nephele/ipc/RPC.java | RPC.getProxy | public static <V extends VersionedProtocol> V getProxy(Class<V> protocol, InetSocketAddress addr)
throws IOException {
return getProxy(protocol, addr, NetUtils.getDefaultSocketFactory());
} | java | public static <V extends VersionedProtocol> V getProxy(Class<V> protocol, InetSocketAddress addr)
throws IOException {
return getProxy(protocol, addr, NetUtils.getDefaultSocketFactory());
} | [
"public",
"static",
"<",
"V",
"extends",
"VersionedProtocol",
">",
"V",
"getProxy",
"(",
"Class",
"<",
"V",
">",
"protocol",
",",
"InetSocketAddress",
"addr",
")",
"throws",
"IOException",
"{",
"return",
"getProxy",
"(",
"protocol",
",",
"addr",
",",
"NetUti... | Construct a client-side proxy object with the default SocketFactory
@param protocol
@param addr
@return
@throws IOException | [
"Construct",
"a",
"client",
"-",
"side",
"proxy",
"object",
"with",
"the",
"default",
"SocketFactory"
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/ipc/RPC.java#L332-L336 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java | WhiteboxImpl.findFieldOrThrowException | private static Field findFieldOrThrowException(Class<?> fieldType, Class<?> where) {
if (fieldType == null || where == null) {
throw new IllegalArgumentException("fieldType and where cannot be null");
}
Field field = null;
for (Field currentField : where.getDeclaredFields()) {
currentField.setAccessible(true);
if (currentField.getType().equals(fieldType)) {
field = currentField;
break;
}
}
if (field == null) {
throw new FieldNotFoundException("Cannot find a field of type " + fieldType + "in where.");
}
return field;
} | java | private static Field findFieldOrThrowException(Class<?> fieldType, Class<?> where) {
if (fieldType == null || where == null) {
throw new IllegalArgumentException("fieldType and where cannot be null");
}
Field field = null;
for (Field currentField : where.getDeclaredFields()) {
currentField.setAccessible(true);
if (currentField.getType().equals(fieldType)) {
field = currentField;
break;
}
}
if (field == null) {
throw new FieldNotFoundException("Cannot find a field of type " + fieldType + "in where.");
}
return field;
} | [
"private",
"static",
"Field",
"findFieldOrThrowException",
"(",
"Class",
"<",
"?",
">",
"fieldType",
",",
"Class",
"<",
"?",
">",
"where",
")",
"{",
"if",
"(",
"fieldType",
"==",
"null",
"||",
"where",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgu... | Find field or throw exception.
@param fieldType the field type
@param where the where
@return the field | [
"Find",
"field",
"or",
"throw",
"exception",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2277-L2293 |
rometools/rome | rome/src/main/java/com/rometools/rome/io/impl/NumberParser.java | NumberParser.parseFloat | public static float parseFloat(final String str, final float def) {
final Float result = parseFloat(str);
if (result == null) {
return def;
} else {
return result.floatValue();
}
} | java | public static float parseFloat(final String str, final float def) {
final Float result = parseFloat(str);
if (result == null) {
return def;
} else {
return result.floatValue();
}
} | [
"public",
"static",
"float",
"parseFloat",
"(",
"final",
"String",
"str",
",",
"final",
"float",
"def",
")",
"{",
"final",
"Float",
"result",
"=",
"parseFloat",
"(",
"str",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"return",
"def",
";",
... | Parse a float from a String, with a default value
@param str
@param def the value to return if the String cannot be parsed | [
"Parse",
"a",
"float",
"from",
"a",
"String",
"with",
"a",
"default",
"value"
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/impl/NumberParser.java#L95-L102 |
nikolavp/approval | approval-core/src/main/java/com/github/approval/reporters/Reporters.java | Reporters.autoApprove | public Reporter autoApprove() {
return new Reporter() {
@Override
public void notTheSame(byte[] oldValue, File fileForVerification, byte[] newValue, File fileForApproval) {
autoApprove(fileForVerification, fileForApproval);
}
@Override
public void approveNew(byte[] value, File fileForApproval, File fileForVerification) {
autoApprove(fileForVerification, fileForApproval);
}
private void autoApprove(File fileForVerification, File fileForApproval) {
try {
Files.move(fileForApproval.toPath(), fileForVerification.toPath());
} catch (IOException e) {
throw new IllegalStateException("Couldn't auto approve the value in " + fileForApproval.getAbsolutePath(), e);
}
}
@Override
public boolean canApprove(File fileForApproval) {
return true;
}
};
} | java | public Reporter autoApprove() {
return new Reporter() {
@Override
public void notTheSame(byte[] oldValue, File fileForVerification, byte[] newValue, File fileForApproval) {
autoApprove(fileForVerification, fileForApproval);
}
@Override
public void approveNew(byte[] value, File fileForApproval, File fileForVerification) {
autoApprove(fileForVerification, fileForApproval);
}
private void autoApprove(File fileForVerification, File fileForApproval) {
try {
Files.move(fileForApproval.toPath(), fileForVerification.toPath());
} catch (IOException e) {
throw new IllegalStateException("Couldn't auto approve the value in " + fileForApproval.getAbsolutePath(), e);
}
}
@Override
public boolean canApprove(File fileForApproval) {
return true;
}
};
} | [
"public",
"Reporter",
"autoApprove",
"(",
")",
"{",
"return",
"new",
"Reporter",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"notTheSame",
"(",
"byte",
"[",
"]",
"oldValue",
",",
"File",
"fileForVerification",
",",
"byte",
"[",
"]",
"newValue",
",",
... | A reporter that auto approves every value passed to it.
<p>
This is especially useful when you are making a big change and want to
auto approve a lot of things. You can then use your version control
system(you are using one of those right?) to see a diff
</p>
@return the auto approving reporter | [
"A",
"reporter",
"that",
"auto",
"approves",
"every",
"value",
"passed",
"to",
"it",
".",
"<p",
">",
"This",
"is",
"especially",
"useful",
"when",
"you",
"are",
"making",
"a",
"big",
"change",
"and",
"want",
"to",
"auto",
"approve",
"a",
"lot",
"of",
"... | train | https://github.com/nikolavp/approval/blob/5e32ecc3bc7f631e94a7049894fdd99a3aa5b1b8/approval-core/src/main/java/com/github/approval/reporters/Reporters.java#L236-L261 |
OpenLiberty/open-liberty | dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/impl/BatchKernelImpl.java | BatchKernelImpl.publishEvent | private void publishEvent(WSJobInstance objectToPublish, String eventToPublishTo, String correlationId) {
if (eventsPublisher != null) {
eventsPublisher.publishJobInstanceEvent(objectToPublish, eventToPublishTo, correlationId);
}
} | java | private void publishEvent(WSJobInstance objectToPublish, String eventToPublishTo, String correlationId) {
if (eventsPublisher != null) {
eventsPublisher.publishJobInstanceEvent(objectToPublish, eventToPublishTo, correlationId);
}
} | [
"private",
"void",
"publishEvent",
"(",
"WSJobInstance",
"objectToPublish",
",",
"String",
"eventToPublishTo",
",",
"String",
"correlationId",
")",
"{",
"if",
"(",
"eventsPublisher",
"!=",
"null",
")",
"{",
"eventsPublisher",
".",
"publishJobInstanceEvent",
"(",
"ob... | Publish jms topic if batch jms event is available
@param objectToPublish WSJobInstance
@param eventToPublish | [
"Publish",
"jms",
"topic",
"if",
"batch",
"jms",
"event",
"is",
"available"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/impl/BatchKernelImpl.java#L306-L310 |
BigBadaboom/androidsvg | androidsvg/src/main/java/com/caverock/androidsvg/SimpleAssetResolver.java | SimpleAssetResolver.getAssetAsString | private String getAssetAsString(String url)
{
InputStream is = null;
try
{
is = assetManager.open(url);
Reader r = new InputStreamReader(is, Charset.forName("UTF-8"));
char[] buffer = new char[4096];
StringBuilder sb = new StringBuilder();
int len = r.read(buffer);
while (len > 0) {
sb.append(buffer, 0, len);
len = r.read(buffer);
}
return sb.toString();
}
catch (IOException e)
{
return null;
}
finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
// Do nothing
}
}
} | java | private String getAssetAsString(String url)
{
InputStream is = null;
try
{
is = assetManager.open(url);
Reader r = new InputStreamReader(is, Charset.forName("UTF-8"));
char[] buffer = new char[4096];
StringBuilder sb = new StringBuilder();
int len = r.read(buffer);
while (len > 0) {
sb.append(buffer, 0, len);
len = r.read(buffer);
}
return sb.toString();
}
catch (IOException e)
{
return null;
}
finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
// Do nothing
}
}
} | [
"private",
"String",
"getAssetAsString",
"(",
"String",
"url",
")",
"{",
"InputStream",
"is",
"=",
"null",
";",
"try",
"{",
"is",
"=",
"assetManager",
".",
"open",
"(",
"url",
")",
";",
"Reader",
"r",
"=",
"new",
"InputStreamReader",
"(",
"is",
",",
"C... | /*
Read the contents of the asset whose name is given by "url" and return it as a String. | [
"/",
"*",
"Read",
"the",
"contents",
"of",
"the",
"asset",
"whose",
"name",
"is",
"given",
"by",
"url",
"and",
"return",
"it",
"as",
"a",
"String",
"."
] | train | https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/SimpleAssetResolver.java#L148-L177 |
fuinorg/units4j | src/main/java/org/fuin/units4j/analyzer/MCAClassVisitor.java | MCAClassVisitor.addCall | public final void addCall(final MCAMethod found, final int line) {
calls.add(new MCAMethodCall(found, className, methodName, methodDescr, source, line));
} | java | public final void addCall(final MCAMethod found, final int line) {
calls.add(new MCAMethodCall(found, className, methodName, methodDescr, source, line));
} | [
"public",
"final",
"void",
"addCall",
"(",
"final",
"MCAMethod",
"found",
",",
"final",
"int",
"line",
")",
"{",
"calls",
".",
"add",
"(",
"new",
"MCAMethodCall",
"(",
"found",
",",
"className",
",",
"methodName",
",",
"methodDescr",
",",
"source",
",",
... | Adds the current method to the list of callers.
@param found
Called method.
@param line
Line number of the call. | [
"Adds",
"the",
"current",
"method",
"to",
"the",
"list",
"of",
"callers",
"."
] | train | https://github.com/fuinorg/units4j/blob/29383e30b0f9c246b309e734df9cc63dc5d5499e/src/main/java/org/fuin/units4j/analyzer/MCAClassVisitor.java#L88-L90 |
mfornos/humanize | humanize-slim/src/main/java/humanize/Humanize.java | Humanize.roundToSignificantFigures | public static Number roundToSignificantFigures(Number num, int precision)
{
return new BigDecimal(num.doubleValue())
.round(new MathContext(precision, RoundingMode.HALF_EVEN));
} | java | public static Number roundToSignificantFigures(Number num, int precision)
{
return new BigDecimal(num.doubleValue())
.round(new MathContext(precision, RoundingMode.HALF_EVEN));
} | [
"public",
"static",
"Number",
"roundToSignificantFigures",
"(",
"Number",
"num",
",",
"int",
"precision",
")",
"{",
"return",
"new",
"BigDecimal",
"(",
"num",
".",
"doubleValue",
"(",
")",
")",
".",
"round",
"(",
"new",
"MathContext",
"(",
"precision",
",",
... | <p>
Rounds a number to significant figures.
</p>
@param num
The number to be rounded
@param precision
The number of significant digits
@return The number rounded to significant figures | [
"<p",
">",
"Rounds",
"a",
"number",
"to",
"significant",
"figures",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-slim/src/main/java/humanize/Humanize.java#L2521-L2525 |
googlemaps/google-maps-services-java | src/main/java/com/google/maps/GeocodingApi.java | GeocodingApi.reverseGeocode | public static GeocodingApiRequest reverseGeocode(GeoApiContext context, LatLng location) {
GeocodingApiRequest request = new GeocodingApiRequest(context);
request.latlng(location);
return request;
} | java | public static GeocodingApiRequest reverseGeocode(GeoApiContext context, LatLng location) {
GeocodingApiRequest request = new GeocodingApiRequest(context);
request.latlng(location);
return request;
} | [
"public",
"static",
"GeocodingApiRequest",
"reverseGeocode",
"(",
"GeoApiContext",
"context",
",",
"LatLng",
"location",
")",
"{",
"GeocodingApiRequest",
"request",
"=",
"new",
"GeocodingApiRequest",
"(",
"context",
")",
";",
"request",
".",
"latlng",
"(",
"location... | Requests the street address of a {@code location}.
@param context The {@link GeoApiContext} to make requests through.
@param location The location to reverse geocode.
@return Returns the request, ready to run. | [
"Requests",
"the",
"street",
"address",
"of",
"a",
"{",
"@code",
"location",
"}",
"."
] | train | https://github.com/googlemaps/google-maps-services-java/blob/23d20d1930f80e310d856d2da51d72ee0db4476b/src/main/java/com/google/maps/GeocodingApi.java#L65-L69 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.assertCurrentActivity | public void assertCurrentActivity(String message, String name, boolean isNewInstance)
{
if(config.commandLogging){
Log.d(config.commandLoggingTag, "assertCurrentActivity("+message+", "+name+", "+isNewInstance+")");
}
asserter.assertCurrentActivity(message, name, isNewInstance);
} | java | public void assertCurrentActivity(String message, String name, boolean isNewInstance)
{
if(config.commandLogging){
Log.d(config.commandLoggingTag, "assertCurrentActivity("+message+", "+name+", "+isNewInstance+")");
}
asserter.assertCurrentActivity(message, name, isNewInstance);
} | [
"public",
"void",
"assertCurrentActivity",
"(",
"String",
"message",
",",
"String",
"name",
",",
"boolean",
"isNewInstance",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"ass... | Asserts that the Activity matching the specified name is active, with the possibility to
verify that the expected Activity is a new instance of the Activity.
@param message the message to display if the assert fails
@param name the name of the Activity that is expected to be active. Example is: {@code "MyActivity"}
@param isNewInstance {@code true} if the expected {@link Activity} is a new instance of the {@link Activity} | [
"Asserts",
"that",
"the",
"Activity",
"matching",
"the",
"specified",
"name",
"is",
"active",
"with",
"the",
"possibility",
"to",
"verify",
"that",
"the",
"expected",
"Activity",
"is",
"a",
"new",
"instance",
"of",
"the",
"Activity",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L1013-L1020 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/osgi/container/config/merge/MailSessionComparator.java | MailSessionComparator.isMatchingString | private boolean isMatchingString(String value1, String value2) {
boolean valuesMatch = true;
if (value1 == null) {
if (value2 != null) {
valuesMatch = false;
}
} else {
valuesMatch = value1.equals(value2);
}
return valuesMatch;
} | java | private boolean isMatchingString(String value1, String value2) {
boolean valuesMatch = true;
if (value1 == null) {
if (value2 != null) {
valuesMatch = false;
}
} else {
valuesMatch = value1.equals(value2);
}
return valuesMatch;
} | [
"private",
"boolean",
"isMatchingString",
"(",
"String",
"value1",
",",
"String",
"value2",
")",
"{",
"boolean",
"valuesMatch",
"=",
"true",
";",
"if",
"(",
"value1",
"==",
"null",
")",
"{",
"if",
"(",
"value2",
"!=",
"null",
")",
"{",
"valuesMatch",
"="... | Compare two string values.
@param value1
@param value2
@return true if matching | [
"Compare",
"two",
"string",
"values",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/osgi/container/config/merge/MailSessionComparator.java#L59-L72 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/classfile/ConstantFloatInfo.java | ConstantFloatInfo.make | static ConstantFloatInfo make(ConstantPool cp, float value) {
ConstantInfo ci = new ConstantFloatInfo(value);
return (ConstantFloatInfo)cp.addConstant(ci);
} | java | static ConstantFloatInfo make(ConstantPool cp, float value) {
ConstantInfo ci = new ConstantFloatInfo(value);
return (ConstantFloatInfo)cp.addConstant(ci);
} | [
"static",
"ConstantFloatInfo",
"make",
"(",
"ConstantPool",
"cp",
",",
"float",
"value",
")",
"{",
"ConstantInfo",
"ci",
"=",
"new",
"ConstantFloatInfo",
"(",
"value",
")",
";",
"return",
"(",
"ConstantFloatInfo",
")",
"cp",
".",
"addConstant",
"(",
"ci",
")... | Will return either a new ConstantFloatInfo object or one already in
the constant pool. If it is a new ConstantFloatInfo, it will be
inserted into the pool. | [
"Will",
"return",
"either",
"a",
"new",
"ConstantFloatInfo",
"object",
"or",
"one",
"already",
"in",
"the",
"constant",
"pool",
".",
"If",
"it",
"is",
"a",
"new",
"ConstantFloatInfo",
"it",
"will",
"be",
"inserted",
"into",
"the",
"pool",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantFloatInfo.java#L35-L38 |
code4everything/util | src/main/java/com/zhazhapan/util/NetUtils.java | NetUtils.responseFile | public static void responseFile(HttpServletResponse response, String local, boolean isDownloaded) throws IOException {
if (Checker.isExists(local)) {
File file = new File(local);
try (FileInputStream in = new FileInputStream(file); ServletOutputStream os = response.getOutputStream()) {
byte[] b;
while (in.available() > 0) {
b = in.available() > 1024 ? new byte[1024] : new byte[in.available()];
in.read(b, 0, b.length);
os.write(b, 0, b.length);
}
os.flush();
}
if (isDownloaded) {
String fn = new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attachment;filename=" + fn);
}
} else {
response.setStatus(404);
}
} | java | public static void responseFile(HttpServletResponse response, String local, boolean isDownloaded) throws IOException {
if (Checker.isExists(local)) {
File file = new File(local);
try (FileInputStream in = new FileInputStream(file); ServletOutputStream os = response.getOutputStream()) {
byte[] b;
while (in.available() > 0) {
b = in.available() > 1024 ? new byte[1024] : new byte[in.available()];
in.read(b, 0, b.length);
os.write(b, 0, b.length);
}
os.flush();
}
if (isDownloaded) {
String fn = new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attachment;filename=" + fn);
}
} else {
response.setStatus(404);
}
} | [
"public",
"static",
"void",
"responseFile",
"(",
"HttpServletResponse",
"response",
",",
"String",
"local",
",",
"boolean",
"isDownloaded",
")",
"throws",
"IOException",
"{",
"if",
"(",
"Checker",
".",
"isExists",
"(",
"local",
")",
")",
"{",
"File",
"file",
... | 响应文件
@param response {@link HttpServletResponse}
@param local 文件路径
@param isDownloaded 是否下载
@throws IOException 异常
@since 1.1.1 | [
"响应文件"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/NetUtils.java#L78-L97 |
spring-projects/spring-ldap | core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerImpl.java | ConverterManagerImpl.addConverter | public void addConverter(Class<?> fromClass, String syntax, Class<?> toClass, Converter converter) {
converters.put(makeConverterKey(fromClass, syntax, toClass), converter);
} | java | public void addConverter(Class<?> fromClass, String syntax, Class<?> toClass, Converter converter) {
converters.put(makeConverterKey(fromClass, syntax, toClass), converter);
} | [
"public",
"void",
"addConverter",
"(",
"Class",
"<",
"?",
">",
"fromClass",
",",
"String",
"syntax",
",",
"Class",
"<",
"?",
">",
"toClass",
",",
"Converter",
"converter",
")",
"{",
"converters",
".",
"put",
"(",
"makeConverterKey",
"(",
"fromClass",
",",
... | Add a {@link Converter} to this <code>ConverterManager</code>.
@param fromClass The class the <code>Converter</code> should be used to convert from.
@param syntax The LDAP syntax that the <code>Converter</code> should be used for.
@param toClass The class the <code>Converter</code> should be used to convert to.
@param converter The <code>Converter</code> to add. | [
"Add",
"a",
"{",
"@link",
"Converter",
"}",
"to",
"this",
"<code",
">",
"ConverterManager<",
"/",
"code",
">",
"."
] | train | https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerImpl.java#L174-L176 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java | ValueEnforcer.isBetweenInclusive | public static BigDecimal isBetweenInclusive (final BigDecimal aValue,
final String sName,
@Nonnull final BigDecimal aLowerBoundInclusive,
@Nonnull final BigDecimal aUpperBoundInclusive)
{
if (isEnabled ())
return isBetweenInclusive (aValue, () -> sName, aLowerBoundInclusive, aUpperBoundInclusive);
return aValue;
} | java | public static BigDecimal isBetweenInclusive (final BigDecimal aValue,
final String sName,
@Nonnull final BigDecimal aLowerBoundInclusive,
@Nonnull final BigDecimal aUpperBoundInclusive)
{
if (isEnabled ())
return isBetweenInclusive (aValue, () -> sName, aLowerBoundInclusive, aUpperBoundInclusive);
return aValue;
} | [
"public",
"static",
"BigDecimal",
"isBetweenInclusive",
"(",
"final",
"BigDecimal",
"aValue",
",",
"final",
"String",
"sName",
",",
"@",
"Nonnull",
"final",
"BigDecimal",
"aLowerBoundInclusive",
",",
"@",
"Nonnull",
"final",
"BigDecimal",
"aUpperBoundInclusive",
")",
... | Check if
<code>nValue ≥ nLowerBoundInclusive && nValue ≤ nUpperBoundInclusive</code>
@param aValue
Value
@param sName
Name
@param aLowerBoundInclusive
Lower bound
@param aUpperBoundInclusive
Upper bound
@return The value | [
"Check",
"if",
"<code",
">",
"nValue",
"&ge",
";",
"nLowerBoundInclusive",
"&",
";",
"&",
";",
"nValue",
"&le",
";",
"nUpperBoundInclusive<",
"/",
"code",
">"
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L2557-L2565 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.jms.2.0.cdi/src/com/ibm/ws/cdi/jms/JMSContextInjectionBean.java | JMSContextInjectionBean.getJMSContext | @Produces
public JMSContext getJMSContext(InjectionPoint injectionPoint) throws NamingException {
//Default connection factory string, if no @JMSConnectionFactory annotation
//is provided, then this value is used for lookup
String connectionFactoryString = "java:comp/DefaultJMSConnectionFactory";
//Default acknowledge mode
int acknowledgeMode = JMSContext.AUTO_ACKNOWLEDGE;
//user name and password
String userName = null;
String password = null;
//Get all the passed annotations and get the values
if (injectionPoint != null)
{
if (injectionPoint.getAnnotated().isAnnotationPresent(JMSConnectionFactory.class)) {
JMSConnectionFactory jmsConnectionFactory = injectionPoint.getAnnotated().getAnnotation(JMSConnectionFactory.class);
connectionFactoryString = jmsConnectionFactory.value();
}
if (injectionPoint.getAnnotated().isAnnotationPresent(JMSPasswordCredential.class)) {
JMSPasswordCredential jmsPasswordCredential = injectionPoint.getAnnotated().getAnnotation(JMSPasswordCredential.class);
userName = jmsPasswordCredential.userName();
password = jmsPasswordCredential.password();
}
if (injectionPoint.getAnnotated().isAnnotationPresent(JMSSessionMode.class)) {
JMSSessionMode jmsSessionMode = injectionPoint.getAnnotated().getAnnotation(JMSSessionMode.class);
acknowledgeMode = jmsSessionMode.value();
}
}
//Create a Info object about the configuration, based on this we can compare if the second
//request for creating the new injected JMSContext within transaction is having the same
//set of parameter, then use the same JMSContext
JMSContextInfo info = new JMSContextInfo(connectionFactoryString, userName, password, acknowledgeMode);
return new JMSContextInjected(info);
} | java | @Produces
public JMSContext getJMSContext(InjectionPoint injectionPoint) throws NamingException {
//Default connection factory string, if no @JMSConnectionFactory annotation
//is provided, then this value is used for lookup
String connectionFactoryString = "java:comp/DefaultJMSConnectionFactory";
//Default acknowledge mode
int acknowledgeMode = JMSContext.AUTO_ACKNOWLEDGE;
//user name and password
String userName = null;
String password = null;
//Get all the passed annotations and get the values
if (injectionPoint != null)
{
if (injectionPoint.getAnnotated().isAnnotationPresent(JMSConnectionFactory.class)) {
JMSConnectionFactory jmsConnectionFactory = injectionPoint.getAnnotated().getAnnotation(JMSConnectionFactory.class);
connectionFactoryString = jmsConnectionFactory.value();
}
if (injectionPoint.getAnnotated().isAnnotationPresent(JMSPasswordCredential.class)) {
JMSPasswordCredential jmsPasswordCredential = injectionPoint.getAnnotated().getAnnotation(JMSPasswordCredential.class);
userName = jmsPasswordCredential.userName();
password = jmsPasswordCredential.password();
}
if (injectionPoint.getAnnotated().isAnnotationPresent(JMSSessionMode.class)) {
JMSSessionMode jmsSessionMode = injectionPoint.getAnnotated().getAnnotation(JMSSessionMode.class);
acknowledgeMode = jmsSessionMode.value();
}
}
//Create a Info object about the configuration, based on this we can compare if the second
//request for creating the new injected JMSContext within transaction is having the same
//set of parameter, then use the same JMSContext
JMSContextInfo info = new JMSContextInfo(connectionFactoryString, userName, password, acknowledgeMode);
return new JMSContextInjected(info);
} | [
"@",
"Produces",
"public",
"JMSContext",
"getJMSContext",
"(",
"InjectionPoint",
"injectionPoint",
")",
"throws",
"NamingException",
"{",
"//Default connection factory string, if no @JMSConnectionFactory annotation ",
"//is provided, then this value is used for lookup",
"String",
"con... | /*
This method is called while JMSContext is injected in the container. For every new @Inject
Annotation a new instance of JMSContext is returned. In case of active transaction when the
injected JMSContext is being used, a new instance is created and added to the transaction
registry so that next request with the same configuration will return the existing JMSContext
rather than creating a new one. | [
"/",
"*",
"This",
"method",
"is",
"called",
"while",
"JMSContext",
"is",
"injected",
"in",
"the",
"container",
".",
"For",
"every",
"new"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0.cdi/src/com/ibm/ws/cdi/jms/JMSContextInjectionBean.java#L35-L74 |
yanzhenjie/Album | album/src/main/java/com/yanzhenjie/album/api/BasicGalleryWrapper.java | BasicGalleryWrapper.currentPosition | public Returner currentPosition(@IntRange(from = 0, to = Integer.MAX_VALUE) int currentPosition) {
this.mCurrentPosition = currentPosition;
return (Returner) this;
} | java | public Returner currentPosition(@IntRange(from = 0, to = Integer.MAX_VALUE) int currentPosition) {
this.mCurrentPosition = currentPosition;
return (Returner) this;
} | [
"public",
"Returner",
"currentPosition",
"(",
"@",
"IntRange",
"(",
"from",
"=",
"0",
",",
"to",
"=",
"Integer",
".",
"MAX_VALUE",
")",
"int",
"currentPosition",
")",
"{",
"this",
".",
"mCurrentPosition",
"=",
"currentPosition",
";",
"return",
"(",
"Returner... | Set the show position of List.
@param currentPosition the current position. | [
"Set",
"the",
"show",
"position",
"of",
"List",
"."
] | train | https://github.com/yanzhenjie/Album/blob/b17506440d32909d42aba41f6a388041a25c8363/album/src/main/java/com/yanzhenjie/album/api/BasicGalleryWrapper.java#L75-L78 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java | SARLQuickfixProvider.fixInvalidExtendedType | @Fix(io.sarl.lang.validation.IssueCodes.INVALID_EXTENDED_TYPE)
public void fixInvalidExtendedType(final Issue issue, IssueResolutionAcceptor acceptor) {
ExtendedTypeRemoveModification.accept(this, issue, acceptor);
} | java | @Fix(io.sarl.lang.validation.IssueCodes.INVALID_EXTENDED_TYPE)
public void fixInvalidExtendedType(final Issue issue, IssueResolutionAcceptor acceptor) {
ExtendedTypeRemoveModification.accept(this, issue, acceptor);
} | [
"@",
"Fix",
"(",
"io",
".",
"sarl",
".",
"lang",
".",
"validation",
".",
"IssueCodes",
".",
"INVALID_EXTENDED_TYPE",
")",
"public",
"void",
"fixInvalidExtendedType",
"(",
"final",
"Issue",
"issue",
",",
"IssueResolutionAcceptor",
"acceptor",
")",
"{",
"ExtendedT... | Quick fix for "Invalid extended type".
@param issue the issue.
@param acceptor the quick fix acceptor. | [
"Quick",
"fix",
"for",
"Invalid",
"extended",
"type",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L815-L818 |
lucee/Lucee | core/src/main/java/lucee/runtime/op/Caster.java | Caster.toLocale | public static Locale toLocale(String strLocale, Locale defaultValue) {
return LocaleFactory.getLocale(strLocale, defaultValue);
} | java | public static Locale toLocale(String strLocale, Locale defaultValue) {
return LocaleFactory.getLocale(strLocale, defaultValue);
} | [
"public",
"static",
"Locale",
"toLocale",
"(",
"String",
"strLocale",
",",
"Locale",
"defaultValue",
")",
"{",
"return",
"LocaleFactory",
".",
"getLocale",
"(",
"strLocale",
",",
"defaultValue",
")",
";",
"}"
] | casts a string to a Locale
@param strLocale
@param defaultValue
@return Locale from String | [
"casts",
"a",
"string",
"to",
"a",
"Locale"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L4233-L4235 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.nested/src/com/ibm/ws/kernel/launch/internal/NoRethrowSecurityManager.java | NoRethrowSecurityManager.isOffendingClass | boolean isOffendingClass(Class<?>[] classes, int j, ProtectionDomain pd2, Permission inPerm) {
// Return true if ...
return (!classes[j].getName().startsWith("java")) && // as long as not
// starting with
// java
(classes[j].getName().indexOf("com.ibm.ws.kernel.launch.internal.NoRethrowSecurityManager") == -1) && // not
// our
// SecurityManager
(classes[j].getName().indexOf("ClassLoader") == -1) && // not a
// class
// loader
// not the end of stack and next is not a class loader
((j == classes.length - 1) ? true : (classes[j + 1].getName().indexOf("ClassLoader") == -1)) &&
// lacks the required permissions
!pd2.implies(inPerm);
} | java | boolean isOffendingClass(Class<?>[] classes, int j, ProtectionDomain pd2, Permission inPerm) {
// Return true if ...
return (!classes[j].getName().startsWith("java")) && // as long as not
// starting with
// java
(classes[j].getName().indexOf("com.ibm.ws.kernel.launch.internal.NoRethrowSecurityManager") == -1) && // not
// our
// SecurityManager
(classes[j].getName().indexOf("ClassLoader") == -1) && // not a
// class
// loader
// not the end of stack and next is not a class loader
((j == classes.length - 1) ? true : (classes[j + 1].getName().indexOf("ClassLoader") == -1)) &&
// lacks the required permissions
!pd2.implies(inPerm);
} | [
"boolean",
"isOffendingClass",
"(",
"Class",
"<",
"?",
">",
"[",
"]",
"classes",
",",
"int",
"j",
",",
"ProtectionDomain",
"pd2",
",",
"Permission",
"inPerm",
")",
"{",
"// Return true if ...",
"return",
"(",
"!",
"classes",
"[",
"j",
"]",
".",
"getName",
... | isOffendingClass determines the offending class from the classes defined
in the stack. | [
"isOffendingClass",
"determines",
"the",
"offending",
"class",
"from",
"the",
"classes",
"defined",
"in",
"the",
"stack",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.nested/src/com/ibm/ws/kernel/launch/internal/NoRethrowSecurityManager.java#L280-L295 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/task/RegularPactTask.java | RegularPactTask.openUserCode | public static void openUserCode(Function stub, Configuration parameters) throws Exception {
try {
stub.open(parameters);
} catch (Throwable t) {
throw new Exception("The user defined 'open(Configuration)' method in " + stub.getClass().toString() + " caused an exception: " + t.getMessage(), t);
}
} | java | public static void openUserCode(Function stub, Configuration parameters) throws Exception {
try {
stub.open(parameters);
} catch (Throwable t) {
throw new Exception("The user defined 'open(Configuration)' method in " + stub.getClass().toString() + " caused an exception: " + t.getMessage(), t);
}
} | [
"public",
"static",
"void",
"openUserCode",
"(",
"Function",
"stub",
",",
"Configuration",
"parameters",
")",
"throws",
"Exception",
"{",
"try",
"{",
"stub",
".",
"open",
"(",
"parameters",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"throw",
... | Opens the given stub using its {@link Function#open(Configuration)} method. If the open call produces
an exception, a new exception with a standard error message is created, using the encountered exception
as its cause.
@param stub The user code instance to be opened.
@param parameters The parameters supplied to the user code.
@throws Exception Thrown, if the user code's open method produces an exception. | [
"Opens",
"the",
"given",
"stub",
"using",
"its",
"{",
"@link",
"Function#open",
"(",
"Configuration",
")",
"}",
"method",
".",
"If",
"the",
"open",
"call",
"produces",
"an",
"exception",
"a",
"new",
"exception",
"with",
"a",
"standard",
"error",
"message",
... | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/task/RegularPactTask.java#L1387-L1393 |
synchronoss/cpo-api | cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/jta/JdbcCpoXaAdapter.java | JdbcCpoXaAdapter.executeObject | @Override
public <T> T executeObject(String name, T object) throws CpoException {
return getCurrentResource().executeObject( name, object );
} | java | @Override
public <T> T executeObject(String name, T object) throws CpoException {
return getCurrentResource().executeObject( name, object );
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"T",
"executeObject",
"(",
"String",
"name",
",",
"T",
"object",
")",
"throws",
"CpoException",
"{",
"return",
"getCurrentResource",
"(",
")",
".",
"executeObject",
"(",
"name",
",",
"object",
")",
";",
"}"
] | Executes an Object whose metadata will call an executable within the datasource. It is assumed that the executable
object exists in the metadatasource. If the executable does not exist, an exception will be thrown.
<p>
<pre>Example:
<code>
<p>
class SomeObject so = new SomeObject();
class CpoAdapter cpo = null;
<p>
try {
cpo = new JdbcCpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false));
} catch (CpoException ce) {
// Handle the error
cpo = null;
}
<p>
if (cpo!=null) {
so.setId(1);
so.setName("SomeName");
try{
cpo.executeObject("execNotifyProc",so);
} catch (CpoException ce) {
// Handle the error
}
}
</code>
</pre>
@param name The filter name which tells the datasource which objects should be returned. The name also signifies
what data in the object will be populated.
@param object This is an object that has been defined within the metadata of the datasource. If the class is not
defined an exception will be thrown. If the object does not exist in the datasource, an exception will be thrown.
This object is used to populate the IN parameters used to retrieve the collection of objects. This object defines
the object type that will be returned in the collection and contain the result set data or the OUT Parameters.
@return A result object populate with the OUT parameters
@throws CpoException DOCUMENT ME! | [
"Executes",
"an",
"Object",
"whose",
"metadata",
"will",
"call",
"an",
"executable",
"within",
"the",
"datasource",
".",
"It",
"is",
"assumed",
"that",
"the",
"executable",
"object",
"exists",
"in",
"the",
"metadatasource",
".",
"If",
"the",
"executable",
"doe... | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/jta/JdbcCpoXaAdapter.java#L772-L775 |
alkacon/opencms-core | src/org/opencms/widgets/CmsVfsFileWidget.java | CmsVfsFileWidget.getDefaultSearchTypes | public static String getDefaultSearchTypes(CmsObject cms, CmsResource resource) {
StringBuffer result = new StringBuffer();
String referenceSitePath = cms.getSitePath(resource);
String configPath;
if (resource == null) {
// not sure if this can ever happen?
configPath = cms.addSiteRoot(cms.getRequestContext().getUri());
} else {
configPath = resource.getRootPath();
}
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(cms, configPath);
Set<String> detailPageTypes = OpenCms.getADEManager().getDetailPageTypes(cms);
for (CmsResourceTypeConfig typeConfig : config.getResourceTypes()) {
String typeName = typeConfig.getTypeName();
if (!detailPageTypes.contains(typeName)) {
continue;
}
if (typeConfig.checkViewable(cms, referenceSitePath)) {
result.append(typeName).append(",");
}
}
result.append(CmsResourceTypeXmlContainerPage.getStaticTypeName()).append(",");
result.append(CmsResourceTypeBinary.getStaticTypeName()).append(",");
result.append(CmsResourceTypeImage.getStaticTypeName()).append(",");
result.append(CmsResourceTypePlain.getStaticTypeName());
return result.toString();
} | java | public static String getDefaultSearchTypes(CmsObject cms, CmsResource resource) {
StringBuffer result = new StringBuffer();
String referenceSitePath = cms.getSitePath(resource);
String configPath;
if (resource == null) {
// not sure if this can ever happen?
configPath = cms.addSiteRoot(cms.getRequestContext().getUri());
} else {
configPath = resource.getRootPath();
}
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(cms, configPath);
Set<String> detailPageTypes = OpenCms.getADEManager().getDetailPageTypes(cms);
for (CmsResourceTypeConfig typeConfig : config.getResourceTypes()) {
String typeName = typeConfig.getTypeName();
if (!detailPageTypes.contains(typeName)) {
continue;
}
if (typeConfig.checkViewable(cms, referenceSitePath)) {
result.append(typeName).append(",");
}
}
result.append(CmsResourceTypeXmlContainerPage.getStaticTypeName()).append(",");
result.append(CmsResourceTypeBinary.getStaticTypeName()).append(",");
result.append(CmsResourceTypeImage.getStaticTypeName()).append(",");
result.append(CmsResourceTypePlain.getStaticTypeName());
return result.toString();
} | [
"public",
"static",
"String",
"getDefaultSearchTypes",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"String",
"referenceSitePath",
"=",
"cms",
".",
"getSitePath",
"(",
"re... | Returns a comma separated list of the default search type names.<p>
@param cms the CMS context
@param resource the edited resource
@return a comma separated list of the default search type names | [
"Returns",
"a",
"comma",
"separated",
"list",
"of",
"the",
"default",
"search",
"type",
"names",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/widgets/CmsVfsFileWidget.java#L229-L256 |
msgpack/msgpack-java | msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java | MessageUnpacker.unpackArrayHeader | public int unpackArrayHeader()
throws IOException
{
byte b = readByte();
if (Code.isFixedArray(b)) { // fixarray
return b & 0x0f;
}
switch (b) {
case Code.ARRAY16: { // array 16
int len = readNextLength16();
return len;
}
case Code.ARRAY32: { // array 32
int len = readNextLength32();
return len;
}
}
throw unexpected("Array", b);
} | java | public int unpackArrayHeader()
throws IOException
{
byte b = readByte();
if (Code.isFixedArray(b)) { // fixarray
return b & 0x0f;
}
switch (b) {
case Code.ARRAY16: { // array 16
int len = readNextLength16();
return len;
}
case Code.ARRAY32: { // array 32
int len = readNextLength32();
return len;
}
}
throw unexpected("Array", b);
} | [
"public",
"int",
"unpackArrayHeader",
"(",
")",
"throws",
"IOException",
"{",
"byte",
"b",
"=",
"readByte",
"(",
")",
";",
"if",
"(",
"Code",
".",
"isFixedArray",
"(",
"b",
")",
")",
"{",
"// fixarray",
"return",
"b",
"&",
"0x0f",
";",
"}",
"switch",
... | Reads header of an array.
<p>
This method returns number of elements to be read. After this method call, you call unpacker methods for
each element. You don't have to call anything at the end of iteration.
@return the size of the array to be read
@throws MessageTypeException when value is not MessagePack Array type
@throws MessageSizeException when size of the array is larger than 2^31 - 1
@throws IOException when underlying input throws IOException | [
"Reads",
"header",
"of",
"an",
"array",
"."
] | train | https://github.com/msgpack/msgpack-java/blob/16e370e348215a72a14c210b42d448d513aee015/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java#L1272-L1290 |
phax/ph-oton | ph-oton-security/src/main/java/com/helger/photon/security/object/StubObject.java | StubObject.createForCurrentUserAndID | @Nonnull
public static StubObject createForCurrentUserAndID (@Nonnull @Nonempty final String sID)
{
return new StubObject (sID, LoggedInUserManager.getInstance ().getCurrentUserID (), null);
} | java | @Nonnull
public static StubObject createForCurrentUserAndID (@Nonnull @Nonempty final String sID)
{
return new StubObject (sID, LoggedInUserManager.getInstance ().getCurrentUserID (), null);
} | [
"@",
"Nonnull",
"public",
"static",
"StubObject",
"createForCurrentUserAndID",
"(",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sID",
")",
"{",
"return",
"new",
"StubObject",
"(",
"sID",
",",
"LoggedInUserManager",
".",
"getInstance",
"(",
")",
".",
"... | Create a {@link StubObject} using the current user ID and the provided
object ID
@param sID
Object ID
@return Never <code>null</code>. | [
"Create",
"a",
"{",
"@link",
"StubObject",
"}",
"using",
"the",
"current",
"user",
"ID",
"and",
"the",
"provided",
"object",
"ID"
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-security/src/main/java/com/helger/photon/security/object/StubObject.java#L143-L147 |
MTDdk/jawn | jawn-core-new/src/main/java/net/javapla/jawn/core/renderers/RendererEngineOrchestratorImpl.java | RendererEngineOrchestratorImpl.mapEngine | private void mapEngine(Map<MediaType, Provider<? extends RendererEngine>> map, Provider<? extends RendererEngine> engine) {
for (MediaType type : engine.get().getContentType()) {
map.put(type, engine);
}
} | java | private void mapEngine(Map<MediaType, Provider<? extends RendererEngine>> map, Provider<? extends RendererEngine> engine) {
for (MediaType type : engine.get().getContentType()) {
map.put(type, engine);
}
} | [
"private",
"void",
"mapEngine",
"(",
"Map",
"<",
"MediaType",
",",
"Provider",
"<",
"?",
"extends",
"RendererEngine",
">",
">",
"map",
",",
"Provider",
"<",
"?",
"extends",
"RendererEngine",
">",
"engine",
")",
"{",
"for",
"(",
"MediaType",
"type",
":",
... | Map the engine to all the content types it supports.
If any kind of overlap exists, a race condition occurs
@param map
@param engine | [
"Map",
"the",
"engine",
"to",
"all",
"the",
"content",
"types",
"it",
"supports",
".",
"If",
"any",
"kind",
"of",
"overlap",
"exists",
"a",
"race",
"condition",
"occurs"
] | train | https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core-new/src/main/java/net/javapla/jawn/core/renderers/RendererEngineOrchestratorImpl.java#L105-L109 |
cqframework/clinical_quality_language | Src/java/cql-to-elm/src/main/java/org/cqframework/cql/cql2elm/Cql2ElmVisitor.java | Cql2ElmVisitor.optimizeDateRangeInQuery | public Expression optimizeDateRangeInQuery(Expression where, AliasedQuerySource aqs) {
if (aqs.getExpression() instanceof Retrieve) {
Retrieve retrieve = (Retrieve) aqs.getExpression();
String alias = aqs.getAlias();
if ((where instanceof IncludedIn || where instanceof In) && attemptDateRangeOptimization((BinaryExpression) where, retrieve, alias)) {
where = null;
}
else if (where instanceof And && attemptDateRangeOptimization((And) where, retrieve, alias)) {
// Now optimize out the trues from the Ands
where = consolidateAnd((And) where);
}
}
return where;
} | java | public Expression optimizeDateRangeInQuery(Expression where, AliasedQuerySource aqs) {
if (aqs.getExpression() instanceof Retrieve) {
Retrieve retrieve = (Retrieve) aqs.getExpression();
String alias = aqs.getAlias();
if ((where instanceof IncludedIn || where instanceof In) && attemptDateRangeOptimization((BinaryExpression) where, retrieve, alias)) {
where = null;
}
else if (where instanceof And && attemptDateRangeOptimization((And) where, retrieve, alias)) {
// Now optimize out the trues from the Ands
where = consolidateAnd((And) where);
}
}
return where;
} | [
"public",
"Expression",
"optimizeDateRangeInQuery",
"(",
"Expression",
"where",
",",
"AliasedQuerySource",
"aqs",
")",
"{",
"if",
"(",
"aqs",
".",
"getExpression",
"(",
")",
"instanceof",
"Retrieve",
")",
"{",
"Retrieve",
"retrieve",
"=",
"(",
"Retrieve",
")",
... | Some systems may wish to optimize performance by restricting retrieves with available date ranges. Specifying
date ranges in a retrieve was removed from the CQL grammar, but it is still possible to extract date ranges from
the where clause and put them in the Retrieve in ELM. The <code>optimizeDateRangeInQuery</code> method
attempts to do this automatically. If optimization is possible, it will remove the corresponding "during" from
the where clause and insert the date range into the Retrieve.
@param aqs the AliasedQuerySource containing the ClinicalRequest to possibly refactor a date range into.
@param where the Where clause to search for potential date range optimizations
@return the where clause with optimized "durings" removed, or <code>null</code> if there is no longer a Where
clause after optimization. | [
"Some",
"systems",
"may",
"wish",
"to",
"optimize",
"performance",
"by",
"restricting",
"retrieves",
"with",
"available",
"date",
"ranges",
".",
"Specifying",
"date",
"ranges",
"in",
"a",
"retrieve",
"was",
"removed",
"from",
"the",
"CQL",
"grammar",
"but",
"i... | train | https://github.com/cqframework/clinical_quality_language/blob/67459d1ef453e49db8d7c5c86e87278377ed0a0b/Src/java/cql-to-elm/src/main/java/org/cqframework/cql/cql2elm/Cql2ElmVisitor.java#L3006-L3019 |
apptik/jus | benchmark/src/perf/java/com/android/volley/toolbox/HurlStack.java | HurlStack.openConnection | private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
HttpURLConnection connection = createConnection(url);
int timeoutMs = request.getTimeoutMs();
connection.setConnectTimeout(timeoutMs);
connection.setReadTimeout(timeoutMs);
connection.setUseCaches(false);
connection.setDoInput(true);
// use caller-provided custom SslSocketFactory, if any, for HTTPS
if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
}
return connection;
} | java | private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
HttpURLConnection connection = createConnection(url);
int timeoutMs = request.getTimeoutMs();
connection.setConnectTimeout(timeoutMs);
connection.setReadTimeout(timeoutMs);
connection.setUseCaches(false);
connection.setDoInput(true);
// use caller-provided custom SslSocketFactory, if any, for HTTPS
if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
}
return connection;
} | [
"private",
"HttpURLConnection",
"openConnection",
"(",
"URL",
"url",
",",
"Request",
"<",
"?",
">",
"request",
")",
"throws",
"IOException",
"{",
"HttpURLConnection",
"connection",
"=",
"createConnection",
"(",
"url",
")",
";",
"int",
"timeoutMs",
"=",
"request"... | Opens an {@link HttpURLConnection} with parameters.
@param url
@return an open connection
@throws IOException | [
"Opens",
"an",
"{"
] | train | https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/benchmark/src/perf/java/com/android/volley/toolbox/HurlStack.java#L185-L200 |
sporniket/core | sporniket-core-io/src/main/java/com/sporniket/libre/io/TextLoader.java | TextLoader.append | public StringBuffer append(Reader source, StringBuffer buffer) throws IOException
{
BufferedReader _bufferedReader = new BufferedReader(source);
char[] _buffer = new char[getBufferSize()]; // load by chunk of 4 ko
try
{
for (int _countReadChars = 0; _countReadChars >= 0;)
{
buffer.append(_buffer, 0, _countReadChars);
_countReadChars = _bufferedReader.read(_buffer);
}
}
finally
{
_bufferedReader.close();
}
return buffer;
} | java | public StringBuffer append(Reader source, StringBuffer buffer) throws IOException
{
BufferedReader _bufferedReader = new BufferedReader(source);
char[] _buffer = new char[getBufferSize()]; // load by chunk of 4 ko
try
{
for (int _countReadChars = 0; _countReadChars >= 0;)
{
buffer.append(_buffer, 0, _countReadChars);
_countReadChars = _bufferedReader.read(_buffer);
}
}
finally
{
_bufferedReader.close();
}
return buffer;
} | [
"public",
"StringBuffer",
"append",
"(",
"Reader",
"source",
",",
"StringBuffer",
"buffer",
")",
"throws",
"IOException",
"{",
"BufferedReader",
"_bufferedReader",
"=",
"new",
"BufferedReader",
"(",
"source",
")",
";",
"char",
"[",
"]",
"_buffer",
"=",
"new",
... | Load a text from the specified reader and put it in the provided StringBuffer.
@param source source reader.
@param buffer buffer to load text into.
@return the buffer
@throws IOException if there is a problem to deal with. | [
"Load",
"a",
"text",
"from",
"the",
"specified",
"reader",
"and",
"put",
"it",
"in",
"the",
"provided",
"StringBuffer",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/TextLoader.java#L188-L205 |
kevoree/kevoree-library | mqttServer/src/main/java/org/dna/mqtt/moquette/parser/netty/Utils.java | Utils.decodeString | static String decodeString(ByteBuf in) throws UnsupportedEncodingException {
if (in.readableBytes() < 2) {
return null;
}
//int strLen = Utils.readWord(in);
int strLen = in.readUnsignedShort();
if (in.readableBytes() < strLen) {
return null;
}
byte[] strRaw = new byte[strLen];
in.readBytes(strRaw);
return new String(strRaw, "UTF-8");
} | java | static String decodeString(ByteBuf in) throws UnsupportedEncodingException {
if (in.readableBytes() < 2) {
return null;
}
//int strLen = Utils.readWord(in);
int strLen = in.readUnsignedShort();
if (in.readableBytes() < strLen) {
return null;
}
byte[] strRaw = new byte[strLen];
in.readBytes(strRaw);
return new String(strRaw, "UTF-8");
} | [
"static",
"String",
"decodeString",
"(",
"ByteBuf",
"in",
")",
"throws",
"UnsupportedEncodingException",
"{",
"if",
"(",
"in",
".",
"readableBytes",
"(",
")",
"<",
"2",
")",
"{",
"return",
"null",
";",
"}",
"//int strLen = Utils.readWord(in);",
"int",
"strLen",
... | Load a string from the given buffer, reading first the two bytes of len
and then the UTF-8 bytes of the string.
@return the decoded string or null if NEED_DATA | [
"Load",
"a",
"string",
"from",
"the",
"given",
"buffer",
"reading",
"first",
"the",
"two",
"bytes",
"of",
"len",
"and",
"then",
"the",
"UTF",
"-",
"8",
"bytes",
"of",
"the",
"string",
"."
] | train | https://github.com/kevoree/kevoree-library/blob/617460e6c5881902ebc488a31ecdea179024d8f1/mqttServer/src/main/java/org/dna/mqtt/moquette/parser/netty/Utils.java#L115-L128 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/TableWorks.java | TableWorks.addForeignKey | void addForeignKey(Constraint c) {
checkCreateForeignKey(c);
Constraint uniqueConstraint =
c.core.mainTable.getUniqueConstraintForColumns(c.core.mainCols,
c.core.refCols);
Index mainIndex = uniqueConstraint.getMainIndex();
uniqueConstraint.checkReferencedRows(session, table, c.core.refCols);
int offset = database.schemaManager.getTableIndex(table);
boolean isForward = c.core.mainTable.getSchemaName()
!= table.getSchemaName();
if (offset != -1
&& offset
< database.schemaManager.getTableIndex(c.core.mainTable)) {
isForward = true;
}
HsqlName indexName = database.nameManager.newAutoName("IDX",
table.getSchemaName(), table.getName(), SchemaObject.INDEX);
Index refIndex = table.createIndexStructure(indexName, c.core.refCols,
null, null, false, false, true, isForward);
HsqlName mainName = database.nameManager.newAutoName("REF",
c.getName().name, table.getSchemaName(), table.getName(),
SchemaObject.INDEX);
c.core.uniqueName = uniqueConstraint.getName();
c.core.mainName = mainName;
c.core.mainIndex = mainIndex;
c.core.refTable = table;
c.core.refName = c.getName();
c.core.refIndex = refIndex;
c.isForward = isForward;
Table tn = table.moveDefinition(session, table.tableType, null, c,
refIndex, -1, 0, emptySet, emptySet);
tn.moveData(session, table, -1, 0);
c.core.mainTable.addConstraint(new Constraint(mainName, c));
database.schemaManager.addSchemaObject(c);
database.persistentStoreCollection.releaseStore(table);
setNewTableInSchema(tn);
updateConstraints(tn, emptySet);
database.schemaManager.recompileDependentObjects(tn);
table = tn;
} | java | void addForeignKey(Constraint c) {
checkCreateForeignKey(c);
Constraint uniqueConstraint =
c.core.mainTable.getUniqueConstraintForColumns(c.core.mainCols,
c.core.refCols);
Index mainIndex = uniqueConstraint.getMainIndex();
uniqueConstraint.checkReferencedRows(session, table, c.core.refCols);
int offset = database.schemaManager.getTableIndex(table);
boolean isForward = c.core.mainTable.getSchemaName()
!= table.getSchemaName();
if (offset != -1
&& offset
< database.schemaManager.getTableIndex(c.core.mainTable)) {
isForward = true;
}
HsqlName indexName = database.nameManager.newAutoName("IDX",
table.getSchemaName(), table.getName(), SchemaObject.INDEX);
Index refIndex = table.createIndexStructure(indexName, c.core.refCols,
null, null, false, false, true, isForward);
HsqlName mainName = database.nameManager.newAutoName("REF",
c.getName().name, table.getSchemaName(), table.getName(),
SchemaObject.INDEX);
c.core.uniqueName = uniqueConstraint.getName();
c.core.mainName = mainName;
c.core.mainIndex = mainIndex;
c.core.refTable = table;
c.core.refName = c.getName();
c.core.refIndex = refIndex;
c.isForward = isForward;
Table tn = table.moveDefinition(session, table.tableType, null, c,
refIndex, -1, 0, emptySet, emptySet);
tn.moveData(session, table, -1, 0);
c.core.mainTable.addConstraint(new Constraint(mainName, c));
database.schemaManager.addSchemaObject(c);
database.persistentStoreCollection.releaseStore(table);
setNewTableInSchema(tn);
updateConstraints(tn, emptySet);
database.schemaManager.recompileDependentObjects(tn);
table = tn;
} | [
"void",
"addForeignKey",
"(",
"Constraint",
"c",
")",
"{",
"checkCreateForeignKey",
"(",
"c",
")",
";",
"Constraint",
"uniqueConstraint",
"=",
"c",
".",
"core",
".",
"mainTable",
".",
"getUniqueConstraintForColumns",
"(",
"c",
".",
"core",
".",
"mainCols",
","... | Creates a foreign key on an existing table. Foreign keys are enforced by
indexes on both the referencing (child) and referenced (main) tables.
<p> Since version 1.7.2, a unique constraint on the referenced columns
must exist. The non-unique index on the referencing table is now always
created whether or not a PK or unique constraint index on the columns
exist. Foriegn keys on temp tables can reference other temp tables with
the same rules above. Foreign keys on permanent tables cannot reference
temp tables. Duplicate foreign keys are now disallowed.
@param c the constraint object | [
"Creates",
"a",
"foreign",
"key",
"on",
"an",
"existing",
"table",
".",
"Foreign",
"keys",
"are",
"enforced",
"by",
"indexes",
"on",
"both",
"the",
"referencing",
"(",
"child",
")",
"and",
"referenced",
"(",
"main",
")",
"tables",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/TableWorks.java#L159-L208 |
teatrove/teatrove | teaapps/src/main/java/org/teatrove/teaapps/contexts/HttpContext.java | HttpContext.doSecurePost | public String doSecurePost(String host, String path, String postData,
int port, Map<String, String> headers,
int timeout)
throws UnknownHostException, ConnectException, IOException {
return doHttpCall(host, path, postData, port, headers, timeout, true);
} | java | public String doSecurePost(String host, String path, String postData,
int port, Map<String, String> headers,
int timeout)
throws UnknownHostException, ConnectException, IOException {
return doHttpCall(host, path, postData, port, headers, timeout, true);
} | [
"public",
"String",
"doSecurePost",
"(",
"String",
"host",
",",
"String",
"path",
",",
"String",
"postData",
",",
"int",
"port",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
",",
"int",
"timeout",
")",
"throws",
"UnknownHostException",
",",
"C... | Perform a secure HTTPS POST at the given path sending in the given post
data returning the results of the response.
@param host The hostname of the request
@param path The path of the request
@param postData The POST data to send in the request
@param port The port of the request
@param headers The headers to pass in the request
@param timeout The timeout of the request in milliseconds
@return The data of the resposne
@throws UnknownHostException if the host cannot be found
@throws ConnectException if the HTTP server does not respond
@throws IOException if an I/O error occurs processing the request | [
"Perform",
"a",
"secure",
"HTTPS",
"POST",
"at",
"the",
"given",
"path",
"sending",
"in",
"the",
"given",
"post",
"data",
"returning",
"the",
"results",
"of",
"the",
"response",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/teaapps/src/main/java/org/teatrove/teaapps/contexts/HttpContext.java#L132-L138 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/MessagesApi.java | MessagesApi.getLastNormalizedMessagesAsync | public com.squareup.okhttp.Call getLastNormalizedMessagesAsync(Integer count, String sdids, String fieldPresence, final ApiCallback<NormalizedMessagesEnvelope> 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 = getLastNormalizedMessagesValidateBeforeCall(count, sdids, fieldPresence, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<NormalizedMessagesEnvelope>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | java | public com.squareup.okhttp.Call getLastNormalizedMessagesAsync(Integer count, String sdids, String fieldPresence, final ApiCallback<NormalizedMessagesEnvelope> 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 = getLastNormalizedMessagesValidateBeforeCall(count, sdids, fieldPresence, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<NormalizedMessagesEnvelope>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"getLastNormalizedMessagesAsync",
"(",
"Integer",
"count",
",",
"String",
"sdids",
",",
"String",
"fieldPresence",
",",
"final",
"ApiCallback",
"<",
"NormalizedMessagesEnvelope",
">",
"callback",
")",
"... | Get Last Normalized Message (asynchronously)
Get last messages normalized.
@param count Number of items to return per query. (optional)
@param sdids Comma separated list of source device IDs (minimum: 1). (optional)
@param fieldPresence String representing a field from the specified device ID. (optional)
@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 | [
"Get",
"Last",
"Normalized",
"Message",
"(",
"asynchronously",
")",
"Get",
"last",
"messages",
"normalized",
"."
] | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/MessagesApi.java#L459-L484 |
JOML-CI/JOML | src/org/joml/Matrix4x3f.java | Matrix4x3f.translationRotate | public Matrix4x3f translationRotate(float tx, float ty, float tz, Quaternionfc quat) {
float dqx = quat.x() + quat.x();
float dqy = quat.y() + quat.y();
float dqz = quat.z() + quat.z();
float q00 = dqx * quat.x();
float q11 = dqy * quat.y();
float q22 = dqz * quat.z();
float q01 = dqx * quat.y();
float q02 = dqx * quat.z();
float q03 = dqx * quat.w();
float q12 = dqy * quat.z();
float q13 = dqy * quat.w();
float q23 = dqz * quat.w();
m00 = 1.0f - (q11 + q22);
m01 = q01 + q23;
m02 = q02 - q13;
m10 = q01 - q23;
m11 = 1.0f - (q22 + q00);
m12 = q12 + q03;
m20 = q02 + q13;
m21 = q12 - q03;
m22 = 1.0f - (q11 + q00);
m30 = tx;
m31 = ty;
m32 = tz;
properties = PROPERTY_ORTHONORMAL;
return this;
} | java | public Matrix4x3f translationRotate(float tx, float ty, float tz, Quaternionfc quat) {
float dqx = quat.x() + quat.x();
float dqy = quat.y() + quat.y();
float dqz = quat.z() + quat.z();
float q00 = dqx * quat.x();
float q11 = dqy * quat.y();
float q22 = dqz * quat.z();
float q01 = dqx * quat.y();
float q02 = dqx * quat.z();
float q03 = dqx * quat.w();
float q12 = dqy * quat.z();
float q13 = dqy * quat.w();
float q23 = dqz * quat.w();
m00 = 1.0f - (q11 + q22);
m01 = q01 + q23;
m02 = q02 - q13;
m10 = q01 - q23;
m11 = 1.0f - (q22 + q00);
m12 = q12 + q03;
m20 = q02 + q13;
m21 = q12 - q03;
m22 = 1.0f - (q11 + q00);
m30 = tx;
m31 = ty;
m32 = tz;
properties = PROPERTY_ORTHONORMAL;
return this;
} | [
"public",
"Matrix4x3f",
"translationRotate",
"(",
"float",
"tx",
",",
"float",
"ty",
",",
"float",
"tz",
",",
"Quaternionfc",
"quat",
")",
"{",
"float",
"dqx",
"=",
"quat",
".",
"x",
"(",
")",
"+",
"quat",
".",
"x",
"(",
")",
";",
"float",
"dqy",
"... | Set <code>this</code> matrix to <code>T * R</code>, where <code>T</code> is a translation by the given <code>(tx, ty, tz)</code> and
<code>R</code> is a rotation transformation specified by the given quaternion.
<p>
When transforming a vector by the resulting matrix the rotation transformation will be applied first and then the translation.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
This method is equivalent to calling: <code>translation(tx, ty, tz).rotate(quat)</code>
@see #translation(float, float, float)
@see #rotate(Quaternionfc)
@param tx
the number of units by which to translate the x-component
@param ty
the number of units by which to translate the y-component
@param tz
the number of units by which to translate the z-component
@param quat
the quaternion representing a rotation
@return this | [
"Set",
"<code",
">",
"this<",
"/",
"code",
">",
"matrix",
"to",
"<code",
">",
"T",
"*",
"R<",
"/",
"code",
">",
"where",
"<code",
">",
"T<",
"/",
"code",
">",
"is",
"a",
"translation",
"by",
"the",
"given",
"<code",
">",
"(",
"tx",
"ty",
"tz",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3f.java#L2900-L2927 |
Alluxio/alluxio | examples/src/main/java/alluxio/examples/Performance.java | Performance.logPerIteration | public static void logPerIteration(long startTimeMs, int times, String msg, int workerId) {
long takenTimeMs = System.currentTimeMillis() - startTimeMs;
double result = 1000.0 * sFileBytes / takenTimeMs / 1024 / 1024;
LOG.info(times + msg + workerId + " : " + result + " Mb/sec. Took " + takenTimeMs + " ms. ");
} | java | public static void logPerIteration(long startTimeMs, int times, String msg, int workerId) {
long takenTimeMs = System.currentTimeMillis() - startTimeMs;
double result = 1000.0 * sFileBytes / takenTimeMs / 1024 / 1024;
LOG.info(times + msg + workerId + " : " + result + " Mb/sec. Took " + takenTimeMs + " ms. ");
} | [
"public",
"static",
"void",
"logPerIteration",
"(",
"long",
"startTimeMs",
",",
"int",
"times",
",",
"String",
"msg",
",",
"int",
"workerId",
")",
"{",
"long",
"takenTimeMs",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"startTimeMs",
";",
"double... | Writes log information.
@param startTimeMs the start time in milliseconds
@param times the number of the iteration
@param msg the message
@param workerId the id of the worker | [
"Writes",
"log",
"information",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/examples/src/main/java/alluxio/examples/Performance.java#L75-L79 |
rhiot/rhiot | gateway/components/camel-webcam/src/main/java/io/rhiot/gateway/camel/webcam/WebcamHelper.java | WebcamHelper.consumeWebcamMotionEvent | public static void consumeWebcamMotionEvent(WebcamMotionEvent motionEvent, Processor processor, WebcamEndpoint endpoint, ExceptionHandler exceptionHandler){
Validate.notNull(motionEvent);
Validate.notNull(processor);
Validate.notNull(endpoint);
try {
Exchange exchange = createOutOnlyExchangeWithBodyAndHeaders(endpoint, motionEvent.getCurrentImage());
exchange.getIn().setHeader(WebcamConstants.WEBCAM_MOTION_EVENT_HEADER, motionEvent);
processor.process(exchange);
} catch (Exception e) {
exceptionHandler.handleException(e);
}
} | java | public static void consumeWebcamMotionEvent(WebcamMotionEvent motionEvent, Processor processor, WebcamEndpoint endpoint, ExceptionHandler exceptionHandler){
Validate.notNull(motionEvent);
Validate.notNull(processor);
Validate.notNull(endpoint);
try {
Exchange exchange = createOutOnlyExchangeWithBodyAndHeaders(endpoint, motionEvent.getCurrentImage());
exchange.getIn().setHeader(WebcamConstants.WEBCAM_MOTION_EVENT_HEADER, motionEvent);
processor.process(exchange);
} catch (Exception e) {
exceptionHandler.handleException(e);
}
} | [
"public",
"static",
"void",
"consumeWebcamMotionEvent",
"(",
"WebcamMotionEvent",
"motionEvent",
",",
"Processor",
"processor",
",",
"WebcamEndpoint",
"endpoint",
",",
"ExceptionHandler",
"exceptionHandler",
")",
"{",
"Validate",
".",
"notNull",
"(",
"motionEvent",
")",... | Consume the motion event from the webcam, all params required.
The event is stored in the header while the latest image is available as the body.
@param motionEvent The motion event that triggered.
@param processor Processor that handles the exchange.
@param endpoint WebcamEndpoint receiving the exchange. | [
"Consume",
"the",
"motion",
"event",
"from",
"the",
"webcam",
"all",
"params",
"required",
".",
"The",
"event",
"is",
"stored",
"in",
"the",
"header",
"while",
"the",
"latest",
"image",
"is",
"available",
"as",
"the",
"body",
"."
] | train | https://github.com/rhiot/rhiot/blob/82eac10e365f72bab9248b8c3bd0ec9a2fc0a721/gateway/components/camel-webcam/src/main/java/io/rhiot/gateway/camel/webcam/WebcamHelper.java#L87-L99 |
phax/ph-oton | ph-oton-core/src/main/java/com/helger/photon/core/form/FormErrorList.java | FormErrorList.addFieldInfo | public void addFieldInfo (@Nonnull @Nonempty final String sFieldName, @Nonnull @Nonempty final String sText)
{
add (SingleError.builderInfo ().setErrorFieldName (sFieldName).setErrorText (sText).build ());
} | java | public void addFieldInfo (@Nonnull @Nonempty final String sFieldName, @Nonnull @Nonempty final String sText)
{
add (SingleError.builderInfo ().setErrorFieldName (sFieldName).setErrorText (sText).build ());
} | [
"public",
"void",
"addFieldInfo",
"(",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sFieldName",
",",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sText",
")",
"{",
"add",
"(",
"SingleError",
".",
"builderInfo",
"(",
")",
".",
"setErrorFieldN... | Add a field specific information message.
@param sFieldName
The field name for which the message is to be recorded. May neither
be <code>null</code> nor empty.
@param sText
The text to use. May neither be <code>null</code> nor empty. | [
"Add",
"a",
"field",
"specific",
"information",
"message",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-core/src/main/java/com/helger/photon/core/form/FormErrorList.java#L52-L55 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java | FirstNonNullHelper.firstNonNull | public static <T, R> R firstNonNull(Function<T, R> function, Supplier<Collection<T>>... suppliers) {
Stream<Supplier<R>> resultStream = Stream.of(suppliers)
.map(s -> (() -> firstNonNull(function, s.get())));
return firstNonNull(Supplier::get, resultStream);
} | java | public static <T, R> R firstNonNull(Function<T, R> function, Supplier<Collection<T>>... suppliers) {
Stream<Supplier<R>> resultStream = Stream.of(suppliers)
.map(s -> (() -> firstNonNull(function, s.get())));
return firstNonNull(Supplier::get, resultStream);
} | [
"public",
"static",
"<",
"T",
",",
"R",
">",
"R",
"firstNonNull",
"(",
"Function",
"<",
"T",
",",
"R",
">",
"function",
",",
"Supplier",
"<",
"Collection",
"<",
"T",
">",
">",
"...",
"suppliers",
")",
"{",
"Stream",
"<",
"Supplier",
"<",
"R",
">>",... | Gets first result of function which is not null.
@param <T> type of values.
@param <R> element to return.
@param function function to apply to each value.
@param suppliers all possible suppliers that might be able to supply a value.
@return first result which was not null,
OR <code>null</code> if result for all supplier's values was <code>null</code>. | [
"Gets",
"first",
"result",
"of",
"function",
"which",
"is",
"not",
"null",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java#L64-L68 |
aws/aws-sdk-java | aws-java-sdk-backup/src/main/java/com/amazonaws/services/backup/model/CreateBackupVaultRequest.java | CreateBackupVaultRequest.withBackupVaultTags | public CreateBackupVaultRequest withBackupVaultTags(java.util.Map<String, String> backupVaultTags) {
setBackupVaultTags(backupVaultTags);
return this;
} | java | public CreateBackupVaultRequest withBackupVaultTags(java.util.Map<String, String> backupVaultTags) {
setBackupVaultTags(backupVaultTags);
return this;
} | [
"public",
"CreateBackupVaultRequest",
"withBackupVaultTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"backupVaultTags",
")",
"{",
"setBackupVaultTags",
"(",
"backupVaultTags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Metadata that you can assign to help organize the resources that you create. Each tag is a key-value pair.
</p>
@param backupVaultTags
Metadata that you can assign to help organize the resources that you create. Each tag is a key-value pair.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Metadata",
"that",
"you",
"can",
"assign",
"to",
"help",
"organize",
"the",
"resources",
"that",
"you",
"create",
".",
"Each",
"tag",
"is",
"a",
"key",
"-",
"value",
"pair",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-backup/src/main/java/com/amazonaws/services/backup/model/CreateBackupVaultRequest.java#L145-L148 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBindingFactory.java | SwingBindingFactory.createBoundShuttleList | public Binding createBoundShuttleList( String selectionFormProperty, Object selectableItems ) {
return createBoundShuttleList(selectionFormProperty, new ValueHolder(selectableItems), null);
} | java | public Binding createBoundShuttleList( String selectionFormProperty, Object selectableItems ) {
return createBoundShuttleList(selectionFormProperty, new ValueHolder(selectableItems), null);
} | [
"public",
"Binding",
"createBoundShuttleList",
"(",
"String",
"selectionFormProperty",
",",
"Object",
"selectableItems",
")",
"{",
"return",
"createBoundShuttleList",
"(",
"selectionFormProperty",
",",
"new",
"ValueHolder",
"(",
"selectableItems",
")",
",",
"null",
")",... | Binds the values specified in the collection contained within
<code>selectableItems</code> (which will be wrapped in a
{@link ValueHolder} to a {@link ShuttleList}, with any user selection
being placed in the form property referred to by
<code>selectionFormProperty</code>. Each item in the list will be
rendered as a String.
<p>
Note that the selection in the bound list will track any changes to the
<code>selectionFormProperty</code>. This is especially useful to
preselect items in the list - if <code>selectionFormProperty</code> is
not empty when the list is bound, then its content will be used for the
initial selection.
@param selectionFormProperty form property to hold user's selection. This
property must be a <code>Collection</code> or array type.
@param selectableItems Collection or array containing the items with
which to populate the selectable list (this object will be wrapped
in a ValueHolder).
@return constructed {@link Binding}. Note that the bound control is of
type {@link ShuttleList}. Access this component to set specific
display properties. | [
"Binds",
"the",
"values",
"specified",
"in",
"the",
"collection",
"contained",
"within",
"<code",
">",
"selectableItems<",
"/",
"code",
">",
"(",
"which",
"will",
"be",
"wrapped",
"in",
"a",
"{",
"@link",
"ValueHolder",
"}",
"to",
"a",
"{",
"@link",
"Shutt... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBindingFactory.java#L414-L416 |
apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/source/workunit/Extract.java | Extract.addDeltaField | @Deprecated
public void addDeltaField(String... deltaFieldName) {
StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, ""));
Joiner.on(",").appendTo(sb, deltaFieldName);
setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, sb.toString());
} | java | @Deprecated
public void addDeltaField(String... deltaFieldName) {
StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, ""));
Joiner.on(",").appendTo(sb, deltaFieldName);
setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, sb.toString());
} | [
"@",
"Deprecated",
"public",
"void",
"addDeltaField",
"(",
"String",
"...",
"deltaFieldName",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"getProp",
"(",
"ConfigurationKeys",
".",
"EXTRACT_DELTA_FIELDS_KEY",
",",
"\"\"",
")",
")",
";",
"Jo... | Add more delta fields to the existing set of delta fields.
@param deltaFieldName delta field names
@deprecated It is recommended to add delta fields in {@code WorkUnit} instead of {@code Extract}. | [
"Add",
"more",
"delta",
"fields",
"to",
"the",
"existing",
"set",
"of",
"delta",
"fields",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/Extract.java#L286-L291 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java | ImageModerationsImpl.oCRMethodAsync | public Observable<OCR> oCRMethodAsync(String language, OCRMethodOptionalParameter oCRMethodOptionalParameter) {
return oCRMethodWithServiceResponseAsync(language, oCRMethodOptionalParameter).map(new Func1<ServiceResponse<OCR>, OCR>() {
@Override
public OCR call(ServiceResponse<OCR> response) {
return response.body();
}
});
} | java | public Observable<OCR> oCRMethodAsync(String language, OCRMethodOptionalParameter oCRMethodOptionalParameter) {
return oCRMethodWithServiceResponseAsync(language, oCRMethodOptionalParameter).map(new Func1<ServiceResponse<OCR>, OCR>() {
@Override
public OCR call(ServiceResponse<OCR> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OCR",
">",
"oCRMethodAsync",
"(",
"String",
"language",
",",
"OCRMethodOptionalParameter",
"oCRMethodOptionalParameter",
")",
"{",
"return",
"oCRMethodWithServiceResponseAsync",
"(",
"language",
",",
"oCRMethodOptionalParameter",
")",
".",
"m... | Returns any text found in the image for the language specified. If no language is specified in input then the detection defaults to English.
@param language Language of the terms.
@param oCRMethodOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OCR object | [
"Returns",
"any",
"text",
"found",
"in",
"the",
"image",
"for",
"the",
"language",
"specified",
".",
"If",
"no",
"language",
"is",
"specified",
"in",
"input",
"then",
"the",
"detection",
"defaults",
"to",
"English",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java#L295-L302 |
phax/ph-commons | ph-jaxb/src/main/java/com/helger/jaxb/JAXBMarshallerHelper.java | JAXBMarshallerHelper.setEncoding | public static void setEncoding (@Nonnull final Marshaller aMarshaller, @Nullable final Charset aEncoding)
{
setEncoding (aMarshaller, aEncoding == null ? null : aEncoding.name ());
} | java | public static void setEncoding (@Nonnull final Marshaller aMarshaller, @Nullable final Charset aEncoding)
{
setEncoding (aMarshaller, aEncoding == null ? null : aEncoding.name ());
} | [
"public",
"static",
"void",
"setEncoding",
"(",
"@",
"Nonnull",
"final",
"Marshaller",
"aMarshaller",
",",
"@",
"Nullable",
"final",
"Charset",
"aEncoding",
")",
"{",
"setEncoding",
"(",
"aMarshaller",
",",
"aEncoding",
"==",
"null",
"?",
"null",
":",
"aEncodi... | Set the standard property for the encoding charset.
@param aMarshaller
The marshaller to set the property. May not be <code>null</code>.
@param aEncoding
the value to be set | [
"Set",
"the",
"standard",
"property",
"for",
"the",
"encoding",
"charset",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-jaxb/src/main/java/com/helger/jaxb/JAXBMarshallerHelper.java#L98-L101 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/servlet/job/impl/PrintJobEntryImpl.java | PrintJobEntryImpl.configureAccess | public final void configureAccess(final Template template, final ApplicationContext context) {
final Configuration configuration = template.getConfiguration();
AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);
accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());
this.access = accessAssertion;
} | java | public final void configureAccess(final Template template, final ApplicationContext context) {
final Configuration configuration = template.getConfiguration();
AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);
accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());
this.access = accessAssertion;
} | [
"public",
"final",
"void",
"configureAccess",
"(",
"final",
"Template",
"template",
",",
"final",
"ApplicationContext",
"context",
")",
"{",
"final",
"Configuration",
"configuration",
"=",
"template",
".",
"getConfiguration",
"(",
")",
";",
"AndAccessAssertion",
"ac... | Configure the access permissions required to access this print job.
@param template the containing print template which should have sufficient information to
configure the access.
@param context the application context | [
"Configure",
"the",
"access",
"permissions",
"required",
"to",
"access",
"this",
"print",
"job",
"."
] | train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/servlet/job/impl/PrintJobEntryImpl.java#L144-L150 |
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.pauseAsync | public Observable<Void> pauseAsync(String resourceGroupName, String serverName, String databaseName) {
return pauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> pauseAsync(String resourceGroupName, String serverName, String databaseName) {
return pauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"pauseAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
")",
"{",
"return",
"pauseWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
",",
"databaseName... | Pauses a data warehouse.
@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 data warehouse to pause.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Pauses",
"a",
"data",
"warehouse",
"."
] | 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#L196-L203 |
cverges/expect4j | src/main/java/expect4j/Expect4j.java | Expect4j.expect | public int expect(String pattern) throws MalformedPatternException, Exception {
logger.trace("Searching for '" + pattern + "' in the reader stream");
return expect(pattern, null);
} | java | public int expect(String pattern) throws MalformedPatternException, Exception {
logger.trace("Searching for '" + pattern + "' in the reader stream");
return expect(pattern, null);
} | [
"public",
"int",
"expect",
"(",
"String",
"pattern",
")",
"throws",
"MalformedPatternException",
",",
"Exception",
"{",
"logger",
".",
"trace",
"(",
"\"Searching for '\"",
"+",
"pattern",
"+",
"\"' in the reader stream\"",
")",
";",
"return",
"expect",
"(",
"patte... | Attempts to detect the provided pattern as an exact match.
@param pattern the pattern to find in the reader stream
@return the number of times the pattern is found,
or an error code
@throws MalformedPatternException if the pattern is invalid
@throws Exception if a generic error is encountered | [
"Attempts",
"to",
"detect",
"the",
"provided",
"pattern",
"as",
"an",
"exact",
"match",
"."
] | train | https://github.com/cverges/expect4j/blob/97b1da9b7bd231344cd7b7ce26d14caf8bb16cd6/src/main/java/expect4j/Expect4j.java#L261-L264 |
Whiley/WhileyCompiler | src/main/java/wyil/transform/VerificationConditionGenerator.java | VerificationConditionGenerator.invertCondition | public Expr invertCondition(Expr expr, WyilFile.Expr elem) {
if (expr instanceof Expr.Operator) {
Expr.Operator binTest = (Expr.Operator) expr;
switch (binTest.getOpcode()) {
case WyalFile.EXPR_eq:
return new Expr.NotEqual(binTest.getAll());
case WyalFile.EXPR_neq:
return new Expr.Equal(binTest.getAll());
case WyalFile.EXPR_gteq:
return new Expr.LessThan(binTest.getAll());
case WyalFile.EXPR_gt:
return new Expr.LessThanOrEqual(binTest.getAll());
case WyalFile.EXPR_lteq:
return new Expr.GreaterThan(binTest.getAll());
case WyalFile.EXPR_lt:
return new Expr.GreaterThanOrEqual(binTest.getAll());
case WyalFile.EXPR_and: {
Expr[] operands = invertConditions(binTest.getAll(), elem);
return new Expr.LogicalOr(operands);
}
case WyalFile.EXPR_or: {
Expr[] operands = invertConditions(binTest.getAll(), elem);
return new Expr.LogicalAnd(operands);
}
}
} else if (expr instanceof Expr.Is) {
Expr.Is ei = (Expr.Is) expr;
WyalFile.Type type = ei.getTestType();
return new Expr.Is(ei.getTestExpr(), new WyalFile.Type.Negation(type));
}
// Otherwise, compare against false
// FIXME: this is just wierd and needs to be fixed.
return new Expr.LogicalNot(expr);
} | java | public Expr invertCondition(Expr expr, WyilFile.Expr elem) {
if (expr instanceof Expr.Operator) {
Expr.Operator binTest = (Expr.Operator) expr;
switch (binTest.getOpcode()) {
case WyalFile.EXPR_eq:
return new Expr.NotEqual(binTest.getAll());
case WyalFile.EXPR_neq:
return new Expr.Equal(binTest.getAll());
case WyalFile.EXPR_gteq:
return new Expr.LessThan(binTest.getAll());
case WyalFile.EXPR_gt:
return new Expr.LessThanOrEqual(binTest.getAll());
case WyalFile.EXPR_lteq:
return new Expr.GreaterThan(binTest.getAll());
case WyalFile.EXPR_lt:
return new Expr.GreaterThanOrEqual(binTest.getAll());
case WyalFile.EXPR_and: {
Expr[] operands = invertConditions(binTest.getAll(), elem);
return new Expr.LogicalOr(operands);
}
case WyalFile.EXPR_or: {
Expr[] operands = invertConditions(binTest.getAll(), elem);
return new Expr.LogicalAnd(operands);
}
}
} else if (expr instanceof Expr.Is) {
Expr.Is ei = (Expr.Is) expr;
WyalFile.Type type = ei.getTestType();
return new Expr.Is(ei.getTestExpr(), new WyalFile.Type.Negation(type));
}
// Otherwise, compare against false
// FIXME: this is just wierd and needs to be fixed.
return new Expr.LogicalNot(expr);
} | [
"public",
"Expr",
"invertCondition",
"(",
"Expr",
"expr",
",",
"WyilFile",
".",
"Expr",
"elem",
")",
"{",
"if",
"(",
"expr",
"instanceof",
"Expr",
".",
"Operator",
")",
"{",
"Expr",
".",
"Operator",
"binTest",
"=",
"(",
"Expr",
".",
"Operator",
")",
"e... | Generate the logically inverted expression corresponding to a given
comparator. For example, inverting "<=" gives ">", inverting "==" gives "!=",
etc.
@param test
--- the binary comparator being inverted.
@return | [
"Generate",
"the",
"logically",
"inverted",
"expression",
"corresponding",
"to",
"a",
"given",
"comparator",
".",
"For",
"example",
"inverting",
"<",
"=",
"gives",
">",
"inverting",
"==",
"gives",
"!",
"=",
"etc",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L2530-L2563 |
google/closure-compiler | src/com/google/javascript/jscomp/TypeValidator.java | TypeValidator.expectObject | boolean expectObject(Node n, JSType type, String msg) {
if (!type.matchesObjectContext()) {
mismatch(n, msg, type, OBJECT_TYPE);
return false;
}
return true;
} | java | boolean expectObject(Node n, JSType type, String msg) {
if (!type.matchesObjectContext()) {
mismatch(n, msg, type, OBJECT_TYPE);
return false;
}
return true;
} | [
"boolean",
"expectObject",
"(",
"Node",
"n",
",",
"JSType",
"type",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"!",
"type",
".",
"matchesObjectContext",
"(",
")",
")",
"{",
"mismatch",
"(",
"n",
",",
"msg",
",",
"type",
",",
"OBJECT_TYPE",
")",
";",
... | Expect the type to be an object, or a type convertible to object. If the expectation is not
met, issue a warning at the provided node's source code position.
@return True if there was no warning, false if there was a mismatch. | [
"Expect",
"the",
"type",
"to",
"be",
"an",
"object",
"or",
"a",
"type",
"convertible",
"to",
"object",
".",
"If",
"the",
"expectation",
"is",
"not",
"met",
"issue",
"a",
"warning",
"at",
"the",
"provided",
"node",
"s",
"source",
"code",
"position",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeValidator.java#L249-L255 |
belaban/JGroups | src/org/jgroups/protocols/pbcast/FLUSH.java | FLUSH.down | public Object down(Event evt) {
if(!bypass){
switch (evt.getType()) {
case Event.CONNECT:
case Event.CONNECT_USE_FLUSH:
return handleConnect(evt,true);
case Event.CONNECT_WITH_STATE_TRANSFER:
case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH:
return handleConnect(evt, false);
case Event.SUSPEND:
startFlush(evt);
return null;
// only for testing, see FLUSH#testFlushWithCrashedFlushCoordinator
case Event.SUSPEND_BUT_FAIL:
if (!flushInProgress.get()) {
flush_promise.reset();
ArrayList<Address> flushParticipants = null;
synchronized (sharedLock) {
flushParticipants = new ArrayList<>(currentView.getMembers());
}
onSuspend(flushParticipants);
}
break;
case Event.RESUME:
onResume(evt);
return null;
case Event.SET_LOCAL_ADDRESS:
localAddress =evt.getArg();
break;
}
}
return down_prot.down(evt);
} | java | public Object down(Event evt) {
if(!bypass){
switch (evt.getType()) {
case Event.CONNECT:
case Event.CONNECT_USE_FLUSH:
return handleConnect(evt,true);
case Event.CONNECT_WITH_STATE_TRANSFER:
case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH:
return handleConnect(evt, false);
case Event.SUSPEND:
startFlush(evt);
return null;
// only for testing, see FLUSH#testFlushWithCrashedFlushCoordinator
case Event.SUSPEND_BUT_FAIL:
if (!flushInProgress.get()) {
flush_promise.reset();
ArrayList<Address> flushParticipants = null;
synchronized (sharedLock) {
flushParticipants = new ArrayList<>(currentView.getMembers());
}
onSuspend(flushParticipants);
}
break;
case Event.RESUME:
onResume(evt);
return null;
case Event.SET_LOCAL_ADDRESS:
localAddress =evt.getArg();
break;
}
}
return down_prot.down(evt);
} | [
"public",
"Object",
"down",
"(",
"Event",
"evt",
")",
"{",
"if",
"(",
"!",
"bypass",
")",
"{",
"switch",
"(",
"evt",
".",
"getType",
"(",
")",
")",
"{",
"case",
"Event",
".",
"CONNECT",
":",
"case",
"Event",
".",
"CONNECT_USE_FLUSH",
":",
"return",
... | /*
------------------- end JMX attributes and operations --------------------- | [
"/",
"*",
"-------------------",
"end",
"JMX",
"attributes",
"and",
"operations",
"---------------------"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/protocols/pbcast/FLUSH.java#L262-L299 |
airbnb/AirMapView | library/src/main/java/com/airbnb/android/airmapview/RuntimePermissionUtils.java | RuntimePermissionUtils.hasSelfPermissions | private static boolean hasSelfPermissions(Context context, String... permissions) {
for (String permission : permissions) {
if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {
return true;
}
}
return false;
} | java | private static boolean hasSelfPermissions(Context context, String... permissions) {
for (String permission : permissions) {
if (checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"hasSelfPermissions",
"(",
"Context",
"context",
",",
"String",
"...",
"permissions",
")",
"{",
"for",
"(",
"String",
"permission",
":",
"permissions",
")",
"{",
"if",
"(",
"checkSelfPermission",
"(",
"context",
",",
"permission",... | Returns true if the context has access to any given permissions. | [
"Returns",
"true",
"if",
"the",
"context",
"has",
"access",
"to",
"any",
"given",
"permissions",
"."
] | train | https://github.com/airbnb/AirMapView/blob/f715197db2cc2903e8d70f78385d339c3f6a1c3b/library/src/main/java/com/airbnb/android/airmapview/RuntimePermissionUtils.java#L41-L48 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/NonRecycleableTaglibs.java | NonRecycleableTaglibs.getAttributes | private static Map<QMethod, String> getAttributes(JavaClass cls) {
Map<QMethod, String> atts = new HashMap<>();
Method[] methods = cls.getMethods();
for (Method m : methods) {
String name = m.getName();
if (name.startsWith("set") && m.isPublic() && !m.isStatic()) {
String sig = m.getSignature();
List<String> args = SignatureUtils.getParameterSignatures(sig);
if ((args.size() == 1) && Values.SIG_VOID.equals(SignatureUtils.getReturnSignature(sig))) {
String parmSig = args.get(0);
if (validAttrTypes.contains(parmSig)) {
Code code = m.getCode();
if ((code != null) && (code.getCode().length < MAX_ATTRIBUTE_CODE_LENGTH)) {
atts.put(new QMethod(name, sig), parmSig);
}
}
}
}
}
return atts;
} | java | private static Map<QMethod, String> getAttributes(JavaClass cls) {
Map<QMethod, String> atts = new HashMap<>();
Method[] methods = cls.getMethods();
for (Method m : methods) {
String name = m.getName();
if (name.startsWith("set") && m.isPublic() && !m.isStatic()) {
String sig = m.getSignature();
List<String> args = SignatureUtils.getParameterSignatures(sig);
if ((args.size() == 1) && Values.SIG_VOID.equals(SignatureUtils.getReturnSignature(sig))) {
String parmSig = args.get(0);
if (validAttrTypes.contains(parmSig)) {
Code code = m.getCode();
if ((code != null) && (code.getCode().length < MAX_ATTRIBUTE_CODE_LENGTH)) {
atts.put(new QMethod(name, sig), parmSig);
}
}
}
}
}
return atts;
} | [
"private",
"static",
"Map",
"<",
"QMethod",
",",
"String",
">",
"getAttributes",
"(",
"JavaClass",
"cls",
")",
"{",
"Map",
"<",
"QMethod",
",",
"String",
">",
"atts",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"Method",
"[",
"]",
"methods",
"=",
"cl... | collect all possible attributes given the name of methods available.
@param cls
the class to look for setter methods to infer properties
@return the map of possible attributes/types | [
"collect",
"all",
"possible",
"attributes",
"given",
"the",
"name",
"of",
"methods",
"available",
"."
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/NonRecycleableTaglibs.java#L120-L140 |
spring-projects/spring-android | spring-android-rest-template/src/main/java/org/springframework/http/client/AbstractClientHttpRequestFactoryWrapper.java | AbstractClientHttpRequestFactoryWrapper.createRequest | public final ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
return createRequest(uri, httpMethod, requestFactory);
} | java | public final ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
return createRequest(uri, httpMethod, requestFactory);
} | [
"public",
"final",
"ClientHttpRequest",
"createRequest",
"(",
"URI",
"uri",
",",
"HttpMethod",
"httpMethod",
")",
"throws",
"IOException",
"{",
"return",
"createRequest",
"(",
"uri",
",",
"httpMethod",
",",
"requestFactory",
")",
";",
"}"
] | This implementation simply calls {@link #createRequest(URI, HttpMethod, ClientHttpRequestFactory)}
with the wrapped request factory provided to the
{@linkplain #AbstractClientHttpRequestFactoryWrapper(ClientHttpRequestFactory) constructor}. | [
"This",
"implementation",
"simply",
"calls",
"{"
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-rest-template/src/main/java/org/springframework/http/client/AbstractClientHttpRequestFactoryWrapper.java#L51-L53 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/Step.java | Step.updateRadioList | protected void updateRadioList(PageElement pageElement, String valueKeyOrKey, Map<String, String> printedValues) throws TechnicalException, FailureException {
final String valueKey = Context.getValue(valueKeyOrKey) != null ? Context.getValue(valueKeyOrKey) : valueKeyOrKey;
try {
final List<WebElement> radioButtons = Context.waitUntil(ExpectedConditions.presenceOfAllElementsLocatedBy(Utilities.getLocator(pageElement)));
String radioToSelect = printedValues.get(valueKey);
if (radioToSelect == null) {
radioToSelect = printedValues.get("Default");
}
for (final WebElement button : radioButtons) {
if (button.getAttribute(VALUE).equals(radioToSelect)) {
button.click();
break;
}
}
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SELECT_RADIO_BUTTON), pageElement), true, pageElement.getPage().getCallBack());
}
} | java | protected void updateRadioList(PageElement pageElement, String valueKeyOrKey, Map<String, String> printedValues) throws TechnicalException, FailureException {
final String valueKey = Context.getValue(valueKeyOrKey) != null ? Context.getValue(valueKeyOrKey) : valueKeyOrKey;
try {
final List<WebElement> radioButtons = Context.waitUntil(ExpectedConditions.presenceOfAllElementsLocatedBy(Utilities.getLocator(pageElement)));
String radioToSelect = printedValues.get(valueKey);
if (radioToSelect == null) {
radioToSelect = printedValues.get("Default");
}
for (final WebElement button : radioButtons) {
if (button.getAttribute(VALUE).equals(radioToSelect)) {
button.click();
break;
}
}
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SELECT_RADIO_BUTTON), pageElement), true, pageElement.getPage().getCallBack());
}
} | [
"protected",
"void",
"updateRadioList",
"(",
"PageElement",
"pageElement",
",",
"String",
"valueKeyOrKey",
",",
"Map",
"<",
"String",
",",
"String",
">",
"printedValues",
")",
"throws",
"TechnicalException",
",",
"FailureException",
"{",
"final",
"String",
"valueKey... | Update html radio button by value (value corresponding to key "index").
@param pageElement
Is concerned element
@param valueKeyOrKey
key printedValues
@param printedValues
contain all possible value (order by key)
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_SELECT_RADIO_BUTTON} message (with screenshot, with exception)
@throws FailureException
if the scenario encounters a functional error | [
"Update",
"html",
"radio",
"button",
"by",
"value",
"(",
"value",
"corresponding",
"to",
"key",
"index",
")",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L601-L618 |
integration-technology/amazon-mws-orders | src/main/java/com/amazonservices/mws/client/MwsUtl.java | MwsUtl.calculateStringToSignV0 | private static String calculateStringToSignV0(Map<String, String> parameters) {
StringBuilder data = new StringBuilder();
data.append(parameters.get("Action")).append(parameters.get("Timestamp"));
return data.toString();
} | java | private static String calculateStringToSignV0(Map<String, String> parameters) {
StringBuilder data = new StringBuilder();
data.append(parameters.get("Action")).append(parameters.get("Timestamp"));
return data.toString();
} | [
"private",
"static",
"String",
"calculateStringToSignV0",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"StringBuilder",
"data",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"data",
".",
"append",
"(",
"parameters",
".",
"get",
"(",
... | Calculate String to Sign for SignatureVersion 0
@param parameters
request parameters
@return String to Sign | [
"Calculate",
"String",
"to",
"Sign",
"for",
"SignatureVersion",
"0"
] | train | https://github.com/integration-technology/amazon-mws-orders/blob/042e8cd5b10588a30150222bf9c91faf4f130b3c/src/main/java/com/amazonservices/mws/client/MwsUtl.java#L128-L132 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/TreeTableExample.java | TreeTableExample.createTable | private WDataTable createTable() {
WDataTable tbl = new WDataTable();
tbl.addColumn(new WTableColumn("First name", new WTextField()));
tbl.addColumn(new WTableColumn("Last name", new WTextField()));
tbl.addColumn(new WTableColumn("DOB", new WDateField()));
tbl.setExpandMode(ExpandMode.CLIENT);
TableTreeNode root = createTree();
tbl.setDataModel(new ExampleTreeTableModel(root));
return tbl;
} | java | private WDataTable createTable() {
WDataTable tbl = new WDataTable();
tbl.addColumn(new WTableColumn("First name", new WTextField()));
tbl.addColumn(new WTableColumn("Last name", new WTextField()));
tbl.addColumn(new WTableColumn("DOB", new WDateField()));
tbl.setExpandMode(ExpandMode.CLIENT);
TableTreeNode root = createTree();
tbl.setDataModel(new ExampleTreeTableModel(root));
return tbl;
} | [
"private",
"WDataTable",
"createTable",
"(",
")",
"{",
"WDataTable",
"tbl",
"=",
"new",
"WDataTable",
"(",
")",
";",
"tbl",
".",
"addColumn",
"(",
"new",
"WTableColumn",
"(",
"\"First name\"",
",",
"new",
"WTextField",
"(",
")",
")",
")",
";",
"tbl",
"."... | Creates and configures the table to be used by the example. The table is configured with global rather than user
data. Although this is not a realistic scenario, it will suffice for this example.
@return a new configured table. | [
"Creates",
"and",
"configures",
"the",
"table",
"to",
"be",
"used",
"by",
"the",
"example",
".",
"The",
"table",
"is",
"configured",
"with",
"global",
"rather",
"than",
"user",
"data",
".",
"Although",
"this",
"is",
"not",
"a",
"realistic",
"scenario",
"it... | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/TreeTableExample.java#L55-L66 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxHttpResponse.java | BoxHttpResponse.getBody | public InputStream getBody(ProgressListener listener) throws BoxException {
if (this.mInputStream == null) {
String contentEncoding = mConnection.getContentEncoding();
try {
if (this.rawInputStream == null) {
this.rawInputStream = mConnection.getInputStream();
}
if (listener == null) {
this.mInputStream = this.rawInputStream;
} else {
this.mInputStream = new ProgressInputStream(this.rawInputStream, listener,
this.getContentLength());
}
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
this.mInputStream = new GZIPInputStream(this.mInputStream);
}
return mInputStream;
} catch (IOException e) {
throw new BoxException("Couldn't connect to the Box API due to a network error.", e);
}
}
return this.mInputStream;
} | java | public InputStream getBody(ProgressListener listener) throws BoxException {
if (this.mInputStream == null) {
String contentEncoding = mConnection.getContentEncoding();
try {
if (this.rawInputStream == null) {
this.rawInputStream = mConnection.getInputStream();
}
if (listener == null) {
this.mInputStream = this.rawInputStream;
} else {
this.mInputStream = new ProgressInputStream(this.rawInputStream, listener,
this.getContentLength());
}
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
this.mInputStream = new GZIPInputStream(this.mInputStream);
}
return mInputStream;
} catch (IOException e) {
throw new BoxException("Couldn't connect to the Box API due to a network error.", e);
}
}
return this.mInputStream;
} | [
"public",
"InputStream",
"getBody",
"(",
"ProgressListener",
"listener",
")",
"throws",
"BoxException",
"{",
"if",
"(",
"this",
".",
"mInputStream",
"==",
"null",
")",
"{",
"String",
"contentEncoding",
"=",
"mConnection",
".",
"getContentEncoding",
"(",
")",
";"... | Gets an InputStream for reading this response's body which will report its read progress to a ProgressListener.
@param listener a listener for monitoring the read progress of the body.
@return an InputStream for reading the response's body.
@throws BoxException thrown if there was an issue getting the body including network issues. | [
"Gets",
"an",
"InputStream",
"for",
"reading",
"this",
"response",
"s",
"body",
"which",
"will",
"report",
"its",
"read",
"progress",
"to",
"a",
"ProgressListener",
"."
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/requests/BoxHttpResponse.java#L103-L128 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/npe/IsNullValue.java | IsNullValue.noKaboomNonNullValue | public static IsNullValue noKaboomNonNullValue(@Nonnull Location ins) {
if (ins == null) {
throw new NullPointerException("ins cannot be null");
}
return new IsNullValue(NO_KABOOM_NN, ins);
} | java | public static IsNullValue noKaboomNonNullValue(@Nonnull Location ins) {
if (ins == null) {
throw new NullPointerException("ins cannot be null");
}
return new IsNullValue(NO_KABOOM_NN, ins);
} | [
"public",
"static",
"IsNullValue",
"noKaboomNonNullValue",
"(",
"@",
"Nonnull",
"Location",
"ins",
")",
"{",
"if",
"(",
"ins",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"ins cannot be null\"",
")",
";",
"}",
"return",
"new",
"IsNul... | Get the instance representing a value known to be non-null because a NPE
would have occurred if it were null. | [
"Get",
"the",
"instance",
"representing",
"a",
"value",
"known",
"to",
"be",
"non",
"-",
"null",
"because",
"a",
"NPE",
"would",
"have",
"occurred",
"if",
"it",
"were",
"null",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/npe/IsNullValue.java#L330-L335 |
cbeust/jcommander | src/main/java/com/beust/jcommander/DefaultUsageFormatter.java | DefaultUsageFormatter.appendCommands | public void appendCommands(StringBuilder out, int indentCount, int descriptionIndent, String indent) {
out.append(indent + " Commands:\n");
// The magic value 3 is the number of spaces between the name of the option and its description
for (Map.Entry<JCommander.ProgramName, JCommander> commands : commander.getRawCommands().entrySet()) {
Object arg = commands.getValue().getObjects().get(0);
Parameters p = arg.getClass().getAnnotation(Parameters.class);
if (p == null || !p.hidden()) {
JCommander.ProgramName progName = commands.getKey();
String dispName = progName.getDisplayName();
String description = indent + s(4) + dispName + s(6) + getCommandDescription(progName.getName());
wrapDescription(out, indentCount + descriptionIndent, description);
out.append("\n");
// Options for this command
JCommander jc = commander.findCommandByAlias(progName.getName());
jc.getUsageFormatter().usage(out, indent + s(6));
out.append("\n");
}
}
} | java | public void appendCommands(StringBuilder out, int indentCount, int descriptionIndent, String indent) {
out.append(indent + " Commands:\n");
// The magic value 3 is the number of spaces between the name of the option and its description
for (Map.Entry<JCommander.ProgramName, JCommander> commands : commander.getRawCommands().entrySet()) {
Object arg = commands.getValue().getObjects().get(0);
Parameters p = arg.getClass().getAnnotation(Parameters.class);
if (p == null || !p.hidden()) {
JCommander.ProgramName progName = commands.getKey();
String dispName = progName.getDisplayName();
String description = indent + s(4) + dispName + s(6) + getCommandDescription(progName.getName());
wrapDescription(out, indentCount + descriptionIndent, description);
out.append("\n");
// Options for this command
JCommander jc = commander.findCommandByAlias(progName.getName());
jc.getUsageFormatter().usage(out, indent + s(6));
out.append("\n");
}
}
} | [
"public",
"void",
"appendCommands",
"(",
"StringBuilder",
"out",
",",
"int",
"indentCount",
",",
"int",
"descriptionIndent",
",",
"String",
"indent",
")",
"{",
"out",
".",
"append",
"(",
"indent",
"+",
"\" Commands:\\n\"",
")",
";",
"// The magic value 3 is the n... | Appends the details of all commands to the argument string builder, indenting every line with
<tt>indentCount</tt>-many <tt>indent</tt>. The commands are obtained from calling
{@link JCommander#getRawCommands()} and the commands are resolved using
{@link JCommander#findCommandByAlias(String)} on the underlying commander instance.
@param out the builder to append to
@param indentCount the amount of indentation to apply
@param descriptionIndent the indentation for the description
@param indent the indentation | [
"Appends",
"the",
"details",
"of",
"all",
"commands",
"to",
"the",
"argument",
"string",
"builder",
"indenting",
"every",
"line",
"with",
"<tt",
">",
"indentCount<",
"/",
"tt",
">",
"-",
"many",
"<tt",
">",
"indent<",
"/",
"tt",
">",
".",
"The",
"command... | train | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/DefaultUsageFormatter.java#L246-L267 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/util/TimingInfo.java | TimingInfo.durationMilliOf | public static double durationMilliOf(long startTimeNano, long endTimeNano) {
double micros = (double)TimeUnit.NANOSECONDS.toMicros(endTimeNano - startTimeNano);
return micros / 1000.0; // convert microseconds to milliseconds in double rather than long, preserving the precision
} | java | public static double durationMilliOf(long startTimeNano, long endTimeNano) {
double micros = (double)TimeUnit.NANOSECONDS.toMicros(endTimeNano - startTimeNano);
return micros / 1000.0; // convert microseconds to milliseconds in double rather than long, preserving the precision
} | [
"public",
"static",
"double",
"durationMilliOf",
"(",
"long",
"startTimeNano",
",",
"long",
"endTimeNano",
")",
"{",
"double",
"micros",
"=",
"(",
"double",
")",
"TimeUnit",
".",
"NANOSECONDS",
".",
"toMicros",
"(",
"endTimeNano",
"-",
"startTimeNano",
")",
";... | Returns the duration in milliseconds as double, preserving the decimal
precision as necessary, for the given start and end time in nanoseconds. | [
"Returns",
"the",
"duration",
"in",
"milliseconds",
"as",
"double",
"preserving",
"the",
"decimal",
"precision",
"as",
"necessary",
"for",
"the",
"given",
"start",
"and",
"end",
"time",
"in",
"nanoseconds",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/TimingInfo.java#L234-L237 |
spotify/scio | scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java | PatchedBigQueryTableRowIterator.getTypedTableRow | private TableRow getTypedTableRow(List<TableFieldSchema> fields, Map<String, Object> rawRow) {
// If rawRow is a TableRow, use it. If not, create a new one.
TableRow row;
List<? extends Map<String, Object>> cells;
if (rawRow instanceof TableRow) {
// Since rawRow is a TableRow it already has TableCell objects in setF. We do not need to do
// any type conversion, but extract the cells for cell-wise processing below.
row = (TableRow) rawRow;
cells = row.getF();
// Clear the cells from the row, so that row.getF() will return null. This matches the
// behavior of rows produced by the BigQuery export API used on the service.
row.setF(null);
} else {
row = new TableRow();
// Since rawRow is a Map<String, Object> we use Map.get("f") instead of TableRow.getF() to
// get its cells. Similarly, when rawCell is a Map<String, Object> instead of a TableCell,
// we will use Map.get("v") instead of TableCell.getV() get its value.
@SuppressWarnings("unchecked")
List<? extends Map<String, Object>> rawCells =
(List<? extends Map<String, Object>>) rawRow.get("f");
cells = rawCells;
}
checkState(cells.size() == fields.size(),
"Expected that the row has the same number of cells %s as fields in the schema %s",
cells.size(), fields.size());
// Loop through all the fields in the row, normalizing their types with the TableFieldSchema
// and storing the normalized values by field name in the Map<String, Object> that
// underlies the TableRow.
Iterator<? extends Map<String, Object>> cellIt = cells.iterator();
Iterator<TableFieldSchema> fieldIt = fields.iterator();
while (cellIt.hasNext()) {
Map<String, Object> cell = cellIt.next();
TableFieldSchema fieldSchema = fieldIt.next();
// Convert the object in this cell to the Java type corresponding to its type in the schema.
Object convertedValue = getTypedCellValue(fieldSchema, cell.get("v"));
String fieldName = fieldSchema.getName();
checkArgument(!RESERVED_FIELD_NAMES.contains(fieldName),
"BigQueryIO does not support records with columns named %s", fieldName);
if (convertedValue == null) {
// BigQuery does not include null values when the export operation (to JSON) is used.
// To match that behavior, BigQueryTableRowiterator, and the DirectRunner,
// intentionally omits columns with null values.
continue;
}
row.set(fieldName, convertedValue);
}
return row;
} | java | private TableRow getTypedTableRow(List<TableFieldSchema> fields, Map<String, Object> rawRow) {
// If rawRow is a TableRow, use it. If not, create a new one.
TableRow row;
List<? extends Map<String, Object>> cells;
if (rawRow instanceof TableRow) {
// Since rawRow is a TableRow it already has TableCell objects in setF. We do not need to do
// any type conversion, but extract the cells for cell-wise processing below.
row = (TableRow) rawRow;
cells = row.getF();
// Clear the cells from the row, so that row.getF() will return null. This matches the
// behavior of rows produced by the BigQuery export API used on the service.
row.setF(null);
} else {
row = new TableRow();
// Since rawRow is a Map<String, Object> we use Map.get("f") instead of TableRow.getF() to
// get its cells. Similarly, when rawCell is a Map<String, Object> instead of a TableCell,
// we will use Map.get("v") instead of TableCell.getV() get its value.
@SuppressWarnings("unchecked")
List<? extends Map<String, Object>> rawCells =
(List<? extends Map<String, Object>>) rawRow.get("f");
cells = rawCells;
}
checkState(cells.size() == fields.size(),
"Expected that the row has the same number of cells %s as fields in the schema %s",
cells.size(), fields.size());
// Loop through all the fields in the row, normalizing their types with the TableFieldSchema
// and storing the normalized values by field name in the Map<String, Object> that
// underlies the TableRow.
Iterator<? extends Map<String, Object>> cellIt = cells.iterator();
Iterator<TableFieldSchema> fieldIt = fields.iterator();
while (cellIt.hasNext()) {
Map<String, Object> cell = cellIt.next();
TableFieldSchema fieldSchema = fieldIt.next();
// Convert the object in this cell to the Java type corresponding to its type in the schema.
Object convertedValue = getTypedCellValue(fieldSchema, cell.get("v"));
String fieldName = fieldSchema.getName();
checkArgument(!RESERVED_FIELD_NAMES.contains(fieldName),
"BigQueryIO does not support records with columns named %s", fieldName);
if (convertedValue == null) {
// BigQuery does not include null values when the export operation (to JSON) is used.
// To match that behavior, BigQueryTableRowiterator, and the DirectRunner,
// intentionally omits columns with null values.
continue;
}
row.set(fieldName, convertedValue);
}
return row;
} | [
"private",
"TableRow",
"getTypedTableRow",
"(",
"List",
"<",
"TableFieldSchema",
">",
"fields",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"rawRow",
")",
"{",
"// If rawRow is a TableRow, use it. If not, create a new one.",
"TableRow",
"row",
";",
"List",
"<",
"... | Converts a row returned from the BigQuery JSON API as a {@code Map<String, Object>} into a
Java {@link TableRow} with nested {@link TableCell TableCells}. The {@code Object} values in
the cells are converted to Java types according to the provided field schemas.
<p>See {@link #getTypedCellValue(TableFieldSchema, Object)} for details on how BigQuery
types are mapped to Java types. | [
"Converts",
"a",
"row",
"returned",
"from",
"the",
"BigQuery",
"JSON",
"API",
"as",
"a",
"{",
"@code",
"Map<String",
"Object",
">",
"}",
"into",
"a",
"Java",
"{",
"@link",
"TableRow",
"}",
"with",
"nested",
"{",
"@link",
"TableCell",
"TableCells",
"}",
"... | train | https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L271-L325 |
mboudreau/Alternator | src/main/java/com/amazonaws/services/dynamodb/model/BatchResponse.java | BatchResponse.setItems | public void setItems(java.util.Collection<java.util.Map<String,AttributeValue>> items) {
if (items == null) {
this.items = null;
return;
}
java.util.List<java.util.Map<String,AttributeValue>> itemsCopy = new java.util.ArrayList<java.util.Map<String,AttributeValue>>(items.size());
itemsCopy.addAll(items);
this.items = itemsCopy;
} | java | public void setItems(java.util.Collection<java.util.Map<String,AttributeValue>> items) {
if (items == null) {
this.items = null;
return;
}
java.util.List<java.util.Map<String,AttributeValue>> itemsCopy = new java.util.ArrayList<java.util.Map<String,AttributeValue>>(items.size());
itemsCopy.addAll(items);
this.items = itemsCopy;
} | [
"public",
"void",
"setItems",
"(",
"java",
".",
"util",
".",
"Collection",
"<",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"AttributeValue",
">",
">",
"items",
")",
"{",
"if",
"(",
"items",
"==",
"null",
")",
"{",
"this",
".",
"items",
"=... | Sets the value of the Items property for this object.
@param items The new value for the Items property for this object. | [
"Sets",
"the",
"value",
"of",
"the",
"Items",
"property",
"for",
"this",
"object",
"."
] | train | https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/model/BatchResponse.java#L55-L64 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/geom/GeomUtil.java | GeomUtil.getLine | public Line getLine(Shape shape, float sx, float sy, int e) {
float[] end = shape.getPoint(e);
Line line = new Line(sx,sy,end[0],end[1]);
return line;
} | java | public Line getLine(Shape shape, float sx, float sy, int e) {
float[] end = shape.getPoint(e);
Line line = new Line(sx,sy,end[0],end[1]);
return line;
} | [
"public",
"Line",
"getLine",
"(",
"Shape",
"shape",
",",
"float",
"sx",
",",
"float",
"sy",
",",
"int",
"e",
")",
"{",
"float",
"[",
"]",
"end",
"=",
"shape",
".",
"getPoint",
"(",
"e",
")",
";",
"Line",
"line",
"=",
"new",
"Line",
"(",
"sx",
"... | Get a line between two points in a shape
@param shape The shape
@param sx The x coordinate of the start point
@param sy The y coordinate of the start point
@param e The index of the end point
@return The line between the two points | [
"Get",
"a",
"line",
"between",
"two",
"points",
"in",
"a",
"shape"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/geom/GeomUtil.java#L428-L433 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.vps_serviceName_plesk_duration_POST | public OvhOrder vps_serviceName_plesk_duration_POST(String serviceName, String duration, OvhPleskLicenseDomainNumberEnum domainNumber) throws IOException {
String qPath = "/order/vps/{serviceName}/plesk/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "domainNumber", domainNumber);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} | java | public OvhOrder vps_serviceName_plesk_duration_POST(String serviceName, String duration, OvhPleskLicenseDomainNumberEnum domainNumber) throws IOException {
String qPath = "/order/vps/{serviceName}/plesk/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "domainNumber", domainNumber);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} | [
"public",
"OvhOrder",
"vps_serviceName_plesk_duration_POST",
"(",
"String",
"serviceName",
",",
"String",
"duration",
",",
"OvhPleskLicenseDomainNumberEnum",
"domainNumber",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/vps/{serviceName}/plesk/{duration}\... | Create order
REST: POST /order/vps/{serviceName}/plesk/{duration}
@param domainNumber [required] Domain number you want to order a licence for
@param serviceName [required] The internal name of your VPS offer
@param duration [required] Duration
@deprecated | [
"Create",
"order"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L3342-L3349 |
alkacon/opencms-core | src/org/opencms/ade/detailpage/CmsDetailPageConfigurationWriter.java | CmsDetailPageConfigurationWriter.writeValue | private void writeValue(String type, CmsUUID id, int index) {
Locale locale = CmsLocaleManager.getLocale("en");
// todo: check actual locale.
m_document.addValue(m_cms, N_DETAIL_PAGE, locale, index);
String typePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_TYPE;
I_CmsXmlContentValue typeVal = m_document.getValue(typePath, locale);
String pagePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_PAGE;
CmsXmlVfsFileValue pageVal = (CmsXmlVfsFileValue)m_document.getValue(pagePath, locale);
typeVal.setStringValue(m_cms, type);
pageVal.setIdValue(m_cms, id);
} | java | private void writeValue(String type, CmsUUID id, int index) {
Locale locale = CmsLocaleManager.getLocale("en");
// todo: check actual locale.
m_document.addValue(m_cms, N_DETAIL_PAGE, locale, index);
String typePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_TYPE;
I_CmsXmlContentValue typeVal = m_document.getValue(typePath, locale);
String pagePath = N_DETAIL_PAGE + "[" + (1 + index) + "]/" + N_PAGE;
CmsXmlVfsFileValue pageVal = (CmsXmlVfsFileValue)m_document.getValue(pagePath, locale);
typeVal.setStringValue(m_cms, type);
pageVal.setIdValue(m_cms, id);
} | [
"private",
"void",
"writeValue",
"(",
"String",
"type",
",",
"CmsUUID",
"id",
",",
"int",
"index",
")",
"{",
"Locale",
"locale",
"=",
"CmsLocaleManager",
".",
"getLocale",
"(",
"\"en\"",
")",
";",
"// todo: check actual locale.",
"m_document",
".",
"addValue",
... | Writes a single item of detail page information to the XML content.<p>
@param type the type which the detail page should render
@param id the page id of the detail page
@param index the position at which the detail page info should be added | [
"Writes",
"a",
"single",
"item",
"of",
"detail",
"page",
"information",
"to",
"the",
"XML",
"content",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/detailpage/CmsDetailPageConfigurationWriter.java#L187-L198 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.installationTemplate_templateName_PUT | public void installationTemplate_templateName_PUT(String templateName, OvhTemplates body) throws IOException {
String qPath = "/me/installationTemplate/{templateName}";
StringBuilder sb = path(qPath, templateName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void installationTemplate_templateName_PUT(String templateName, OvhTemplates body) throws IOException {
String qPath = "/me/installationTemplate/{templateName}";
StringBuilder sb = path(qPath, templateName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"installationTemplate_templateName_PUT",
"(",
"String",
"templateName",
",",
"OvhTemplates",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/installationTemplate/{templateName}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
... | Alter this object properties
REST: PUT /me/installationTemplate/{templateName}
@param body [required] New object properties
@param templateName [required] This template name | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L3452-L3456 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/Input.java | Input.isControlDwn | private boolean isControlDwn(int index, int controllerIndex) {
switch (index) {
case LEFT:
return isControllerLeft(controllerIndex);
case RIGHT:
return isControllerRight(controllerIndex);
case UP:
return isControllerUp(controllerIndex);
case DOWN:
return isControllerDown(controllerIndex);
}
if (index >= BUTTON1) {
return isButtonPressed((index-BUTTON1), controllerIndex);
}
throw new RuntimeException("Unknown control index");
} | java | private boolean isControlDwn(int index, int controllerIndex) {
switch (index) {
case LEFT:
return isControllerLeft(controllerIndex);
case RIGHT:
return isControllerRight(controllerIndex);
case UP:
return isControllerUp(controllerIndex);
case DOWN:
return isControllerDown(controllerIndex);
}
if (index >= BUTTON1) {
return isButtonPressed((index-BUTTON1), controllerIndex);
}
throw new RuntimeException("Unknown control index");
} | [
"private",
"boolean",
"isControlDwn",
"(",
"int",
"index",
",",
"int",
"controllerIndex",
")",
"{",
"switch",
"(",
"index",
")",
"{",
"case",
"LEFT",
":",
"return",
"isControllerLeft",
"(",
"controllerIndex",
")",
";",
"case",
"RIGHT",
":",
"return",
"isCont... | Check if a particular control is currently pressed
@param index The index of the control
@param controllerIndex The index of the control to which the control belongs
@return True if the control is pressed | [
"Check",
"if",
"a",
"particular",
"control",
"is",
"currently",
"pressed"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/Input.java#L1476-L1493 |
hawkular/hawkular-agent | hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/JBossASClient.java | JBossASClient.setPossibleExpression | public static ModelNode setPossibleExpression(ModelNode node, String name, String value) {
if (value != null) {
if (value.contains("${")) {
return node.get(name).set(new ValueExpression(value));
} else {
return node.get(name).set(value);
}
} else {
return node.get(name).clear();
}
} | java | public static ModelNode setPossibleExpression(ModelNode node, String name, String value) {
if (value != null) {
if (value.contains("${")) {
return node.get(name).set(new ValueExpression(value));
} else {
return node.get(name).set(value);
}
} else {
return node.get(name).clear();
}
} | [
"public",
"static",
"ModelNode",
"setPossibleExpression",
"(",
"ModelNode",
"node",
",",
"String",
"name",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"if",
"(",
"value",
".",
"contains",
"(",
"\"${\"",
")",
")",
"{",
... | This sets the given node's named attribute to the given value. If the value
appears to be an expression (that is, contains "${" somewhere in it), this will
set the value as an expression on the node.
@param node the node whose attribute is to be set
@param name the name of the attribute whose value is to be set
@param value the value, possibly an expression
@return returns the node | [
"This",
"sets",
"the",
"given",
"node",
"s",
"named",
"attribute",
"to",
"the",
"given",
"value",
".",
"If",
"the",
"value",
"appears",
"to",
"be",
"an",
"expression",
"(",
"that",
"is",
"contains",
"$",
"{",
"somewhere",
"in",
"it",
")",
"this",
"will... | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/JBossASClient.java#L251-L261 |
twilio/twilio-java | src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java | EngagementReader.nextPage | @Override
public Page<Engagement> nextPage(final Page<Engagement> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.STUDIO.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<Engagement> nextPage(final Page<Engagement> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getNextPageUrl(
Domains.STUDIO.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"Engagement",
">",
"nextPage",
"(",
"final",
"Page",
"<",
"Engagement",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
"... | Retrieve the next page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Next Page | [
"Retrieve",
"the",
"next",
"page",
"from",
"the",
"Twilio",
"API",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java#L90-L101 |
jenkinsci/jenkins | core/src/main/java/jenkins/model/ParameterizedJobMixIn.java | ParameterizedJobMixIn.getTrigger | public static @CheckForNull <T extends Trigger<?>> T getTrigger(Job<?,?> job, Class<T> clazz) {
if (!(job instanceof ParameterizedJob)) {
return null;
}
for (Trigger<?> t : ((ParameterizedJob<?, ?>) job).getTriggers().values()) {
if (clazz.isInstance(t)) {
return clazz.cast(t);
}
}
return null;
} | java | public static @CheckForNull <T extends Trigger<?>> T getTrigger(Job<?,?> job, Class<T> clazz) {
if (!(job instanceof ParameterizedJob)) {
return null;
}
for (Trigger<?> t : ((ParameterizedJob<?, ?>) job).getTriggers().values()) {
if (clazz.isInstance(t)) {
return clazz.cast(t);
}
}
return null;
} | [
"public",
"static",
"@",
"CheckForNull",
"<",
"T",
"extends",
"Trigger",
"<",
"?",
">",
">",
"T",
"getTrigger",
"(",
"Job",
"<",
"?",
",",
"?",
">",
"job",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"if",
"(",
"!",
"(",
"job",
"instanceof",
... | Checks for the existence of a specific trigger on a job.
@param <T> a trigger type
@param job a job
@param clazz the type of the trigger
@return a configured trigger of the requested type, or null if there is none such, or {@code job} is not a {@link ParameterizedJob}
@since 1.621 | [
"Checks",
"for",
"the",
"existence",
"of",
"a",
"specific",
"trigger",
"on",
"a",
"job",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/ParameterizedJobMixIn.java#L306-L316 |
IBM/ibm-cos-sdk-java | ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/s3/internal/crypto/ContentCryptoMaterial.java | ContentCryptoMaterial.secureCEK | private static SecuredCEK secureCEK(SecretKey cek,
EncryptionMaterials materials, S3KeyWrapScheme kwScheme,
SecureRandom srand, Provider p, AWSKMS kms,
AmazonWebServiceRequest req) {
final Map<String,String> matdesc;
if (materials.isKMSEnabled()) {
matdesc = mergeMaterialDescriptions(materials, req);
EncryptRequest encryptRequest = new EncryptRequest()
.withEncryptionContext(matdesc)
.withKeyId(materials.getCustomerMasterKeyId())
.withPlaintext(ByteBuffer.wrap(cek.getEncoded()))
;
encryptRequest
.withGeneralProgressListener(req.getGeneralProgressListener())
.withRequestMetricCollector(req.getRequestMetricCollector())
;
EncryptResult encryptResult = kms.encrypt(encryptRequest);
byte[] keyBlob = copyAllBytesFrom(encryptResult.getCiphertextBlob());
return new KMSSecuredCEK(keyBlob, matdesc);
} else {
matdesc = materials.getMaterialsDescription();
}
Key kek;
if (materials.getKeyPair() != null) {
// Do envelope encryption with public key from key pair
kek = materials.getKeyPair().getPublic();
} else {
// Do envelope encryption with symmetric key
kek = materials.getSymmetricKey();
}
String keyWrapAlgo = kwScheme.getKeyWrapAlgorithm(kek);
try {
if (keyWrapAlgo != null) {
Cipher cipher = p == null ? Cipher
.getInstance(keyWrapAlgo) : Cipher.getInstance(
keyWrapAlgo, p);
cipher.init(Cipher.WRAP_MODE, kek, srand);
return new SecuredCEK(cipher.wrap(cek), keyWrapAlgo, matdesc);
}
// fall back to the Encryption Only (EO) key encrypting method
Cipher cipher;
byte[] toBeEncryptedBytes = cek.getEncoded();
String algo = kek.getAlgorithm();
if (p != null) {
cipher = Cipher.getInstance(algo, p);
} else {
cipher = Cipher.getInstance(algo); // Use default JCE Provider
}
cipher.init(Cipher.ENCRYPT_MODE, kek);
return new SecuredCEK(cipher.doFinal(toBeEncryptedBytes), null, matdesc);
} catch (Exception e) {
throw failure(e, "Unable to encrypt symmetric key");
}
} | java | private static SecuredCEK secureCEK(SecretKey cek,
EncryptionMaterials materials, S3KeyWrapScheme kwScheme,
SecureRandom srand, Provider p, AWSKMS kms,
AmazonWebServiceRequest req) {
final Map<String,String> matdesc;
if (materials.isKMSEnabled()) {
matdesc = mergeMaterialDescriptions(materials, req);
EncryptRequest encryptRequest = new EncryptRequest()
.withEncryptionContext(matdesc)
.withKeyId(materials.getCustomerMasterKeyId())
.withPlaintext(ByteBuffer.wrap(cek.getEncoded()))
;
encryptRequest
.withGeneralProgressListener(req.getGeneralProgressListener())
.withRequestMetricCollector(req.getRequestMetricCollector())
;
EncryptResult encryptResult = kms.encrypt(encryptRequest);
byte[] keyBlob = copyAllBytesFrom(encryptResult.getCiphertextBlob());
return new KMSSecuredCEK(keyBlob, matdesc);
} else {
matdesc = materials.getMaterialsDescription();
}
Key kek;
if (materials.getKeyPair() != null) {
// Do envelope encryption with public key from key pair
kek = materials.getKeyPair().getPublic();
} else {
// Do envelope encryption with symmetric key
kek = materials.getSymmetricKey();
}
String keyWrapAlgo = kwScheme.getKeyWrapAlgorithm(kek);
try {
if (keyWrapAlgo != null) {
Cipher cipher = p == null ? Cipher
.getInstance(keyWrapAlgo) : Cipher.getInstance(
keyWrapAlgo, p);
cipher.init(Cipher.WRAP_MODE, kek, srand);
return new SecuredCEK(cipher.wrap(cek), keyWrapAlgo, matdesc);
}
// fall back to the Encryption Only (EO) key encrypting method
Cipher cipher;
byte[] toBeEncryptedBytes = cek.getEncoded();
String algo = kek.getAlgorithm();
if (p != null) {
cipher = Cipher.getInstance(algo, p);
} else {
cipher = Cipher.getInstance(algo); // Use default JCE Provider
}
cipher.init(Cipher.ENCRYPT_MODE, kek);
return new SecuredCEK(cipher.doFinal(toBeEncryptedBytes), null, matdesc);
} catch (Exception e) {
throw failure(e, "Unable to encrypt symmetric key");
}
} | [
"private",
"static",
"SecuredCEK",
"secureCEK",
"(",
"SecretKey",
"cek",
",",
"EncryptionMaterials",
"materials",
",",
"S3KeyWrapScheme",
"kwScheme",
",",
"SecureRandom",
"srand",
",",
"Provider",
"p",
",",
"AWSKMS",
"kms",
",",
"AmazonWebServiceRequest",
"req",
")"... | Secure the given CEK. Note network calls are involved if the CEK is to
be protected by KMS.
@param cek content encrypting key to be secured
@param materials used to provide the key-encryption-key (KEK); or if
it is KMS-enabled, the customer master key id and material description.
@param contentCryptoScheme the content crypto scheme
@param p optional security provider; can be null if the default is used.
@return a secured CEK in the form of ciphertext or ciphertext blob. | [
"Secure",
"the",
"given",
"CEK",
".",
"Note",
"network",
"calls",
"are",
"involved",
"if",
"the",
"CEK",
"is",
"to",
"be",
"protected",
"by",
"KMS",
"."
] | train | https://github.com/IBM/ibm-cos-sdk-java/blob/d0bb2dd754c328a05e7dba8dc42e28b271b6daf2/ibm-cos-java-sdk-s3/src/main/java/com/ibm/cloud/objectstorage/services/s3/internal/crypto/ContentCryptoMaterial.java#L843-L897 |
google/closure-templates | java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java | JavaQualifiedNames.getFileClassName | static String getFileClassName(FileDescriptor file, ProtoFlavor flavor) {
return getFileClassName(file.toProto(), flavor);
} | java | static String getFileClassName(FileDescriptor file, ProtoFlavor flavor) {
return getFileClassName(file.toProto(), flavor);
} | [
"static",
"String",
"getFileClassName",
"(",
"FileDescriptor",
"file",
",",
"ProtoFlavor",
"flavor",
")",
"{",
"return",
"getFileClassName",
"(",
"file",
".",
"toProto",
"(",
")",
",",
"flavor",
")",
";",
"}"
] | Derives the outer class name based on the protobuf (.proto) file name. | [
"Derives",
"the",
"outer",
"class",
"name",
"based",
"on",
"the",
"protobuf",
"(",
".",
"proto",
")",
"file",
"name",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/internal/proto/JavaQualifiedNames.java#L246-L248 |
guardtime/ksi-java-sdk | ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryAggregationHashChain.java | InMemoryAggregationHashChain.calculateOutputHash | public final ChainResult calculateOutputHash(long level) throws KSIException {
// TODO task KSIJAVAAPI-207 If the aggregation hash chain component contains the `input data' field, hash the value part of the field
// using the hash algorithm specified by the first octet of the `input hash' field and verify that the result of
// hashing `input data' equals `input hash'; terminate with a consistency error if they do not match.(spec. 4.1.1.2)
// TODO task KSIJAVAAPI-207 if current aggregation hash chain isn't the first component of the hash chain and the chain
// contains 'input data' field then terminate with a format error. (spec 4.1.1.2)
DataHash lastHash = inputHash;
long currentLevel = level;
for (AggregationChainLink aggregationChainLink : chain) {
ChainResult step = aggregationChainLink.calculateChainStep(lastHash.getImprint(), currentLevel, aggregationAlgorithm);
lastHash = step.getOutputHash();
currentLevel = step.getLevel();
}
this.outputHash = lastHash;
return new InMemoryChainResult(lastHash, currentLevel);
} | java | public final ChainResult calculateOutputHash(long level) throws KSIException {
// TODO task KSIJAVAAPI-207 If the aggregation hash chain component contains the `input data' field, hash the value part of the field
// using the hash algorithm specified by the first octet of the `input hash' field and verify that the result of
// hashing `input data' equals `input hash'; terminate with a consistency error if they do not match.(spec. 4.1.1.2)
// TODO task KSIJAVAAPI-207 if current aggregation hash chain isn't the first component of the hash chain and the chain
// contains 'input data' field then terminate with a format error. (spec 4.1.1.2)
DataHash lastHash = inputHash;
long currentLevel = level;
for (AggregationChainLink aggregationChainLink : chain) {
ChainResult step = aggregationChainLink.calculateChainStep(lastHash.getImprint(), currentLevel, aggregationAlgorithm);
lastHash = step.getOutputHash();
currentLevel = step.getLevel();
}
this.outputHash = lastHash;
return new InMemoryChainResult(lastHash, currentLevel);
} | [
"public",
"final",
"ChainResult",
"calculateOutputHash",
"(",
"long",
"level",
")",
"throws",
"KSIException",
"{",
"// TODO task KSIJAVAAPI-207 If the aggregation hash chain component contains the `input data' field, hash the value part of the field",
"// using the hash algorithm specified b... | Calculate hash chain output hash.
@param level
hash chain level
@return hash chain result | [
"Calculate",
"hash",
"chain",
"output",
"hash",
"."
] | train | https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-api/src/main/java/com/guardtime/ksi/unisignature/inmemory/InMemoryAggregationHashChain.java#L140-L157 |
hankcs/HanLP | src/main/java/com/hankcs/hanlp/dependency/nnparser/Matrix.java | Matrix.setMatrix | public void setMatrix(int i0, int i1, int j0, int j1, Matrix X)
{
try
{
for (int i = i0; i <= i1; i++)
{
for (int j = j0; j <= j1; j++)
{
A[i][j] = X.get(i - i0, j - j0);
}
}
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
} | java | public void setMatrix(int i0, int i1, int j0, int j1, Matrix X)
{
try
{
for (int i = i0; i <= i1; i++)
{
for (int j = j0; j <= j1; j++)
{
A[i][j] = X.get(i - i0, j - j0);
}
}
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
} | [
"public",
"void",
"setMatrix",
"(",
"int",
"i0",
",",
"int",
"i1",
",",
"int",
"j0",
",",
"int",
"j1",
",",
"Matrix",
"X",
")",
"{",
"try",
"{",
"for",
"(",
"int",
"i",
"=",
"i0",
";",
"i",
"<=",
"i1",
";",
"i",
"++",
")",
"{",
"for",
"(",
... | Set a submatrix.
@param i0 Initial row index
@param i1 Final row index
@param j0 Initial column index
@param j1 Final column index
@param X A(i0:i1,j0:j1)
@throws ArrayIndexOutOfBoundsException Submatrix indices | [
"Set",
"a",
"submatrix",
"."
] | train | https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dependency/nnparser/Matrix.java#L500-L516 |
bazaarvoice/jolt | cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java | JoltCliUtilities.createJsonObjectFromFile | public static Object createJsonObjectFromFile( File file, boolean suppressOutput ) {
Object jsonObject = null;
try {
FileInputStream inputStream = new FileInputStream( file );
jsonObject = JsonUtils.jsonToObject( inputStream );
inputStream.close();
} catch ( IOException e ) {
if ( e instanceof JsonParseException ) {
printToStandardOut( "File " + file.getAbsolutePath() + " did not contain properly formatted JSON.", suppressOutput );
} else {
printToStandardOut( "Failed to open file: " + file.getAbsolutePath(), suppressOutput );
}
System.exit( 1 );
}
return jsonObject;
} | java | public static Object createJsonObjectFromFile( File file, boolean suppressOutput ) {
Object jsonObject = null;
try {
FileInputStream inputStream = new FileInputStream( file );
jsonObject = JsonUtils.jsonToObject( inputStream );
inputStream.close();
} catch ( IOException e ) {
if ( e instanceof JsonParseException ) {
printToStandardOut( "File " + file.getAbsolutePath() + " did not contain properly formatted JSON.", suppressOutput );
} else {
printToStandardOut( "Failed to open file: " + file.getAbsolutePath(), suppressOutput );
}
System.exit( 1 );
}
return jsonObject;
} | [
"public",
"static",
"Object",
"createJsonObjectFromFile",
"(",
"File",
"file",
",",
"boolean",
"suppressOutput",
")",
"{",
"Object",
"jsonObject",
"=",
"null",
";",
"try",
"{",
"FileInputStream",
"inputStream",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
";... | Uses the File to build a Map containing JSON data found in the file. This method will
System exit with an error code of 1 if has any trouble opening the file or the file did not
contain properly formatted JSON (i.e. the JSON parser was unable to parse its contents)
@return the Map containing the JSON data | [
"Uses",
"the",
"File",
"to",
"build",
"a",
"Map",
"containing",
"JSON",
"data",
"found",
"in",
"the",
"file",
".",
"This",
"method",
"will",
"System",
"exit",
"with",
"an",
"error",
"code",
"of",
"1",
"if",
"has",
"any",
"trouble",
"opening",
"the",
"f... | train | https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/cli/src/main/java/com/bazaarvoice/jolt/JoltCliUtilities.java#L49-L64 |
xwiki/xwiki-rendering | xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/reference/GenericLinkReferenceParser.java | GenericLinkReferenceParser.parseElementAfterString | protected String parseElementAfterString(StringBuilder content, String separator)
{
String element = null;
// Find the first non escaped separator (starting from the end of the content buffer).
int index = content.lastIndexOf(separator);
while (index != -1) {
// Check if the element is found and it's not escaped.
if (!shouldEscape(content, index)) {
element = content.substring(index + separator.length()).trim();
content.delete(index, content.length());
break;
}
if (index > 0) {
index = content.lastIndexOf(separator, index - 1);
} else {
break;
}
}
return element;
} | java | protected String parseElementAfterString(StringBuilder content, String separator)
{
String element = null;
// Find the first non escaped separator (starting from the end of the content buffer).
int index = content.lastIndexOf(separator);
while (index != -1) {
// Check if the element is found and it's not escaped.
if (!shouldEscape(content, index)) {
element = content.substring(index + separator.length()).trim();
content.delete(index, content.length());
break;
}
if (index > 0) {
index = content.lastIndexOf(separator, index - 1);
} else {
break;
}
}
return element;
} | [
"protected",
"String",
"parseElementAfterString",
"(",
"StringBuilder",
"content",
",",
"String",
"separator",
")",
"{",
"String",
"element",
"=",
"null",
";",
"// Find the first non escaped separator (starting from the end of the content buffer).",
"int",
"index",
"=",
"cont... | Find out the element located to the right of the passed separator.
@param content the string to parse. This parameter will be modified by the method to remove the parsed content.
@param separator the separator string to locate the element
@return the parsed element or null if the separator string wasn't found | [
"Find",
"out",
"the",
"element",
"located",
"to",
"the",
"right",
"of",
"the",
"passed",
"separator",
"."
] | train | https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-api/src/main/java/org/xwiki/rendering/internal/parser/reference/GenericLinkReferenceParser.java#L260-L282 |
dasein-cloud/dasein-cloud-aws | src/main/java/org/dasein/cloud/aws/AWSCloud.java | AWSCloud.addValueIfNotNull | public static void addValueIfNotNull( @Nonnull Map<String, String> parameters, @Nonnull String key, Object value ) {
if( value == null ) {
return;
}
parameters.put(key, value.toString());
} | java | public static void addValueIfNotNull( @Nonnull Map<String, String> parameters, @Nonnull String key, Object value ) {
if( value == null ) {
return;
}
parameters.put(key, value.toString());
} | [
"public",
"static",
"void",
"addValueIfNotNull",
"(",
"@",
"Nonnull",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
",",
"@",
"Nonnull",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
... | Puts the given key/value into the given map only if the value is not null.
@param parameters the map to add to
@param key the key of the value
@param value the value to add if not null | [
"Puts",
"the",
"given",
"key",
"/",
"value",
"into",
"the",
"given",
"map",
"only",
"if",
"the",
"value",
"is",
"not",
"null",
"."
] | train | https://github.com/dasein-cloud/dasein-cloud-aws/blob/05098574197a1f573f77447cadc39a76bf00b99d/src/main/java/org/dasein/cloud/aws/AWSCloud.java#L1436-L1441 |
GCRC/nunaliit | nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java | Files.emptyDirectory | static public void emptyDirectory(File dir) throws Exception {
String[] fileNames = dir.list();
if( null != fileNames ) {
for(String fileName : fileNames){
File file = new File(dir,fileName);
if( file.isDirectory() ) {
emptyDirectory(file);
}
boolean deleted = false;
try {
deleted = file.delete();
} catch(Exception e) {
throw new Exception("Unable to delete: "+file.getAbsolutePath(),e);
}
if( !deleted ){
throw new Exception("Unable to delete: "+file.getAbsolutePath());
}
}
}
} | java | static public void emptyDirectory(File dir) throws Exception {
String[] fileNames = dir.list();
if( null != fileNames ) {
for(String fileName : fileNames){
File file = new File(dir,fileName);
if( file.isDirectory() ) {
emptyDirectory(file);
}
boolean deleted = false;
try {
deleted = file.delete();
} catch(Exception e) {
throw new Exception("Unable to delete: "+file.getAbsolutePath(),e);
}
if( !deleted ){
throw new Exception("Unable to delete: "+file.getAbsolutePath());
}
}
}
} | [
"static",
"public",
"void",
"emptyDirectory",
"(",
"File",
"dir",
")",
"throws",
"Exception",
"{",
"String",
"[",
"]",
"fileNames",
"=",
"dir",
".",
"list",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"fileNames",
")",
"{",
"for",
"(",
"String",
"fileName"... | Given a directory, removes all the content found in the directory.
@param dir The directory to be emptied
@throws Exception | [
"Given",
"a",
"directory",
"removes",
"all",
"the",
"content",
"found",
"in",
"the",
"directory",
"."
] | train | https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java#L157-L176 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/block/decomposition/hessenberg/TridiagonalHelper_DDRB.java | TridiagonalHelper_DDRB.tridiagUpperRow | public static void tridiagUpperRow( final int blockLength ,
final DSubmatrixD1 A ,
final double gammas[] ,
final DSubmatrixD1 V )
{
int blockHeight = Math.min(blockLength,A.row1-A.row0);
if( blockHeight <= 1 )
return;
int width = A.col1-A.col0;
int num = Math.min(width-1,blockHeight);
int applyIndex = Math.min(width,blockHeight);
// step through rows in the block
for( int i = 0; i < num; i++ ) {
// compute the new reflector and save it in a row in 'A'
computeHouseHolderRow(blockLength,A,gammas,i);
double gamma = gammas[A.row0+i];
// compute y
computeY(blockLength,A,V,i,gamma);
// compute v from y
computeRowOfV(blockLength,A,V,i,gamma);
// Apply the reflectors to the next row in 'A' only
if( i+1 < applyIndex ) {
applyReflectorsToRow( blockLength , A , V , i+1 );
}
}
} | java | public static void tridiagUpperRow( final int blockLength ,
final DSubmatrixD1 A ,
final double gammas[] ,
final DSubmatrixD1 V )
{
int blockHeight = Math.min(blockLength,A.row1-A.row0);
if( blockHeight <= 1 )
return;
int width = A.col1-A.col0;
int num = Math.min(width-1,blockHeight);
int applyIndex = Math.min(width,blockHeight);
// step through rows in the block
for( int i = 0; i < num; i++ ) {
// compute the new reflector and save it in a row in 'A'
computeHouseHolderRow(blockLength,A,gammas,i);
double gamma = gammas[A.row0+i];
// compute y
computeY(blockLength,A,V,i,gamma);
// compute v from y
computeRowOfV(blockLength,A,V,i,gamma);
// Apply the reflectors to the next row in 'A' only
if( i+1 < applyIndex ) {
applyReflectorsToRow( blockLength , A , V , i+1 );
}
}
} | [
"public",
"static",
"void",
"tridiagUpperRow",
"(",
"final",
"int",
"blockLength",
",",
"final",
"DSubmatrixD1",
"A",
",",
"final",
"double",
"gammas",
"[",
"]",
",",
"final",
"DSubmatrixD1",
"V",
")",
"{",
"int",
"blockHeight",
"=",
"Math",
".",
"min",
"(... | <p>
Performs a tridiagonal decomposition on the upper row only.
</p>
<p>
For each row 'a' in 'A':
Compute 'u' the householder reflector.
y(:) = A*u
v(i) = y - (1/2)*(y^T*u)*u
a(i+1) = a(i) - u*γ*v^T - v*u^t
</p>
@param blockLength Size of a block
@param A is the row block being decomposed. Modified.
@param gammas Householder gammas.
@param V Where computed 'v' are stored in a row block. Modified. | [
"<p",
">",
"Performs",
"a",
"tridiagonal",
"decomposition",
"on",
"the",
"upper",
"row",
"only",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/block/decomposition/hessenberg/TridiagonalHelper_DDRB.java#L52-L81 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/security/servletfilters/Cache.java | Cache.getCacheElement | private final synchronized CacheElement getCacheElement(String userid) {
String m = getCacheAbbrev() + " getCacheElement() ";
CacheElement cacheElement = null;
String key = getKey(userid);
logger.debug(m + "key==" + key);
if (cache.containsKey(key)) {
logger.debug(m + "cache already has element");
} else {
logger.debug(m + "cache does not have element; create and put");
CacheElement itemtemp =
new CacheElement(userid, getCacheId(), getCacheAbbrev());
cache.put(key, itemtemp);
}
cacheElement = (CacheElement) cache.get(key);
if (cacheElement == null) {
logger.error(m + "cache does not contain element");
} else {
logger.debug(m + "element retrieved from cache successfully");
}
return cacheElement;
} | java | private final synchronized CacheElement getCacheElement(String userid) {
String m = getCacheAbbrev() + " getCacheElement() ";
CacheElement cacheElement = null;
String key = getKey(userid);
logger.debug(m + "key==" + key);
if (cache.containsKey(key)) {
logger.debug(m + "cache already has element");
} else {
logger.debug(m + "cache does not have element; create and put");
CacheElement itemtemp =
new CacheElement(userid, getCacheId(), getCacheAbbrev());
cache.put(key, itemtemp);
}
cacheElement = (CacheElement) cache.get(key);
if (cacheElement == null) {
logger.error(m + "cache does not contain element");
} else {
logger.debug(m + "element retrieved from cache successfully");
}
return cacheElement;
} | [
"private",
"final",
"synchronized",
"CacheElement",
"getCacheElement",
"(",
"String",
"userid",
")",
"{",
"String",
"m",
"=",
"getCacheAbbrev",
"(",
")",
"+",
"\" getCacheElement() \"",
";",
"CacheElement",
"cacheElement",
"=",
"null",
";",
"String",
"key",
"=",
... | /*
synchronize so that each access gets the same item instance (protect
against overlapping calls) note that expiration logic of cache element
changes the element's state -- elements are never removed from cache or
replaced | [
"/",
"*",
"synchronize",
"so",
"that",
"each",
"access",
"gets",
"the",
"same",
"item",
"instance",
"(",
"protect",
"against",
"overlapping",
"calls",
")",
"note",
"that",
"expiration",
"logic",
"of",
"cache",
"element",
"changes",
"the",
"element",
"s",
"st... | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/security/servletfilters/Cache.java#L132-L152 |
haifengl/smile | core/src/main/java/smile/util/SmileUtils.java | SmileUtils.learnGaussianRadialBasis | public static <T> GaussianRadialBasis learnGaussianRadialBasis(T[] x, T[] centers, Metric<T> distance) {
int k = centers.length;
CLARANS<T> clarans = new CLARANS<>(x, distance, k, Math.min(100, (int) Math.round(0.01 * k * (x.length - k))));
System.arraycopy(clarans.medoids(), 0, centers, 0, k);
double r0 = 0.0;
for (int i = 0; i < k; i++) {
for (int j = 0; j < i; j++) {
double d = distance.d(centers[i], centers[j]);
if (r0 < d) {
r0 = d;
}
}
}
r0 /= Math.sqrt(2*k);
return new GaussianRadialBasis(r0);
} | java | public static <T> GaussianRadialBasis learnGaussianRadialBasis(T[] x, T[] centers, Metric<T> distance) {
int k = centers.length;
CLARANS<T> clarans = new CLARANS<>(x, distance, k, Math.min(100, (int) Math.round(0.01 * k * (x.length - k))));
System.arraycopy(clarans.medoids(), 0, centers, 0, k);
double r0 = 0.0;
for (int i = 0; i < k; i++) {
for (int j = 0; j < i; j++) {
double d = distance.d(centers[i], centers[j]);
if (r0 < d) {
r0 = d;
}
}
}
r0 /= Math.sqrt(2*k);
return new GaussianRadialBasis(r0);
} | [
"public",
"static",
"<",
"T",
">",
"GaussianRadialBasis",
"learnGaussianRadialBasis",
"(",
"T",
"[",
"]",
"x",
",",
"T",
"[",
"]",
"centers",
",",
"Metric",
"<",
"T",
">",
"distance",
")",
"{",
"int",
"k",
"=",
"centers",
".",
"length",
";",
"CLARANS",... | Learns Gaussian RBF function and centers from data. The centers are
chosen as the medoids of CLARANS. Let d<sub>max</sub> be the maximum
distance between the chosen centers, the standard deviation (i.e. width)
of Gaussian radial basis function is d<sub>max</sub> / sqrt(2*k), where
k is number of centers. In this way, the radial basis functions are not
too peaked or too flat. This choice would be close to the optimal
solution if the data were uniformly distributed in the input space,
leading to a uniform distribution of medoids.
@param x the training dataset.
@param centers an array to store centers on output. Its length is used as k of CLARANS.
@param distance the distance functor.
@return a Gaussian RBF function with parameter learned from data. | [
"Learns",
"Gaussian",
"RBF",
"function",
"and",
"centers",
"from",
"data",
".",
"The",
"centers",
"are",
"chosen",
"as",
"the",
"medoids",
"of",
"CLARANS",
".",
"Let",
"d<sub",
">",
"max<",
"/",
"sub",
">",
"be",
"the",
"maximum",
"distance",
"between",
... | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/util/SmileUtils.java#L204-L221 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Event.java | Event.setMentions | public void setMentions(int i, EventMention v) {
if (Event_Type.featOkTst && ((Event_Type)jcasType).casFeat_mentions == null)
jcasType.jcas.throwFeatMissing("mentions", "de.julielab.jules.types.ace.Event");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Event_Type)jcasType).casFeatCode_mentions), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Event_Type)jcasType).casFeatCode_mentions), i, jcasType.ll_cas.ll_getFSRef(v));} | java | public void setMentions(int i, EventMention v) {
if (Event_Type.featOkTst && ((Event_Type)jcasType).casFeat_mentions == null)
jcasType.jcas.throwFeatMissing("mentions", "de.julielab.jules.types.ace.Event");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Event_Type)jcasType).casFeatCode_mentions), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Event_Type)jcasType).casFeatCode_mentions), i, jcasType.ll_cas.ll_getFSRef(v));} | [
"public",
"void",
"setMentions",
"(",
"int",
"i",
",",
"EventMention",
"v",
")",
"{",
"if",
"(",
"Event_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"Event_Type",
")",
"jcasType",
")",
".",
"casFeat_mentions",
"==",
"null",
")",
"jcasType",
".",
"jcas",
".",... | indexed setter for mentions - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"mentions",
"-",
"sets",
"an",
"indexed",
"value",
"-"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Event.java#L292-L296 |
jMetal/jMetal | jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/espea/util/ScalarizationUtils.java | ScalarizationUtils.angleUtility | public static <S extends Solution<?>> void angleUtility(List<S> solutionsList, double[][] extremePoints) {
for (S solution : solutionsList) {
double fraction = 0.0;
for (int i = 0; i < extremePoints.length; i++) {
double numerator = 0.0;
double denominator = 0.0;
for (int j = 0; j < extremePoints.length; j++) {
if (i == j) {
denominator = Math.abs(extremePoints[i][j] - solution.getObjective(j));
} else {
numerator += Math.pow(extremePoints[i][j] - solution.getObjective(j), 2.0);
}
}
// Avoid numeric instability and division by 0.
if (denominator > 10e-6) {
fraction = Math.max(fraction, Math.sqrt(numerator) / denominator);
} else {
fraction = Double.MAX_VALUE;
}
}
setScalarizationValue(solution, Math.atan(fraction));
}
} | java | public static <S extends Solution<?>> void angleUtility(List<S> solutionsList, double[][] extremePoints) {
for (S solution : solutionsList) {
double fraction = 0.0;
for (int i = 0; i < extremePoints.length; i++) {
double numerator = 0.0;
double denominator = 0.0;
for (int j = 0; j < extremePoints.length; j++) {
if (i == j) {
denominator = Math.abs(extremePoints[i][j] - solution.getObjective(j));
} else {
numerator += Math.pow(extremePoints[i][j] - solution.getObjective(j), 2.0);
}
}
// Avoid numeric instability and division by 0.
if (denominator > 10e-6) {
fraction = Math.max(fraction, Math.sqrt(numerator) / denominator);
} else {
fraction = Double.MAX_VALUE;
}
}
setScalarizationValue(solution, Math.atan(fraction));
}
} | [
"public",
"static",
"<",
"S",
"extends",
"Solution",
"<",
"?",
">",
">",
"void",
"angleUtility",
"(",
"List",
"<",
"S",
">",
"solutionsList",
",",
"double",
"[",
"]",
"[",
"]",
"extremePoints",
")",
"{",
"for",
"(",
"S",
"solution",
":",
"solutionsList... | Scalarization values based on angle utility (see Angle-based Preference
Models in Multi-objective Optimization by Braun et al.).
@param solutionsList A list of solutions.
@param extremePoints used for angle computation. | [
"Scalarization",
"values",
"based",
"on",
"angle",
"utility",
"(",
"see",
"Angle",
"-",
"based",
"Preference",
"Models",
"in",
"Multi",
"-",
"objective",
"Optimization",
"by",
"Braun",
"et",
"al",
".",
")",
"."
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/espea/util/ScalarizationUtils.java#L272-L294 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxTermsOfService.java | BoxTermsOfService.getAllTermsOfServices | public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,
BoxTermsOfService.TermsOfServiceType
termsOfServiceType) {
QueryStringBuilder builder = new QueryStringBuilder();
if (termsOfServiceType != null) {
builder.appendParam("tos_type", termsOfServiceType.toString());
}
URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());
BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
int totalCount = responseJSON.get("total_count").asInt();
List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);
JsonArray entries = responseJSON.get("entries").asArray();
for (JsonValue value : entries) {
JsonObject termsOfServiceJSON = value.asObject();
BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get("id").asString());
BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);
termsOfServices.add(info);
}
return termsOfServices;
} | java | public static List<BoxTermsOfService.Info> getAllTermsOfServices(final BoxAPIConnection api,
BoxTermsOfService.TermsOfServiceType
termsOfServiceType) {
QueryStringBuilder builder = new QueryStringBuilder();
if (termsOfServiceType != null) {
builder.appendParam("tos_type", termsOfServiceType.toString());
}
URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString());
BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
int totalCount = responseJSON.get("total_count").asInt();
List<BoxTermsOfService.Info> termsOfServices = new ArrayList<BoxTermsOfService.Info>(totalCount);
JsonArray entries = responseJSON.get("entries").asArray();
for (JsonValue value : entries) {
JsonObject termsOfServiceJSON = value.asObject();
BoxTermsOfService termsOfService = new BoxTermsOfService(api, termsOfServiceJSON.get("id").asString());
BoxTermsOfService.Info info = termsOfService.new Info(termsOfServiceJSON);
termsOfServices.add(info);
}
return termsOfServices;
} | [
"public",
"static",
"List",
"<",
"BoxTermsOfService",
".",
"Info",
">",
"getAllTermsOfServices",
"(",
"final",
"BoxAPIConnection",
"api",
",",
"BoxTermsOfService",
".",
"TermsOfServiceType",
"termsOfServiceType",
")",
"{",
"QueryStringBuilder",
"builder",
"=",
"new",
... | Retrieves a list of Terms of Service that belong to your Enterprise as an Iterable.
@param api api the API connection to be used by the resource.
@param termsOfServiceType the type of terms of service to be retrieved. Can be set to "managed" or "external"
@return the Iterable of Terms of Service in an Enterprise that match the filter parameters. | [
"Retrieves",
"a",
"list",
"of",
"Terms",
"of",
"Service",
"that",
"belong",
"to",
"your",
"Enterprise",
"as",
"an",
"Iterable",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxTermsOfService.java#L102-L126 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/BundleRepositoryRegistry.java | BundleRepositoryRegistry.addBundleRepository | public synchronized static void addBundleRepository(String installDir, String featureType) {
BundleRepositoryHolder bundleRepositoryHolder = new BundleRepositoryHolder(installDir, cacheServerName, featureType);
if (!repositoryHolders.containsKey(featureType))
repositoryHolders.put(featureType, bundleRepositoryHolder);
} | java | public synchronized static void addBundleRepository(String installDir, String featureType) {
BundleRepositoryHolder bundleRepositoryHolder = new BundleRepositoryHolder(installDir, cacheServerName, featureType);
if (!repositoryHolders.containsKey(featureType))
repositoryHolders.put(featureType, bundleRepositoryHolder);
} | [
"public",
"synchronized",
"static",
"void",
"addBundleRepository",
"(",
"String",
"installDir",
",",
"String",
"featureType",
")",
"{",
"BundleRepositoryHolder",
"bundleRepositoryHolder",
"=",
"new",
"BundleRepositoryHolder",
"(",
"installDir",
",",
"cacheServerName",
","... | Add a bundle repository to the map if one for that feature type has not
already been added.
@param installDir The install location for the repository. This can vary, i.e. product extensions.
@param featureType The "name" for this repository. "" for default, "usr" for the user extension, etc. | [
"Add",
"a",
"bundle",
"repository",
"to",
"the",
"map",
"if",
"one",
"for",
"that",
"feature",
"type",
"has",
"not",
"already",
"been",
"added",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/provisioning/BundleRepositoryRegistry.java#L68-L73 |
UrielCh/ovh-java-sdk | ovh-java-sdk-vrack/src/main/java/net/minidev/ovh/api/ApiOvhVrack.java | ApiOvhVrack.serviceName_dedicatedCloudDatacenter_datacenter_GET | public OvhPccDatacenter serviceName_dedicatedCloudDatacenter_datacenter_GET(String serviceName, String datacenter) throws IOException {
String qPath = "/vrack/{serviceName}/dedicatedCloudDatacenter/{datacenter}";
StringBuilder sb = path(qPath, serviceName, datacenter);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPccDatacenter.class);
} | java | public OvhPccDatacenter serviceName_dedicatedCloudDatacenter_datacenter_GET(String serviceName, String datacenter) throws IOException {
String qPath = "/vrack/{serviceName}/dedicatedCloudDatacenter/{datacenter}";
StringBuilder sb = path(qPath, serviceName, datacenter);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPccDatacenter.class);
} | [
"public",
"OvhPccDatacenter",
"serviceName_dedicatedCloudDatacenter_datacenter_GET",
"(",
"String",
"serviceName",
",",
"String",
"datacenter",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/vrack/{serviceName}/dedicatedCloudDatacenter/{datacenter}\"",
";",
"Strin... | Get this object properties
REST: GET /vrack/{serviceName}/dedicatedCloudDatacenter/{datacenter}
@param serviceName [required] The internal name of your vrack
@param datacenter [required] Your dedicatedCloud datacenter name | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vrack/src/main/java/net/minidev/ovh/api/ApiOvhVrack.java#L154-L159 |
nostra13/Android-Universal-Image-Loader | library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java | ImageLoader.displayImage | public void displayImage(String uri, ImageView imageView, ImageSize targetImageSize) {
displayImage(uri, new ImageViewAware(imageView), null, targetImageSize, null, null);
} | java | public void displayImage(String uri, ImageView imageView, ImageSize targetImageSize) {
displayImage(uri, new ImageViewAware(imageView), null, targetImageSize, null, null);
} | [
"public",
"void",
"displayImage",
"(",
"String",
"uri",
",",
"ImageView",
"imageView",
",",
"ImageSize",
"targetImageSize",
")",
"{",
"displayImage",
"(",
"uri",
",",
"new",
"ImageViewAware",
"(",
"imageView",
")",
",",
"null",
",",
"targetImageSize",
",",
"nu... | Adds display image task to execution pool. Image will be set to ImageView when it's turn. <br/>
Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration
configuration} will be used.<br />
<b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call
@param uri Image URI (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png")
@param imageView {@link ImageView} which should display image
@throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before
@throws IllegalArgumentException if passed <b>imageView</b> is null | [
"Adds",
"display",
"image",
"task",
"to",
"execution",
"pool",
".",
"Image",
"will",
"be",
"set",
"to",
"ImageView",
"when",
"it",
"s",
"turn",
".",
"<br",
"/",
">",
"Default",
"{",
"@linkplain",
"DisplayImageOptions",
"display",
"image",
"options",
"}",
"... | train | https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/core/ImageLoader.java#L330-L332 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncMembersInner.java | SyncMembersInner.getAsync | public Observable<SyncMemberInner> getAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName, String syncMemberName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName, syncMemberName).map(new Func1<ServiceResponse<SyncMemberInner>, SyncMemberInner>() {
@Override
public SyncMemberInner call(ServiceResponse<SyncMemberInner> response) {
return response.body();
}
});
} | java | public Observable<SyncMemberInner> getAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName, String syncMemberName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName, syncMemberName).map(new Func1<ServiceResponse<SyncMemberInner>, SyncMemberInner>() {
@Override
public SyncMemberInner call(ServiceResponse<SyncMemberInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SyncMemberInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"String",
"syncGroupName",
",",
"String",
"syncMemberName",
")",
"{",
"return",
"getWithServiceRespons... | Gets a sync member.
@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 on which the sync group is hosted.
@param syncGroupName The name of the sync group on which the sync member is hosted.
@param syncMemberName The name of the sync member.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SyncMemberInner object | [
"Gets",
"a",
"sync",
"member",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncMembersInner.java#L164-L171 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/detect/StreamResourceTracker.java | StreamResourceTracker.addStreamEscape | public void addStreamEscape(Stream source, Location target) {
StreamEscape streamEscape = new StreamEscape(source, target);
streamEscapeSet.add(streamEscape);
if (FindOpenStream.DEBUG) {
System.out.println("Adding potential stream escape " + streamEscape);
}
} | java | public void addStreamEscape(Stream source, Location target) {
StreamEscape streamEscape = new StreamEscape(source, target);
streamEscapeSet.add(streamEscape);
if (FindOpenStream.DEBUG) {
System.out.println("Adding potential stream escape " + streamEscape);
}
} | [
"public",
"void",
"addStreamEscape",
"(",
"Stream",
"source",
",",
"Location",
"target",
")",
"{",
"StreamEscape",
"streamEscape",
"=",
"new",
"StreamEscape",
"(",
"source",
",",
"target",
")",
";",
"streamEscapeSet",
".",
"add",
"(",
"streamEscape",
")",
";",... | Indicate that a stream escapes at the given target Location.
@param source
the Stream that is escaping
@param target
the target Location (where the stream escapes) | [
"Indicate",
"that",
"a",
"stream",
"escapes",
"at",
"the",
"given",
"target",
"Location",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/detect/StreamResourceTracker.java#L118-L124 |
beihaifeiwu/dolphin | dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java | AnnotationUtils.findAnnotationDeclaringClass | public static Class<?> findAnnotationDeclaringClass(Class<? extends Annotation> annotationType, Class<?> clazz) {
Assert.notNull(annotationType, "Annotation type must not be null");
if (clazz == null || clazz.equals(Object.class)) {
return null;
}
if (isAnnotationDeclaredLocally(annotationType, clazz)) {
return clazz;
}
return findAnnotationDeclaringClass(annotationType, clazz.getSuperclass());
} | java | public static Class<?> findAnnotationDeclaringClass(Class<? extends Annotation> annotationType, Class<?> clazz) {
Assert.notNull(annotationType, "Annotation type must not be null");
if (clazz == null || clazz.equals(Object.class)) {
return null;
}
if (isAnnotationDeclaredLocally(annotationType, clazz)) {
return clazz;
}
return findAnnotationDeclaringClass(annotationType, clazz.getSuperclass());
} | [
"public",
"static",
"Class",
"<",
"?",
">",
"findAnnotationDeclaringClass",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"Assert",
".",
"notNull",
"(",
"annotationType",
",",
"\"Annot... | Find the first {@link Class} in the inheritance hierarchy of the specified {@code clazz}
(including the specified {@code clazz} itself) which declares an annotation for the
specified {@code annotationType}, or {@code null} if not found. If the supplied
{@code clazz} is {@code null}, {@code null} will be returned.
<p>If the supplied {@code clazz} is an interface, only the interface itself will be checked;
the inheritance hierarchy for interfaces will not be traversed.
<p>The standard {@link Class} API does not provide a mechanism for determining which class
in an inheritance hierarchy actually declares an {@link Annotation}, so we need to handle
this explicitly.
@param annotationType the annotation type to look for, both locally and as a meta-annotation
@param clazz the class on which to check for the annotation (may be {@code null})
@return the first {@link Class} in the inheritance hierarchy of the specified {@code clazz}
which declares an annotation for the specified {@code annotationType}, or {@code null}
if not found
@see Class#isAnnotationPresent(Class)
@see Class#getDeclaredAnnotations()
@see #findAnnotationDeclaringClassForTypes(List, Class)
@see #isAnnotationDeclaredLocally(Class, Class) | [
"Find",
"the",
"first",
"{"
] | train | https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/annotation/AnnotationUtils.java#L406-L415 |
Netflix/ribbon | ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/LoadBalancingRxClient.java | LoadBalancingRxClient.addLoadBalancerListener | private void addLoadBalancerListener() {
if (!(lbContext.getLoadBalancer() instanceof BaseLoadBalancer)) {
return;
}
((BaseLoadBalancer) lbContext.getLoadBalancer()).addServerListChangeListener(new ServerListChangeListener() {
@Override
public void serverListChanged(List<Server> oldList, List<Server> newList) {
Set<Server> removedServers = new HashSet<Server>(oldList);
removedServers.removeAll(newList);
for (Server server: rxClientCache.keySet()) {
if (removedServers.contains(server)) {
// this server is no longer in UP status
removeClient(server);
}
}
}
});
} | java | private void addLoadBalancerListener() {
if (!(lbContext.getLoadBalancer() instanceof BaseLoadBalancer)) {
return;
}
((BaseLoadBalancer) lbContext.getLoadBalancer()).addServerListChangeListener(new ServerListChangeListener() {
@Override
public void serverListChanged(List<Server> oldList, List<Server> newList) {
Set<Server> removedServers = new HashSet<Server>(oldList);
removedServers.removeAll(newList);
for (Server server: rxClientCache.keySet()) {
if (removedServers.contains(server)) {
// this server is no longer in UP status
removeClient(server);
}
}
}
});
} | [
"private",
"void",
"addLoadBalancerListener",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"lbContext",
".",
"getLoadBalancer",
"(",
")",
"instanceof",
"BaseLoadBalancer",
")",
")",
"{",
"return",
";",
"}",
"(",
"(",
"BaseLoadBalancer",
")",
"lbContext",
".",
"getLoa... | Add a listener that is responsible for removing an HttpClient and shutting down
its connection pool if it is no longer available from load balancer. | [
"Add",
"a",
"listener",
"that",
"is",
"responsible",
"for",
"removing",
"an",
"HttpClient",
"and",
"shutting",
"down",
"its",
"connection",
"pool",
"if",
"it",
"is",
"no",
"longer",
"available",
"from",
"load",
"balancer",
"."
] | train | https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/LoadBalancingRxClient.java#L191-L209 |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/OsmMapShapeConverter.java | OsmMapShapeConverter.addLatLngToMap | public static Marker addLatLngToMap(MapView map, GeoPoint latLng,
MarkerOptions options) {
Marker m = new Marker(map);
m.setPosition(latLng);
if (options!=null) {
if (options.getIcon()!=null){
m.setIcon(options.getIcon());
}
m.setAlpha(options.getAlpha());
m.setTitle(options.getTitle());
m.setSubDescription(options.getSubdescription());
m.setInfoWindow(new BasicInfoWindow(R.layout.bonuspack_bubble, map));
}
map.getOverlayManager().add(m);
return m;
} | java | public static Marker addLatLngToMap(MapView map, GeoPoint latLng,
MarkerOptions options) {
Marker m = new Marker(map);
m.setPosition(latLng);
if (options!=null) {
if (options.getIcon()!=null){
m.setIcon(options.getIcon());
}
m.setAlpha(options.getAlpha());
m.setTitle(options.getTitle());
m.setSubDescription(options.getSubdescription());
m.setInfoWindow(new BasicInfoWindow(R.layout.bonuspack_bubble, map));
}
map.getOverlayManager().add(m);
return m;
} | [
"public",
"static",
"Marker",
"addLatLngToMap",
"(",
"MapView",
"map",
",",
"GeoPoint",
"latLng",
",",
"MarkerOptions",
"options",
")",
"{",
"Marker",
"m",
"=",
"new",
"Marker",
"(",
"map",
")",
";",
"m",
".",
"setPosition",
"(",
"latLng",
")",
";",
"if"... | Add a LatLng to the map
@param map
@param latLng
@param options
@return | [
"Add",
"a",
"LatLng",
"to",
"the",
"map"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/OsmMapShapeConverter.java#L682-L697 |
JOML-CI/JOML | src/org/joml/Intersectionf.java | Intersectionf.intersectLineCircle | public static boolean intersectLineCircle(float a, float b, float c, float centerX, float centerY, float radius, Vector3f intersectionCenterAndHL) {
float invDenom = 1.0f / (float) Math.sqrt(a * a + b * b);
float dist = (a * centerX + b * centerY + c) * invDenom;
if (-radius <= dist && dist <= radius) {
intersectionCenterAndHL.x = centerX + dist * a * invDenom;
intersectionCenterAndHL.y = centerY + dist * b * invDenom;
intersectionCenterAndHL.z = (float) Math.sqrt(radius * radius - dist * dist);
return true;
}
return false;
} | java | public static boolean intersectLineCircle(float a, float b, float c, float centerX, float centerY, float radius, Vector3f intersectionCenterAndHL) {
float invDenom = 1.0f / (float) Math.sqrt(a * a + b * b);
float dist = (a * centerX + b * centerY + c) * invDenom;
if (-radius <= dist && dist <= radius) {
intersectionCenterAndHL.x = centerX + dist * a * invDenom;
intersectionCenterAndHL.y = centerY + dist * b * invDenom;
intersectionCenterAndHL.z = (float) Math.sqrt(radius * radius - dist * dist);
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"intersectLineCircle",
"(",
"float",
"a",
",",
"float",
"b",
",",
"float",
"c",
",",
"float",
"centerX",
",",
"float",
"centerY",
",",
"float",
"radius",
",",
"Vector3f",
"intersectionCenterAndHL",
")",
"{",
"float",
"invDenom",
... | Test whether the line with the general line equation <i>a*x + b*y + c = 0</i> intersects the circle with center
<code>(centerX, centerY)</code> and <code>radius</code>, and store the center of the line segment of
intersection in the <code>(x, y)</code> components of the supplied vector and the half-length of that line segment in the z component.
<p>
Reference: <a href="http://math.stackexchange.com/questions/943383/determine-circle-of-intersection-of-plane-and-sphere">http://math.stackexchange.com</a>
@param a
the x factor in the line equation
@param b
the y factor in the line equation
@param c
the constant in the line equation
@param centerX
the x coordinate of the circle's center
@param centerY
the y coordinate of the circle's center
@param radius
the radius of the circle
@param intersectionCenterAndHL
will hold the center of the line segment of intersection in the <code>(x, y)</code> components and the half-length in the z component
@return <code>true</code> iff the line intersects the circle; <code>false</code> otherwise | [
"Test",
"whether",
"the",
"line",
"with",
"the",
"general",
"line",
"equation",
"<i",
">",
"a",
"*",
"x",
"+",
"b",
"*",
"y",
"+",
"c",
"=",
"0<",
"/",
"i",
">",
"intersects",
"the",
"circle",
"with",
"center",
"<code",
">",
"(",
"centerX",
"center... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectionf.java#L3433-L3443 |
amaembo/streamex | src/main/java/one/util/streamex/StreamEx.java | StreamEx.toMap | public <K, V> Map<K, V> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valMapper, BinaryOperator<V> mergeFunction) {
return rawCollect(Collectors.toMap(keyMapper, valMapper, mergeFunction, HashMap::new));
} | java | public <K, V> Map<K, V> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valMapper, BinaryOperator<V> mergeFunction) {
return rawCollect(Collectors.toMap(keyMapper, valMapper, mergeFunction, HashMap::new));
} | [
"public",
"<",
"K",
",",
"V",
">",
"Map",
"<",
"K",
",",
"V",
">",
"toMap",
"(",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"K",
">",
"keyMapper",
",",
"Function",
"<",
"?",
"super",
"T",
",",
"?",
"extends",
"V",
">",
"valMapper"... | Returns a {@link Map} whose keys and values are the result of applying
the provided mapping functions to the input elements.
<p>
This is a <a href="package-summary.html#StreamOps">terminal</a>
operation.
<p>
If the mapped keys contains duplicates (according to
{@link Object#equals(Object)}), the value mapping function is applied to
each equal element, and the results are merged using the provided merging
function.
<p>
Returned {@code Map} is guaranteed to be modifiable.
@param <K> the output type of the key mapping function
@param <V> the output type of the value mapping function
@param keyMapper a mapping function to produce keys
@param valMapper a mapping function to produce values
@param mergeFunction a merge function, used to resolve collisions between
values associated with the same key, as supplied to
{@link Map#merge(Object, Object, BiFunction)}
@return a {@code Map} whose keys are the result of applying a key mapping
function to the input elements, and whose values are the result
of applying a value mapping function to all input elements equal
to the key and combining them using the merge function
@see Collectors#toMap(Function, Function, BinaryOperator)
@see Collectors#toConcurrentMap(Function, Function, BinaryOperator)
@see #toMap(Function, Function)
@since 0.1.0 | [
"Returns",
"a",
"{",
"@link",
"Map",
"}",
"whose",
"keys",
"and",
"values",
"are",
"the",
"result",
"of",
"applying",
"the",
"provided",
"mapping",
"functions",
"to",
"the",
"input",
"elements",
"."
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L1000-L1003 |
paypal/SeLion | dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/XmlDataProviderImpl.java | XmlDataProviderImpl.getAllKeyValueData | @Override
public Object[][] getAllKeyValueData() {
logger.entering();
Object[][] objectArray;
try {
JAXBContext context = JAXBContext.newInstance(resource.getCls());
Unmarshaller unmarshaller = context.createUnmarshaller();
StreamSource xmlStreamSource = new StreamSource(resource.getInputStream());
Map<String, KeyValuePair> keyValueItems = unmarshaller
.unmarshal(xmlStreamSource, KeyValueMap.class).getValue().getMap();
objectArray = DataProviderHelper.convertToObjectArray(keyValueItems);
} catch (JAXBException excp) {
throw new DataProviderException("Error unmarshalling XML file.", excp);
}
// Passing no arguments to exiting() because implementation to print 2D array could be highly recursive.
logger.exiting();
return objectArray;
} | java | @Override
public Object[][] getAllKeyValueData() {
logger.entering();
Object[][] objectArray;
try {
JAXBContext context = JAXBContext.newInstance(resource.getCls());
Unmarshaller unmarshaller = context.createUnmarshaller();
StreamSource xmlStreamSource = new StreamSource(resource.getInputStream());
Map<String, KeyValuePair> keyValueItems = unmarshaller
.unmarshal(xmlStreamSource, KeyValueMap.class).getValue().getMap();
objectArray = DataProviderHelper.convertToObjectArray(keyValueItems);
} catch (JAXBException excp) {
throw new DataProviderException("Error unmarshalling XML file.", excp);
}
// Passing no arguments to exiting() because implementation to print 2D array could be highly recursive.
logger.exiting();
return objectArray;
} | [
"@",
"Override",
"public",
"Object",
"[",
"]",
"[",
"]",
"getAllKeyValueData",
"(",
")",
"{",
"logger",
".",
"entering",
"(",
")",
";",
"Object",
"[",
"]",
"[",
"]",
"objectArray",
";",
"try",
"{",
"JAXBContext",
"context",
"=",
"JAXBContext",
".",
"ne... | Generates a two dimensional array for TestNG DataProvider from the XML data representing a map of name value
collection.
This method needs the referenced {@link DataResource} to be instantiated using its constructors with
parameter {@code Class<?> cls} and set to {@code KeyValueMap.class}. The implementation in this method is tightly
coupled with {@link KeyValueMap} and {@link KeyValuePair}.
The hierarchy and name of the nodes are strictly as instructed. A name value pair should be represented as nodes
'key' and 'value' as child nodes contained in a parent node named 'item'. A sample data with proper tag names is
shown here as an example:
<pre>
<items>
<item>
<key>k1</key>
<value>val1</value>
</item>
<item>
<key>k2</key>
<value>val2</value>
</item>
<item>
<key>k3</key>
<value>val3</value>
</item>
</items>
</pre>
@return A two dimensional object array. | [
"Generates",
"a",
"two",
"dimensional",
"array",
"for",
"TestNG",
"DataProvider",
"from",
"the",
"XML",
"data",
"representing",
"a",
"map",
"of",
"name",
"value",
"collection",
"."
] | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/XmlDataProviderImpl.java#L212-L231 |
google/closure-templates | java/src/com/google/template/soy/jssrc/dsl/Expression.java | Expression.operation | public static Expression operation(Operator op, List<Expression> operands) {
Preconditions.checkArgument(operands.size() == op.getNumOperands());
Preconditions.checkArgument(
op != Operator.AND && op != Operator.OR && op != Operator.CONDITIONAL);
switch (op.getNumOperands()) {
case 1:
return PrefixUnaryOperation.create(op, operands.get(0));
case 2:
return BinaryOperation.create(op, operands.get(0), operands.get(1));
default:
throw new AssertionError();
}
} | java | public static Expression operation(Operator op, List<Expression> operands) {
Preconditions.checkArgument(operands.size() == op.getNumOperands());
Preconditions.checkArgument(
op != Operator.AND && op != Operator.OR && op != Operator.CONDITIONAL);
switch (op.getNumOperands()) {
case 1:
return PrefixUnaryOperation.create(op, operands.get(0));
case 2:
return BinaryOperation.create(op, operands.get(0), operands.get(1));
default:
throw new AssertionError();
}
} | [
"public",
"static",
"Expression",
"operation",
"(",
"Operator",
"op",
",",
"List",
"<",
"Expression",
">",
"operands",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"operands",
".",
"size",
"(",
")",
"==",
"op",
".",
"getNumOperands",
"(",
")",
")"... | Creates a code chunk representing the given Soy operator applied to the given operands.
<p>Cannot be used for {@link Operator#AND}, {@link Operator#OR}, or {@link
Operator#CONDITIONAL}, as they require access to a {@link Generator} to generate temporary
variables for short-circuiting. Use {@link Expression#and}, {@link Expression#or}, and {@link
Generator#conditionalExpression} instead. | [
"Creates",
"a",
"code",
"chunk",
"representing",
"the",
"given",
"Soy",
"operator",
"applied",
"to",
"the",
"given",
"operands",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jssrc/dsl/Expression.java#L198-L210 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/productinfo/ProductInfo.java | ProductInfo.getUserExtensionVersionFiles | public static File[] getUserExtensionVersionFiles(File installDir) {
File[] versionFiles = null;
String userDirLoc = System.getenv(BootstrapConstants.ENV_WLP_USER_DIR);
File userDir = (userDirLoc != null) ? new File(userDirLoc) : ((installDir != null) ? new File(installDir, "usr") : null);
if (userDir != null && userDir.exists()) {
File userExtVersionDir = new File(userDir, "extension/lib/versions");
if (userExtVersionDir.exists()) {
versionFiles = userExtVersionDir.listFiles(versionFileFilter);
}
}
return versionFiles;
} | java | public static File[] getUserExtensionVersionFiles(File installDir) {
File[] versionFiles = null;
String userDirLoc = System.getenv(BootstrapConstants.ENV_WLP_USER_DIR);
File userDir = (userDirLoc != null) ? new File(userDirLoc) : ((installDir != null) ? new File(installDir, "usr") : null);
if (userDir != null && userDir.exists()) {
File userExtVersionDir = new File(userDir, "extension/lib/versions");
if (userExtVersionDir.exists()) {
versionFiles = userExtVersionDir.listFiles(versionFileFilter);
}
}
return versionFiles;
} | [
"public",
"static",
"File",
"[",
"]",
"getUserExtensionVersionFiles",
"(",
"File",
"installDir",
")",
"{",
"File",
"[",
"]",
"versionFiles",
"=",
"null",
";",
"String",
"userDirLoc",
"=",
"System",
".",
"getenv",
"(",
"BootstrapConstants",
".",
"ENV_WLP_USER_DIR... | Retrieves the product extension jar bundles located in the installation's usr directory.
@return The array of product extension jar bundles in the default (usr) location. | [
"Retrieves",
"the",
"product",
"extension",
"jar",
"bundles",
"located",
"in",
"the",
"installation",
"s",
"usr",
"directory",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/productinfo/ProductInfo.java#L233-L247 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.