repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 218 | func_name stringlengths 5 140 | whole_func_string stringlengths 79 3.99k | language stringclasses 1
value | func_code_string stringlengths 79 3.99k | func_code_tokens listlengths 20 624 | func_documentation_string stringlengths 61 1.96k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 107 339 |
|---|---|---|---|---|---|---|---|---|---|---|
Twitter4J/Twitter4J | twitter4j-core/src/internal-http/java/twitter4j/HttpParameter.java | HttpParameter.decodeParameters | public static List<HttpParameter> decodeParameters(String queryParameters) {
List<HttpParameter> result=new ArrayList<HttpParameter>();
for (String pair : queryParameters.split("&")) {
String[] parts=pair.split("=", 2);
if(parts.length == 2) {
String name=decode(parts[0]);
String value=decode(parts[1]);
if(!name.equals("") && !value.equals(""))
result.add(new HttpParameter(name, value));
}
}
return result;
} | java | public static List<HttpParameter> decodeParameters(String queryParameters) {
List<HttpParameter> result=new ArrayList<HttpParameter>();
for (String pair : queryParameters.split("&")) {
String[] parts=pair.split("=", 2);
if(parts.length == 2) {
String name=decode(parts[0]);
String value=decode(parts[1]);
if(!name.equals("") && !value.equals(""))
result.add(new HttpParameter(name, value));
}
}
return result;
} | [
"public",
"static",
"List",
"<",
"HttpParameter",
">",
"decodeParameters",
"(",
"String",
"queryParameters",
")",
"{",
"List",
"<",
"HttpParameter",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"HttpParameter",
">",
"(",
")",
";",
"for",
"(",
"String",
"pair... | Parses a query string without the leading "?"
@param queryParameters a query parameter string, like a=hello&b=world
@return decoded parameters | [
"Parses",
"a",
"query",
"string",
"without",
"the",
"leading",
"?"
] | train | https://github.com/Twitter4J/Twitter4J/blob/8376fade8d557896bb9319fb46e39a55b134b166/twitter4j-core/src/internal-http/java/twitter4j/HttpParameter.java#L332-L344 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.recoverDeletedCertificateAsync | public Observable<CertificateBundle> recoverDeletedCertificateAsync(String vaultBaseUrl, String certificateName) {
return recoverDeletedCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<CertificateBundle>, CertificateBundle>() {
@Override
public CertificateBundle call(ServiceResponse<CertificateBundle> response) {
return response.body();
}
});
} | java | public Observable<CertificateBundle> recoverDeletedCertificateAsync(String vaultBaseUrl, String certificateName) {
return recoverDeletedCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<CertificateBundle>, CertificateBundle>() {
@Override
public CertificateBundle call(ServiceResponse<CertificateBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"CertificateBundle",
">",
"recoverDeletedCertificateAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
")",
"{",
"return",
"recoverDeletedCertificateWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"certificateName",
")",... | Recovers the deleted certificate back to its current version under /certificates.
The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the deleted certificate's attributes). This operation requires the certificates/recover permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the deleted certificate
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the CertificateBundle object | [
"Recovers",
"the",
"deleted",
"certificate",
"back",
"to",
"its",
"current",
"version",
"under",
"/",
"certificates",
".",
"The",
"RecoverDeletedCertificate",
"operation",
"performs",
"the",
"reversal",
"of",
"the",
"Delete",
"operation",
".",
"The",
"operation",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L8736-L8743 |
threerings/nenya | core/src/main/java/com/threerings/media/image/Quantize.java | Quantize.quantizeImage | public static int[] quantizeImage(int pixels[][], int max_colors) {
Cube cube = new Cube(pixels, max_colors);
cube.classification();
cube.reduction();
cube.assignment();
return cube.colormap;
} | java | public static int[] quantizeImage(int pixels[][], int max_colors) {
Cube cube = new Cube(pixels, max_colors);
cube.classification();
cube.reduction();
cube.assignment();
return cube.colormap;
} | [
"public",
"static",
"int",
"[",
"]",
"quantizeImage",
"(",
"int",
"pixels",
"[",
"]",
"[",
"]",
",",
"int",
"max_colors",
")",
"{",
"Cube",
"cube",
"=",
"new",
"Cube",
"(",
"pixels",
",",
"max_colors",
")",
";",
"cube",
".",
"classification",
"(",
")... | Reduce the image to the given number of colors.
@param pixels an in/out parameter that should initially contain
[A]RGB values but that will contain color palette indicies upon return.
@return The new color palette. | [
"Reduce",
"the",
"image",
"to",
"the",
"given",
"number",
"of",
"colors",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/image/Quantize.java#L310-L316 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/TableCellWithActionExample.java | TableCellWithActionExample.createTableModel | private TableDataModel createTableModel() {
return new AbstractTableDataModel() {
/**
* Column id for the first name column.
*/
private static final int FIRST_NAME = 0;
/**
* Column id for the last name column.
*/
private static final int LAST_NAME = 1;
/**
* Column id for the date of birth column.
*/
private static final int DOB = 2;
/**
* Column id for the action column.
*/
private static final int BUTTON = 3;
private final List<Person> data
= Arrays.asList(new Person[]{new Person(123, "Joe", "Bloggs",
parse("01/02/1973")),
new Person(456, "Jane", "Bloggs", parse("04/05/1976")),
new Person(789, "Kid", "Bloggs", parse("31/12/1999"))});
/**
* {@inheritDoc}
*/
@Override
public Object getValueAt(final int row, final int col) {
Person person = data.get(row);
switch (col) {
case FIRST_NAME:
return person.getFirstName();
case LAST_NAME:
return person.getLastName();
case DOB: {
if (person.getDateOfBirth() == null) {
return null;
}
return person.getDateOfBirth();
}
case BUTTON: {
return person;
}
default:
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public int getRowCount() {
return data.size();
}
};
} | java | private TableDataModel createTableModel() {
return new AbstractTableDataModel() {
/**
* Column id for the first name column.
*/
private static final int FIRST_NAME = 0;
/**
* Column id for the last name column.
*/
private static final int LAST_NAME = 1;
/**
* Column id for the date of birth column.
*/
private static final int DOB = 2;
/**
* Column id for the action column.
*/
private static final int BUTTON = 3;
private final List<Person> data
= Arrays.asList(new Person[]{new Person(123, "Joe", "Bloggs",
parse("01/02/1973")),
new Person(456, "Jane", "Bloggs", parse("04/05/1976")),
new Person(789, "Kid", "Bloggs", parse("31/12/1999"))});
/**
* {@inheritDoc}
*/
@Override
public Object getValueAt(final int row, final int col) {
Person person = data.get(row);
switch (col) {
case FIRST_NAME:
return person.getFirstName();
case LAST_NAME:
return person.getLastName();
case DOB: {
if (person.getDateOfBirth() == null) {
return null;
}
return person.getDateOfBirth();
}
case BUTTON: {
return person;
}
default:
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public int getRowCount() {
return data.size();
}
};
} | [
"private",
"TableDataModel",
"createTableModel",
"(",
")",
"{",
"return",
"new",
"AbstractTableDataModel",
"(",
")",
"{",
"/**\n\t\t\t * Column id for the first name column.\n\t\t\t */",
"private",
"static",
"final",
"int",
"FIRST_NAME",
"=",
"0",
";",
"/**\n\t\t\t * Column... | Creates a table data model containing some dummy person data.
@return a new data model. | [
"Creates",
"a",
"table",
"data",
"model",
"containing",
"some",
"dummy",
"person",
"data",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/datatable/TableCellWithActionExample.java#L103-L170 |
trustathsh/ifmapj | src/main/java/de/hshannover/f4/trust/ifmapj/identifier/Identity.java | Identity.extendedIdentifierEquals | private boolean extendedIdentifierEquals(String eid1, String eid2) {
try {
return DomHelpers.compare(DomHelpers.toDocument(eid1, null),
DomHelpers.toDocument(eid2, null));
} catch (MarshalException e) {
return false;
}
} | java | private boolean extendedIdentifierEquals(String eid1, String eid2) {
try {
return DomHelpers.compare(DomHelpers.toDocument(eid1, null),
DomHelpers.toDocument(eid2, null));
} catch (MarshalException e) {
return false;
}
} | [
"private",
"boolean",
"extendedIdentifierEquals",
"(",
"String",
"eid1",
",",
"String",
"eid2",
")",
"{",
"try",
"{",
"return",
"DomHelpers",
".",
"compare",
"(",
"DomHelpers",
".",
"toDocument",
"(",
"eid1",
",",
"null",
")",
",",
"DomHelpers",
".",
"toDocu... | Compare two extended identifiers
@param eid1 Extended identifier XML string
@param eid2 Extended identifier XML string
@return boolean true if both are equal
@since 0.1.5 | [
"Compare",
"two",
"extended",
"identifiers"
] | train | https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/de/hshannover/f4/trust/ifmapj/identifier/Identity.java#L181-L188 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java | FutureUtils.retryOperation | private static <T> void retryOperation(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Executor executor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationFuture = operation.get();
operationFuture.whenCompleteAsync(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(new RetryException("Operation future was cancelled.", throwable));
} else {
if (retries > 0) {
retryOperation(
resultFuture,
operation,
retries - 1,
executor);
} else {
resultFuture.completeExceptionally(new RetryException("Could not complete the operation. Number of retries " +
"has been exhausted.", throwable));
}
}
} else {
resultFuture.complete(t);
}
},
executor);
resultFuture.whenComplete(
(t, throwable) -> operationFuture.cancel(false));
}
} | java | private static <T> void retryOperation(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Executor executor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationFuture = operation.get();
operationFuture.whenCompleteAsync(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(new RetryException("Operation future was cancelled.", throwable));
} else {
if (retries > 0) {
retryOperation(
resultFuture,
operation,
retries - 1,
executor);
} else {
resultFuture.completeExceptionally(new RetryException("Could not complete the operation. Number of retries " +
"has been exhausted.", throwable));
}
}
} else {
resultFuture.complete(t);
}
},
executor);
resultFuture.whenComplete(
(t, throwable) -> operationFuture.cancel(false));
}
} | [
"private",
"static",
"<",
"T",
">",
"void",
"retryOperation",
"(",
"final",
"CompletableFuture",
"<",
"T",
">",
"resultFuture",
",",
"final",
"Supplier",
"<",
"CompletableFuture",
"<",
"T",
">",
">",
"operation",
",",
"final",
"int",
"retries",
",",
"final",... | Helper method which retries the provided operation in case of a failure.
@param resultFuture to complete
@param operation to retry
@param retries until giving up
@param executor to run the futures
@param <T> type of the future's result | [
"Helper",
"method",
"which",
"retries",
"the",
"provided",
"operation",
"in",
"case",
"of",
"a",
"failure",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java#L97-L132 |
jeluard/semantic-versioning | api/src/main/java/org/osjava/jardiff/JarDiff.java | JarDiff.loadClasses | private void loadClasses(Map infoMap, URL path) throws DiffException {
try {
File jarFile = null;
if(!"file".equals(path.getProtocol()) || path.getHost() != null) {
// If it's not a local file, store it as a temporary jar file.
// java.util.jar.JarFile requires a local file handle.
jarFile = File.createTempFile("jardiff","jar");
// Mark it to be deleted on exit.
jarFile.deleteOnExit();
InputStream in = path.openStream();
OutputStream out = new FileOutputStream(jarFile);
byte[] buffer = new byte[4096];
int i;
while( (i = in.read(buffer,0,buffer.length)) != -1) {
out.write(buffer, 0, i);
}
in.close();
out.close();
} else {
// Else it's a local file, nothing special to do.
jarFile = new File(path.getPath());
}
loadClasses(infoMap, jarFile);
} catch (IOException ioe) {
throw new DiffException(ioe);
}
} | java | private void loadClasses(Map infoMap, URL path) throws DiffException {
try {
File jarFile = null;
if(!"file".equals(path.getProtocol()) || path.getHost() != null) {
// If it's not a local file, store it as a temporary jar file.
// java.util.jar.JarFile requires a local file handle.
jarFile = File.createTempFile("jardiff","jar");
// Mark it to be deleted on exit.
jarFile.deleteOnExit();
InputStream in = path.openStream();
OutputStream out = new FileOutputStream(jarFile);
byte[] buffer = new byte[4096];
int i;
while( (i = in.read(buffer,0,buffer.length)) != -1) {
out.write(buffer, 0, i);
}
in.close();
out.close();
} else {
// Else it's a local file, nothing special to do.
jarFile = new File(path.getPath());
}
loadClasses(infoMap, jarFile);
} catch (IOException ioe) {
throw new DiffException(ioe);
}
} | [
"private",
"void",
"loadClasses",
"(",
"Map",
"infoMap",
",",
"URL",
"path",
")",
"throws",
"DiffException",
"{",
"try",
"{",
"File",
"jarFile",
"=",
"null",
";",
"if",
"(",
"!",
"\"file\"",
".",
"equals",
"(",
"path",
".",
"getProtocol",
"(",
")",
")"... | Load all the classes from the specified URL and store information
about them in the specified map.
This currently only works for jar files, <b>not</b> directories
which contain classes in subdirectories or in the current directory.
@param infoMap the map to store the ClassInfo in.
@throws DiffException if there is an exception reading info about a
class. | [
"Load",
"all",
"the",
"classes",
"from",
"the",
"specified",
"URL",
"and",
"store",
"information",
"about",
"them",
"in",
"the",
"specified",
"map",
".",
"This",
"currently",
"only",
"works",
"for",
"jar",
"files",
"<b",
">",
"not<",
"/",
"b",
">",
"dire... | train | https://github.com/jeluard/semantic-versioning/blob/d0bfbeddca8ac4202f5225810227c72a708360a9/api/src/main/java/org/osjava/jardiff/JarDiff.java#L178-L204 |
Alluxio/alluxio | minicluster/src/main/java/alluxio/multi/process/Master.java | Master.updateConf | public void updateConf(PropertyKey key, @Nullable String value) {
if (value == null) {
mProperties.remove(key);
} else {
mProperties.put(key, value);
}
} | java | public void updateConf(PropertyKey key, @Nullable String value) {
if (value == null) {
mProperties.remove(key);
} else {
mProperties.put(key, value);
}
} | [
"public",
"void",
"updateConf",
"(",
"PropertyKey",
"key",
",",
"@",
"Nullable",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"mProperties",
".",
"remove",
"(",
"key",
")",
";",
"}",
"else",
"{",
"mProperties",
".",
"put",
... | Updates the master's configuration. This update will take effect the next time the master
is started.
@param key the conf key to update
@param value the value to set, or null to unset the key | [
"Updates",
"the",
"master",
"s",
"configuration",
".",
"This",
"update",
"will",
"take",
"effect",
"the",
"next",
"time",
"the",
"master",
"is",
"started",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/minicluster/src/main/java/alluxio/multi/process/Master.java#L57-L63 |
web3j/web3j | core/src/main/java/org/web3j/crypto/Bip44WalletUtils.java | Bip44WalletUtils.generateBip44Wallet | public static Bip39Wallet generateBip44Wallet(String password, File destinationDirectory)
throws CipherException, IOException {
return generateBip44Wallet(password, destinationDirectory, false);
} | java | public static Bip39Wallet generateBip44Wallet(String password, File destinationDirectory)
throws CipherException, IOException {
return generateBip44Wallet(password, destinationDirectory, false);
} | [
"public",
"static",
"Bip39Wallet",
"generateBip44Wallet",
"(",
"String",
"password",
",",
"File",
"destinationDirectory",
")",
"throws",
"CipherException",
",",
"IOException",
"{",
"return",
"generateBip44Wallet",
"(",
"password",
",",
"destinationDirectory",
",",
"fals... | Generates a BIP-44 compatible Ethereum wallet on top of BIP-39 generated seed.
@param password Will be used for both wallet encryption and passphrase for BIP-39 seed
@param destinationDirectory The directory containing the wallet
@return A BIP-39 compatible Ethereum wallet
@throws CipherException if the underlying cipher is not available
@throws IOException if the destination cannot be written to | [
"Generates",
"a",
"BIP",
"-",
"44",
"compatible",
"Ethereum",
"wallet",
"on",
"top",
"of",
"BIP",
"-",
"39",
"generated",
"seed",
"."
] | train | https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/crypto/Bip44WalletUtils.java#L19-L22 |
codelibs/fess | src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java | FessMessages.addConstraintsLengthMessage | public FessMessages addConstraintsLengthMessage(String property, String min, String max) {
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_Length_MESSAGE, min, max));
return this;
} | java | public FessMessages addConstraintsLengthMessage(String property, String min, String max) {
assertPropertyNotNull(property);
add(property, new UserMessage(CONSTRAINTS_Length_MESSAGE, min, max));
return this;
} | [
"public",
"FessMessages",
"addConstraintsLengthMessage",
"(",
"String",
"property",
",",
"String",
"min",
",",
"String",
"max",
")",
"{",
"assertPropertyNotNull",
"(",
"property",
")",
";",
"add",
"(",
"property",
",",
"new",
"UserMessage",
"(",
"CONSTRAINTS_Lengt... | Add the created action message for the key 'constraints.Length.message' with parameters.
<pre>
message: Length of {item} must be between {min} and {max}.
</pre>
@param property The property name for the message. (NotNull)
@param min The parameter min for message. (NotNull)
@param max The parameter max for message. (NotNull)
@return this. (NotNull) | [
"Add",
"the",
"created",
"action",
"message",
"for",
"the",
"key",
"constraints",
".",
"Length",
".",
"message",
"with",
"parameters",
".",
"<pre",
">",
"message",
":",
"Length",
"of",
"{",
"item",
"}",
"must",
"be",
"between",
"{",
"min",
"}",
"and",
... | train | https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L844-L848 |
belaban/JGroups | src/org/jgroups/util/CondVar.java | CondVar.waitFor | public boolean waitFor(Condition condition, long timeout, TimeUnit unit) {
boolean intr=false;
final long timeout_ns=TimeUnit.NANOSECONDS.convert(timeout, unit);
lock.lock();
try {
for(long wait_time=timeout_ns, start=System.nanoTime(); wait_time > 0 && !condition.isMet();) {
try {
wait_time=cond.awaitNanos(wait_time);
}
catch(InterruptedException e) {
wait_time=timeout_ns - (System.nanoTime() - start);
intr=true;
}
}
return condition.isMet();
}
finally {
lock.unlock();
if(intr) Thread.currentThread().interrupt();
}
} | java | public boolean waitFor(Condition condition, long timeout, TimeUnit unit) {
boolean intr=false;
final long timeout_ns=TimeUnit.NANOSECONDS.convert(timeout, unit);
lock.lock();
try {
for(long wait_time=timeout_ns, start=System.nanoTime(); wait_time > 0 && !condition.isMet();) {
try {
wait_time=cond.awaitNanos(wait_time);
}
catch(InterruptedException e) {
wait_time=timeout_ns - (System.nanoTime() - start);
intr=true;
}
}
return condition.isMet();
}
finally {
lock.unlock();
if(intr) Thread.currentThread().interrupt();
}
} | [
"public",
"boolean",
"waitFor",
"(",
"Condition",
"condition",
",",
"long",
"timeout",
",",
"TimeUnit",
"unit",
")",
"{",
"boolean",
"intr",
"=",
"false",
";",
"final",
"long",
"timeout_ns",
"=",
"TimeUnit",
".",
"NANOSECONDS",
".",
"convert",
"(",
"timeout"... | Blocks until condition is true or the time elapsed
@param condition The condition
@param timeout The timeout to wait. A value <= 0 causes immediate return
@param unit TimeUnit
@return The condition's status | [
"Blocks",
"until",
"condition",
"is",
"true",
"or",
"the",
"time",
"elapsed"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/CondVar.java#L56-L76 |
bwkimmel/java-util | src/main/java/ca/eandb/util/progress/ProgressDialog.java | ProgressDialog.setProgressBarValue | private void setProgressBarValue(int value, int maximum) {
this.progressBar.setIndeterminate(false);
if (this.progressBar.getMaximum() != maximum) {
this.progressBar.setMaximum(maximum);
}
this.progressBar.setValue(value);
} | java | private void setProgressBarValue(int value, int maximum) {
this.progressBar.setIndeterminate(false);
if (this.progressBar.getMaximum() != maximum) {
this.progressBar.setMaximum(maximum);
}
this.progressBar.setValue(value);
} | [
"private",
"void",
"setProgressBarValue",
"(",
"int",
"value",
",",
"int",
"maximum",
")",
"{",
"this",
".",
"progressBar",
".",
"setIndeterminate",
"(",
"false",
")",
";",
"if",
"(",
"this",
".",
"progressBar",
".",
"getMaximum",
"(",
")",
"!=",
"maximum"... | Updates the progress bar on this dialog.
@param value The number of parts of the operation that have been
completed.
@param maximum The number of parts that compose the operation. | [
"Updates",
"the",
"progress",
"bar",
"on",
"this",
"dialog",
"."
] | train | https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/progress/ProgressDialog.java#L184-L194 |
ragnor/simple-spring-memcached | simple-spring-memcached/src/main/java/com/google/code/ssm/json/ClassAliasTypeResolverBuilder.java | ClassAliasTypeResolverBuilder.setClassToId | public void setClassToId(final Map<Class<?>, String> classToId) {
Map<String, Class<?>> reverseMap = new HashMap<String, Class<?>>();
for (Map.Entry<Class<?>, String> entry : classToId.entrySet()) {
Assert.notNull(entry.getKey(), "Class cannot be null: " + entry);
Assert.hasText(entry.getValue(), "Alias (id) cannot be null or contain only whitespaces" + entry);
if (reverseMap.put(entry.getValue(), entry.getKey()) != null) {
throw new IllegalArgumentException("Two or more classes with the same alias (id): " + entry.getValue());
}
}
this.classToId = classToId;
this.idToClass = reverseMap;
} | java | public void setClassToId(final Map<Class<?>, String> classToId) {
Map<String, Class<?>> reverseMap = new HashMap<String, Class<?>>();
for (Map.Entry<Class<?>, String> entry : classToId.entrySet()) {
Assert.notNull(entry.getKey(), "Class cannot be null: " + entry);
Assert.hasText(entry.getValue(), "Alias (id) cannot be null or contain only whitespaces" + entry);
if (reverseMap.put(entry.getValue(), entry.getKey()) != null) {
throw new IllegalArgumentException("Two or more classes with the same alias (id): " + entry.getValue());
}
}
this.classToId = classToId;
this.idToClass = reverseMap;
} | [
"public",
"void",
"setClassToId",
"(",
"final",
"Map",
"<",
"Class",
"<",
"?",
">",
",",
"String",
">",
"classToId",
")",
"{",
"Map",
"<",
"String",
",",
"Class",
"<",
"?",
">",
">",
"reverseMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Class",
... | Registers mappings between classes and aliases (ids).
@param classToId | [
"Registers",
"mappings",
"between",
"classes",
"and",
"aliases",
"(",
"ids",
")",
"."
] | train | https://github.com/ragnor/simple-spring-memcached/blob/83db68aa1af219397e132426e377d45f397d31e7/simple-spring-memcached/src/main/java/com/google/code/ssm/json/ClassAliasTypeResolverBuilder.java#L63-L77 |
wildfly-swarm-archive/ARCHIVE-wildfly-swarm | batch-jberet/api/src/main/java/org/wildfly/swarm/batch/jberet/BatchFraction.java | BatchFraction.defaultJobRepository | public BatchFraction defaultJobRepository(final String name, final DatasourcesFraction datasource) {
jdbcJobRepository(name, datasource);
return defaultJobRepository(name);
} | java | public BatchFraction defaultJobRepository(final String name, final DatasourcesFraction datasource) {
jdbcJobRepository(name, datasource);
return defaultJobRepository(name);
} | [
"public",
"BatchFraction",
"defaultJobRepository",
"(",
"final",
"String",
"name",
",",
"final",
"DatasourcesFraction",
"datasource",
")",
"{",
"jdbcJobRepository",
"(",
"name",
",",
"datasource",
")",
";",
"return",
"defaultJobRepository",
"(",
"name",
")",
";",
... | Adds a new JDBC job repository and sets it as the default job repository.
@param name the name for the JDBC job repository
@param datasource the datasource to use to connect to the database
@return this fraction | [
"Adds",
"a",
"new",
"JDBC",
"job",
"repository",
"and",
"sets",
"it",
"as",
"the",
"default",
"job",
"repository",
"."
] | train | https://github.com/wildfly-swarm-archive/ARCHIVE-wildfly-swarm/blob/28ef71bcfa743a7267666e0ed2919c37b356c09b/batch-jberet/api/src/main/java/org/wildfly/swarm/batch/jberet/BatchFraction.java#L108-L111 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/xml/MessageValidatorRegistryParser.java | MessageValidatorRegistryParser.parseValidators | private void parseValidators(BeanDefinitionBuilder builder, Element element) {
ManagedList validators = new ManagedList();
for (Element validator : DomUtils.getChildElementsByTagName(element, "validator")) {
if (validator.hasAttribute("ref")) {
validators.add(new RuntimeBeanReference(validator.getAttribute("ref")));
} else {
validators.add(BeanDefinitionBuilder.rootBeanDefinition(validator.getAttribute("class")).getBeanDefinition());
}
}
if (!validators.isEmpty()) {
builder.addPropertyValue("messageValidators", validators);
}
} | java | private void parseValidators(BeanDefinitionBuilder builder, Element element) {
ManagedList validators = new ManagedList();
for (Element validator : DomUtils.getChildElementsByTagName(element, "validator")) {
if (validator.hasAttribute("ref")) {
validators.add(new RuntimeBeanReference(validator.getAttribute("ref")));
} else {
validators.add(BeanDefinitionBuilder.rootBeanDefinition(validator.getAttribute("class")).getBeanDefinition());
}
}
if (!validators.isEmpty()) {
builder.addPropertyValue("messageValidators", validators);
}
} | [
"private",
"void",
"parseValidators",
"(",
"BeanDefinitionBuilder",
"builder",
",",
"Element",
"element",
")",
"{",
"ManagedList",
"validators",
"=",
"new",
"ManagedList",
"(",
")",
";",
"for",
"(",
"Element",
"validator",
":",
"DomUtils",
".",
"getChildElementsBy... | Parses all variable definitions and adds those to the bean definition
builder as property value.
@param builder the target bean definition builder.
@param element the source element. | [
"Parses",
"all",
"variable",
"definitions",
"and",
"adds",
"those",
"to",
"the",
"bean",
"definition",
"builder",
"as",
"property",
"value",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/xml/MessageValidatorRegistryParser.java#L51-L65 |
javamelody/javamelody | javamelody-swing/src/main/java/net/bull/javamelody/swing/ImageFileChooser.java | ImageFileChooser.chooseImage | public static File chooseImage(Component parent, boolean openOrSave, String fileName) {
final int result;
if (fileName != null) {
IMAGE_FILE_CHOOSER.setSelectedFile(new File(fileName));
}
if (openOrSave) {
result = IMAGE_FILE_CHOOSER.showOpenDialog(parent);
} else {
result = IMAGE_FILE_CHOOSER.showSaveDialog(parent);
}
if (result == JFileChooser.APPROVE_OPTION) {
File file = IMAGE_FILE_CHOOSER.getSelectedFile();
file = IMAGE_FILE_CHOOSER.checkFile(file);
return file;
}
return null;
} | java | public static File chooseImage(Component parent, boolean openOrSave, String fileName) {
final int result;
if (fileName != null) {
IMAGE_FILE_CHOOSER.setSelectedFile(new File(fileName));
}
if (openOrSave) {
result = IMAGE_FILE_CHOOSER.showOpenDialog(parent);
} else {
result = IMAGE_FILE_CHOOSER.showSaveDialog(parent);
}
if (result == JFileChooser.APPROVE_OPTION) {
File file = IMAGE_FILE_CHOOSER.getSelectedFile();
file = IMAGE_FILE_CHOOSER.checkFile(file);
return file;
}
return null;
} | [
"public",
"static",
"File",
"chooseImage",
"(",
"Component",
"parent",
",",
"boolean",
"openOrSave",
",",
"String",
"fileName",
")",
"{",
"final",
"int",
"result",
";",
"if",
"(",
"fileName",
"!=",
"null",
")",
"{",
"IMAGE_FILE_CHOOSER",
".",
"setSelectedFile"... | Ouvre la boîte de dialogue de choix de fichier image.
<br>Retourne le fichier choisi, ou null si annulé.
@param parent Component
@param openOrSave boolean
@param fileName String
@return File | [
"Ouvre",
"la",
"boîte",
"de",
"dialogue",
"de",
"choix",
"de",
"fichier",
"image",
".",
"<br",
">",
"Retourne",
"le",
"fichier",
"choisi",
"ou",
"null",
"si",
"annulé",
"."
] | train | https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/ImageFileChooser.java#L70-L86 |
ontop/ontop | binding/rdf4j/src/main/java/it/unibz/inf/ontop/rdf4j/repository/impl/OntopVirtualRepository.java | OntopVirtualRepository.getConnection | @Override
public RepositoryConnection getConnection() throws RepositoryException {
try {
return new OntopRepositoryConnection(this, getOntopConnection(), inputQueryFactory);
} catch (Exception e) {
logger.error("Error creating repo connection: " + e.getMessage());
throw new RepositoryException(e);
}
} | java | @Override
public RepositoryConnection getConnection() throws RepositoryException {
try {
return new OntopRepositoryConnection(this, getOntopConnection(), inputQueryFactory);
} catch (Exception e) {
logger.error("Error creating repo connection: " + e.getMessage());
throw new RepositoryException(e);
}
} | [
"@",
"Override",
"public",
"RepositoryConnection",
"getConnection",
"(",
")",
"throws",
"RepositoryException",
"{",
"try",
"{",
"return",
"new",
"OntopRepositoryConnection",
"(",
"this",
",",
"getOntopConnection",
"(",
")",
",",
"inputQueryFactory",
")",
";",
"}",
... | Returns a new RepositoryConnection.
(No repository connection sharing for the sake
of thread-safeness) | [
"Returns",
"a",
"new",
"RepositoryConnection",
"."
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/binding/rdf4j/src/main/java/it/unibz/inf/ontop/rdf4j/repository/impl/OntopVirtualRepository.java#L63-L71 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTableRowRenderer.java | WTableRowRenderer.addColumn | void addColumn(final WTableColumn column, final int columnIndex) {
WComponent renderer = column.getRenderer();
if (renderer == null) {
Class<? extends WComponent> rendererClass = column.getRendererClass();
if (!(BeanProviderBound.class.isAssignableFrom(rendererClass))
&& !(BeanBound.class.isAssignableFrom(rendererClass))
&& !(DataBound.class.isAssignableFrom(rendererClass))) {
throw new IllegalArgumentException(
"Column renderers must be BeanProvider-, Bean- or Data-Bound");
}
add(new RendererWrapper(this, rendererClass, columnIndex));
} else {
if (!(renderer instanceof BeanProviderBound) && !(renderer instanceof BeanBound)
&& !(renderer instanceof DataBound)) {
throw new IllegalArgumentException(
"Column renderers must be BeanProvider-, Bean- or Data-Bound");
}
add(new RendererWrapper(this, renderer, columnIndex));
}
} | java | void addColumn(final WTableColumn column, final int columnIndex) {
WComponent renderer = column.getRenderer();
if (renderer == null) {
Class<? extends WComponent> rendererClass = column.getRendererClass();
if (!(BeanProviderBound.class.isAssignableFrom(rendererClass))
&& !(BeanBound.class.isAssignableFrom(rendererClass))
&& !(DataBound.class.isAssignableFrom(rendererClass))) {
throw new IllegalArgumentException(
"Column renderers must be BeanProvider-, Bean- or Data-Bound");
}
add(new RendererWrapper(this, rendererClass, columnIndex));
} else {
if (!(renderer instanceof BeanProviderBound) && !(renderer instanceof BeanBound)
&& !(renderer instanceof DataBound)) {
throw new IllegalArgumentException(
"Column renderers must be BeanProvider-, Bean- or Data-Bound");
}
add(new RendererWrapper(this, renderer, columnIndex));
}
} | [
"void",
"addColumn",
"(",
"final",
"WTableColumn",
"column",
",",
"final",
"int",
"columnIndex",
")",
"{",
"WComponent",
"renderer",
"=",
"column",
".",
"getRenderer",
"(",
")",
";",
"if",
"(",
"renderer",
"==",
"null",
")",
"{",
"Class",
"<",
"?",
"exte... | Adds a column to the renderer. This method is called by {@link WTable} to keep the renderer's and table's columns
in sync.
@param column the column to add.
@param columnIndex the index of the column. Zero based. | [
"Adds",
"a",
"column",
"to",
"the",
"renderer",
".",
"This",
"method",
"is",
"called",
"by",
"{",
"@link",
"WTable",
"}",
"to",
"keep",
"the",
"renderer",
"s",
"and",
"table",
"s",
"columns",
"in",
"sync",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTableRowRenderer.java#L319-L342 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Calendar.java | Calendar.computeZoneOffset | protected int computeZoneOffset(long millis, int millisInDay) {
int[] offsets = new int[2];
long wall = millis + millisInDay;
if (zone instanceof BasicTimeZone) {
int duplicatedTimeOpt = (repeatedWallTime == WALLTIME_FIRST) ? BasicTimeZone.LOCAL_FORMER : BasicTimeZone.LOCAL_LATTER;
int nonExistingTimeOpt = (skippedWallTime == WALLTIME_FIRST) ? BasicTimeZone.LOCAL_LATTER : BasicTimeZone.LOCAL_FORMER;
((BasicTimeZone)zone).getOffsetFromLocal(wall, nonExistingTimeOpt, duplicatedTimeOpt, offsets);
} else {
// By default, TimeZone#getOffset behaves WALLTIME_LAST for both.
zone.getOffset(wall, true, offsets);
boolean sawRecentNegativeShift = false;
if (repeatedWallTime == WALLTIME_FIRST) {
// Check if the given wall time falls into repeated time range
long tgmt = wall - (offsets[0] + offsets[1]);
// Any negative zone transition within last 6 hours?
// Note: The maximum historic negative zone transition is -3 hours in the tz database.
// 6 hour window would be sufficient for this purpose.
int offsetBefore6 = zone.getOffset(tgmt - 6*60*60*1000);
int offsetDelta = (offsets[0] + offsets[1]) - offsetBefore6;
assert offsetDelta > -6*60*60*1000 : offsetDelta;
if (offsetDelta < 0) {
sawRecentNegativeShift = true;
// Negative shift within last 6 hours. When WALLTIME_FIRST is used and the given wall time falls
// into the repeated time range, use offsets before the transition.
// Note: If it does not fall into the repeated time range, offsets remain unchanged below.
zone.getOffset(wall + offsetDelta, true, offsets);
}
}
if (!sawRecentNegativeShift && skippedWallTime == WALLTIME_FIRST) {
// When skipped wall time option is WALLTIME_FIRST,
// recalculate offsets from the resolved time (non-wall).
// When the given wall time falls into skipped wall time,
// the offsets will be based on the zone offsets AFTER
// the transition (which means, earliest possibe interpretation).
long tgmt = wall - (offsets[0] + offsets[1]);
zone.getOffset(tgmt, false, offsets);
}
}
return offsets[0] + offsets[1];
} | java | protected int computeZoneOffset(long millis, int millisInDay) {
int[] offsets = new int[2];
long wall = millis + millisInDay;
if (zone instanceof BasicTimeZone) {
int duplicatedTimeOpt = (repeatedWallTime == WALLTIME_FIRST) ? BasicTimeZone.LOCAL_FORMER : BasicTimeZone.LOCAL_LATTER;
int nonExistingTimeOpt = (skippedWallTime == WALLTIME_FIRST) ? BasicTimeZone.LOCAL_LATTER : BasicTimeZone.LOCAL_FORMER;
((BasicTimeZone)zone).getOffsetFromLocal(wall, nonExistingTimeOpt, duplicatedTimeOpt, offsets);
} else {
// By default, TimeZone#getOffset behaves WALLTIME_LAST for both.
zone.getOffset(wall, true, offsets);
boolean sawRecentNegativeShift = false;
if (repeatedWallTime == WALLTIME_FIRST) {
// Check if the given wall time falls into repeated time range
long tgmt = wall - (offsets[0] + offsets[1]);
// Any negative zone transition within last 6 hours?
// Note: The maximum historic negative zone transition is -3 hours in the tz database.
// 6 hour window would be sufficient for this purpose.
int offsetBefore6 = zone.getOffset(tgmt - 6*60*60*1000);
int offsetDelta = (offsets[0] + offsets[1]) - offsetBefore6;
assert offsetDelta > -6*60*60*1000 : offsetDelta;
if (offsetDelta < 0) {
sawRecentNegativeShift = true;
// Negative shift within last 6 hours. When WALLTIME_FIRST is used and the given wall time falls
// into the repeated time range, use offsets before the transition.
// Note: If it does not fall into the repeated time range, offsets remain unchanged below.
zone.getOffset(wall + offsetDelta, true, offsets);
}
}
if (!sawRecentNegativeShift && skippedWallTime == WALLTIME_FIRST) {
// When skipped wall time option is WALLTIME_FIRST,
// recalculate offsets from the resolved time (non-wall).
// When the given wall time falls into skipped wall time,
// the offsets will be based on the zone offsets AFTER
// the transition (which means, earliest possibe interpretation).
long tgmt = wall - (offsets[0] + offsets[1]);
zone.getOffset(tgmt, false, offsets);
}
}
return offsets[0] + offsets[1];
} | [
"protected",
"int",
"computeZoneOffset",
"(",
"long",
"millis",
",",
"int",
"millisInDay",
")",
"{",
"int",
"[",
"]",
"offsets",
"=",
"new",
"int",
"[",
"2",
"]",
";",
"long",
"wall",
"=",
"millis",
"+",
"millisInDay",
";",
"if",
"(",
"zone",
"instance... | This method can assume EXTENDED_YEAR has been set.
@param millis milliseconds of the date fields (local midnight millis)
@param millisInDay milliseconds of the time fields; may be out
or range.
@return total zone offset (raw + DST) for the given moment
@deprecated This method suffers from a potential integer overflow and may be removed or
changed in a future release. See <a href="http://bugs.icu-project.org/trac/ticket/11632">
ICU ticket #11632</a> for details. | [
"This",
"method",
"can",
"assume",
"EXTENDED_YEAR",
"has",
"been",
"set",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Calendar.java#L5531-L5573 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/util/ZooKeeperUtils.java | ZooKeeperUtils.createLeaderElectionService | public static ZooKeeperLeaderElectionService createLeaderElectionService(
final CuratorFramework client,
final Configuration configuration,
final String pathSuffix) {
final String latchPath = configuration.getString(
HighAvailabilityOptions.HA_ZOOKEEPER_LATCH_PATH) + pathSuffix;
final String leaderPath = configuration.getString(
HighAvailabilityOptions.HA_ZOOKEEPER_LEADER_PATH) + pathSuffix;
return new ZooKeeperLeaderElectionService(client, latchPath, leaderPath);
} | java | public static ZooKeeperLeaderElectionService createLeaderElectionService(
final CuratorFramework client,
final Configuration configuration,
final String pathSuffix) {
final String latchPath = configuration.getString(
HighAvailabilityOptions.HA_ZOOKEEPER_LATCH_PATH) + pathSuffix;
final String leaderPath = configuration.getString(
HighAvailabilityOptions.HA_ZOOKEEPER_LEADER_PATH) + pathSuffix;
return new ZooKeeperLeaderElectionService(client, latchPath, leaderPath);
} | [
"public",
"static",
"ZooKeeperLeaderElectionService",
"createLeaderElectionService",
"(",
"final",
"CuratorFramework",
"client",
",",
"final",
"Configuration",
"configuration",
",",
"final",
"String",
"pathSuffix",
")",
"{",
"final",
"String",
"latchPath",
"=",
"configura... | Creates a {@link ZooKeeperLeaderElectionService} instance.
@param client The {@link CuratorFramework} ZooKeeper client to use
@param configuration {@link Configuration} object containing the configuration values
@param pathSuffix The path suffix which we want to append
@return {@link ZooKeeperLeaderElectionService} instance. | [
"Creates",
"a",
"{",
"@link",
"ZooKeeperLeaderElectionService",
"}",
"instance",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/util/ZooKeeperUtils.java#L217-L227 |
ysc/word | src/main/java/org/apdplat/word/analysis/ManhattanDistanceTextSimilarity.java | ManhattanDistanceTextSimilarity.scoreImpl | @Override
protected double scoreImpl(List<Word> words1, List<Word> words2) {
//用词频来标注词的权重
taggingWeightWithWordFrequency(words1, words2);
//构造权重快速搜索容器
Map<String, Float> weights1 = toFastSearchMap(words1);
Map<String, Float> weights2 = toFastSearchMap(words2);
//所有的不重复词
Set<Word> words = new HashSet<>();
words.addAll(words1);
words.addAll(words2);
//向量的维度为words的大小,每一个维度的权重是词频
//manhattanDistance=|x1-x2|+|y1-y2|
AtomicFloat manhattanDistance = new AtomicFloat();
//计算
words
.parallelStream()
.forEach(word -> {
Float x1 = weights1.get(word.getText());
Float x2 = weights2.get(word.getText());
if (x1 == null) {
x1 = 0f;
}
if (x2 == null) {
x2 = 0f;
}
//|x1-x2|
float oneOfTheDimension = Math.abs(x1 - x2);
//+
manhattanDistance.addAndGet(oneOfTheDimension);
});
double score = 0;
if(manhattanDistance.get() == 0){
//距离为0,表示完全相同
score = 1.0;
}else {
//使用BigDecimal保证精确计算浮点数
//score = 1 / (double)(manhattanDistance.get()+1);
score = BigDecimal.valueOf(1).divide(BigDecimal.valueOf(manhattanDistance.get()+1), 9, BigDecimal.ROUND_HALF_UP).doubleValue();
}
if(LOGGER.isDebugEnabled()){
LOGGER.debug("文本1和文本2的曼哈顿距离:"+manhattanDistance.get());
LOGGER.debug("文本1和文本2的相似度分值:1 / (double)("+manhattanDistance.get()+"+1)="+score);
}
return score;
} | java | @Override
protected double scoreImpl(List<Word> words1, List<Word> words2) {
//用词频来标注词的权重
taggingWeightWithWordFrequency(words1, words2);
//构造权重快速搜索容器
Map<String, Float> weights1 = toFastSearchMap(words1);
Map<String, Float> weights2 = toFastSearchMap(words2);
//所有的不重复词
Set<Word> words = new HashSet<>();
words.addAll(words1);
words.addAll(words2);
//向量的维度为words的大小,每一个维度的权重是词频
//manhattanDistance=|x1-x2|+|y1-y2|
AtomicFloat manhattanDistance = new AtomicFloat();
//计算
words
.parallelStream()
.forEach(word -> {
Float x1 = weights1.get(word.getText());
Float x2 = weights2.get(word.getText());
if (x1 == null) {
x1 = 0f;
}
if (x2 == null) {
x2 = 0f;
}
//|x1-x2|
float oneOfTheDimension = Math.abs(x1 - x2);
//+
manhattanDistance.addAndGet(oneOfTheDimension);
});
double score = 0;
if(manhattanDistance.get() == 0){
//距离为0,表示完全相同
score = 1.0;
}else {
//使用BigDecimal保证精确计算浮点数
//score = 1 / (double)(manhattanDistance.get()+1);
score = BigDecimal.valueOf(1).divide(BigDecimal.valueOf(manhattanDistance.get()+1), 9, BigDecimal.ROUND_HALF_UP).doubleValue();
}
if(LOGGER.isDebugEnabled()){
LOGGER.debug("文本1和文本2的曼哈顿距离:"+manhattanDistance.get());
LOGGER.debug("文本1和文本2的相似度分值:1 / (double)("+manhattanDistance.get()+"+1)="+score);
}
return score;
} | [
"@",
"Override",
"protected",
"double",
"scoreImpl",
"(",
"List",
"<",
"Word",
">",
"words1",
",",
"List",
"<",
"Word",
">",
"words2",
")",
"{",
"//用词频来标注词的权重",
"taggingWeightWithWordFrequency",
"(",
"words1",
",",
"words2",
")",
";",
"//构造权重快速搜索容器",
"Map",
... | 判定相似度的方式:曼哈顿距离
曼哈顿距离原理:
设A(x1, y1),B(x2, y2)是平面上任意两点
两点间的距离dist(A,B)=|x1-x2|+|y1-y2|
@param words1 词列表1
@param words2 词列表2
@return 相似度分值 | [
"判定相似度的方式:曼哈顿距离",
"曼哈顿距离原理:",
"设A",
"(",
"x1",
"y1",
")",
",B",
"(",
"x2",
"y2",
")",
"是平面上任意两点",
"两点间的距离dist",
"(",
"A",
"B",
")",
"=",
"|x1",
"-",
"x2|",
"+",
"|y1",
"-",
"y2|"
] | train | https://github.com/ysc/word/blob/5e45607f4e97207f55d1e3bc561abda6b34f7c54/src/main/java/org/apdplat/word/analysis/ManhattanDistanceTextSimilarity.java#L50-L95 |
codescape/bitvunit | bitvunit-core/src/main/java/de/codescape/bitvunit/BitvUnit.java | BitvUnit.assertAccessibility | public static void assertAccessibility(InputStream inputStream, Testable testable) {
assertThat(inputStream, is(compliantTo(testable)));
} | java | public static void assertAccessibility(InputStream inputStream, Testable testable) {
assertThat(inputStream, is(compliantTo(testable)));
} | [
"public",
"static",
"void",
"assertAccessibility",
"(",
"InputStream",
"inputStream",
",",
"Testable",
"testable",
")",
"{",
"assertThat",
"(",
"inputStream",
",",
"is",
"(",
"compliantTo",
"(",
"testable",
")",
")",
")",
";",
"}"
] | JUnit Assertion to verify a {@link java.io.InputStream} instance for accessibility.
@param inputStream {@link java.io.InputStream} instance
@param testable rule(s) to apply | [
"JUnit",
"Assertion",
"to",
"verify",
"a",
"{",
"@link",
"java",
".",
"io",
".",
"InputStream",
"}",
"instance",
"for",
"accessibility",
"."
] | train | https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/BitvUnit.java#L78-L80 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/MessageRouterImpl.java | MessageRouterImpl.removeMsgFromLogHandler | protected void removeMsgFromLogHandler(String msgId, String handlerId) {
Set<String> logHandlerIdSet = getOrCreateLogHandlerIdSet(msgId);
logHandlerIdSet.remove(handlerId);
} | java | protected void removeMsgFromLogHandler(String msgId, String handlerId) {
Set<String> logHandlerIdSet = getOrCreateLogHandlerIdSet(msgId);
logHandlerIdSet.remove(handlerId);
} | [
"protected",
"void",
"removeMsgFromLogHandler",
"(",
"String",
"msgId",
",",
"String",
"handlerId",
")",
"{",
"Set",
"<",
"String",
">",
"logHandlerIdSet",
"=",
"getOrCreateLogHandlerIdSet",
"(",
"msgId",
")",
";",
"logHandlerIdSet",
".",
"remove",
"(",
"handlerId... | Remove the specified log handler from the message ID's routing list. | [
"Remove",
"the",
"specified",
"log",
"handler",
"from",
"the",
"message",
"ID",
"s",
"routing",
"list",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/MessageRouterImpl.java#L178-L181 |
carewebframework/carewebframework-core | org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/spring/FrameworkBeanFactory.java | FrameworkBeanFactory.registerBeanDefinition | @Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
boolean canOverride = defaultOverriding;
BeanDefinition oldBeanDefinition = containsBeanDefinition(beanName) ? getBeanDefinition(beanName) : null;
String override = oldBeanDefinition == null ? null : getAttribute(beanDefinition, CAN_OVERRIDE_ATTR);
String isfinal = oldBeanDefinition == null ? null : getAttribute(oldBeanDefinition, IS_FINAL_ATTR);
if (override != null) {
switch (BeanOverride.valueOf(override.toUpperCase())) {
case ALWAYS:
canOverride = true;
break;
case NEVER:
canOverride = false;
break;
case IGNORE:
return;
case DEFAULT:
break;
}
}
if (canOverride && "true".equalsIgnoreCase(isfinal)) {
canOverride = false;
}
super.setAllowBeanDefinitionOverriding(canOverride);
super.registerBeanDefinition(beanName, beanDefinition);
} | java | @Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
boolean canOverride = defaultOverriding;
BeanDefinition oldBeanDefinition = containsBeanDefinition(beanName) ? getBeanDefinition(beanName) : null;
String override = oldBeanDefinition == null ? null : getAttribute(beanDefinition, CAN_OVERRIDE_ATTR);
String isfinal = oldBeanDefinition == null ? null : getAttribute(oldBeanDefinition, IS_FINAL_ATTR);
if (override != null) {
switch (BeanOverride.valueOf(override.toUpperCase())) {
case ALWAYS:
canOverride = true;
break;
case NEVER:
canOverride = false;
break;
case IGNORE:
return;
case DEFAULT:
break;
}
}
if (canOverride && "true".equalsIgnoreCase(isfinal)) {
canOverride = false;
}
super.setAllowBeanDefinitionOverriding(canOverride);
super.registerBeanDefinition(beanName, beanDefinition);
} | [
"@",
"Override",
"public",
"void",
"registerBeanDefinition",
"(",
"String",
"beanName",
",",
"BeanDefinition",
"beanDefinition",
")",
"throws",
"BeanDefinitionStoreException",
"{",
"boolean",
"canOverride",
"=",
"defaultOverriding",
";",
"BeanDefinition",
"oldBeanDefinition... | Intercepts the call set the override behavior of the bean factory prior to registering the
bean. The override behavior is set to the cwf:override setting of the bean definition or, in
the absence of this setting, to the default override behavior for the bean factory and by the
cwf:final setting which can be used to prevent a bean declaration from ever being overridden. | [
"Intercepts",
"the",
"call",
"set",
"the",
"override",
"behavior",
"of",
"the",
"bean",
"factory",
"prior",
"to",
"registering",
"the",
"bean",
".",
"The",
"override",
"behavior",
"is",
"set",
"to",
"the",
"cwf",
":",
"override",
"setting",
"of",
"the",
"b... | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/spring/FrameworkBeanFactory.java#L143-L174 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/interest/FactoryDetectPoint.java | FactoryDetectPoint.createMedian | public static <T extends ImageGray<T>, D extends ImageGray<D>>
GeneralFeatureDetector<T, D> createMedian(@Nullable ConfigGeneralDetector configDetector, Class<T> imageType) {
if( configDetector == null)
configDetector = new ConfigGeneralDetector();
BlurStorageFilter<T> medianFilter = FactoryBlurFilter.median(ImageType.single(imageType), configDetector.radius);
GeneralFeatureIntensity<T, D> intensity = new WrapperMedianCornerIntensity<>(medianFilter);
return createGeneral(intensity, configDetector);
} | java | public static <T extends ImageGray<T>, D extends ImageGray<D>>
GeneralFeatureDetector<T, D> createMedian(@Nullable ConfigGeneralDetector configDetector, Class<T> imageType) {
if( configDetector == null)
configDetector = new ConfigGeneralDetector();
BlurStorageFilter<T> medianFilter = FactoryBlurFilter.median(ImageType.single(imageType), configDetector.radius);
GeneralFeatureIntensity<T, D> intensity = new WrapperMedianCornerIntensity<>(medianFilter);
return createGeneral(intensity, configDetector);
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
",",
"D",
"extends",
"ImageGray",
"<",
"D",
">",
">",
"GeneralFeatureDetector",
"<",
"T",
",",
"D",
">",
"createMedian",
"(",
"@",
"Nullable",
"ConfigGeneralDetector",
"configDetector",
","... | Creates a median filter corner detector.
@param configDetector Configuration for feature detector.
@param imageType Type of input image.
@see boofcv.alg.feature.detect.intensity.MedianCornerIntensity | [
"Creates",
"a",
"median",
"filter",
"corner",
"detector",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/factory/feature/detect/interest/FactoryDetectPoint.java#L169-L178 |
oehf/ipf-oht-atna | auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/dicom/SecurityAlertEvent.java | SecurityAlertEvent.addURIParticipantObject | public void addURIParticipantObject(String failedUri, String failureDescription)
{
List<TypeValuePairType> failureDescriptionValue = new LinkedList<>();
if (!EventUtils.isEmptyOrNull(failureDescription)) {
failureDescriptionValue.add(getTypeValuePair("Alert Description", failureDescription.getBytes()));
}
this.addParticipantObjectIdentification(
new RFC3881ParticipantObjectCodes.RFC3881ParticipantObjectIDTypeCodes.PatientNumber(),
null,
null,
failureDescriptionValue,
failedUri,
RFC3881ParticipantObjectTypeCodes.SYSTEM,
RFC3881ParticipantObjectTypeRoleCodes.MASTER_FILE,
null,
null);
} | java | public void addURIParticipantObject(String failedUri, String failureDescription)
{
List<TypeValuePairType> failureDescriptionValue = new LinkedList<>();
if (!EventUtils.isEmptyOrNull(failureDescription)) {
failureDescriptionValue.add(getTypeValuePair("Alert Description", failureDescription.getBytes()));
}
this.addParticipantObjectIdentification(
new RFC3881ParticipantObjectCodes.RFC3881ParticipantObjectIDTypeCodes.PatientNumber(),
null,
null,
failureDescriptionValue,
failedUri,
RFC3881ParticipantObjectTypeCodes.SYSTEM,
RFC3881ParticipantObjectTypeRoleCodes.MASTER_FILE,
null,
null);
} | [
"public",
"void",
"addURIParticipantObject",
"(",
"String",
"failedUri",
",",
"String",
"failureDescription",
")",
"{",
"List",
"<",
"TypeValuePairType",
">",
"failureDescriptionValue",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"if",
"(",
"!",
"EventUtils",
... | Adds a Participant Object representing the URI resource that was accessed and
generated the Security Alert
@param failedUri The URI accessed
@param failureDescription A description of why the alert was created | [
"Adds",
"a",
"Participant",
"Object",
"representing",
"the",
"URI",
"resource",
"that",
"was",
"accessed",
"and",
"generated",
"the",
"Security",
"Alert"
] | train | https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/dicom/SecurityAlertEvent.java#L90-L106 |
actorapp/actor-platform | actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageDrawing.java | ImageDrawing.drawMasked | public static void drawMasked(Bitmap src, Drawable mask, Bitmap dest, int clearColor) {
clearBitmap(dest, clearColor);
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(src,
new Rect(0, 0, src.getWidth(), src.getHeight()),
new Rect(0, 0, dest.getWidth(), dest.getHeight()),
new Paint(Paint.FILTER_BITMAP_FLAG));
if (mask instanceof BitmapDrawable) {
((BitmapDrawable) mask).getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
} else if (mask instanceof NinePatchDrawable) {
((NinePatchDrawable) mask).getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
} else {
throw new RuntimeException("Supported only BitmapDrawable or NinePatchDrawable");
}
mask.setBounds(0, 0, mask.getIntrinsicWidth(), mask.getIntrinsicHeight());
mask.draw(canvas);
canvas.setBitmap(null);
} | java | public static void drawMasked(Bitmap src, Drawable mask, Bitmap dest, int clearColor) {
clearBitmap(dest, clearColor);
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(src,
new Rect(0, 0, src.getWidth(), src.getHeight()),
new Rect(0, 0, dest.getWidth(), dest.getHeight()),
new Paint(Paint.FILTER_BITMAP_FLAG));
if (mask instanceof BitmapDrawable) {
((BitmapDrawable) mask).getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
} else if (mask instanceof NinePatchDrawable) {
((NinePatchDrawable) mask).getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
} else {
throw new RuntimeException("Supported only BitmapDrawable or NinePatchDrawable");
}
mask.setBounds(0, 0, mask.getIntrinsicWidth(), mask.getIntrinsicHeight());
mask.draw(canvas);
canvas.setBitmap(null);
} | [
"public",
"static",
"void",
"drawMasked",
"(",
"Bitmap",
"src",
",",
"Drawable",
"mask",
",",
"Bitmap",
"dest",
",",
"int",
"clearColor",
")",
"{",
"clearBitmap",
"(",
"dest",
",",
"clearColor",
")",
";",
"Canvas",
"canvas",
"=",
"new",
"Canvas",
"(",
"d... | Drawing src bitmap to dest bitmap with applied mask.
@param src source bitmap
@param mask bitmap mask
@param dest destination bitmap
@param clearColor clear color | [
"Drawing",
"src",
"bitmap",
"to",
"dest",
"bitmap",
"with",
"applied",
"mask",
"."
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/util/images/ops/ImageDrawing.java#L81-L100 |
stapler/stapler | jelly/src/main/java/org/kohsuke/stapler/jelly/JellyClassTearOff.java | JellyClassTearOff.serveIndexJelly | public boolean serveIndexJelly(StaplerRequest req, StaplerResponse rsp, Object node) throws ServletException, IOException {
try {
Script script = findScript("index.jelly");
if(script!=null) {
String src = "index.jelly";
if (script instanceof JellyViewScript) {
JellyViewScript jvs = (JellyViewScript) script;
src = jvs.getName();
}
Dispatcher.anonymizedTraceEval(req, rsp, node, "%s: Jelly index: %s", src);
if(traceable()) {
trace(req,rsp,"-> %s on <%s>",src,node);
}
facet.scriptInvoker.invokeScript(req, rsp, script, node);
return true;
}
return false;
} catch (JellyException e) {
throw new ServletException(e);
}
} | java | public boolean serveIndexJelly(StaplerRequest req, StaplerResponse rsp, Object node) throws ServletException, IOException {
try {
Script script = findScript("index.jelly");
if(script!=null) {
String src = "index.jelly";
if (script instanceof JellyViewScript) {
JellyViewScript jvs = (JellyViewScript) script;
src = jvs.getName();
}
Dispatcher.anonymizedTraceEval(req, rsp, node, "%s: Jelly index: %s", src);
if(traceable()) {
trace(req,rsp,"-> %s on <%s>",src,node);
}
facet.scriptInvoker.invokeScript(req, rsp, script, node);
return true;
}
return false;
} catch (JellyException e) {
throw new ServletException(e);
}
} | [
"public",
"boolean",
"serveIndexJelly",
"(",
"StaplerRequest",
"req",
",",
"StaplerResponse",
"rsp",
",",
"Object",
"node",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"try",
"{",
"Script",
"script",
"=",
"findScript",
"(",
"\"index.jelly\"",
")",
... | Serves <tt>index.jelly</tt> if it's available, and returns true. | [
"Serves",
"<tt",
">",
"index",
".",
"jelly<",
"/",
"tt",
">",
"if",
"it",
"s",
"available",
"and",
"returns",
"true",
"."
] | train | https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/jelly/src/main/java/org/kohsuke/stapler/jelly/JellyClassTearOff.java#L101-L121 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataMaxCardinalityImpl_CustomFieldSerializer.java | OWLDataMaxCardinalityImpl_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLDataMaxCardinalityImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLDataMaxCardinalityImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLDataMaxCardinalityImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"
] | Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataMaxCardinalityImpl_CustomFieldSerializer.java#L95-L98 |
BranchMetrics/android-branch-deep-linking | Branch-SDK/src/io/branch/referral/Branch.java | Branch.setIdentity | public void setIdentity(@NonNull String userId, @Nullable BranchReferralInitListener
callback) {
ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
} else {
if (((ServerRequestIdentifyUserRequest) req).isExistingID()) {
((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_);
}
}
} | java | public void setIdentity(@NonNull String userId, @Nullable BranchReferralInitListener
callback) {
ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
} else {
if (((ServerRequestIdentifyUserRequest) req).isExistingID()) {
((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_);
}
}
} | [
"public",
"void",
"setIdentity",
"(",
"@",
"NonNull",
"String",
"userId",
",",
"@",
"Nullable",
"BranchReferralInitListener",
"callback",
")",
"{",
"ServerRequest",
"req",
"=",
"new",
"ServerRequestIdentifyUserRequest",
"(",
"context_",
",",
"callback",
",",
"userId... | <p>Identifies the current user to the Branch API by supplying a unique identifier as a
{@link String} value, with a callback specified to perform a defined action upon successful
response to request.</p>
@param userId A {@link String} value containing the unique identifier of the user.
@param callback A {@link BranchReferralInitListener} callback instance that will return
the data associated with the user id being assigned, if available. | [
"<p",
">",
"Identifies",
"the",
"current",
"user",
"to",
"the",
"Branch",
"API",
"by",
"supplying",
"a",
"unique",
"identifier",
"as",
"a",
"{",
"@link",
"String",
"}",
"value",
"with",
"a",
"callback",
"specified",
"to",
"perform",
"a",
"defined",
"action... | train | https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/Branch.java#L1773-L1783 |
omadahealth/CircularBarPager | library/src/main/java/com/github/omadahealth/circularbarpager/library/viewpager/WrapContentViewPager.java | WrapContentViewPager.onMeasure | @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) {
height = h;
}
}
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (RuntimeException e) {
Log.e(TAG, "Exception during WrapContentViewPager onMeasure " + e.toString());
}
} | java | @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) {
height = h;
}
}
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (RuntimeException e) {
Log.e(TAG, "Exception during WrapContentViewPager onMeasure " + e.toString());
}
} | [
"@",
"Override",
"protected",
"void",
"onMeasure",
"(",
"int",
"widthMeasureSpec",
",",
"int",
"heightMeasureSpec",
")",
"{",
"try",
"{",
"int",
"mode",
"=",
"MeasureSpec",
".",
"getMode",
"(",
"heightMeasureSpec",
")",
";",
"if",
"(",
"mode",
"==",
"Measure... | Allows to redraw the view size to wrap the content of the bigger child.
@param widthMeasureSpec with measured
@param heightMeasureSpec height measured | [
"Allows",
"to",
"redraw",
"the",
"view",
"size",
"to",
"wrap",
"the",
"content",
"of",
"the",
"bigger",
"child",
"."
] | train | https://github.com/omadahealth/CircularBarPager/blob/3a43e8828849da727fd13345e83b8432f7271155/library/src/main/java/com/github/omadahealth/circularbarpager/library/viewpager/WrapContentViewPager.java#L90-L115 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/DiscoveryUtils.java | DiscoveryUtils.loadImplementorClass | private static Class loadImplementorClass( String className, Class interfaceType, ClassLoader classLoader )
{
try
{
if ( _log.isDebugEnabled() )
{
_log.debug( "Trying to load implementor class for interface " + interfaceType.getName()
+ ": " + className );
}
Class implementorClass = classLoader.loadClass( className );
if ( interfaceType.isAssignableFrom( implementorClass ) )
{
return implementorClass;
}
else
{
_log.error( "Implementor class " + className + " does not implement interface "
+ interfaceType.getName() );
}
}
catch ( ClassNotFoundException cnfe )
{
//
// This will happen when the user class was built against an out-of-date interface.
//
_log.error( "Could not find implementor class " + className + " for interface " + interfaceType.getName(),
cnfe );
}
catch ( LinkageError le )
{
_log.error( "Linkage error when loading implementor class " + className + " for interface "
+ interfaceType.getName(), le );
}
return null;
} | java | private static Class loadImplementorClass( String className, Class interfaceType, ClassLoader classLoader )
{
try
{
if ( _log.isDebugEnabled() )
{
_log.debug( "Trying to load implementor class for interface " + interfaceType.getName()
+ ": " + className );
}
Class implementorClass = classLoader.loadClass( className );
if ( interfaceType.isAssignableFrom( implementorClass ) )
{
return implementorClass;
}
else
{
_log.error( "Implementor class " + className + " does not implement interface "
+ interfaceType.getName() );
}
}
catch ( ClassNotFoundException cnfe )
{
//
// This will happen when the user class was built against an out-of-date interface.
//
_log.error( "Could not find implementor class " + className + " for interface " + interfaceType.getName(),
cnfe );
}
catch ( LinkageError le )
{
_log.error( "Linkage error when loading implementor class " + className + " for interface "
+ interfaceType.getName(), le );
}
return null;
} | [
"private",
"static",
"Class",
"loadImplementorClass",
"(",
"String",
"className",
",",
"Class",
"interfaceType",
",",
"ClassLoader",
"classLoader",
")",
"{",
"try",
"{",
"if",
"(",
"_log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"_log",
".",
"debug",
"(",... | Load an implementor class from the context classloader.
@param className the name of the implementor class.
@param interfaceType the interface that the given class should implement.
@param classLoader the ClassLoader from which to load the implementor class.
@return the implementor Class, or <code>null</code> if an error occurred (the error will be logged). | [
"Load",
"an",
"implementor",
"class",
"from",
"the",
"context",
"classloader",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/util/internal/DiscoveryUtils.java#L168-L205 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/util/bdb/BDBRecordSet.java | BDBRecordSet.put | public void put(String keyStr, String valueStr) throws DatabaseException {
DatabaseEntry key = new DatabaseEntry(stringToBytes(keyStr));
DatabaseEntry data = new DatabaseEntry(stringToBytes(valueStr));
db.put(null, key, data);
} | java | public void put(String keyStr, String valueStr) throws DatabaseException {
DatabaseEntry key = new DatabaseEntry(stringToBytes(keyStr));
DatabaseEntry data = new DatabaseEntry(stringToBytes(valueStr));
db.put(null, key, data);
} | [
"public",
"void",
"put",
"(",
"String",
"keyStr",
",",
"String",
"valueStr",
")",
"throws",
"DatabaseException",
"{",
"DatabaseEntry",
"key",
"=",
"new",
"DatabaseEntry",
"(",
"stringToBytes",
"(",
"keyStr",
")",
")",
";",
"DatabaseEntry",
"data",
"=",
"new",
... | persistantly store key-value pair
@param keyStr
@param valueStr
@throws DatabaseException | [
"persistantly",
"store",
"key",
"-",
"value",
"pair"
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/util/bdb/BDBRecordSet.java#L190-L194 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java | ApiOvhEmailexchange.organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_DELETE | public OvhTask organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_DELETE(String organizationName, String exchangeService, Long notifiedAccountId) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId}";
StringBuilder sb = path(qPath, organizationName, exchangeService, notifiedAccountId);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_DELETE(String organizationName, String exchangeService, Long notifiedAccountId) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId}";
StringBuilder sb = path(qPath, organizationName, exchangeService, notifiedAccountId);
String resp = exec(qPath, "DELETE", sb.toString(), null);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"organizationName_service_exchangeService_protocol_activeSyncMailNotification_notifiedAccountId_DELETE",
"(",
"String",
"organizationName",
",",
"String",
"exchangeService",
",",
"Long",
"notifiedAccountId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",... | Unubscribe address from ActiveSync quarantine notifications
REST: DELETE /email/exchange/{organizationName}/service/{exchangeService}/protocol/activeSyncMailNotification/{notifiedAccountId}
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service
@param notifiedAccountId [required] Notified Account Id | [
"Unubscribe",
"address",
"from",
"ActiveSync",
"quarantine",
"notifications"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L2326-L2331 |
micronaut-projects/micronaut-core | inject-java/src/main/java/io/micronaut/annotation/processing/GenericUtils.java | GenericUtils.resolveGenericTypes | protected Map<String, Object> resolveGenericTypes(TypeMirror type, Map<String, Object> boundTypes) {
if (type.getKind().isPrimitive() || type.getKind() == VOID || type.getKind() == ARRAY) {
return Collections.emptyMap();
}
if (type instanceof DeclaredType) {
DeclaredType declaredType = (DeclaredType) type;
return resolveGenericTypes(declaredType, (TypeElement) declaredType.asElement(), boundTypes);
} else if (type instanceof TypeVariable) {
TypeVariable var = (TypeVariable) type;
TypeMirror upperBound = var.getUpperBound();
if (upperBound instanceof DeclaredType) {
return resolveGenericTypes(upperBound, boundTypes);
}
}
return Collections.emptyMap();
} | java | protected Map<String, Object> resolveGenericTypes(TypeMirror type, Map<String, Object> boundTypes) {
if (type.getKind().isPrimitive() || type.getKind() == VOID || type.getKind() == ARRAY) {
return Collections.emptyMap();
}
if (type instanceof DeclaredType) {
DeclaredType declaredType = (DeclaredType) type;
return resolveGenericTypes(declaredType, (TypeElement) declaredType.asElement(), boundTypes);
} else if (type instanceof TypeVariable) {
TypeVariable var = (TypeVariable) type;
TypeMirror upperBound = var.getUpperBound();
if (upperBound instanceof DeclaredType) {
return resolveGenericTypes(upperBound, boundTypes);
}
}
return Collections.emptyMap();
} | [
"protected",
"Map",
"<",
"String",
",",
"Object",
">",
"resolveGenericTypes",
"(",
"TypeMirror",
"type",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"boundTypes",
")",
"{",
"if",
"(",
"type",
".",
"getKind",
"(",
")",
".",
"isPrimitive",
"(",
")",
"... | Resolve the generic type arguments for the given type mirror and bound type arguments.
@param type The type mirror
@param boundTypes The bound types (such as those declared on the class)
@return A map of generic type arguments | [
"Resolve",
"the",
"generic",
"type",
"arguments",
"for",
"the",
"given",
"type",
"mirror",
"and",
"bound",
"type",
"arguments",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject-java/src/main/java/io/micronaut/annotation/processing/GenericUtils.java#L149-L164 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/content/SharedPreferencesUtils.java | SharedPreferencesUtils.putDouble | public static SharedPreferences.Editor putDouble(SharedPreferences.Editor editor, String key, double value) {
return editor.putString(key, String.valueOf(value));
} | java | public static SharedPreferences.Editor putDouble(SharedPreferences.Editor editor, String key, double value) {
return editor.putString(key, String.valueOf(value));
} | [
"public",
"static",
"SharedPreferences",
".",
"Editor",
"putDouble",
"(",
"SharedPreferences",
".",
"Editor",
"editor",
",",
"String",
"key",
",",
"double",
"value",
")",
"{",
"return",
"editor",
".",
"putString",
"(",
"key",
",",
"String",
".",
"valueOf",
"... | Set a double value in the preferences editor.
@see android.content.SharedPreferences.Editor
@param editor the editor
@param key The name of the preference to modify.
@param value The new value for the preference.
@return the editor. | [
"Set",
"a",
"double",
"value",
"in",
"the",
"preferences",
"editor",
"."
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/content/SharedPreferencesUtils.java#L39-L41 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.entryEquals | public static boolean entryEquals(File f1, File f2, String path1, String path2) {
ZipFile zf1 = null;
ZipFile zf2 = null;
try {
zf1 = new ZipFile(f1);
zf2 = new ZipFile(f2);
return doEntryEquals(zf1, zf2, path1, path2);
}
catch (IOException e) {
throw ZipExceptionUtil.rethrow(e);
}
finally {
closeQuietly(zf1);
closeQuietly(zf2);
}
} | java | public static boolean entryEquals(File f1, File f2, String path1, String path2) {
ZipFile zf1 = null;
ZipFile zf2 = null;
try {
zf1 = new ZipFile(f1);
zf2 = new ZipFile(f2);
return doEntryEquals(zf1, zf2, path1, path2);
}
catch (IOException e) {
throw ZipExceptionUtil.rethrow(e);
}
finally {
closeQuietly(zf1);
closeQuietly(zf2);
}
} | [
"public",
"static",
"boolean",
"entryEquals",
"(",
"File",
"f1",
",",
"File",
"f2",
",",
"String",
"path1",
",",
"String",
"path2",
")",
"{",
"ZipFile",
"zf1",
"=",
"null",
";",
"ZipFile",
"zf2",
"=",
"null",
";",
"try",
"{",
"zf1",
"=",
"new",
"ZipF... | Compares two ZIP entries (byte-by-byte). .
@param f1
first ZIP file.
@param f2
second ZIP file.
@param path1
name of the first entry.
@param path2
name of the second entry.
@return <code>true</code> if the contents of the entries were same. | [
"Compares",
"two",
"ZIP",
"entries",
"(",
"byte",
"-",
"by",
"-",
"byte",
")",
".",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L3231-L3248 |
yidongnan/grpc-spring-boot-starter | examples/security-grpc-bearerAuth-server/src/main/java/net/devh/boot/grpc/examples/security/server/GrpcServerService.java | GrpcServerService.sayHello | @Override
@Secured("ROLE_TEST")
public void sayHello(final HelloRequest req, final StreamObserver<HelloReply> responseObserver) {
final HelloReply reply = HelloReply.newBuilder().setMessage("Hello ==> " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
} | java | @Override
@Secured("ROLE_TEST")
public void sayHello(final HelloRequest req, final StreamObserver<HelloReply> responseObserver) {
final HelloReply reply = HelloReply.newBuilder().setMessage("Hello ==> " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
} | [
"@",
"Override",
"@",
"Secured",
"(",
"\"ROLE_TEST\"",
")",
"public",
"void",
"sayHello",
"(",
"final",
"HelloRequest",
"req",
",",
"final",
"StreamObserver",
"<",
"HelloReply",
">",
"responseObserver",
")",
"{",
"final",
"HelloReply",
"reply",
"=",
"HelloReply"... | A grpc method that requests the user to be authenticated and have the role "ROLE_GREET". | [
"A",
"grpc",
"method",
"that",
"requests",
"the",
"user",
"to",
"be",
"authenticated",
"and",
"have",
"the",
"role",
"ROLE_GREET",
"."
] | train | https://github.com/yidongnan/grpc-spring-boot-starter/blob/07f8853cfafc9707584f2371aff012e590217b85/examples/security-grpc-bearerAuth-server/src/main/java/net/devh/boot/grpc/examples/security/server/GrpcServerService.java#L37-L43 |
Azure/azure-sdk-for-java | labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java | GlobalUsersInner.getPersonalPreferencesAsync | public Observable<GetPersonalPreferencesResponseInner> getPersonalPreferencesAsync(String userName, PersonalPreferencesOperationsPayload personalPreferencesOperationsPayload) {
return getPersonalPreferencesWithServiceResponseAsync(userName, personalPreferencesOperationsPayload).map(new Func1<ServiceResponse<GetPersonalPreferencesResponseInner>, GetPersonalPreferencesResponseInner>() {
@Override
public GetPersonalPreferencesResponseInner call(ServiceResponse<GetPersonalPreferencesResponseInner> response) {
return response.body();
}
});
} | java | public Observable<GetPersonalPreferencesResponseInner> getPersonalPreferencesAsync(String userName, PersonalPreferencesOperationsPayload personalPreferencesOperationsPayload) {
return getPersonalPreferencesWithServiceResponseAsync(userName, personalPreferencesOperationsPayload).map(new Func1<ServiceResponse<GetPersonalPreferencesResponseInner>, GetPersonalPreferencesResponseInner>() {
@Override
public GetPersonalPreferencesResponseInner call(ServiceResponse<GetPersonalPreferencesResponseInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"GetPersonalPreferencesResponseInner",
">",
"getPersonalPreferencesAsync",
"(",
"String",
"userName",
",",
"PersonalPreferencesOperationsPayload",
"personalPreferencesOperationsPayload",
")",
"{",
"return",
"getPersonalPreferencesWithServiceResponseAsync",
... | Get personal preferences for a user.
@param userName The name of the user.
@param personalPreferencesOperationsPayload Represents payload for any Environment operations like get, start, stop, connect
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the GetPersonalPreferencesResponseInner object | [
"Get",
"personal",
"preferences",
"for",
"a",
"user",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java#L492-L499 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.csiv2/src/com/ibm/ws/security/csiv2/server/config/tss/ServerConfigHelper.java | ServerConfigHelper.extractSSLTransport | private TSSTransportMechConfig extractSSLTransport(Map<String, Object> transportLayerProperties, Map<String, List<TransportAddress>> addrMap) throws SSLException {
String sslAliasName = (String) transportLayerProperties.get(KEY_SSL_REF);
if (sslAliasName == null)
sslAliasName = defaultAlias;
OptionsKey options = SecurityServices.getSSLConfig().getAssociationOptions(sslAliasName);
TSSSSLTransportConfig transportLayerConfig = new TSSSSLTransportConfig(authenticator);
transportLayerConfig.setSupports(options.supports);
transportLayerConfig.setRequires(options.requires);
List<TransportAddress> addresses = addrMap.get(sslAliasName);
if (addresses == null) {
if (addrMap.size() == 1) {
String messageFromBundle = Tr.formatMessage(tc, "CSIv2_SERVER_TRANSPORT_NO_SSL_CONFIGS_IN_IIOP_ENDPOINT", sslAliasName);
throw new IllegalStateException(messageFromBundle);
} else {
String messageFromBundle = Tr.formatMessage(tc, "CSIv2_SERVER_TRANSPORT_MISMATCHED_SSL_CONFIG", sslAliasName);
throw new IllegalStateException(messageFromBundle);
}
}
transportLayerConfig.setTransportAddresses(addresses);
return transportLayerConfig;
} | java | private TSSTransportMechConfig extractSSLTransport(Map<String, Object> transportLayerProperties, Map<String, List<TransportAddress>> addrMap) throws SSLException {
String sslAliasName = (String) transportLayerProperties.get(KEY_SSL_REF);
if (sslAliasName == null)
sslAliasName = defaultAlias;
OptionsKey options = SecurityServices.getSSLConfig().getAssociationOptions(sslAliasName);
TSSSSLTransportConfig transportLayerConfig = new TSSSSLTransportConfig(authenticator);
transportLayerConfig.setSupports(options.supports);
transportLayerConfig.setRequires(options.requires);
List<TransportAddress> addresses = addrMap.get(sslAliasName);
if (addresses == null) {
if (addrMap.size() == 1) {
String messageFromBundle = Tr.formatMessage(tc, "CSIv2_SERVER_TRANSPORT_NO_SSL_CONFIGS_IN_IIOP_ENDPOINT", sslAliasName);
throw new IllegalStateException(messageFromBundle);
} else {
String messageFromBundle = Tr.formatMessage(tc, "CSIv2_SERVER_TRANSPORT_MISMATCHED_SSL_CONFIG", sslAliasName);
throw new IllegalStateException(messageFromBundle);
}
}
transportLayerConfig.setTransportAddresses(addresses);
return transportLayerConfig;
} | [
"private",
"TSSTransportMechConfig",
"extractSSLTransport",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"transportLayerProperties",
",",
"Map",
"<",
"String",
",",
"List",
"<",
"TransportAddress",
">",
">",
"addrMap",
")",
"throws",
"SSLException",
"{",
"String... | /*
This method extract the fields corresponding to TAG_TLS_SEC_TRANS. Referring to CORBA spec, this corresponds to a
TaggedComponent, and have structure as below.
struct TLS_SEC_TRANS {
----AssociationOptions target_supports;
----AssociationOptions target_requires;
----TransportAddressList addresses;
};
and
struct TransportAddress {
----string host_name;
----unsigned short port;
}; | [
"/",
"*",
"This",
"method",
"extract",
"the",
"fields",
"corresponding",
"to",
"TAG_TLS_SEC_TRANS",
".",
"Referring",
"to",
"CORBA",
"spec",
"this",
"corresponds",
"to",
"a",
"TaggedComponent",
"and",
"have",
"structure",
"as",
"below",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2/src/com/ibm/ws/security/csiv2/server/config/tss/ServerConfigHelper.java#L206-L228 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClient.java | ThriftClient.onPersist | @Override
protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
{
Connection conn = getConnection();
try
{
// if entity is embeddable...call cql translator to get cql string!
// use thrift client to execute cql query.
if (isCql3Enabled(entityMetadata))
{
cqlClient.persist(entityMetadata, entity, conn.getClient(), rlHolders,
getTtlValues().get(entityMetadata.getTableName()));
}
else
{
Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
prepareMutation(entityMetadata, entity, id, rlHolders, mutationMap);
// Write Mutation map to database
conn.getClient().batch_mutate(mutationMap, getConsistencyLevel());
mutationMap.clear();
mutationMap = null;
}
}
catch (InvalidRequestException e)
{
log.error("Error while persisting record, Caused by: .", e);
throw new KunderaException(e);
}
catch (TException e)
{
log.error("Error while persisting record, Caused by: .", e);
throw new KunderaException(e);
}
catch (UnsupportedEncodingException e)
{
log.error("Error while persisting record, Caused by: .", e);
throw new KunderaException(e);
}
finally
{
releaseConnection(conn);
if (isTtlPerRequest())
{
getTtlValues().clear();
}
}
} | java | @Override
protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
{
Connection conn = getConnection();
try
{
// if entity is embeddable...call cql translator to get cql string!
// use thrift client to execute cql query.
if (isCql3Enabled(entityMetadata))
{
cqlClient.persist(entityMetadata, entity, conn.getClient(), rlHolders,
getTtlValues().get(entityMetadata.getTableName()));
}
else
{
Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
prepareMutation(entityMetadata, entity, id, rlHolders, mutationMap);
// Write Mutation map to database
conn.getClient().batch_mutate(mutationMap, getConsistencyLevel());
mutationMap.clear();
mutationMap = null;
}
}
catch (InvalidRequestException e)
{
log.error("Error while persisting record, Caused by: .", e);
throw new KunderaException(e);
}
catch (TException e)
{
log.error("Error while persisting record, Caused by: .", e);
throw new KunderaException(e);
}
catch (UnsupportedEncodingException e)
{
log.error("Error while persisting record, Caused by: .", e);
throw new KunderaException(e);
}
finally
{
releaseConnection(conn);
if (isTtlPerRequest())
{
getTtlValues().clear();
}
}
} | [
"@",
"Override",
"protected",
"void",
"onPersist",
"(",
"EntityMetadata",
"entityMetadata",
",",
"Object",
"entity",
",",
"Object",
"id",
",",
"List",
"<",
"RelationHolder",
">",
"rlHolders",
")",
"{",
"Connection",
"conn",
"=",
"getConnection",
"(",
")",
";",... | Persists a {@link Node} to database.
@param entityMetadata
the entity metadata
@param entity
the entity
@param id
the id
@param rlHolders
the rl holders | [
"Persists",
"a",
"{",
"@link",
"Node",
"}",
"to",
"database",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClient.java#L182-L232 |
xmlunit/xmlunit | xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/DifferenceEngine.java | DifferenceEngine.unequalNotNull | private boolean unequalNotNull(Object expected, Object actual) {
if ((XMLUnit.getIgnoreWhitespace() || XMLUnit.getNormalizeWhitespace())
&& expected instanceof String && actual instanceof String) {
String expectedString = ((String) expected).trim();
String actualString = ((String) actual).trim();
if (XMLUnit.getNormalizeWhitespace()) {
expectedString = normalizeWhitespace(expectedString);
actualString = normalizeWhitespace(actualString);
}
return !expectedString.equals(actualString);
}
return !(expected.equals(actual));
} | java | private boolean unequalNotNull(Object expected, Object actual) {
if ((XMLUnit.getIgnoreWhitespace() || XMLUnit.getNormalizeWhitespace())
&& expected instanceof String && actual instanceof String) {
String expectedString = ((String) expected).trim();
String actualString = ((String) actual).trim();
if (XMLUnit.getNormalizeWhitespace()) {
expectedString = normalizeWhitespace(expectedString);
actualString = normalizeWhitespace(actualString);
}
return !expectedString.equals(actualString);
}
return !(expected.equals(actual));
} | [
"private",
"boolean",
"unequalNotNull",
"(",
"Object",
"expected",
",",
"Object",
"actual",
")",
"{",
"if",
"(",
"(",
"XMLUnit",
".",
"getIgnoreWhitespace",
"(",
")",
"||",
"XMLUnit",
".",
"getNormalizeWhitespace",
"(",
")",
")",
"&&",
"expected",
"instanceof"... | Test two non-null values for inequality
@param expected
@param actual
@return TRUE if the values are not equals() equal (taking whitespace
into account if necessary) | [
"Test",
"two",
"non",
"-",
"null",
"values",
"for",
"inequality"
] | train | https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/DifferenceEngine.java#L908-L920 |
hsiafan/apk-parser | src/main/java/net/dongliu/apk/parser/utils/Buffers.java | Buffers.sliceAndSkip | public static ByteBuffer sliceAndSkip(ByteBuffer buffer, int size) {
ByteBuffer buf = buffer.slice().order(ByteOrder.LITTLE_ENDIAN);
ByteBuffer slice = (ByteBuffer) ((Buffer) buf).limit(buf.position() + size);
skip(buffer, size);
return slice;
} | java | public static ByteBuffer sliceAndSkip(ByteBuffer buffer, int size) {
ByteBuffer buf = buffer.slice().order(ByteOrder.LITTLE_ENDIAN);
ByteBuffer slice = (ByteBuffer) ((Buffer) buf).limit(buf.position() + size);
skip(buffer, size);
return slice;
} | [
"public",
"static",
"ByteBuffer",
"sliceAndSkip",
"(",
"ByteBuffer",
"buffer",
",",
"int",
"size",
")",
"{",
"ByteBuffer",
"buf",
"=",
"buffer",
".",
"slice",
"(",
")",
".",
"order",
"(",
"ByteOrder",
".",
"LITTLE_ENDIAN",
")",
";",
"ByteBuffer",
"slice",
... | Return one new ByteBuffer from current position, with size, the byte order of new buffer will be set to little endian;
And advance the original buffer with size. | [
"Return",
"one",
"new",
"ByteBuffer",
"from",
"current",
"position",
"with",
"size",
"the",
"byte",
"order",
"of",
"new",
"buffer",
"will",
"be",
"set",
"to",
"little",
"endian",
";",
"And",
"advance",
"the",
"original",
"buffer",
"with",
"size",
"."
] | train | https://github.com/hsiafan/apk-parser/blob/8993ddd52017b37b8f2e784ae0a15417d9ede932/src/main/java/net/dongliu/apk/parser/utils/Buffers.java#L122-L127 |
pravega/pravega | common/src/main/java/io/pravega/common/io/serialization/VersionedSerializer.java | VersionedSerializer.ensureCondition | void ensureCondition(boolean condition, String messageFormat, Object... args) throws SerializationException {
if (!condition) {
throw new SerializationException(String.format(messageFormat, args));
}
} | java | void ensureCondition(boolean condition, String messageFormat, Object... args) throws SerializationException {
if (!condition) {
throw new SerializationException(String.format(messageFormat, args));
}
} | [
"void",
"ensureCondition",
"(",
"boolean",
"condition",
",",
"String",
"messageFormat",
",",
"Object",
"...",
"args",
")",
"throws",
"SerializationException",
"{",
"if",
"(",
"!",
"condition",
")",
"{",
"throw",
"new",
"SerializationException",
"(",
"String",
".... | Verifies that the given condition is true. If not, throws a SerializationException. | [
"Verifies",
"that",
"the",
"given",
"condition",
"is",
"true",
".",
"If",
"not",
"throws",
"a",
"SerializationException",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/io/serialization/VersionedSerializer.java#L160-L164 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java | PathBuilder.get | @SuppressWarnings("unchecked")
public <A extends Comparable<?>> DateTimePath<A> get(DateTimePath<A> path) {
DateTimePath<A> newPath = getDateTime(toString(path), (Class<A>) path.getType());
return addMetadataOf(newPath, path);
} | java | @SuppressWarnings("unchecked")
public <A extends Comparable<?>> DateTimePath<A> get(DateTimePath<A> path) {
DateTimePath<A> newPath = getDateTime(toString(path), (Class<A>) path.getType());
return addMetadataOf(newPath, path);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"A",
"extends",
"Comparable",
"<",
"?",
">",
">",
"DateTimePath",
"<",
"A",
">",
"get",
"(",
"DateTimePath",
"<",
"A",
">",
"path",
")",
"{",
"DateTimePath",
"<",
"A",
">",
"newPath",
"... | Create a new DateTime path
@param <A>
@param path existing path
@return property path | [
"Create",
"a",
"new",
"DateTime",
"path"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/PathBuilder.java#L287-L291 |
Erudika/para | para-client/src/main/java/com/erudika/para/client/ParaClient.java | ParaClient.getLinkedObjects | @SuppressWarnings("unchecked")
public <P extends ParaObject> List<P> getLinkedObjects(ParaObject obj, String type2, Pager... pager) {
if (obj == null || obj.getId() == null || type2 == null) {
return Collections.emptyList();
}
String url = Utils.formatMessage("{0}/links/{1}", obj.getObjectURI(), type2);
return getItems((Map<String, Object>) getEntity(invokeGet(url, pagerToParams(pager)), Map.class), pager);
} | java | @SuppressWarnings("unchecked")
public <P extends ParaObject> List<P> getLinkedObjects(ParaObject obj, String type2, Pager... pager) {
if (obj == null || obj.getId() == null || type2 == null) {
return Collections.emptyList();
}
String url = Utils.formatMessage("{0}/links/{1}", obj.getObjectURI(), type2);
return getItems((Map<String, Object>) getEntity(invokeGet(url, pagerToParams(pager)), Map.class), pager);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"P",
"extends",
"ParaObject",
">",
"List",
"<",
"P",
">",
"getLinkedObjects",
"(",
"ParaObject",
"obj",
",",
"String",
"type2",
",",
"Pager",
"...",
"pager",
")",
"{",
"if",
"(",
"obj",
"... | Returns all objects linked to the given one. Only applicable to many-to-many relationships.
@param <P> type of linked objects
@param type2 type of linked objects to search for
@param obj the object to execute this method on
@param pager a {@link com.erudika.para.utils.Pager}
@return a list of linked objects | [
"Returns",
"all",
"objects",
"linked",
"to",
"the",
"given",
"one",
".",
"Only",
"applicable",
"to",
"many",
"-",
"to",
"-",
"many",
"relationships",
"."
] | train | https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L958-L965 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/discrim/SingleDiscriminatorAlgorithm.java | SingleDiscriminatorAlgorithm.discriminate | public int discriminate(VirtualConnection vc, Object discrimData, ConnectionLink prevChannelLink) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "discriminate: " + vc);
}
ConnectionLink nextChannelLink = nextChannel.getConnectionLink(vc);
prevChannelLink.setApplicationCallback(nextChannelLink);
nextChannelLink.setDeviceLink(prevChannelLink);
return DiscriminationProcess.SUCCESS;
} | java | public int discriminate(VirtualConnection vc, Object discrimData, ConnectionLink prevChannelLink) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "discriminate: " + vc);
}
ConnectionLink nextChannelLink = nextChannel.getConnectionLink(vc);
prevChannelLink.setApplicationCallback(nextChannelLink);
nextChannelLink.setDeviceLink(prevChannelLink);
return DiscriminationProcess.SUCCESS;
} | [
"public",
"int",
"discriminate",
"(",
"VirtualConnection",
"vc",
",",
"Object",
"discrimData",
",",
"ConnectionLink",
"prevChannelLink",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")"... | Use a VirtualConnection rather than a InboundVirtualConnection for discrimination | [
"Use",
"a",
"VirtualConnection",
"rather",
"than",
"a",
"InboundVirtualConnection",
"for",
"discrimination"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/channelfw/internal/discrim/SingleDiscriminatorAlgorithm.java#L57-L65 |
jhy/jsoup | src/main/java/org/jsoup/nodes/DataNode.java | DataNode.createFromEncoded | public static DataNode createFromEncoded(String encodedData, String baseUri) {
String data = Entities.unescape(encodedData);
return new DataNode(data);
} | java | public static DataNode createFromEncoded(String encodedData, String baseUri) {
String data = Entities.unescape(encodedData);
return new DataNode(data);
} | [
"public",
"static",
"DataNode",
"createFromEncoded",
"(",
"String",
"encodedData",
",",
"String",
"baseUri",
")",
"{",
"String",
"data",
"=",
"Entities",
".",
"unescape",
"(",
"encodedData",
")",
";",
"return",
"new",
"DataNode",
"(",
"data",
")",
";",
"}"
] | Create a new DataNode from HTML encoded data.
@param encodedData encoded data
@param baseUri bass URI
@return new DataNode | [
"Create",
"a",
"new",
"DataNode",
"from",
"HTML",
"encoded",
"data",
"."
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/DataNode.java#L68-L71 |
structr/structr | structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java | HtmlServlet.findNodeByUuid | private AbstractNode findNodeByUuid(final SecurityContext securityContext, final String uuid) throws FrameworkException {
if (!uuid.isEmpty()) {
logger.debug("Requested id: {}", uuid);
return (AbstractNode) StructrApp.getInstance(securityContext).getNodeById(uuid);
}
return null;
} | java | private AbstractNode findNodeByUuid(final SecurityContext securityContext, final String uuid) throws FrameworkException {
if (!uuid.isEmpty()) {
logger.debug("Requested id: {}", uuid);
return (AbstractNode) StructrApp.getInstance(securityContext).getNodeById(uuid);
}
return null;
} | [
"private",
"AbstractNode",
"findNodeByUuid",
"(",
"final",
"SecurityContext",
"securityContext",
",",
"final",
"String",
"uuid",
")",
"throws",
"FrameworkException",
"{",
"if",
"(",
"!",
"uuid",
".",
"isEmpty",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
... | Find node by uuid
@param securityContext
@param request
@param uuid
@return node
@throws FrameworkException | [
"Find",
"node",
"by",
"uuid"
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java#L1004-L1014 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/LongTermRetentionBackupsInner.java | LongTermRetentionBackupsInner.listByDatabaseAsync | public Observable<Page<LongTermRetentionBackupInner>> listByDatabaseAsync(final String locationName, final String longTermRetentionServerName, final String longTermRetentionDatabaseName) {
return listByDatabaseWithServiceResponseAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName)
.map(new Func1<ServiceResponse<Page<LongTermRetentionBackupInner>>, Page<LongTermRetentionBackupInner>>() {
@Override
public Page<LongTermRetentionBackupInner> call(ServiceResponse<Page<LongTermRetentionBackupInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<LongTermRetentionBackupInner>> listByDatabaseAsync(final String locationName, final String longTermRetentionServerName, final String longTermRetentionDatabaseName) {
return listByDatabaseWithServiceResponseAsync(locationName, longTermRetentionServerName, longTermRetentionDatabaseName)
.map(new Func1<ServiceResponse<Page<LongTermRetentionBackupInner>>, Page<LongTermRetentionBackupInner>>() {
@Override
public Page<LongTermRetentionBackupInner> call(ServiceResponse<Page<LongTermRetentionBackupInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"LongTermRetentionBackupInner",
">",
">",
"listByDatabaseAsync",
"(",
"final",
"String",
"locationName",
",",
"final",
"String",
"longTermRetentionServerName",
",",
"final",
"String",
"longTermRetentionDatabaseName",
")",
"{",
"... | Lists all long term retention backups for a database.
@param locationName The location of the database
@param longTermRetentionServerName the String value
@param longTermRetentionDatabaseName the String value
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<LongTermRetentionBackupInner> object | [
"Lists",
"all",
"long",
"term",
"retention",
"backups",
"for",
"a",
"database",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/LongTermRetentionBackupsInner.java#L434-L442 |
cdk/cdk | base/reaction/src/main/java/org/openscience/cdk/reaction/ReactionEngine.java | ReactionEngine.initiateDictionary | private EntryReact initiateDictionary(String nameDict, IReactionProcess reaction) {
DictionaryDatabase db = new DictionaryDatabase();
dictionary = db.getDictionary(nameDict);
String entryString = reaction.getSpecification().getSpecificationReference();
entryString = entryString.substring(entryString.indexOf('#') + 1, entryString.length());
return (EntryReact) dictionary.getEntry(entryString.toLowerCase());
} | java | private EntryReact initiateDictionary(String nameDict, IReactionProcess reaction) {
DictionaryDatabase db = new DictionaryDatabase();
dictionary = db.getDictionary(nameDict);
String entryString = reaction.getSpecification().getSpecificationReference();
entryString = entryString.substring(entryString.indexOf('#') + 1, entryString.length());
return (EntryReact) dictionary.getEntry(entryString.toLowerCase());
} | [
"private",
"EntryReact",
"initiateDictionary",
"(",
"String",
"nameDict",
",",
"IReactionProcess",
"reaction",
")",
"{",
"DictionaryDatabase",
"db",
"=",
"new",
"DictionaryDatabase",
"(",
")",
";",
"dictionary",
"=",
"db",
".",
"getDictionary",
"(",
"nameDict",
")... | Open the Dictionary OWLReact.
@param nameDict Name of the Dictionary
@param reaction The IReactionProcess
@return The entry for this reaction | [
"Open",
"the",
"Dictionary",
"OWLReact",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/reaction/src/main/java/org/openscience/cdk/reaction/ReactionEngine.java#L102-L109 |
cqframework/clinical_quality_language | Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java | ElmBaseVisitor.visitExpressionDef | public T visitExpressionDef(ExpressionDef elm, C context) {
visitElement(elm.getExpression(), context);
return null;
} | java | public T visitExpressionDef(ExpressionDef elm, C context) {
visitElement(elm.getExpression(), context);
return null;
} | [
"public",
"T",
"visitExpressionDef",
"(",
"ExpressionDef",
"elm",
",",
"C",
"context",
")",
"{",
"visitElement",
"(",
"elm",
".",
"getExpression",
"(",
")",
",",
"context",
")",
";",
"return",
"null",
";",
"}"
] | Visit a ExpressionDef. This method will be called for
every node in the tree that is a ExpressionDef.
@param elm the ELM tree
@param context the context passed to the visitor
@return the visitor result | [
"Visit",
"a",
"ExpressionDef",
".",
"This",
"method",
"will",
"be",
"called",
"for",
"every",
"node",
"in",
"the",
"tree",
"that",
"is",
"a",
"ExpressionDef",
"."
] | train | https://github.com/cqframework/clinical_quality_language/blob/67459d1ef453e49db8d7c5c86e87278377ed0a0b/Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java#L316-L319 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/SelectionCriteria.java | SelectionCriteria.setAlias | public void setAlias(String alias)
{
m_alias = alias;
String attributePath = (String)getAttribute();
boolean allPathsAliased = true;
m_userAlias = new UserAlias(alias, attributePath, allPathsAliased);
} | java | public void setAlias(String alias)
{
m_alias = alias;
String attributePath = (String)getAttribute();
boolean allPathsAliased = true;
m_userAlias = new UserAlias(alias, attributePath, allPathsAliased);
} | [
"public",
"void",
"setAlias",
"(",
"String",
"alias",
")",
"{",
"m_alias",
"=",
"alias",
";",
"String",
"attributePath",
"=",
"(",
"String",
")",
"getAttribute",
"(",
")",
";",
"boolean",
"allPathsAliased",
"=",
"true",
";",
"m_userAlias",
"=",
"new",
"Use... | Sets the alias. By default the entire attribute path participates in the alias
@param alias The name of the alias to set | [
"Sets",
"the",
"alias",
".",
"By",
"default",
"the",
"entire",
"attribute",
"path",
"participates",
"in",
"the",
"alias"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/SelectionCriteria.java#L215-L222 |
glyptodon/guacamole-client | extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/tunnel/ActiveConnectionMultimap.java | ActiveConnectionMultimap.put | public void put(String identifier, ActiveConnectionRecord record) {
synchronized (records) {
// Get set of active connection records, creating if necessary
Set<ActiveConnectionRecord> connections = records.get(identifier);
if (connections == null) {
connections = Collections.synchronizedSet(Collections.newSetFromMap(new LinkedHashMap<ActiveConnectionRecord, Boolean>()));
records.put(identifier, connections);
}
// Add active connection
connections.add(record);
}
} | java | public void put(String identifier, ActiveConnectionRecord record) {
synchronized (records) {
// Get set of active connection records, creating if necessary
Set<ActiveConnectionRecord> connections = records.get(identifier);
if (connections == null) {
connections = Collections.synchronizedSet(Collections.newSetFromMap(new LinkedHashMap<ActiveConnectionRecord, Boolean>()));
records.put(identifier, connections);
}
// Add active connection
connections.add(record);
}
} | [
"public",
"void",
"put",
"(",
"String",
"identifier",
",",
"ActiveConnectionRecord",
"record",
")",
"{",
"synchronized",
"(",
"records",
")",
"{",
"// Get set of active connection records, creating if necessary",
"Set",
"<",
"ActiveConnectionRecord",
">",
"connections",
"... | Stores the given connection record in the list of active connections
associated with the object having the given identifier.
@param identifier
The identifier of the object being connected to.
@param record
The record associated with the active connection. | [
"Stores",
"the",
"given",
"connection",
"record",
"in",
"the",
"list",
"of",
"active",
"connections",
"associated",
"with",
"the",
"object",
"having",
"the",
"given",
"identifier",
"."
] | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/tunnel/ActiveConnectionMultimap.java#L53-L67 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/spi/ServiceProviderFinderFactory.java | ServiceProviderFinderFactory._getServiceProviderFinderFromInitParam | private static ServiceProviderFinder _getServiceProviderFinderFromInitParam(ExternalContext context)
{
String initializerClassName = context.getInitParameter(SERVICE_PROVIDER_FINDER_PARAM);
if (initializerClassName != null)
{
try
{
// get Class object
Class<?> clazz = ClassUtils.classForName(initializerClassName);
if (!ServiceProviderFinder.class.isAssignableFrom(clazz))
{
throw new FacesException("Class " + clazz
+ " does not implement ServiceProviderFinder");
}
// create instance and return it
return (ServiceProviderFinder) ClassUtils.newInstance(clazz);
}
catch (ClassNotFoundException cnfe)
{
throw new FacesException("Could not find class of specified ServiceProviderFinder", cnfe);
}
}
return null;
} | java | private static ServiceProviderFinder _getServiceProviderFinderFromInitParam(ExternalContext context)
{
String initializerClassName = context.getInitParameter(SERVICE_PROVIDER_FINDER_PARAM);
if (initializerClassName != null)
{
try
{
// get Class object
Class<?> clazz = ClassUtils.classForName(initializerClassName);
if (!ServiceProviderFinder.class.isAssignableFrom(clazz))
{
throw new FacesException("Class " + clazz
+ " does not implement ServiceProviderFinder");
}
// create instance and return it
return (ServiceProviderFinder) ClassUtils.newInstance(clazz);
}
catch (ClassNotFoundException cnfe)
{
throw new FacesException("Could not find class of specified ServiceProviderFinder", cnfe);
}
}
return null;
} | [
"private",
"static",
"ServiceProviderFinder",
"_getServiceProviderFinderFromInitParam",
"(",
"ExternalContext",
"context",
")",
"{",
"String",
"initializerClassName",
"=",
"context",
".",
"getInitParameter",
"(",
"SERVICE_PROVIDER_FINDER_PARAM",
")",
";",
"if",
"(",
"initia... | Gets a ServiceProviderFinder from the web.xml config param.
@param context
@return | [
"Gets",
"a",
"ServiceProviderFinder",
"from",
"the",
"web",
".",
"xml",
"config",
"param",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/spi/ServiceProviderFinderFactory.java#L103-L127 |
pravega/pravega | controller/src/main/java/io/pravega/controller/task/Stream/StreamMetadataTasks.java | StreamMetadataTasks.manualScale | public CompletableFuture<ScaleResponse> manualScale(String scope, String stream, List<Long> segmentsToSeal,
List<Map.Entry<Double, Double>> newRanges, long scaleTimestamp,
OperationContext context) {
final long requestId = requestTracker.getRequestIdFor("scaleStream", scope, stream, String.valueOf(scaleTimestamp));
ScaleOpEvent event = new ScaleOpEvent(scope, stream, segmentsToSeal, newRanges, true, scaleTimestamp, requestId);
return addIndexAndSubmitTask(event,
() -> streamMetadataStore.submitScale(scope, stream, segmentsToSeal, new ArrayList<>(newRanges),
scaleTimestamp, null, context, executor))
.handle((startScaleResponse, e) -> {
ScaleResponse.Builder response = ScaleResponse.newBuilder();
if (e != null) {
Throwable cause = Exceptions.unwrap(e);
if (cause instanceof EpochTransitionOperationExceptions.PreConditionFailureException) {
response.setStatus(ScaleResponse.ScaleStreamStatus.PRECONDITION_FAILED);
} else {
log.warn(requestId, "Scale for stream {}/{} failed with exception {}", scope, stream, cause);
response.setStatus(ScaleResponse.ScaleStreamStatus.FAILURE);
}
} else {
log.info(requestId, "scale for stream {}/{} started successfully", scope, stream);
response.setStatus(ScaleResponse.ScaleStreamStatus.STARTED);
response.addAllSegments(
startScaleResponse.getObject().getNewSegmentsWithRange().entrySet()
.stream()
.map(segment -> convert(scope, stream, segment))
.collect(Collectors.toList()));
response.setEpoch(startScaleResponse.getObject().getActiveEpoch());
}
return response.build();
});
} | java | public CompletableFuture<ScaleResponse> manualScale(String scope, String stream, List<Long> segmentsToSeal,
List<Map.Entry<Double, Double>> newRanges, long scaleTimestamp,
OperationContext context) {
final long requestId = requestTracker.getRequestIdFor("scaleStream", scope, stream, String.valueOf(scaleTimestamp));
ScaleOpEvent event = new ScaleOpEvent(scope, stream, segmentsToSeal, newRanges, true, scaleTimestamp, requestId);
return addIndexAndSubmitTask(event,
() -> streamMetadataStore.submitScale(scope, stream, segmentsToSeal, new ArrayList<>(newRanges),
scaleTimestamp, null, context, executor))
.handle((startScaleResponse, e) -> {
ScaleResponse.Builder response = ScaleResponse.newBuilder();
if (e != null) {
Throwable cause = Exceptions.unwrap(e);
if (cause instanceof EpochTransitionOperationExceptions.PreConditionFailureException) {
response.setStatus(ScaleResponse.ScaleStreamStatus.PRECONDITION_FAILED);
} else {
log.warn(requestId, "Scale for stream {}/{} failed with exception {}", scope, stream, cause);
response.setStatus(ScaleResponse.ScaleStreamStatus.FAILURE);
}
} else {
log.info(requestId, "scale for stream {}/{} started successfully", scope, stream);
response.setStatus(ScaleResponse.ScaleStreamStatus.STARTED);
response.addAllSegments(
startScaleResponse.getObject().getNewSegmentsWithRange().entrySet()
.stream()
.map(segment -> convert(scope, stream, segment))
.collect(Collectors.toList()));
response.setEpoch(startScaleResponse.getObject().getActiveEpoch());
}
return response.build();
});
} | [
"public",
"CompletableFuture",
"<",
"ScaleResponse",
">",
"manualScale",
"(",
"String",
"scope",
",",
"String",
"stream",
",",
"List",
"<",
"Long",
">",
"segmentsToSeal",
",",
"List",
"<",
"Map",
".",
"Entry",
"<",
"Double",
",",
"Double",
">",
">",
"newRa... | Helper method to perform scale operation against an scale request.
This method posts a request in the request stream and then starts the scale operation while
tracking it's progress. Eventually, after scale completion, it sends a response to the caller.
@param scope scope.
@param stream stream name.
@param segmentsToSeal segments to be sealed.
@param newRanges key ranges for new segments.
@param scaleTimestamp scaling time stamp.
@param context optional context
@return returns the newly created segments. | [
"Helper",
"method",
"to",
"perform",
"scale",
"operation",
"against",
"an",
"scale",
"request",
".",
"This",
"method",
"posts",
"a",
"request",
"in",
"the",
"request",
"stream",
"and",
"then",
"starts",
"the",
"scale",
"operation",
"while",
"tracking",
"it",
... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/task/Stream/StreamMetadataTasks.java#L532-L564 |
Whiley/WhileyCompiler | src/main/java/wyil/interpreter/Interpreter.java | Interpreter.executeSkip | private Status executeSkip(Stmt.Skip stmt, CallStack frame, EnclosingScope scope) {
// skip !
return Status.NEXT;
} | java | private Status executeSkip(Stmt.Skip stmt, CallStack frame, EnclosingScope scope) {
// skip !
return Status.NEXT;
} | [
"private",
"Status",
"executeSkip",
"(",
"Stmt",
".",
"Skip",
"stmt",
",",
"CallStack",
"frame",
",",
"EnclosingScope",
"scope",
")",
"{",
"// skip !",
"return",
"Status",
".",
"NEXT",
";",
"}"
] | Execute a skip statement at a given point in the function or method
body
@param stmt
--- The skip statement to execute
@param frame
--- The current stack frame
@return | [
"Execute",
"a",
"skip",
"statement",
"at",
"a",
"given",
"point",
"in",
"the",
"function",
"or",
"method",
"body"
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/interpreter/Interpreter.java#L469-L472 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/InstrumentedFileSystemUtils.java | InstrumentedFileSystemUtils.replaceScheme | public static FileStatus replaceScheme(FileStatus st, String replace, String replacement) {
if (replace != null && replace.equals(replacement)) {
return st;
}
try {
return new FileStatus(st.getLen(), st.isDir(), st.getReplication(), st.getBlockSize(), st.getModificationTime(),
st.getAccessTime(), st.getPermission(), st.getOwner(), st.getGroup(), st.isSymlink() ? st.getSymlink() : null,
replaceScheme(st.getPath(), replace, replacement));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
} | java | public static FileStatus replaceScheme(FileStatus st, String replace, String replacement) {
if (replace != null && replace.equals(replacement)) {
return st;
}
try {
return new FileStatus(st.getLen(), st.isDir(), st.getReplication(), st.getBlockSize(), st.getModificationTime(),
st.getAccessTime(), st.getPermission(), st.getOwner(), st.getGroup(), st.isSymlink() ? st.getSymlink() : null,
replaceScheme(st.getPath(), replace, replacement));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
} | [
"public",
"static",
"FileStatus",
"replaceScheme",
"(",
"FileStatus",
"st",
",",
"String",
"replace",
",",
"String",
"replacement",
")",
"{",
"if",
"(",
"replace",
"!=",
"null",
"&&",
"replace",
".",
"equals",
"(",
"replacement",
")",
")",
"{",
"return",
"... | Replace the scheme of the input {@link FileStatus} if it matches the string to replace. | [
"Replace",
"the",
"scheme",
"of",
"the",
"input",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/InstrumentedFileSystemUtils.java#L89-L100 |
antopen/alipay-sdk-java | src/main/java/com/alipay/api/internal/util/WebUtils.java | WebUtils.doPost | public static String doPost(String url, Map<String, String> params, String charset,
int connectTimeout, int readTimeout, String proxyHost,
int proxyPort) throws IOException {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
byte[] content = {};
if (query != null) {
content = query.getBytes(charset);
}
return doPost(url, ctype, content, connectTimeout, readTimeout, proxyHost, proxyPort);
} | java | public static String doPost(String url, Map<String, String> params, String charset,
int connectTimeout, int readTimeout, String proxyHost,
int proxyPort) throws IOException {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
byte[] content = {};
if (query != null) {
content = query.getBytes(charset);
}
return doPost(url, ctype, content, connectTimeout, readTimeout, proxyHost, proxyPort);
} | [
"public",
"static",
"String",
"doPost",
"(",
"String",
"url",
",",
"Map",
"<",
"String",
",",
"String",
">",
"params",
",",
"String",
"charset",
",",
"int",
"connectTimeout",
",",
"int",
"readTimeout",
",",
"String",
"proxyHost",
",",
"int",
"proxyPort",
"... | 执行HTTP POST请求,可使用代理proxy。
@param url 请求地址
@param params 请求参数
@param charset 字符集,如UTF-8, GBK, GB2312
@param connectTimeout 连接超时时间
@param readTimeout 请求超时时间
@param proxyHost 代理host,传null表示不使用代理
@param proxyPort 代理端口,传0表示不使用代理
@return 响应字符串
@throws IOException | [
"执行HTTP",
"POST请求,可使用代理proxy。"
] | train | https://github.com/antopen/alipay-sdk-java/blob/e82aeac7d0239330ee173c7e393596e51e41c1cd/src/main/java/com/alipay/api/internal/util/WebUtils.java#L107-L117 |
alkacon/opencms-core | src/org/opencms/ui/util/table/CmsTableUtil.java | CmsTableUtil.createIconButton | public static Button createIconButton(Resource icon, String caption) {
Button button = new Button();
button.addStyleName(OpenCmsTheme.BUTTON_TABLE_ICON);
button.addStyleName(ValoTheme.BUTTON_BORDERLESS);
button.setIcon(icon);
button.setDescription(caption);
return button;
} | java | public static Button createIconButton(Resource icon, String caption) {
Button button = new Button();
button.addStyleName(OpenCmsTheme.BUTTON_TABLE_ICON);
button.addStyleName(ValoTheme.BUTTON_BORDERLESS);
button.setIcon(icon);
button.setDescription(caption);
return button;
} | [
"public",
"static",
"Button",
"createIconButton",
"(",
"Resource",
"icon",
",",
"String",
"caption",
")",
"{",
"Button",
"button",
"=",
"new",
"Button",
"(",
")",
";",
"button",
".",
"addStyleName",
"(",
"OpenCmsTheme",
".",
"BUTTON_TABLE_ICON",
")",
";",
"b... | Creates an icon button.<p>
@param icon the resource for the icon
@param caption the caption
@return the created button | [
"Creates",
"an",
"icon",
"button",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/util/table/CmsTableUtil.java#L56-L65 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java | ZipEntryUtil.copyEntry | static void copyEntry(ZipEntry originalEntry, InputStream in, ZipOutputStream out, boolean preserveTimestamps) throws IOException {
ZipEntry copy = copy(originalEntry);
if (preserveTimestamps) {
TimestampStrategyFactory.getInstance().setTime(copy, originalEntry);
}
else {
copy.setTime(System.currentTimeMillis());
}
addEntry(copy, new BufferedInputStream(in), out);
} | java | static void copyEntry(ZipEntry originalEntry, InputStream in, ZipOutputStream out, boolean preserveTimestamps) throws IOException {
ZipEntry copy = copy(originalEntry);
if (preserveTimestamps) {
TimestampStrategyFactory.getInstance().setTime(copy, originalEntry);
}
else {
copy.setTime(System.currentTimeMillis());
}
addEntry(copy, new BufferedInputStream(in), out);
} | [
"static",
"void",
"copyEntry",
"(",
"ZipEntry",
"originalEntry",
",",
"InputStream",
"in",
",",
"ZipOutputStream",
"out",
",",
"boolean",
"preserveTimestamps",
")",
"throws",
"IOException",
"{",
"ZipEntry",
"copy",
"=",
"copy",
"(",
"originalEntry",
")",
";",
"i... | Copies a given ZIP entry to a ZIP file. If this.preserveTimestamps is true, original timestamp
is carried over, otherwise uses current time.
@param originalEntry
a ZIP entry from existing ZIP file.
@param in
contents of the ZIP entry.
@param out
target ZIP stream. | [
"Copies",
"a",
"given",
"ZIP",
"entry",
"to",
"a",
"ZIP",
"file",
".",
"If",
"this",
".",
"preserveTimestamps",
"is",
"true",
"original",
"timestamp",
"is",
"carried",
"over",
"otherwise",
"uses",
"current",
"time",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java#L105-L116 |
UrielCh/ovh-java-sdk | ovh-java-sdk-connectivity/src/main/java/net/minidev/ovh/api/ApiOvhConnectivity.java | ApiOvhConnectivity.eligibility_search_buildingDetails_POST | public OvhAsyncTask<OvhBuilding> eligibility_search_buildingDetails_POST(String building) throws IOException {
String qPath = "/connectivity/eligibility/search/buildingDetails";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "building", building);
String resp = execN(qPath, "POST", sb.toString(), o);
return convertTo(resp, t5);
} | java | public OvhAsyncTask<OvhBuilding> eligibility_search_buildingDetails_POST(String building) throws IOException {
String qPath = "/connectivity/eligibility/search/buildingDetails";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "building", building);
String resp = execN(qPath, "POST", sb.toString(), o);
return convertTo(resp, t5);
} | [
"public",
"OvhAsyncTask",
"<",
"OvhBuilding",
">",
"eligibility_search_buildingDetails_POST",
"(",
"String",
"building",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/connectivity/eligibility/search/buildingDetails\"",
";",
"StringBuilder",
"sb",
"=",
"path... | Get the details for a building
REST: POST /connectivity/eligibility/search/buildingDetails
@param building [required] Building identifier, that can be found using /connectivity/eligibility/search/building* methods | [
"Get",
"the",
"details",
"for",
"a",
"building"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-connectivity/src/main/java/net/minidev/ovh/api/ApiOvhConnectivity.java#L104-L111 |
deeplearning4j/deeplearning4j | nd4j/nd4j-serde/nd4j-aeron/src/main/java/org/nd4j/aeron/ipc/response/NDArrayResponseFragmentHandler.java | NDArrayResponseFragmentHandler.onFragment | @Override
public void onFragment(DirectBuffer buffer, int offset, int length, Header header) {
if (buffer != null && length > 0) {
ByteBuffer byteBuffer = buffer.byteBuffer().order(ByteOrder.nativeOrder());
byteBuffer.position(offset);
byte[] b = new byte[length];
byteBuffer.get(b);
String hostPort = new String(b);
System.out.println("Host port " + hostPort + " offset " + offset + " length " + length);
String[] split = hostPort.split(":");
if (split == null || split.length != 3) {
System.err.println("no host port stream found");
return;
}
int port = Integer.parseInt(split[1]);
int streamToPublish = Integer.parseInt(split[2]);
String channel = AeronUtil.aeronChannel(split[0], port);
INDArray arrGet = holder.get();
AeronNDArrayPublisher publisher = AeronNDArrayPublisher.builder().streamId(streamToPublish).aeron(aeron)
.channel(channel).build();
try {
publisher.publish(arrGet);
} catch (Exception e) {
e.printStackTrace();
}
try {
publisher.close();
} catch (Exception e) {
}
}
} | java | @Override
public void onFragment(DirectBuffer buffer, int offset, int length, Header header) {
if (buffer != null && length > 0) {
ByteBuffer byteBuffer = buffer.byteBuffer().order(ByteOrder.nativeOrder());
byteBuffer.position(offset);
byte[] b = new byte[length];
byteBuffer.get(b);
String hostPort = new String(b);
System.out.println("Host port " + hostPort + " offset " + offset + " length " + length);
String[] split = hostPort.split(":");
if (split == null || split.length != 3) {
System.err.println("no host port stream found");
return;
}
int port = Integer.parseInt(split[1]);
int streamToPublish = Integer.parseInt(split[2]);
String channel = AeronUtil.aeronChannel(split[0], port);
INDArray arrGet = holder.get();
AeronNDArrayPublisher publisher = AeronNDArrayPublisher.builder().streamId(streamToPublish).aeron(aeron)
.channel(channel).build();
try {
publisher.publish(arrGet);
} catch (Exception e) {
e.printStackTrace();
}
try {
publisher.close();
} catch (Exception e) {
}
}
} | [
"@",
"Override",
"public",
"void",
"onFragment",
"(",
"DirectBuffer",
"buffer",
",",
"int",
"offset",
",",
"int",
"length",
",",
"Header",
"header",
")",
"{",
"if",
"(",
"buffer",
"!=",
"null",
"&&",
"length",
">",
"0",
")",
"{",
"ByteBuffer",
"byteBuffe... | Callback for handling fragments of data being read from a log.
@param buffer containing the data.
@param offset at which the data begins.
@param length of the data in bytes.
@param header representing the meta data for the data. | [
"Callback",
"for",
"handling",
"fragments",
"of",
"data",
"being",
"read",
"from",
"a",
"log",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-aeron/src/main/java/org/nd4j/aeron/ipc/response/NDArrayResponseFragmentHandler.java#L59-L92 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/ssh/JschUtil.java | JschUtil.bindPort | public static boolean bindPort(Session session, String remoteHost, int remotePort, int localPort) throws JschRuntimeException {
if (session != null && session.isConnected()) {
try {
session.setPortForwardingL(localPort, remoteHost, remotePort);
} catch (JSchException e) {
throw new JschRuntimeException(e, "From [{}] mapping to [{}] error!", remoteHost, localPort);
}
return true;
}
return false;
} | java | public static boolean bindPort(Session session, String remoteHost, int remotePort, int localPort) throws JschRuntimeException {
if (session != null && session.isConnected()) {
try {
session.setPortForwardingL(localPort, remoteHost, remotePort);
} catch (JSchException e) {
throw new JschRuntimeException(e, "From [{}] mapping to [{}] error!", remoteHost, localPort);
}
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"bindPort",
"(",
"Session",
"session",
",",
"String",
"remoteHost",
",",
"int",
"remotePort",
",",
"int",
"localPort",
")",
"throws",
"JschRuntimeException",
"{",
"if",
"(",
"session",
"!=",
"null",
"&&",
"session",
".",
"isConne... | 绑定端口到本地。 一个会话可绑定多个端口
@param session 需要绑定端口的SSH会话
@param remoteHost 远程主机
@param remotePort 远程端口
@param localPort 本地端口
@return 成功与否
@throws JschRuntimeException 端口绑定失败异常 | [
"绑定端口到本地。",
"一个会话可绑定多个端口"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/ssh/JschUtil.java#L116-L126 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer/src/com/ibm/ws/ejbcontainer/osgi/internal/naming/EJBJavaColonNamingHelper.java | EJBJavaColonNamingHelper.removeAppBindings | public void removeAppBindings(ModuleMetaData mmd, List<String> names) {
ApplicationMetaData amd = mmd.getApplicationMetaData();
Lock writeLock = javaColonLock.writeLock();
writeLock.lock();
try {
JavaColonNamespaceBindings<EJBBinding> bindings = getAppBindingMap(amd);
// getAppBindings returns a non-null value
for (String name : names) {
bindings.unbind(name);
}
} finally {
writeLock.unlock();
}
} | java | public void removeAppBindings(ModuleMetaData mmd, List<String> names) {
ApplicationMetaData amd = mmd.getApplicationMetaData();
Lock writeLock = javaColonLock.writeLock();
writeLock.lock();
try {
JavaColonNamespaceBindings<EJBBinding> bindings = getAppBindingMap(amd);
// getAppBindings returns a non-null value
for (String name : names) {
bindings.unbind(name);
}
} finally {
writeLock.unlock();
}
} | [
"public",
"void",
"removeAppBindings",
"(",
"ModuleMetaData",
"mmd",
",",
"List",
"<",
"String",
">",
"names",
")",
"{",
"ApplicationMetaData",
"amd",
"=",
"mmd",
".",
"getApplicationMetaData",
"(",
")",
";",
"Lock",
"writeLock",
"=",
"javaColonLock",
".",
"wr... | Remove names from the application mapping. If all the bindings have
been removed for an application, remove the application mapping.
@param moduleMetaData Name of the application being used.
@param names List of names to remove. | [
"Remove",
"names",
"from",
"the",
"application",
"mapping",
".",
"If",
"all",
"the",
"bindings",
"have",
"been",
"removed",
"for",
"an",
"application",
"remove",
"the",
"application",
"mapping",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer/src/com/ibm/ws/ejbcontainer/osgi/internal/naming/EJBJavaColonNamingHelper.java#L451-L469 |
cloudendpoints/endpoints-management-java | endpoints-control/src/main/java/com/google/api/control/model/Distributions.java | Distributions.createExponential | public static Distribution createExponential(int numFiniteBuckets, double growthFactor,
double scale) {
if (numFiniteBuckets <= 0) {
throw new IllegalArgumentException(MSG_BAD_NUM_FINITE_BUCKETS);
}
if (growthFactor <= 1.0) {
throw new IllegalArgumentException(String.format(MSG_DOUBLE_TOO_LOW, "growth factor", 1.0));
}
if (scale <= 0.0) {
throw new IllegalArgumentException(String.format(MSG_DOUBLE_TOO_LOW, "scale", 0.0));
}
ExponentialBuckets buckets = ExponentialBuckets.newBuilder().setGrowthFactor(growthFactor)
.setNumFiniteBuckets(numFiniteBuckets).setScale(scale).build();
Builder builder = Distribution.newBuilder().setExponentialBuckets(buckets);
for (int i = 0; i < numFiniteBuckets + 2; i++) {
builder.addBucketCounts(0L);
}
return builder.build();
} | java | public static Distribution createExponential(int numFiniteBuckets, double growthFactor,
double scale) {
if (numFiniteBuckets <= 0) {
throw new IllegalArgumentException(MSG_BAD_NUM_FINITE_BUCKETS);
}
if (growthFactor <= 1.0) {
throw new IllegalArgumentException(String.format(MSG_DOUBLE_TOO_LOW, "growth factor", 1.0));
}
if (scale <= 0.0) {
throw new IllegalArgumentException(String.format(MSG_DOUBLE_TOO_LOW, "scale", 0.0));
}
ExponentialBuckets buckets = ExponentialBuckets.newBuilder().setGrowthFactor(growthFactor)
.setNumFiniteBuckets(numFiniteBuckets).setScale(scale).build();
Builder builder = Distribution.newBuilder().setExponentialBuckets(buckets);
for (int i = 0; i < numFiniteBuckets + 2; i++) {
builder.addBucketCounts(0L);
}
return builder.build();
} | [
"public",
"static",
"Distribution",
"createExponential",
"(",
"int",
"numFiniteBuckets",
",",
"double",
"growthFactor",
",",
"double",
"scale",
")",
"{",
"if",
"(",
"numFiniteBuckets",
"<=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"MSG_BAD_... | Creates an {@code Distribution} with {@code ExponentialBuckets}.
@param numFiniteBuckets initializes the number of finite buckets
@param growthFactor initializes the growth factor
@param scale initializes the scale
@return a {@code Distribution} with {@code ExponentialBuckets}
@throws IllegalArgumentException if a bad input prevents creation. | [
"Creates",
"an",
"{",
"@code",
"Distribution",
"}",
"with",
"{",
"@code",
"ExponentialBuckets",
"}",
"."
] | train | https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/Distributions.java#L60-L78 |
groovy/groovy-core | src/examples/groovy/swing/MyTableModel.java | MyTableModel.setValueAt | public void setValueAt(Object value, int row, int col) {
if (log.isLoggable(Level.FINE)) {
log.fine(
"Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
}
if (data[0][col] instanceof Integer && !(value instanceof Integer)) {
//With JFC/Swing 1.1 and JDK 1.2, we need to create
//an Integer from the value; otherwise, the column
//switches to contain Strings. Starting with v 1.3,
//the table automatically converts value to an Integer,
//so you only need the code in the 'else' part of this
//'if' block.
//XXX: See TableEditDemo.java for a better solution!!!
try {
data[row][col] = Integer.valueOf(value.toString());
fireTableCellUpdated(row, col);
}
catch (NumberFormatException e) {
log.log(Level.SEVERE, "The \"" + getColumnName(col) + "\" column accepts only integer values.");
}
}
else {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
} | java | public void setValueAt(Object value, int row, int col) {
if (log.isLoggable(Level.FINE)) {
log.fine(
"Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")");
}
if (data[0][col] instanceof Integer && !(value instanceof Integer)) {
//With JFC/Swing 1.1 and JDK 1.2, we need to create
//an Integer from the value; otherwise, the column
//switches to contain Strings. Starting with v 1.3,
//the table automatically converts value to an Integer,
//so you only need the code in the 'else' part of this
//'if' block.
//XXX: See TableEditDemo.java for a better solution!!!
try {
data[row][col] = Integer.valueOf(value.toString());
fireTableCellUpdated(row, col);
}
catch (NumberFormatException e) {
log.log(Level.SEVERE, "The \"" + getColumnName(col) + "\" column accepts only integer values.");
}
}
else {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
} | [
"public",
"void",
"setValueAt",
"(",
"Object",
"value",
",",
"int",
"row",
",",
"int",
"col",
")",
"{",
"if",
"(",
"log",
".",
"isLoggable",
"(",
"Level",
".",
"FINE",
")",
")",
"{",
"log",
".",
"fine",
"(",
"\"Setting value at \"",
"+",
"row",
"+",
... | /*
Don't need to implement this method unless your table's
data can change. | [
"/",
"*",
"Don",
"t",
"need",
"to",
"implement",
"this",
"method",
"unless",
"your",
"table",
"s",
"data",
"can",
"change",
"."
] | train | https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/examples/groovy/swing/MyTableModel.java#L96-L122 |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/service/RowService.java | RowService.addScoreColumn | protected Row addScoreColumn(Row row, long timestamp, Float score) {
ColumnFamily cf = row.cf;
CellName cellName = rowMapper.makeCellName(cf);
ByteBuffer cellValue = UTF8Type.instance.decompose(score.toString());
ColumnFamily dcf = ArrayBackedSortedColumns.factory.create(baseCfs.metadata);
dcf.addColumn(cellName, cellValue, timestamp);
dcf.addAll(row.cf);
return new Row(row.key, dcf);
} | java | protected Row addScoreColumn(Row row, long timestamp, Float score) {
ColumnFamily cf = row.cf;
CellName cellName = rowMapper.makeCellName(cf);
ByteBuffer cellValue = UTF8Type.instance.decompose(score.toString());
ColumnFamily dcf = ArrayBackedSortedColumns.factory.create(baseCfs.metadata);
dcf.addColumn(cellName, cellValue, timestamp);
dcf.addAll(row.cf);
return new Row(row.key, dcf);
} | [
"protected",
"Row",
"addScoreColumn",
"(",
"Row",
"row",
",",
"long",
"timestamp",
",",
"Float",
"score",
")",
"{",
"ColumnFamily",
"cf",
"=",
"row",
".",
"cf",
";",
"CellName",
"cellName",
"=",
"rowMapper",
".",
"makeCellName",
"(",
"cf",
")",
";",
"Byt... | Adds to the specified {@link Row} the specified Lucene score column.
@param row A {@link Row}.
@param timestamp The score column timestamp.
@param score The score column value.
@return The {@link Row} with the score. | [
"Adds",
"to",
"the",
"specified",
"{",
"@link",
"Row",
"}",
"the",
"specified",
"Lucene",
"score",
"column",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/RowService.java#L397-L407 |
JDBDT/jdbdt | src/main/java/org/jdbdt/Log.java | Log.write | void write(CallInfo callInfo, DeltaAssertion assertion) {
Element rootNode = root(callInfo);
DataSource ds = assertion.getSource();
write(rootNode, ds);
Element daNode = createNode(rootNode, DELTA_ASSERTION_TAG);
List<MetaData.ColumnInfo> mdCols = ds.getMetaData().columns();
Element expectedNode = createNode(daNode, EXPECTED_TAG);
write(expectedNode,
OLD_DATA_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.OLD_DATA_EXPECTED));
write(expectedNode,
NEW_DATA_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.NEW_DATA_EXPECTED));
if (! assertion.passed()) {
Element errorsNode = createNode(daNode, ERRORS_TAG);
Element oldDataErrors = createNode(errorsNode, OLD_DATA_TAG);
Element newDataErrors = createNode(errorsNode, NEW_DATA_TAG);
write(oldDataErrors,
EXPECTED_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.OLD_DATA_ERRORS_EXPECTED));
write(oldDataErrors,
ACTUAL_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.OLD_DATA_ERRORS_ACTUAL));
write(newDataErrors,
EXPECTED_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.NEW_DATA_ERRORS_EXPECTED));
write(newDataErrors,
ACTUAL_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.NEW_DATA_ERRORS_ACTUAL));
}
flush(rootNode);
} | java | void write(CallInfo callInfo, DeltaAssertion assertion) {
Element rootNode = root(callInfo);
DataSource ds = assertion.getSource();
write(rootNode, ds);
Element daNode = createNode(rootNode, DELTA_ASSERTION_TAG);
List<MetaData.ColumnInfo> mdCols = ds.getMetaData().columns();
Element expectedNode = createNode(daNode, EXPECTED_TAG);
write(expectedNode,
OLD_DATA_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.OLD_DATA_EXPECTED));
write(expectedNode,
NEW_DATA_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.NEW_DATA_EXPECTED));
if (! assertion.passed()) {
Element errorsNode = createNode(daNode, ERRORS_TAG);
Element oldDataErrors = createNode(errorsNode, OLD_DATA_TAG);
Element newDataErrors = createNode(errorsNode, NEW_DATA_TAG);
write(oldDataErrors,
EXPECTED_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.OLD_DATA_ERRORS_EXPECTED));
write(oldDataErrors,
ACTUAL_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.OLD_DATA_ERRORS_ACTUAL));
write(newDataErrors,
EXPECTED_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.NEW_DATA_ERRORS_EXPECTED));
write(newDataErrors,
ACTUAL_TAG,
mdCols,
assertion.data(DeltaAssertion.IteratorType.NEW_DATA_ERRORS_ACTUAL));
}
flush(rootNode);
} | [
"void",
"write",
"(",
"CallInfo",
"callInfo",
",",
"DeltaAssertion",
"assertion",
")",
"{",
"Element",
"rootNode",
"=",
"root",
"(",
"callInfo",
")",
";",
"DataSource",
"ds",
"=",
"assertion",
".",
"getSource",
"(",
")",
";",
"write",
"(",
"rootNode",
",",... | Log delta assertion.
@param callInfo Call info.
@param assertion Delta assertion. | [
"Log",
"delta",
"assertion",
"."
] | train | https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/Log.java#L253-L291 |
Netflix/conductor | client/src/main/java/com/netflix/conductor/client/http/WorkflowClient.java | WorkflowClient.skipTaskFromWorkflow | public void skipTaskFromWorkflow(String workflowId, String taskReferenceName) {
Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank");
Preconditions.checkArgument(StringUtils.isNotBlank(taskReferenceName), "Task reference name cannot be blank");
put("workflow/{workflowId}/skiptask/{taskReferenceName}", null, workflowId, taskReferenceName);
} | java | public void skipTaskFromWorkflow(String workflowId, String taskReferenceName) {
Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank");
Preconditions.checkArgument(StringUtils.isNotBlank(taskReferenceName), "Task reference name cannot be blank");
put("workflow/{workflowId}/skiptask/{taskReferenceName}", null, workflowId, taskReferenceName);
} | [
"public",
"void",
"skipTaskFromWorkflow",
"(",
"String",
"workflowId",
",",
"String",
"taskReferenceName",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"workflowId",
")",
",",
"\"workflow id cannot be blank\"",
")",
";",... | Skips a given task from a current RUNNING workflow
@param workflowId the id of the workflow instance
@param taskReferenceName the reference name of the task to be skipped | [
"Skips",
"a",
"given",
"task",
"from",
"a",
"current",
"RUNNING",
"workflow"
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/client/src/main/java/com/netflix/conductor/client/http/WorkflowClient.java#L264-L269 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DefaultErrorHandler.java | DefaultErrorHandler.getErrorWriter | public PrintWriter getErrorWriter() {
// Defer creating the java.io.PrintWriter until an error needs to be
// reported.
if (m_pw == null) {
m_pw = new PrintWriter(System.err, true);
}
return m_pw;
} | java | public PrintWriter getErrorWriter() {
// Defer creating the java.io.PrintWriter until an error needs to be
// reported.
if (m_pw == null) {
m_pw = new PrintWriter(System.err, true);
}
return m_pw;
} | [
"public",
"PrintWriter",
"getErrorWriter",
"(",
")",
"{",
"// Defer creating the java.io.PrintWriter until an error needs to be",
"// reported.",
"if",
"(",
"m_pw",
"==",
"null",
")",
"{",
"m_pw",
"=",
"new",
"PrintWriter",
"(",
"System",
".",
"err",
",",
"true",
")... | Retrieve <code>java.io.PrintWriter</code> to which errors are being
directed.
@return The <code>PrintWriter</code> installed via the constructor
or the default <code>PrintWriter</code> | [
"Retrieve",
"<code",
">",
"java",
".",
"io",
".",
"PrintWriter<",
"/",
"code",
">",
"to",
"which",
"errors",
"are",
"being",
"directed",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DefaultErrorHandler.java#L92-L99 |
JodaOrg/joda-time | src/main/java/org/joda/time/Period.java | Period.plusHours | public Period plusHours(int hours) {
if (hours == 0) {
return this;
}
int[] values = getValues(); // cloned
getPeriodType().addIndexedField(this, PeriodType.HOUR_INDEX, values, hours);
return new Period(values, getPeriodType());
} | java | public Period plusHours(int hours) {
if (hours == 0) {
return this;
}
int[] values = getValues(); // cloned
getPeriodType().addIndexedField(this, PeriodType.HOUR_INDEX, values, hours);
return new Period(values, getPeriodType());
} | [
"public",
"Period",
"plusHours",
"(",
"int",
"hours",
")",
"{",
"if",
"(",
"hours",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"int",
"[",
"]",
"values",
"=",
"getValues",
"(",
")",
";",
"// cloned",
"getPeriodType",
"(",
")",
".",
"addIndexedF... | Returns a new period plus the specified number of hours added.
<p>
This period instance is immutable and unaffected by this method call.
@param hours the amount of hours to add, may be negative
@return the new period plus the increased hours
@throws UnsupportedOperationException if the field is not supported | [
"Returns",
"a",
"new",
"period",
"plus",
"the",
"specified",
"number",
"of",
"hours",
"added",
".",
"<p",
">",
"This",
"period",
"instance",
"is",
"immutable",
"and",
"unaffected",
"by",
"this",
"method",
"call",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/Period.java#L1141-L1148 |
powermock/powermock | powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java | Whitebox.getInternalState | public static <T> T getInternalState(Object object, String fieldName) {
return WhiteboxImpl.getInternalState(object, fieldName);
} | java | public static <T> T getInternalState(Object object, String fieldName) {
return WhiteboxImpl.getInternalState(object, fieldName);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getInternalState",
"(",
"Object",
"object",
",",
"String",
"fieldName",
")",
"{",
"return",
"WhiteboxImpl",
".",
"getInternalState",
"(",
"object",
",",
"fieldName",
")",
";",
"}"
] | Get the value of a field using reflection. This method will iterate
through the entire class hierarchy and return the value of the first
field named <tt>fieldName</tt>. If you want to get a specific field value
at specific place in the class hierarchy please refer to
{@link #getInternalState(Object, String, Class)}.
@param object
the object to modify
@param fieldName
the name of the field | [
"Get",
"the",
"value",
"of",
"a",
"field",
"using",
"reflection",
".",
"This",
"method",
"will",
"iterate",
"through",
"the",
"entire",
"class",
"hierarchy",
"and",
"return",
"the",
"value",
"of",
"the",
"first",
"field",
"named",
"<tt",
">",
"fieldName<",
... | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java#L291-L293 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/client/ApiClient.java | ApiClient.getJWTUri | public String getJWTUri(String clientId, String redirectURI, String oAuthBasePath) {
return UriBuilder.fromUri(oAuthBasePath)
.scheme("https")
.path("/oauth/auth")
.queryParam("response_type", "code")
.queryParam("scope", "signature%20impersonation")
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectURI)
.build().toString();
} | java | public String getJWTUri(String clientId, String redirectURI, String oAuthBasePath) {
return UriBuilder.fromUri(oAuthBasePath)
.scheme("https")
.path("/oauth/auth")
.queryParam("response_type", "code")
.queryParam("scope", "signature%20impersonation")
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectURI)
.build().toString();
} | [
"public",
"String",
"getJWTUri",
"(",
"String",
"clientId",
",",
"String",
"redirectURI",
",",
"String",
"oAuthBasePath",
")",
"{",
"return",
"UriBuilder",
".",
"fromUri",
"(",
"oAuthBasePath",
")",
".",
"scheme",
"(",
"\"https\"",
")",
".",
"path",
"(",
"\"... | Helper method to build the OAuth JWT grant uri (used once to get a user consent for impersonation)
@param clientId OAuth2 client ID
@param redirectURI OAuth2 redirect uri
@return the OAuth JWT grant uri as a String | [
"Helper",
"method",
"to",
"build",
"the",
"OAuth",
"JWT",
"grant",
"uri",
"(",
"used",
"once",
"to",
"get",
"a",
"user",
"consent",
"for",
"impersonation",
")"
] | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/client/ApiClient.java#L650-L659 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java | LogRecordBrowser.recordsInProcess | public OnePidRecordListImpl recordsInProcess(long min, long max, final LogRecordHeaderFilter filter) {
return startRecordsInProcess(min, max, filter==null ? new AllAcceptVerifier() : new HeadFilterVerifier(filter));
} | java | public OnePidRecordListImpl recordsInProcess(long min, long max, final LogRecordHeaderFilter filter) {
return startRecordsInProcess(min, max, filter==null ? new AllAcceptVerifier() : new HeadFilterVerifier(filter));
} | [
"public",
"OnePidRecordListImpl",
"recordsInProcess",
"(",
"long",
"min",
",",
"long",
"max",
",",
"final",
"LogRecordHeaderFilter",
"filter",
")",
"{",
"return",
"startRecordsInProcess",
"(",
"min",
",",
"max",
",",
"filter",
"==",
"null",
"?",
"new",
"AllAccep... | Returns records belonging to a process and satisfying the filter.
@param min the low time limit (the oldest log record).
@param max the upper time limit (the youngest log record).
@param filter criteria to filter logs records on.
@return the iterable list of records. | [
"Returns",
"records",
"belonging",
"to",
"a",
"process",
"and",
"satisfying",
"the",
"filter",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java#L101-L103 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java | CacheConfigurationBuilder.withKeySerializer | public CacheConfigurationBuilder<K, V> withKeySerializer(Class<? extends Serializer<K>> keySerializerClass) {
return withSerializer(new DefaultSerializerConfiguration<>(requireNonNull(keySerializerClass, "Null key serializer class"), DefaultSerializerConfiguration.Type.KEY));
} | java | public CacheConfigurationBuilder<K, V> withKeySerializer(Class<? extends Serializer<K>> keySerializerClass) {
return withSerializer(new DefaultSerializerConfiguration<>(requireNonNull(keySerializerClass, "Null key serializer class"), DefaultSerializerConfiguration.Type.KEY));
} | [
"public",
"CacheConfigurationBuilder",
"<",
"K",
",",
"V",
">",
"withKeySerializer",
"(",
"Class",
"<",
"?",
"extends",
"Serializer",
"<",
"K",
">",
">",
"keySerializerClass",
")",
"{",
"return",
"withSerializer",
"(",
"new",
"DefaultSerializerConfiguration",
"<>"... | Adds a {@link Serializer} class for cache keys to the configured builder.
<p>
{@link Serializer}s are what enables cache storage beyond the heap tier.
@param keySerializerClass the key serializer to use
@return a new builder with the added key serializer | [
"Adds",
"a",
"{",
"@link",
"Serializer",
"}",
"class",
"for",
"cache",
"keys",
"to",
"the",
"configured",
"builder",
".",
"<p",
">",
"{",
"@link",
"Serializer",
"}",
"s",
"are",
"what",
"enables",
"cache",
"storage",
"beyond",
"the",
"heap",
"tier",
"."
... | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java#L468-L470 |
meltmedia/cadmium | email/src/main/java/com/meltmedia/cadmium/email/HtmlTextEmail.java | HtmlTextEmail.newMessage | public MimeMessage newMessage( Session session )
throws MessagingException, EmailException
{
MimeMessage message = new MimeMessage( session );
// populate the addresses and subject.
populate(message);
// create the multipart content.
MimeMultipart containingMultipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED);
// create the message multipart content.
MimeMultipart messageMultipart = new MimeMultipart(EmailUtil.SUBTYPE_ALTERNATIVE);
containingMultipart.addBodyPart(EmailUtil.newMultipartBodyPart(messageMultipart));
// create the text part.
messageMultipart.addBodyPart(EmailUtil.newTextBodyPart(getText()));
// create the html part.
MimeMultipart htmlMultipart = new MimeMultipart(EmailUtil.SUBTYPE_RELATED);
htmlMultipart.addBodyPart(EmailUtil.newHtmlBodyPart(getHtml()));
messageMultipart.addBodyPart(EmailUtil.newMultipartBodyPart(htmlMultipart));
/*
// iterate over the html context, creating new elements for each.
Iterator htmlAttachmentIterator = htmlAttachmentMap.entrySet().iterator();
while( htmlAttachmentIterator.hasNext() ) {
Map.Entry htmlAttachmentEntry = (Map.Entry)htmlAttachmentIterator.next();
htmlMultipart.addBodyPart(EmailUtil.newHtmlAttachmentPart((URL)htmlAttachmentEntry.getKey(), (String)htmlAttachmentPart.getValue());
}
// add the html multipart to the message multipart.
messageMultipart.addBodyPart(EmailUtil.newMultipartBodyPart(htmlMultipartBodyPart));
*/
// create the attachments.
for( URL attachmentUrl : attachmentUrlSet ) {
containingMultipart.addBodyPart(EmailUtil.newAttachmentBodyPart(attachmentUrl, null));
}
try {
for( StringAttachment attachment : attachmentStrings ) {
containingMultipart.addBodyPart(EmailUtil.newAttachmentBodyPart(attachment.getContent(), null, attachment.getMimeType(), attachment.getFilename()));
}
} catch (IOException ioe) {
throw new MessagingException("Unable to create attachment for string.", ioe);
}
message.setContent(containingMultipart);
// save the changes.
message.saveChanges();
// return the email.
return message;
} | java | public MimeMessage newMessage( Session session )
throws MessagingException, EmailException
{
MimeMessage message = new MimeMessage( session );
// populate the addresses and subject.
populate(message);
// create the multipart content.
MimeMultipart containingMultipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED);
// create the message multipart content.
MimeMultipart messageMultipart = new MimeMultipart(EmailUtil.SUBTYPE_ALTERNATIVE);
containingMultipart.addBodyPart(EmailUtil.newMultipartBodyPart(messageMultipart));
// create the text part.
messageMultipart.addBodyPart(EmailUtil.newTextBodyPart(getText()));
// create the html part.
MimeMultipart htmlMultipart = new MimeMultipart(EmailUtil.SUBTYPE_RELATED);
htmlMultipart.addBodyPart(EmailUtil.newHtmlBodyPart(getHtml()));
messageMultipart.addBodyPart(EmailUtil.newMultipartBodyPart(htmlMultipart));
/*
// iterate over the html context, creating new elements for each.
Iterator htmlAttachmentIterator = htmlAttachmentMap.entrySet().iterator();
while( htmlAttachmentIterator.hasNext() ) {
Map.Entry htmlAttachmentEntry = (Map.Entry)htmlAttachmentIterator.next();
htmlMultipart.addBodyPart(EmailUtil.newHtmlAttachmentPart((URL)htmlAttachmentEntry.getKey(), (String)htmlAttachmentPart.getValue());
}
// add the html multipart to the message multipart.
messageMultipart.addBodyPart(EmailUtil.newMultipartBodyPart(htmlMultipartBodyPart));
*/
// create the attachments.
for( URL attachmentUrl : attachmentUrlSet ) {
containingMultipart.addBodyPart(EmailUtil.newAttachmentBodyPart(attachmentUrl, null));
}
try {
for( StringAttachment attachment : attachmentStrings ) {
containingMultipart.addBodyPart(EmailUtil.newAttachmentBodyPart(attachment.getContent(), null, attachment.getMimeType(), attachment.getFilename()));
}
} catch (IOException ioe) {
throw new MessagingException("Unable to create attachment for string.", ioe);
}
message.setContent(containingMultipart);
// save the changes.
message.saveChanges();
// return the email.
return message;
} | [
"public",
"MimeMessage",
"newMessage",
"(",
"Session",
"session",
")",
"throws",
"MessagingException",
",",
"EmailException",
"{",
"MimeMessage",
"message",
"=",
"new",
"MimeMessage",
"(",
"session",
")",
";",
"// populate the addresses and subject.",
"populate",
"(",
... | Creates a mime message for an html emails with the following structure:
mime/mixed
- mime/alternative
- text/plain
- mime/related
- text/html
- image/*
- image/*
- (attachment mime type)
- (attachment mime type) | [
"Creates",
"a",
"mime",
"message",
"for",
"an",
"html",
"emails",
"with",
"the",
"following",
"structure",
":",
"mime",
"/",
"mixed",
"-",
"mime",
"/",
"alternative",
"-",
"text",
"/",
"plain",
"-",
"mime",
"/",
"related",
"-",
"text",
"/",
"html",
"-"... | train | https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/HtmlTextEmail.java#L98-L153 |
mikepenz/FastAdapter | library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java | FastAdapter.notifyAdapterItemMoved | public void notifyAdapterItemMoved(int fromPosition, int toPosition) {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.notifyAdapterItemMoved(fromPosition, toPosition);
}
notifyItemMoved(fromPosition, toPosition);
} | java | public void notifyAdapterItemMoved(int fromPosition, int toPosition) {
// handle our extensions
for (IAdapterExtension<Item> ext : mExtensions.values()) {
ext.notifyAdapterItemMoved(fromPosition, toPosition);
}
notifyItemMoved(fromPosition, toPosition);
} | [
"public",
"void",
"notifyAdapterItemMoved",
"(",
"int",
"fromPosition",
",",
"int",
"toPosition",
")",
"{",
"// handle our extensions",
"for",
"(",
"IAdapterExtension",
"<",
"Item",
">",
"ext",
":",
"mExtensions",
".",
"values",
"(",
")",
")",
"{",
"ext",
".",... | wraps notifyItemMoved
@param fromPosition the global fromPosition
@param toPosition the global toPosition | [
"wraps",
"notifyItemMoved"
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java#L1319-L1325 |
twitter/hraven | hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryService.java | JobHistoryService.getFlowByJobID | public Flow getFlowByJobID(String cluster, String jobId,
boolean populateTasks) throws IOException {
Flow flow = null;
JobKey key = idService.getJobKeyById(new QualifiedJobId(cluster, jobId));
if (key != null) {
byte[] startRow =
ByteUtil.join(Constants.SEP_BYTES, Bytes.toBytes(key.getCluster()),
Bytes.toBytes(key.getUserName()), Bytes.toBytes(key.getAppId()),
Bytes.toBytes(key.getEncodedRunId()), Constants.EMPTY_BYTES);
LOG.info("Reading job_history rows start at "
+ Bytes.toStringBinary(startRow));
Scan scan = new Scan();
// start scanning history at cluster!user!app!run!
scan.setStartRow(startRow);
// require that all results match this flow prefix
scan.setFilter(new WhileMatchFilter(new PrefixFilter(startRow)));
List<Flow> flows = createFromResults(scan, populateTasks, 1);
if (flows.size() > 0) {
flow = flows.get(0);
}
}
return flow;
} | java | public Flow getFlowByJobID(String cluster, String jobId,
boolean populateTasks) throws IOException {
Flow flow = null;
JobKey key = idService.getJobKeyById(new QualifiedJobId(cluster, jobId));
if (key != null) {
byte[] startRow =
ByteUtil.join(Constants.SEP_BYTES, Bytes.toBytes(key.getCluster()),
Bytes.toBytes(key.getUserName()), Bytes.toBytes(key.getAppId()),
Bytes.toBytes(key.getEncodedRunId()), Constants.EMPTY_BYTES);
LOG.info("Reading job_history rows start at "
+ Bytes.toStringBinary(startRow));
Scan scan = new Scan();
// start scanning history at cluster!user!app!run!
scan.setStartRow(startRow);
// require that all results match this flow prefix
scan.setFilter(new WhileMatchFilter(new PrefixFilter(startRow)));
List<Flow> flows = createFromResults(scan, populateTasks, 1);
if (flows.size() > 0) {
flow = flows.get(0);
}
}
return flow;
} | [
"public",
"Flow",
"getFlowByJobID",
"(",
"String",
"cluster",
",",
"String",
"jobId",
",",
"boolean",
"populateTasks",
")",
"throws",
"IOException",
"{",
"Flow",
"flow",
"=",
"null",
";",
"JobKey",
"key",
"=",
"idService",
".",
"getJobKeyById",
"(",
"new",
"... | Returns the {@link Flow} instance containing the given job ID.
@param cluster the cluster identifier
@param jobId the job identifier
@return | [
"Returns",
"the",
"{",
"@link",
"Flow",
"}",
"instance",
"containing",
"the",
"given",
"job",
"ID",
"."
] | train | https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryService.java#L192-L216 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.license_cpanel_new_duration_GET | public OvhOrder license_cpanel_new_duration_GET(String duration, String ip, OvhLicenseTypeEnum serviceType, OvhOrderableCpanelVersionEnum version) throws IOException {
String qPath = "/order/license/cpanel/new/{duration}";
StringBuilder sb = path(qPath, duration);
query(sb, "ip", ip);
query(sb, "serviceType", serviceType);
query(sb, "version", version);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
} | java | public OvhOrder license_cpanel_new_duration_GET(String duration, String ip, OvhLicenseTypeEnum serviceType, OvhOrderableCpanelVersionEnum version) throws IOException {
String qPath = "/order/license/cpanel/new/{duration}";
StringBuilder sb = path(qPath, duration);
query(sb, "ip", ip);
query(sb, "serviceType", serviceType);
query(sb, "version", version);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhOrder.class);
} | [
"public",
"OvhOrder",
"license_cpanel_new_duration_GET",
"(",
"String",
"duration",
",",
"String",
"ip",
",",
"OvhLicenseTypeEnum",
"serviceType",
",",
"OvhOrderableCpanelVersionEnum",
"version",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/license... | Get prices and contracts information
REST: GET /order/license/cpanel/new/{duration}
@param serviceType [required] # DEPRECATED # The kind of service on which this license will be used # Will not be used, keeped only for compatibility #
@param ip [required] Ip on which this license would be installed
@param version [required] This license version
@param duration [required] Duration | [
"Get",
"prices",
"and",
"contracts",
"information"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L1445-L1453 |
molgenis/molgenis | molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/PretendingEntity.java | PretendingEntity.getEntity | @Override
@SuppressWarnings("unchecked")
public <E extends Entity> E getEntity(String attributeName, Class<E> clazz) {
Entity entity = delegate().getEntity(attributeName, clazz);
if (clazz.equals(FileMeta.class)) {
return entity != null ? (E) new FileMeta(newPretendingEntity(entity)) : null;
} else {
throw new UnsupportedOperationException("Can't return typed pretending entities");
}
} | java | @Override
@SuppressWarnings("unchecked")
public <E extends Entity> E getEntity(String attributeName, Class<E> clazz) {
Entity entity = delegate().getEntity(attributeName, clazz);
if (clazz.equals(FileMeta.class)) {
return entity != null ? (E) new FileMeta(newPretendingEntity(entity)) : null;
} else {
throw new UnsupportedOperationException("Can't return typed pretending entities");
}
} | [
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"E",
"extends",
"Entity",
">",
"E",
"getEntity",
"(",
"String",
"attributeName",
",",
"Class",
"<",
"E",
">",
"clazz",
")",
"{",
"Entity",
"entity",
"=",
"delegate",
"(",
... | Because the File datatype has a reference to {@link FileMetaMetadata} it can happen that a
typed FileMeta Entity is requested. | [
"Because",
"the",
"File",
"datatype",
"has",
"a",
"reference",
"to",
"{"
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-navigator/src/main/java/org/molgenis/navigator/copy/service/PretendingEntity.java#L48-L57 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/time/DateUtils.java | DateUtils.getFragment | @GwtIncompatible("incompatible method")
private static long getFragment(final Date date, final int fragment, final TimeUnit unit) {
validateDateNotNull(date);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return getFragment(calendar, fragment, unit);
} | java | @GwtIncompatible("incompatible method")
private static long getFragment(final Date date, final int fragment, final TimeUnit unit) {
validateDateNotNull(date);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return getFragment(calendar, fragment, unit);
} | [
"@",
"GwtIncompatible",
"(",
"\"incompatible method\"",
")",
"private",
"static",
"long",
"getFragment",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"fragment",
",",
"final",
"TimeUnit",
"unit",
")",
"{",
"validateDateNotNull",
"(",
"date",
")",
";",
"f... | Gets a Date fragment for any unit.
@param date the date to work with, not null
@param fragment the Calendar field part of date to calculate
@param unit the time unit
@return number of units within the fragment of the date
@throws IllegalArgumentException if the date is <code>null</code> or
fragment is not supported
@since 2.4 | [
"Gets",
"a",
"Date",
"fragment",
"for",
"any",
"unit",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L1664-L1670 |
eclipse/hawkbit | hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentication.java | AmqpControllerAuthentication.doAuthenticate | public Authentication doAuthenticate(final DmfTenantSecurityToken securityToken) {
resolveTenant(securityToken);
PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(null, null);
for (final PreAuthenticationFilter filter : filterChain) {
final PreAuthenticatedAuthenticationToken authenticationRest = createAuthentication(filter, securityToken);
if (authenticationRest != null) {
authentication = authenticationRest;
authentication.setDetails(new TenantAwareAuthenticationDetails(securityToken.getTenant(), true));
break;
}
}
return preAuthenticatedAuthenticationProvider.authenticate(authentication);
} | java | public Authentication doAuthenticate(final DmfTenantSecurityToken securityToken) {
resolveTenant(securityToken);
PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(null, null);
for (final PreAuthenticationFilter filter : filterChain) {
final PreAuthenticatedAuthenticationToken authenticationRest = createAuthentication(filter, securityToken);
if (authenticationRest != null) {
authentication = authenticationRest;
authentication.setDetails(new TenantAwareAuthenticationDetails(securityToken.getTenant(), true));
break;
}
}
return preAuthenticatedAuthenticationProvider.authenticate(authentication);
} | [
"public",
"Authentication",
"doAuthenticate",
"(",
"final",
"DmfTenantSecurityToken",
"securityToken",
")",
"{",
"resolveTenant",
"(",
"securityToken",
")",
";",
"PreAuthenticatedAuthenticationToken",
"authentication",
"=",
"new",
"PreAuthenticatedAuthenticationToken",
"(",
"... | Performs authentication with the security token.
@param securityToken
the authentication request object
@return the authentication object | [
"Performs",
"authentication",
"with",
"the",
"security",
"token",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentication.java#L124-L137 |
elki-project/elki | elki/src/main/java/de/lmu/ifi/dbs/elki/data/model/CorrelationAnalysisSolution.java | CorrelationAnalysisSolution.squaredDistance | public double squaredDistance(V p) {
// V_affin = V + a
// dist(p, V_affin) = d(p-a, V) = ||p - a - proj_V(p-a) ||
double[] p_minus_a = minusEquals(p.toArray(), centroid);
return squareSum(minusEquals(p_minus_a, times(strongEigenvectors, transposeTimes(strongEigenvectors, p_minus_a))));
} | java | public double squaredDistance(V p) {
// V_affin = V + a
// dist(p, V_affin) = d(p-a, V) = ||p - a - proj_V(p-a) ||
double[] p_minus_a = minusEquals(p.toArray(), centroid);
return squareSum(minusEquals(p_minus_a, times(strongEigenvectors, transposeTimes(strongEigenvectors, p_minus_a))));
} | [
"public",
"double",
"squaredDistance",
"(",
"V",
"p",
")",
"{",
"// V_affin = V + a",
"// dist(p, V_affin) = d(p-a, V) = ||p - a - proj_V(p-a) ||",
"double",
"[",
"]",
"p_minus_a",
"=",
"minusEquals",
"(",
"p",
".",
"toArray",
"(",
")",
",",
"centroid",
")",
";",
... | Returns the distance of NumberVector p from the hyperplane underlying this
solution.
@param p a vector in the space underlying this solution
@return the distance of p from the hyperplane underlying this solution | [
"Returns",
"the",
"distance",
"of",
"NumberVector",
"p",
"from",
"the",
"hyperplane",
"underlying",
"this",
"solution",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/data/model/CorrelationAnalysisSolution.java#L190-L195 |
jroyalty/jglm | src/main/java/com/hackoeur/jglm/support/FastMath.java | FastMath.cosQ | private static double cosQ(double xa, double xb) {
final double pi2a = 1.5707963267948966;
final double pi2b = 6.123233995736766E-17;
final double a = pi2a - xa;
double b = -(a - pi2a + xa);
b += pi2b - xb;
return sinQ(a, b);
} | java | private static double cosQ(double xa, double xb) {
final double pi2a = 1.5707963267948966;
final double pi2b = 6.123233995736766E-17;
final double a = pi2a - xa;
double b = -(a - pi2a + xa);
b += pi2b - xb;
return sinQ(a, b);
} | [
"private",
"static",
"double",
"cosQ",
"(",
"double",
"xa",
",",
"double",
"xb",
")",
"{",
"final",
"double",
"pi2a",
"=",
"1.5707963267948966",
";",
"final",
"double",
"pi2b",
"=",
"6.123233995736766E-17",
";",
"final",
"double",
"a",
"=",
"pi2a",
"-",
"x... | Compute cosine in the first quadrant by subtracting input from PI/2 and
then calling sinQ. This is more accurate as the input approaches PI/2.
@param xa number from which cosine is requested
@param xb extra bits for x (may be 0.0)
@return cos(xa + xb) | [
"Compute",
"cosine",
"in",
"the",
"first",
"quadrant",
"by",
"subtracting",
"input",
"from",
"PI",
"/",
"2",
"and",
"then",
"calling",
"sinQ",
".",
"This",
"is",
"more",
"accurate",
"as",
"the",
"input",
"approaches",
"PI",
"/",
"2",
"."
] | train | https://github.com/jroyalty/jglm/blob/9397c2fcf0d4d62844c64d0b14065ee7bf8cafc6/src/main/java/com/hackoeur/jglm/support/FastMath.java#L1880-L1889 |
dbracewell/hermes | hermes-wordnet/src/main/java/com/davidbracewell/hermes/wordnet/WordNet.java | WordNet.getRelation | public WordNetRelation getRelation(Sense from, Sense to) {
if (from == null || to == null) {
return null;
}
return db.getRelation(from, to);
} | java | public WordNetRelation getRelation(Sense from, Sense to) {
if (from == null || to == null) {
return null;
}
return db.getRelation(from, to);
} | [
"public",
"WordNetRelation",
"getRelation",
"(",
"Sense",
"from",
",",
"Sense",
"to",
")",
"{",
"if",
"(",
"from",
"==",
"null",
"||",
"to",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"db",
".",
"getRelation",
"(",
"from",
",",
"to... | Gets relation.
@param from the from
@param to the to
@return the relation | [
"Gets",
"relation",
"."
] | train | https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-wordnet/src/main/java/com/davidbracewell/hermes/wordnet/WordNet.java#L412-L417 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/caps/cache/SimpleDirectoryPersistentCache.java | SimpleDirectoryPersistentCache.writeInfoToFile | private static void writeInfoToFile(File file, DiscoverInfo info) throws IOException {
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(file))) {
dos.writeUTF(info.toXML().toString());
}
} | java | private static void writeInfoToFile(File file, DiscoverInfo info) throws IOException {
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(file))) {
dos.writeUTF(info.toXML().toString());
}
} | [
"private",
"static",
"void",
"writeInfoToFile",
"(",
"File",
"file",
",",
"DiscoverInfo",
"info",
")",
"throws",
"IOException",
"{",
"try",
"(",
"DataOutputStream",
"dos",
"=",
"new",
"DataOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
"... | Writes the DiscoverInfo stanza to an file
@param file
@param info
@throws IOException | [
"Writes",
"the",
"DiscoverInfo",
"stanza",
"to",
"an",
"file"
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/cache/SimpleDirectoryPersistentCache.java#L132-L136 |
querydsl/querydsl | querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java | Expressions.asNumber | public static <T extends Number & Comparable<?>> NumberExpression<T> asNumber(Expression<T> expr) {
Expression<T> underlyingMixin = ExpressionUtils.extract(expr);
if (underlyingMixin instanceof PathImpl) {
return new NumberPath<T>((PathImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof OperationImpl) {
return new NumberOperation<T>((OperationImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof TemplateExpressionImpl) {
return new NumberTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin);
} else {
return new NumberExpression<T>(underlyingMixin) {
private static final long serialVersionUID = -8712299418891960222L;
@Override
public <R, C> R accept(Visitor<R, C> v, C context) {
return this.mixin.accept(v, context);
}
};
}
} | java | public static <T extends Number & Comparable<?>> NumberExpression<T> asNumber(Expression<T> expr) {
Expression<T> underlyingMixin = ExpressionUtils.extract(expr);
if (underlyingMixin instanceof PathImpl) {
return new NumberPath<T>((PathImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof OperationImpl) {
return new NumberOperation<T>((OperationImpl<T>) underlyingMixin);
} else if (underlyingMixin instanceof TemplateExpressionImpl) {
return new NumberTemplate<T>((TemplateExpressionImpl<T>) underlyingMixin);
} else {
return new NumberExpression<T>(underlyingMixin) {
private static final long serialVersionUID = -8712299418891960222L;
@Override
public <R, C> R accept(Visitor<R, C> v, C context) {
return this.mixin.accept(v, context);
}
};
}
} | [
"public",
"static",
"<",
"T",
"extends",
"Number",
"&",
"Comparable",
"<",
"?",
">",
">",
"NumberExpression",
"<",
"T",
">",
"asNumber",
"(",
"Expression",
"<",
"T",
">",
"expr",
")",
"{",
"Expression",
"<",
"T",
">",
"underlyingMixin",
"=",
"ExpressionU... | Create a new NumberExpression
@param expr Expression of type Number
@return new NumberExpression | [
"Create",
"a",
"new",
"NumberExpression"
] | train | https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/Expressions.java#L2093-L2113 |
forge/javaee-descriptors | impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/facesconfig20/WebFacesConfigDescriptorImpl.java | WebFacesConfigDescriptorImpl.addNamespace | public WebFacesConfigDescriptor addNamespace(String name, String value)
{
model.attribute(name, value);
return this;
} | java | public WebFacesConfigDescriptor addNamespace(String name, String value)
{
model.attribute(name, value);
return this;
} | [
"public",
"WebFacesConfigDescriptor",
"addNamespace",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"model",
".",
"attribute",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds a new namespace
@return the current instance of <code>WebFacesConfigDescriptor</code> | [
"Adds",
"a",
"new",
"namespace"
] | train | https://github.com/forge/javaee-descriptors/blob/cb914330a1a0b04bfc1d0f199bd9cde3bbf0b3ed/impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/facesconfig20/WebFacesConfigDescriptorImpl.java#L97-L101 |
alkacon/opencms-core | src/org/opencms/main/CmsShellCommands.java | CmsShellCommands.login | public void login(String username, String password) {
username = OpenCms.getImportExportManager().translateUser(username);
try {
m_cms.loginUser(username, password);
// reset the settings, this will switch the startup site root etc.
m_shell.initSettings();
m_shell.getOut().println(getMessages().key(Messages.GUI_SHELL_LOGIN_1, whoami().getName()));
// output the login message if required
CmsLoginMessage message = OpenCms.getLoginManager().getLoginMessage();
if ((message != null) && (message.isActive())) {
m_shell.getOut().println(message.getMessage());
}
} catch (Exception exc) {
m_shell.getOut().println(getMessages().key(Messages.GUI_SHELL_LOGIN_FAILED_0));
}
} | java | public void login(String username, String password) {
username = OpenCms.getImportExportManager().translateUser(username);
try {
m_cms.loginUser(username, password);
// reset the settings, this will switch the startup site root etc.
m_shell.initSettings();
m_shell.getOut().println(getMessages().key(Messages.GUI_SHELL_LOGIN_1, whoami().getName()));
// output the login message if required
CmsLoginMessage message = OpenCms.getLoginManager().getLoginMessage();
if ((message != null) && (message.isActive())) {
m_shell.getOut().println(message.getMessage());
}
} catch (Exception exc) {
m_shell.getOut().println(getMessages().key(Messages.GUI_SHELL_LOGIN_FAILED_0));
}
} | [
"public",
"void",
"login",
"(",
"String",
"username",
",",
"String",
"password",
")",
"{",
"username",
"=",
"OpenCms",
".",
"getImportExportManager",
"(",
")",
".",
"translateUser",
"(",
"username",
")",
";",
"try",
"{",
"m_cms",
".",
"loginUser",
"(",
"us... | Log a user in to the the CmsSell.<p>
@param username the name of the user to log in
@param password the password of the user | [
"Log",
"a",
"user",
"in",
"to",
"the",
"the",
"CmsSell",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L1011-L1027 |
the-fascinator/plugin-indexer-solr | src/main/java/com/googlecode/fascinator/indexer/rules/AddField.java | AddField.run | @Override
public void run(Reader in, Writer out) throws RuleException {
//log("Adding field [" + field + "]");
try {
AddDoc addDoc = AddDoc.read(in);
addDoc.getFields().add(field);
addDoc.write(out);
} catch (JAXBException jaxbe) {
throw new RuleException(jaxbe.getLinkedException());
}
} | java | @Override
public void run(Reader in, Writer out) throws RuleException {
//log("Adding field [" + field + "]");
try {
AddDoc addDoc = AddDoc.read(in);
addDoc.getFields().add(field);
addDoc.write(out);
} catch (JAXBException jaxbe) {
throw new RuleException(jaxbe.getLinkedException());
}
} | [
"@",
"Override",
"public",
"void",
"run",
"(",
"Reader",
"in",
",",
"Writer",
"out",
")",
"throws",
"RuleException",
"{",
"//log(\"Adding field [\" + field + \"]\");",
"try",
"{",
"AddDoc",
"addDoc",
"=",
"AddDoc",
".",
"read",
"(",
"in",
")",
";",
"addDoc",
... | Adds a single field to a Solr document
@param in Solr document
@param out Solr document with added field | [
"Adds",
"a",
"single",
"field",
"to",
"a",
"Solr",
"document"
] | train | https://github.com/the-fascinator/plugin-indexer-solr/blob/001159b18b78a87daa5d8b2a17ced28694bae156/src/main/java/com/googlecode/fascinator/indexer/rules/AddField.java#L76-L86 |
dkpro/dkpro-argumentation | dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java | JCasUtil2.updateBegin | public static void updateBegin(final Annotation annotation, final int begin)
{
annotation.removeFromIndexes();
annotation.setBegin(begin);
annotation.addToIndexes();
} | java | public static void updateBegin(final Annotation annotation, final int begin)
{
annotation.removeFromIndexes();
annotation.setBegin(begin);
annotation.addToIndexes();
} | [
"public",
"static",
"void",
"updateBegin",
"(",
"final",
"Annotation",
"annotation",
",",
"final",
"int",
"begin",
")",
"{",
"annotation",
".",
"removeFromIndexes",
"(",
")",
";",
"annotation",
".",
"setBegin",
"(",
"begin",
")",
";",
"annotation",
".",
"add... | Sets the begin value of the annotation, updating indexes appropriately
@param annotation the annotation
@param begin the new begin value | [
"Sets",
"the",
"begin",
"value",
"of",
"the",
"annotation",
"updating",
"indexes",
"appropriately"
] | train | https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L300-L305 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/collections/spatial/RTree.java | RTree.adjustTree | private void adjustTree(Node n, Node nn)
{
// special case for root
if (n == root) {
if (nn != null) {
root = buildRoot(false);
root.addChild(n);
root.addChild(nn);
}
root.enclose();
return;
}
boolean updateParent = n.enclose();
if (nn != null) {
nn.enclose();
updateParent = true;
if (splitStrategy.needToSplit(n.getParent())) {
Node[] groups = splitStrategy.split(n.getParent());
adjustTree(groups[0], groups[1]);
}
}
if (n.getParent() != null && updateParent) {
adjustTree(n.getParent(), null);
}
} | java | private void adjustTree(Node n, Node nn)
{
// special case for root
if (n == root) {
if (nn != null) {
root = buildRoot(false);
root.addChild(n);
root.addChild(nn);
}
root.enclose();
return;
}
boolean updateParent = n.enclose();
if (nn != null) {
nn.enclose();
updateParent = true;
if (splitStrategy.needToSplit(n.getParent())) {
Node[] groups = splitStrategy.split(n.getParent());
adjustTree(groups[0], groups[1]);
}
}
if (n.getParent() != null && updateParent) {
adjustTree(n.getParent(), null);
}
} | [
"private",
"void",
"adjustTree",
"(",
"Node",
"n",
",",
"Node",
"nn",
")",
"{",
"// special case for root",
"if",
"(",
"n",
"==",
"root",
")",
"{",
"if",
"(",
"nn",
"!=",
"null",
")",
"{",
"root",
"=",
"buildRoot",
"(",
"false",
")",
";",
"root",
"... | This description is from the original paper.
AT1. [Initialize]. Set N=L. If L was split previously, set NN to be the resulting second node.
AT2. [Check if done]. If N is the root, stop.
AT3. [Adjust covering rectangle in parent entry]. Let P be the parent node of N, and let Ev(N)I be N's entry in P.
Adjust Ev(N)I so that it tightly encloses all entry rectangles in N.
AT4. [Propagate node split upward]. If N has a partner NN resulting from an earlier split, create a new entry
Ev(NN) with Ev(NN)p pointing to NN and Ev(NN)I enclosing all rectangles in NN. Add Ev(NN) to p is there is room.
Otherwise, invoke {@link SplitStrategy} split to product p and pp containing Ev(NN) and all p's old entries.
@param n - first node to adjust
@param nn - optional second node to adjust | [
"This",
"description",
"is",
"from",
"the",
"original",
"paper",
"."
] | train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/collections/spatial/RTree.java#L192-L220 |
alkacon/opencms-core | src/org/opencms/search/CmsSearch.java | CmsSearch.addFieldQueryShould | public void addFieldQueryShould(String fieldName, String searchQuery) {
addFieldQuery(fieldName, searchQuery, BooleanClause.Occur.SHOULD);
} | java | public void addFieldQueryShould(String fieldName, String searchQuery) {
addFieldQuery(fieldName, searchQuery, BooleanClause.Occur.SHOULD);
} | [
"public",
"void",
"addFieldQueryShould",
"(",
"String",
"fieldName",
",",
"String",
"searchQuery",
")",
"{",
"addFieldQuery",
"(",
"fieldName",
",",
"searchQuery",
",",
"BooleanClause",
".",
"Occur",
".",
"SHOULD",
")",
";",
"}"
] | Adds an individual query for a search field that SHOULD occur.<p>
If this is used, any setting made with {@link #setQuery(String)} and {@link #setField(String[])}
will be ignored and only the individual field search settings will be used.<p>
When combining occurrences of SHOULD, MUST and MUST_NOT, keep the following in mind:
All SHOULD clauses will be grouped and wrapped in one query,
all MUST and MUST_NOT clauses will be grouped in another query.
This means that at least one of the terms which are given as a SHOULD query must occur in the
search result.<p>
@param fieldName the field name
@param searchQuery the search query
@since 7.5.1 | [
"Adds",
"an",
"individual",
"query",
"for",
"a",
"search",
"field",
"that",
"SHOULD",
"occur",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearch.java#L231-L234 |
Azure/autorest-clientruntime-for-java | azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/utils/SdkContext.java | SdkContext.randomResourceName | public static String randomResourceName(String prefix, int maxLen) {
ResourceNamer resourceNamer = SdkContext.getResourceNamerFactory().createResourceNamer("");
return resourceNamer.randomName(prefix, maxLen);
} | java | public static String randomResourceName(String prefix, int maxLen) {
ResourceNamer resourceNamer = SdkContext.getResourceNamerFactory().createResourceNamer("");
return resourceNamer.randomName(prefix, maxLen);
} | [
"public",
"static",
"String",
"randomResourceName",
"(",
"String",
"prefix",
",",
"int",
"maxLen",
")",
"{",
"ResourceNamer",
"resourceNamer",
"=",
"SdkContext",
".",
"getResourceNamerFactory",
"(",
")",
".",
"createResourceNamer",
"(",
"\"\"",
")",
";",
"return",... | Gets a random name.
@param prefix the prefix to be used if possible
@param maxLen the maximum length for the random generated name
@return the random name | [
"Gets",
"a",
"random",
"name",
"."
] | train | https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/utils/SdkContext.java#L45-L48 |
LearnLib/automatalib | serialization/fsm/src/main/java/net/automatalib/serialization/fsm/parser/FSM2MealyParserAlternating.java | FSM2MealyParserAlternating.checkTransitions | @Override
protected void checkTransitions(StreamTokenizer streamTokenizer) throws FSMParseException {
// Only if no states are defined we add all from the transitions we found.
// This is necessary because states are not necessarily defined in FSMs.
if (getStates().isEmpty()) {
getStates().addAll(transitionsFSM.keySet());
}
// copy the set of states
final Set<Integer> newStates = new HashSet<>(getStates());
// retrieve the initial state in the FSM source
final Integer initialState = getStates().iterator().next();
// make the actual FSM transitions
makeTransitions(initialState, null, newStates, 0, output != null ? new WordBuilder<>() : null, streamTokenizer);
// check we do not have a partial FSM
if (!newStates.isEmpty()) {
throw new FSMParseException(String.format(PARTIAL_FSM, newStates, initialState), streamTokenizer);
}
} | java | @Override
protected void checkTransitions(StreamTokenizer streamTokenizer) throws FSMParseException {
// Only if no states are defined we add all from the transitions we found.
// This is necessary because states are not necessarily defined in FSMs.
if (getStates().isEmpty()) {
getStates().addAll(transitionsFSM.keySet());
}
// copy the set of states
final Set<Integer> newStates = new HashSet<>(getStates());
// retrieve the initial state in the FSM source
final Integer initialState = getStates().iterator().next();
// make the actual FSM transitions
makeTransitions(initialState, null, newStates, 0, output != null ? new WordBuilder<>() : null, streamTokenizer);
// check we do not have a partial FSM
if (!newStates.isEmpty()) {
throw new FSMParseException(String.format(PARTIAL_FSM, newStates, initialState), streamTokenizer);
}
} | [
"@",
"Override",
"protected",
"void",
"checkTransitions",
"(",
"StreamTokenizer",
"streamTokenizer",
")",
"throws",
"FSMParseException",
"{",
"// Only if no states are defined we add all from the transitions we found.",
"// This is necessary because states are not necessarily defined in FS... | Creates the actual Mealy machine transitions.
@throws FSMParseException
when the Mealy machine is partial. | [
"Creates",
"the",
"actual",
"Mealy",
"machine",
"transitions",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/serialization/fsm/src/main/java/net/automatalib/serialization/fsm/parser/FSM2MealyParserAlternating.java#L248-L270 |
alkacon/opencms-core | src/org/opencms/module/CmsModuleUpdater.java | CmsModuleUpdater.checkCompatibleModuleResources | public static boolean checkCompatibleModuleResources(CmsModule installedModule, CmsModule newModule) {
if (!(installedModule.hasOnlySystemAndSharedResources() && newModule.hasOnlySystemAndSharedResources())) {
String oldSite = installedModule.getSite();
String newSite = newModule.getSite();
if (!((oldSite != null) && (newSite != null) && CmsStringUtil.comparePaths(oldSite, newSite))) {
return false;
}
}
for (String oldModRes : installedModule.getResources()) {
for (String newModRes : newModule.getResources()) {
if (CmsStringUtil.isProperPrefixPath(oldModRes, newModRes)) {
return false;
}
}
}
return true;
} | java | public static boolean checkCompatibleModuleResources(CmsModule installedModule, CmsModule newModule) {
if (!(installedModule.hasOnlySystemAndSharedResources() && newModule.hasOnlySystemAndSharedResources())) {
String oldSite = installedModule.getSite();
String newSite = newModule.getSite();
if (!((oldSite != null) && (newSite != null) && CmsStringUtil.comparePaths(oldSite, newSite))) {
return false;
}
}
for (String oldModRes : installedModule.getResources()) {
for (String newModRes : newModule.getResources()) {
if (CmsStringUtil.isProperPrefixPath(oldModRes, newModRes)) {
return false;
}
}
}
return true;
} | [
"public",
"static",
"boolean",
"checkCompatibleModuleResources",
"(",
"CmsModule",
"installedModule",
",",
"CmsModule",
"newModule",
")",
"{",
"if",
"(",
"!",
"(",
"installedModule",
".",
"hasOnlySystemAndSharedResources",
"(",
")",
"&&",
"newModule",
".",
"hasOnlySys... | Checks whether the module resources and sites of the two module versions are suitable for updating.<p>
@param installedModule the installed module
@param newModule the module to import
@return true if the module resources are compatible | [
"Checks",
"whether",
"the",
"module",
"resources",
"and",
"sites",
"of",
"the",
"two",
"module",
"versions",
"are",
"suitable",
"for",
"updating",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/module/CmsModuleUpdater.java#L119-L138 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/NotificationsApi.java | NotificationsApi.notificationsUnsubscribeWithHttpInfo | public ApiResponse<Void> notificationsUnsubscribeWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = notificationsUnsubscribeValidateBeforeCall(null, null);
return apiClient.execute(call);
} | java | public ApiResponse<Void> notificationsUnsubscribeWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = notificationsUnsubscribeValidateBeforeCall(null, null);
return apiClient.execute(call);
} | [
"public",
"ApiResponse",
"<",
"Void",
">",
"notificationsUnsubscribeWithHttpInfo",
"(",
")",
"throws",
"ApiException",
"{",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"call",
"=",
"notificationsUnsubscribeValidateBeforeCall",
"(",
"null",
",",
"null",
")",
... | Unsubscribes from CometD channel notification
See the [CometD documentation](https://docs.cometd.org/current/reference/#_bayeux_meta_unsubscribe) for details.
@return ApiResponse<Void>
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Unsubscribes",
"from",
"CometD",
"channel",
"notification",
"See",
"the",
"[",
"CometD",
"documentation",
"]",
"(",
"https",
":",
"//",
"docs",
".",
"cometd",
".",
"org",
"/",
"current",
"/",
"reference",
"/",
"#_bayeux_meta_unsubscribe",
")",
"for",
"details... | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/NotificationsApi.java#L673-L676 |
plume-lib/options | src/main/java/org/plumelib/options/OptionsDoclet.java | OptionsDoclet.javadocToHtml | public static String javadocToHtml(Doc doc) {
StringBuilder b = new StringBuilder();
Tag[] tags = doc.inlineTags();
for (Tag tag : tags) {
String kind = tag.kind();
String text = tag.text();
if (tag instanceof SeeTag) {
b.append("<code>" + text.replace('#', '.') + "</code>");
} else {
if (kind.equals("@code")) {
b.append("<code>" + StringEscapeUtils.escapeHtml4(text) + "</code>");
} else {
b.append(text);
}
}
}
SeeTag[] seetags = doc.seeTags();
if (seetags.length > 0) {
b.append(" See: ");
{
StringJoiner bb = new StringJoiner(", ");
for (SeeTag tag : seetags) {
bb.add("<code>" + tag.text() + "</code>");
}
b.append(bb);
}
b.append(".");
}
return b.toString();
} | java | public static String javadocToHtml(Doc doc) {
StringBuilder b = new StringBuilder();
Tag[] tags = doc.inlineTags();
for (Tag tag : tags) {
String kind = tag.kind();
String text = tag.text();
if (tag instanceof SeeTag) {
b.append("<code>" + text.replace('#', '.') + "</code>");
} else {
if (kind.equals("@code")) {
b.append("<code>" + StringEscapeUtils.escapeHtml4(text) + "</code>");
} else {
b.append(text);
}
}
}
SeeTag[] seetags = doc.seeTags();
if (seetags.length > 0) {
b.append(" See: ");
{
StringJoiner bb = new StringJoiner(", ");
for (SeeTag tag : seetags) {
bb.add("<code>" + tag.text() + "</code>");
}
b.append(bb);
}
b.append(".");
}
return b.toString();
} | [
"public",
"static",
"String",
"javadocToHtml",
"(",
"Doc",
"doc",
")",
"{",
"StringBuilder",
"b",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"Tag",
"[",
"]",
"tags",
"=",
"doc",
".",
"inlineTags",
"(",
")",
";",
"for",
"(",
"Tag",
"tag",
":",
"tags"... | Replace the @link tags and block @see tags in a Javadoc comment with HTML.
<p>Currently, the output is non-hyperlinked HTML. This keeps most of the information in the
comment while still being presentable. Ideally, @link/@see tags would be converted to HTML
links that point to actual documentation.
@param doc a Javadoc comment to convert to HTML
@return HTML version of doc | [
"Replace",
"the",
"@link",
"tags",
"and",
"block",
"@see",
"tags",
"in",
"a",
"Javadoc",
"comment",
"with",
"HTML",
"."
] | train | https://github.com/plume-lib/options/blob/1bdd0ac7a1794bdf9dd373e279f69d43395154f0/src/main/java/org/plumelib/options/OptionsDoclet.java#L850-L879 |
zaproxy/zaproxy | src/org/parosproxy/paros/core/scanner/VariantCustom.java | VariantCustom.addParamHeader | public void addParamHeader(String name, String value) {
addParam(name, value, NameValuePair.TYPE_HEADER);
} | java | public void addParamHeader(String name, String value) {
addParam(name, value, NameValuePair.TYPE_HEADER);
} | [
"public",
"void",
"addParamHeader",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"addParam",
"(",
"name",
",",
"value",
",",
"NameValuePair",
".",
"TYPE_HEADER",
")",
";",
"}"
] | Support method to add a new Header param to this custom variant
@param name the param name
@param value the value of this parameter | [
"Support",
"method",
"to",
"add",
"a",
"new",
"Header",
"param",
"to",
"this",
"custom",
"variant"
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/core/scanner/VariantCustom.java#L170-L172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.