repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
rolfl/MicroBench | src/main/java/net/tuis/ubench/ScaleDetect.java | ScaleDetect.newtonSolve | private static double[] newtonSolve(Function<double[], double[]> function, double[] initial, double tolerance) {
RealVector dx = new ArrayRealVector(initial.length);
dx.set(tolerance + 1);
int iterations = 0;
int d = initial.length;
double[] values = Arrays.copyOf(initial, initial.length);
while (dx.getNorm() > tolerance) {
double[] fx = function.apply(values);
Array2DRowRealMatrix df = new Array2DRowRealMatrix(fx.length, d);
ArrayRealVector fxVector = new ArrayRealVector(fx);
for (int i = 0; i < d; i++) {
double originalValue = values[i];
values[i] += H;
double[] fxi = function.apply(values);
values[i] = originalValue;
ArrayRealVector fxiVector = new ArrayRealVector(fxi);
RealVector result = fxiVector.subtract(fxVector);
result = result.mapDivide(H);
df.setColumn(i, result.toArray());
}
dx = new RRQRDecomposition(df).getSolver().solve(fxVector.mapMultiply(-1));
// df has size = initial, and fx has size equal to whatever that function produces.
for (int i = 0; i < values.length; i++) {
values[i] += dx.getEntry(i);
}
iterations++;
if (iterations % 100 == 0) {
tolerance *= 10;
}
}
return values;
} | java | private static double[] newtonSolve(Function<double[], double[]> function, double[] initial, double tolerance) {
RealVector dx = new ArrayRealVector(initial.length);
dx.set(tolerance + 1);
int iterations = 0;
int d = initial.length;
double[] values = Arrays.copyOf(initial, initial.length);
while (dx.getNorm() > tolerance) {
double[] fx = function.apply(values);
Array2DRowRealMatrix df = new Array2DRowRealMatrix(fx.length, d);
ArrayRealVector fxVector = new ArrayRealVector(fx);
for (int i = 0; i < d; i++) {
double originalValue = values[i];
values[i] += H;
double[] fxi = function.apply(values);
values[i] = originalValue;
ArrayRealVector fxiVector = new ArrayRealVector(fxi);
RealVector result = fxiVector.subtract(fxVector);
result = result.mapDivide(H);
df.setColumn(i, result.toArray());
}
dx = new RRQRDecomposition(df).getSolver().solve(fxVector.mapMultiply(-1));
// df has size = initial, and fx has size equal to whatever that function produces.
for (int i = 0; i < values.length; i++) {
values[i] += dx.getEntry(i);
}
iterations++;
if (iterations % 100 == 0) {
tolerance *= 10;
}
}
return values;
} | [
"private",
"static",
"double",
"[",
"]",
"newtonSolve",
"(",
"Function",
"<",
"double",
"[",
"]",
",",
"double",
"[",
"]",
">",
"function",
",",
"double",
"[",
"]",
"initial",
",",
"double",
"tolerance",
")",
"{",
"RealVector",
"dx",
"=",
"new",
"Array... | Finding the best fit using least-squares method for an equation system
@param function Equation system to find fit for. Input: Parameters, Output: Residuals.
@param initial Initial 'guess' for function parameters
@param tolerance How much the function parameters may change before a solution is accepted
@return The parameters to the function that causes the least residuals | [
"Finding",
"the",
"best",
"fit",
"using",
"least",
"-",
"squares",
"method",
"for",
"an",
"equation",
"system"
] | train | https://github.com/rolfl/MicroBench/blob/f2bfa92dacd7ea0d6b8eae4d4fe2975139d317ce/src/main/java/net/tuis/ubench/ScaleDetect.java#L32-L64 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/ZipUtil.java | ZipUtil.replaceEntry | public static boolean replaceEntry(File zip, String path, File file, File destZip) {
return replaceEntry(zip, new FileSource(path, file), destZip);
} | java | public static boolean replaceEntry(File zip, String path, File file, File destZip) {
return replaceEntry(zip, new FileSource(path, file), destZip);
} | [
"public",
"static",
"boolean",
"replaceEntry",
"(",
"File",
"zip",
",",
"String",
"path",
",",
"File",
"file",
",",
"File",
"destZip",
")",
"{",
"return",
"replaceEntry",
"(",
"zip",
",",
"new",
"FileSource",
"(",
"path",
",",
"file",
")",
",",
"destZip"... | Copies an existing ZIP file and replaces a given entry in it.
@param zip
an existing ZIP file (only read).
@param path
new ZIP entry path.
@param file
new entry.
@param destZip
new ZIP file created.
@return <code>true</code> if the entry was replaced. | [
"Copies",
"an",
"existing",
"ZIP",
"file",
"and",
"replaces",
"a",
"given",
"entry",
"in",
"it",
"."
] | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2502-L2504 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java | Utility.lookup | public static int lookup(String source, String[] target) {
for (int i = 0; i < target.length; ++i) {
if (source.equals(target[i])) return i;
}
return -1;
} | java | public static int lookup(String source, String[] target) {
for (int i = 0; i < target.length; ++i) {
if (source.equals(target[i])) return i;
}
return -1;
} | [
"public",
"static",
"int",
"lookup",
"(",
"String",
"source",
",",
"String",
"[",
"]",
"target",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"target",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"source",
".",
"equals",
"... | Look up a given string in a string array. Returns the index at
which the first occurrence of the string was found in the
array, or -1 if it was not found.
@param source the string to search for
@param target the array of zero or more strings in which to
look for source
@return the index of target at which source first occurs, or -1
if not found | [
"Look",
"up",
"a",
"given",
"string",
"in",
"a",
"string",
"array",
".",
"Returns",
"the",
"index",
"at",
"which",
"the",
"first",
"occurrence",
"of",
"the",
"string",
"was",
"found",
"in",
"the",
"array",
"or",
"-",
"1",
"if",
"it",
"was",
"not",
"f... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Utility.java#L1112-L1117 |
fcrepo3/fcrepo | fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/Uploader.java | Uploader.main | public static void main(String[] args) {
try {
if (args.length == 5 || args.length == 6) {
String protocol = args[0];
int port = Integer.parseInt(args[1]);
String user = args[2];
String password = args[3];
String fileName = args[4];
String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;
if (args.length == 6 && !args[5].isEmpty()) {
context = args[5];
}
Uploader uploader =
new Uploader(protocol, port, context, user, password);
File f = new File(fileName);
System.out.println(uploader.upload(new FileInputStream(f)));
System.out.println(uploader.upload(f));
uploader =
new Uploader(protocol,
port,
context,
user + "test",
password);
System.out.println(uploader.upload(f));
} else {
System.err
.println("Usage: Uploader host port user password file [context]");
}
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
}
} | java | public static void main(String[] args) {
try {
if (args.length == 5 || args.length == 6) {
String protocol = args[0];
int port = Integer.parseInt(args[1]);
String user = args[2];
String password = args[3];
String fileName = args[4];
String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;
if (args.length == 6 && !args[5].isEmpty()) {
context = args[5];
}
Uploader uploader =
new Uploader(protocol, port, context, user, password);
File f = new File(fileName);
System.out.println(uploader.upload(new FileInputStream(f)));
System.out.println(uploader.upload(f));
uploader =
new Uploader(protocol,
port,
context,
user + "test",
password);
System.out.println(uploader.upload(f));
} else {
System.err
.println("Usage: Uploader host port user password file [context]");
}
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"if",
"(",
"args",
".",
"length",
"==",
"5",
"||",
"args",
".",
"length",
"==",
"6",
")",
"{",
"String",
"protocol",
"=",
"args",
"[",
"0",
"]",
";",
"in... | Test this class by uploading the given file three times. First, with the
provided credentials, as an InputStream. Second, with the provided
credentials, as a File. Third, with bogus credentials, as a File. | [
"Test",
"this",
"class",
"by",
"uploading",
"the",
"given",
"file",
"three",
"times",
".",
"First",
"with",
"the",
"provided",
"credentials",
"as",
"an",
"InputStream",
".",
"Second",
"with",
"the",
"provided",
"credentials",
"as",
"a",
"File",
".",
"Third",... | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/Uploader.java#L159-L193 |
molgenis/molgenis | molgenis-r/src/main/java/org/molgenis/r/RScriptExecutor.java | RScriptExecutor.executeScriptGetFileRequest | private void executeScriptGetFileRequest(
String openCpuSessionKey, String scriptOutputFilename, String outputPathname)
throws IOException {
URI scriptGetValueResponseUri =
getScriptGetFileResponseUri(openCpuSessionKey, scriptOutputFilename);
HttpGet httpGet = new HttpGet(scriptGetValueResponseUri);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
HttpEntity entity = response.getEntity();
Files.copy(entity.getContent(), Paths.get(outputPathname));
EntityUtils.consume(entity);
} else {
throw new ClientProtocolException(format(FORMAT_UNEXPECTED_RESPONSE_STATUS, statusCode));
}
}
} | java | private void executeScriptGetFileRequest(
String openCpuSessionKey, String scriptOutputFilename, String outputPathname)
throws IOException {
URI scriptGetValueResponseUri =
getScriptGetFileResponseUri(openCpuSessionKey, scriptOutputFilename);
HttpGet httpGet = new HttpGet(scriptGetValueResponseUri);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
HttpEntity entity = response.getEntity();
Files.copy(entity.getContent(), Paths.get(outputPathname));
EntityUtils.consume(entity);
} else {
throw new ClientProtocolException(format(FORMAT_UNEXPECTED_RESPONSE_STATUS, statusCode));
}
}
} | [
"private",
"void",
"executeScriptGetFileRequest",
"(",
"String",
"openCpuSessionKey",
",",
"String",
"scriptOutputFilename",
",",
"String",
"outputPathname",
")",
"throws",
"IOException",
"{",
"URI",
"scriptGetValueResponseUri",
"=",
"getScriptGetFileResponseUri",
"(",
"ope... | Retrieve R script file response using OpenCPU and write to file
@param openCpuSessionKey OpenCPU session key
@param scriptOutputFilename R script output filename
@param outputPathname Output pathname
@throws IOException if error occured during script response retrieval | [
"Retrieve",
"R",
"script",
"file",
"response",
"using",
"OpenCPU",
"and",
"write",
"to",
"file"
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-r/src/main/java/org/molgenis/r/RScriptExecutor.java#L137-L153 |
google/closure-compiler | src/com/google/javascript/jscomp/Compiler.java | Compiler.resolveSibling | private static String resolveSibling(String fromPath, String toPath) {
// If the destination is an absolute path, nothing to do.
if (toPath.startsWith("/")) {
return toPath;
}
List<String> fromPathParts = new ArrayList<>(Arrays.asList(fromPath.split("/")));
List<String> toPathParts = new ArrayList<>(Arrays.asList(toPath.split("/")));
if (!fromPathParts.isEmpty()) {
fromPathParts.remove(fromPathParts.size() - 1);
}
while (!fromPathParts.isEmpty() && !toPathParts.isEmpty()) {
if (toPathParts.get(0).equals(".")) {
toPathParts.remove(0);
} else if (toPathParts.get(0).equals("..")) {
toPathParts.remove(0);
fromPathParts.remove(fromPathParts.size() - 1);
} else {
break;
}
}
fromPathParts.addAll(toPathParts);
return String.join("/", fromPathParts);
} | java | private static String resolveSibling(String fromPath, String toPath) {
// If the destination is an absolute path, nothing to do.
if (toPath.startsWith("/")) {
return toPath;
}
List<String> fromPathParts = new ArrayList<>(Arrays.asList(fromPath.split("/")));
List<String> toPathParts = new ArrayList<>(Arrays.asList(toPath.split("/")));
if (!fromPathParts.isEmpty()) {
fromPathParts.remove(fromPathParts.size() - 1);
}
while (!fromPathParts.isEmpty() && !toPathParts.isEmpty()) {
if (toPathParts.get(0).equals(".")) {
toPathParts.remove(0);
} else if (toPathParts.get(0).equals("..")) {
toPathParts.remove(0);
fromPathParts.remove(fromPathParts.size() - 1);
} else {
break;
}
}
fromPathParts.addAll(toPathParts);
return String.join("/", fromPathParts);
} | [
"private",
"static",
"String",
"resolveSibling",
"(",
"String",
"fromPath",
",",
"String",
"toPath",
")",
"{",
"// If the destination is an absolute path, nothing to do.",
"if",
"(",
"toPath",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"return",
"toPath",
";",
... | Simplistic implementation of the java.nio.file.Path resolveSibling method that works with GWT.
@param fromPath - must be a file (not directory)
@param toPath - must be a file (not directory) | [
"Simplistic",
"implementation",
"of",
"the",
"java",
".",
"nio",
".",
"file",
".",
"Path",
"resolveSibling",
"method",
"that",
"works",
"with",
"GWT",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Compiler.java#L3618-L3643 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/capability/RuntimeCapability.java | RuntimeCapability.buildDynamicCapabilityName | public static String buildDynamicCapabilityName(String baseName, String ... dynamicNameElement) {
assert baseName != null;
assert dynamicNameElement != null;
assert dynamicNameElement.length > 0;
StringBuilder sb = new StringBuilder(baseName);
for (String part:dynamicNameElement){
sb.append(".").append(part);
}
return sb.toString();
} | java | public static String buildDynamicCapabilityName(String baseName, String ... dynamicNameElement) {
assert baseName != null;
assert dynamicNameElement != null;
assert dynamicNameElement.length > 0;
StringBuilder sb = new StringBuilder(baseName);
for (String part:dynamicNameElement){
sb.append(".").append(part);
}
return sb.toString();
} | [
"public",
"static",
"String",
"buildDynamicCapabilityName",
"(",
"String",
"baseName",
",",
"String",
"...",
"dynamicNameElement",
")",
"{",
"assert",
"baseName",
"!=",
"null",
";",
"assert",
"dynamicNameElement",
"!=",
"null",
";",
"assert",
"dynamicNameElement",
"... | Constructs a full capability name from a static base name and a dynamic element.
@param baseName the base name. Cannot be {@code null}
@param dynamicNameElement the dynamic portion of the name. Cannot be {@code null}
@return the full capability name. Will not return {@code null} | [
"Constructs",
"a",
"full",
"capability",
"name",
"from",
"a",
"static",
"base",
"name",
"and",
"a",
"dynamic",
"element",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/capability/RuntimeCapability.java#L63-L72 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/db/QueryTable.java | QueryTable.init | public void init(BaseDatabase database, Record record)
{
super.init(database, record);
if (((QueryRecord)record).getBaseRecord() != null)
m_tableNext = ((QueryRecord)record).getBaseRecord().getTable(); // Pass most commands thru to the main record's table
} | java | public void init(BaseDatabase database, Record record)
{
super.init(database, record);
if (((QueryRecord)record).getBaseRecord() != null)
m_tableNext = ((QueryRecord)record).getBaseRecord().getTable(); // Pass most commands thru to the main record's table
} | [
"public",
"void",
"init",
"(",
"BaseDatabase",
"database",
",",
"Record",
"record",
")",
"{",
"super",
".",
"init",
"(",
"database",
",",
"record",
")",
";",
"if",
"(",
"(",
"(",
"QueryRecord",
")",
"record",
")",
".",
"getBaseRecord",
"(",
")",
"!=",
... | QueryTable Constructor.
@param database The database for this table.
@param record The queryRecord for this table. | [
"QueryTable",
"Constructor",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/QueryTable.java#L46-L51 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/logging/MyfacesLogger.java | MyfacesLogger.exiting | public void exiting(String sourceClass, String sourceMethod, Object result)
{
_log.exiting(sourceClass, sourceMethod, result);
} | java | public void exiting(String sourceClass, String sourceMethod, Object result)
{
_log.exiting(sourceClass, sourceMethod, result);
} | [
"public",
"void",
"exiting",
"(",
"String",
"sourceClass",
",",
"String",
"sourceMethod",
",",
"Object",
"result",
")",
"{",
"_log",
".",
"exiting",
"(",
"sourceClass",
",",
"sourceMethod",
",",
"result",
")",
";",
"}"
] | Log a method return, with result object.
<p>
This is a convenience method that can be used to log returning
from a method. A LogRecord with message "RETURN {0}", log level
FINER, and the gives sourceMethod, sourceClass, and result
object is logged.
<p>
@param sourceClass name of class that issued the logging request
@param sourceMethod name of the method
@param result Object that is being returned | [
"Log",
"a",
"method",
"return",
"with",
"result",
"object",
".",
"<p",
">",
"This",
"is",
"a",
"convenience",
"method",
"that",
"can",
"be",
"used",
"to",
"log",
"returning",
"from",
"a",
"method",
".",
"A",
"LogRecord",
"with",
"message",
"RETURN",
"{",... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/logging/MyfacesLogger.java#L774-L777 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/util/ClassLoaderUtil.java | ClassLoaderUtil.validateClassLoadable | public static boolean validateClassLoadable(ClassNotFoundException cnfe, ClassLoader cl) {
try {
String className = cnfe.getMessage();
Class.forName(className, false, cl);
return true;
}
catch (ClassNotFoundException e) {
return false;
}
catch (Exception e) {
return false;
}
} | java | public static boolean validateClassLoadable(ClassNotFoundException cnfe, ClassLoader cl) {
try {
String className = cnfe.getMessage();
Class.forName(className, false, cl);
return true;
}
catch (ClassNotFoundException e) {
return false;
}
catch (Exception e) {
return false;
}
} | [
"public",
"static",
"boolean",
"validateClassLoadable",
"(",
"ClassNotFoundException",
"cnfe",
",",
"ClassLoader",
"cl",
")",
"{",
"try",
"{",
"String",
"className",
"=",
"cnfe",
".",
"getMessage",
"(",
")",
";",
"Class",
".",
"forName",
"(",
"className",
",",... | Checks, whether the class that was not found in the given exception, can be resolved through
the given class loader.
@param cnfe The ClassNotFoundException that defines the name of the class.
@param cl The class loader to use for the class resolution.
@return True, if the class can be resolved with the given class loader, false if not. | [
"Checks",
"whether",
"the",
"class",
"that",
"was",
"not",
"found",
"in",
"the",
"given",
"exception",
"can",
"be",
"resolved",
"through",
"the",
"given",
"class",
"loader",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/util/ClassLoaderUtil.java#L119-L131 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/nvrtc/JNvrtc.java | JNvrtc.nvrtcGetLoweredName | public static int nvrtcGetLoweredName(nvrtcProgram prog, String name_expression, String lowered_name[])
{
return checkResult(nvrtcGetLoweredNameNative(prog, name_expression, lowered_name));
} | java | public static int nvrtcGetLoweredName(nvrtcProgram prog, String name_expression, String lowered_name[])
{
return checkResult(nvrtcGetLoweredNameNative(prog, name_expression, lowered_name));
} | [
"public",
"static",
"int",
"nvrtcGetLoweredName",
"(",
"nvrtcProgram",
"prog",
",",
"String",
"name_expression",
",",
"String",
"lowered_name",
"[",
"]",
")",
"{",
"return",
"checkResult",
"(",
"nvrtcGetLoweredNameNative",
"(",
"prog",
",",
"name_expression",
",",
... | Extracts the lowered (mangled) name for a __global__ function or
function template instantiation, and updates *lowered_name to point
to it. The memory containing the name is released when the NVRTC
program is destroyed by nvrtcDestroyProgram.<br>
<br>
The identical name expression must have been previously
provided to nvrtcAddNameExpression.
@param prog CUDA Runtime Compilation program.
@param name_expression constant expression denoting a __global__
function or function template instantiation.
@param lowered_name initialized by the function to point to a
C string containing the lowered (mangled) name corresponding
to the provided name expression.
@return NVRTC_SUCCESS, NVRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION,
NVRTC_ERROR_NAME_EXPRESSION_NOT_VALID
@see #nvrtcAddNameExpression | [
"Extracts",
"the",
"lowered",
"(",
"mangled",
")",
"name",
"for",
"a",
"__global__",
"function",
"or",
"function",
"template",
"instantiation",
"and",
"updates",
"*",
"lowered_name",
"to",
"point",
"to",
"it",
".",
"The",
"memory",
"containing",
"the",
"name",... | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/nvrtc/JNvrtc.java#L327-L330 |
ontop/ontop | client/protege/src/main/java/it/unibz/inf/ontop/protege/utils/JDBCConnectionManager.java | JDBCConnectionManager.createConnection | public Connection createConnection(String url, String username, String password) throws SQLException {
if (connection != null && !connection.isClosed())
return connection;
connection = DriverManager.getConnection(url, username, password);
return connection;
} | java | public Connection createConnection(String url, String username, String password) throws SQLException {
if (connection != null && !connection.isClosed())
return connection;
connection = DriverManager.getConnection(url, username, password);
return connection;
} | [
"public",
"Connection",
"createConnection",
"(",
"String",
"url",
",",
"String",
"username",
",",
"String",
"password",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"connection",
"!=",
"null",
"&&",
"!",
"connection",
".",
"isClosed",
"(",
")",
")",
"retur... | Constructs a new database connection object and retrieves it.
@return The connection object.
@throws SQLException | [
"Constructs",
"a",
"new",
"database",
"connection",
"object",
"and",
"retrieves",
"it",
"."
] | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/client/protege/src/main/java/it/unibz/inf/ontop/protege/utils/JDBCConnectionManager.java#L79-L86 |
alipay/sofa-rpc | core/common/src/main/java/com/alipay/sofa/rpc/common/struct/MapDifference.java | MapDifference.valueEquals | private boolean valueEquals(V leftValue, V rightValue) {
if (leftValue == rightValue) {
return true;
}
if (leftValue == null || rightValue == null) {
return false;
}
return leftValue.equals(rightValue);
} | java | private boolean valueEquals(V leftValue, V rightValue) {
if (leftValue == rightValue) {
return true;
}
if (leftValue == null || rightValue == null) {
return false;
}
return leftValue.equals(rightValue);
} | [
"private",
"boolean",
"valueEquals",
"(",
"V",
"leftValue",
",",
"V",
"rightValue",
")",
"{",
"if",
"(",
"leftValue",
"==",
"rightValue",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"leftValue",
"==",
"null",
"||",
"rightValue",
"==",
"null",
")",
... | Value equals.
@param leftValue
the left value
@param rightValue
the right value
@return the boolean | [
"Value",
"equals",
"."
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/common/src/main/java/com/alipay/sofa/rpc/common/struct/MapDifference.java#L101-L109 |
Hygieia/Hygieia | collectors/feature/versionone/src/main/java/com/capitalone/dashboard/util/DateUtil.java | DateUtil.evaluateSprintLength | public boolean evaluateSprintLength(String startDate, String endDate, int maxKanbanIterationLength) {
boolean sprintIndicator = false;
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
if (!StringUtils.isAnyEmpty(startDate) && !StringUtils.isAnyEmpty(endDate)) {
Date strDt = convertIntoDate(startDate.substring(0, 4) + "-" + startDate.substring(5, 7) + "-" + startDate.substring(8, 10), "yyyy-MM-dd" );
Date endDt = convertIntoDate(endDate.substring(0, 4) + "-" + endDate.substring(5, 7) + "-" + endDate.substring(8, 10), "yyyy-MM-dd");
if (strDt != null && endDate != null) {
startCalendar.setTime(strDt);
endCalendar.setTime(endDt);
long diffMill = endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis();
long diffDays = TimeUnit.DAYS.convert(diffMill, TimeUnit.MILLISECONDS);
if (diffDays <= maxKanbanIterationLength) {
// Scrum-enough
sprintIndicator = true;
}
}
} else {
// Default to kanban
sprintIndicator = false;
}
return sprintIndicator;
} | java | public boolean evaluateSprintLength(String startDate, String endDate, int maxKanbanIterationLength) {
boolean sprintIndicator = false;
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
if (!StringUtils.isAnyEmpty(startDate) && !StringUtils.isAnyEmpty(endDate)) {
Date strDt = convertIntoDate(startDate.substring(0, 4) + "-" + startDate.substring(5, 7) + "-" + startDate.substring(8, 10), "yyyy-MM-dd" );
Date endDt = convertIntoDate(endDate.substring(0, 4) + "-" + endDate.substring(5, 7) + "-" + endDate.substring(8, 10), "yyyy-MM-dd");
if (strDt != null && endDate != null) {
startCalendar.setTime(strDt);
endCalendar.setTime(endDt);
long diffMill = endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis();
long diffDays = TimeUnit.DAYS.convert(diffMill, TimeUnit.MILLISECONDS);
if (diffDays <= maxKanbanIterationLength) {
// Scrum-enough
sprintIndicator = true;
}
}
} else {
// Default to kanban
sprintIndicator = false;
}
return sprintIndicator;
} | [
"public",
"boolean",
"evaluateSprintLength",
"(",
"String",
"startDate",
",",
"String",
"endDate",
",",
"int",
"maxKanbanIterationLength",
")",
"{",
"boolean",
"sprintIndicator",
"=",
"false",
";",
"Calendar",
"startCalendar",
"=",
"Calendar",
".",
"getInstance",
"(... | Evaluates whether a sprint length appears to be kanban or scrum
@param startDate
The start date of a sprint in ISO format
@param endDate
The end date of a sprint in ISO format
@return True indicates a scrum sprint; False indicates a Kanban sprint | [
"Evaluates",
"whether",
"a",
"sprint",
"length",
"appears",
"to",
"be",
"kanban",
"or",
"scrum"
] | train | https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/feature/versionone/src/main/java/com/capitalone/dashboard/util/DateUtil.java#L85-L114 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/QuickSelect.java | QuickSelect.quickSelect | public static double quickSelect(double[] data, int rank) {
quickSelect(data, 0, data.length, rank);
return data[rank];
} | java | public static double quickSelect(double[] data, int rank) {
quickSelect(data, 0, data.length, rank);
return data[rank];
} | [
"public",
"static",
"double",
"quickSelect",
"(",
"double",
"[",
"]",
"data",
",",
"int",
"rank",
")",
"{",
"quickSelect",
"(",
"data",
",",
"0",
",",
"data",
".",
"length",
",",
"rank",
")",
";",
"return",
"data",
"[",
"rank",
"]",
";",
"}"
] | QuickSelect is essentially quicksort, except that we only "sort" that half
of the array that we are interested in.
Note: the array is <b>modified</b> by this.
@param data Data to process
@param rank Rank position that we are interested in (integer!)
@return Value at the given rank | [
"QuickSelect",
"is",
"essentially",
"quicksort",
"except",
"that",
"we",
"only",
"sort",
"that",
"half",
"of",
"the",
"array",
"that",
"we",
"are",
"interested",
"in",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/QuickSelect.java#L362-L365 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/clustering/GvmSpace.java | GvmSpace.distance | public double distance(Object pt1, Object pt2) {
Object p = newCopy(pt1);
subtract(p, pt2);
return magnitude(p);
} | java | public double distance(Object pt1, Object pt2) {
Object p = newCopy(pt1);
subtract(p, pt2);
return magnitude(p);
} | [
"public",
"double",
"distance",
"(",
"Object",
"pt1",
",",
"Object",
"pt2",
")",
"{",
"Object",
"p",
"=",
"newCopy",
"(",
"pt1",
")",
";",
"subtract",
"(",
"p",
",",
"pt2",
")",
";",
"return",
"magnitude",
"(",
"p",
")",
";",
"}"
] | not used directly in algorithm, but useful - override for good performance | [
"not",
"used",
"directly",
"in",
"algorithm",
"but",
"useful",
"-",
"override",
"for",
"good",
"performance"
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/clustering/GvmSpace.java#L24-L28 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VpnSitesInner.java | VpnSitesInner.beginUpdateTagsAsync | public Observable<VpnSiteInner> beginUpdateTagsAsync(String resourceGroupName, String vpnSiteName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, vpnSiteName, tags).map(new Func1<ServiceResponse<VpnSiteInner>, VpnSiteInner>() {
@Override
public VpnSiteInner call(ServiceResponse<VpnSiteInner> response) {
return response.body();
}
});
} | java | public Observable<VpnSiteInner> beginUpdateTagsAsync(String resourceGroupName, String vpnSiteName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, vpnSiteName, tags).map(new Func1<ServiceResponse<VpnSiteInner>, VpnSiteInner>() {
@Override
public VpnSiteInner call(ServiceResponse<VpnSiteInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"VpnSiteInner",
">",
"beginUpdateTagsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"vpnSiteName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"beginUpdateTagsWithServiceResponseAsync",
"(",
"re... | Updates VpnSite tags.
@param resourceGroupName The resource group name of the VpnSite.
@param vpnSiteName The name of the VpnSite being updated.
@param tags Resource tags.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the VpnSiteInner object | [
"Updates",
"VpnSite",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/VpnSitesInner.java#L629-L636 |
liferay/com-liferay-commerce | commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java | CommerceNotificationTemplatePersistenceImpl.findAll | @Override
public List<CommerceNotificationTemplate> findAll(int start, int end) {
return findAll(start, end, null);
} | java | @Override
public List<CommerceNotificationTemplate> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceNotificationTemplate",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce notification templates.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceNotificationTemplateModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce notification templates
@param end the upper bound of the range of commerce notification templates (not inclusive)
@return the range of commerce notification templates | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"notification",
"templates",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java#L5177-L5180 |
cloudfoundry/uaa | server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtils.java | UaaTokenUtils.murmurhash3x8632 | public static int murmurhash3x8632(byte[] data, int offset, int len, int seed) {
int c1 = 0xcc9e2d51;
int c2 = 0x1b873593;
int h1 = seed;
int roundedEnd = offset + (len & 0xfffffffc); // round down to 4 byte block
for (int i = offset; i < roundedEnd; i += 4) {
// little endian load order
int k1 = (data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | ((data[i + 2] & 0xff) << 16) | (data[i + 3] << 24);
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13);
h1 = h1 * 5 + 0xe6546b64;
}
// tail
int k1 = 0;
switch(len & 0x03) {
case 3:
k1 = (data[roundedEnd + 2] & 0xff) << 16;
// fallthrough
case 2:
k1 |= (data[roundedEnd + 1] & 0xff) << 8;
// fallthrough
case 1:
k1 |= data[roundedEnd] & 0xff;
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
default:
}
// finalization
h1 ^= len;
// fmix(h1);
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
return h1;
} | java | public static int murmurhash3x8632(byte[] data, int offset, int len, int seed) {
int c1 = 0xcc9e2d51;
int c2 = 0x1b873593;
int h1 = seed;
int roundedEnd = offset + (len & 0xfffffffc); // round down to 4 byte block
for (int i = offset; i < roundedEnd; i += 4) {
// little endian load order
int k1 = (data[i] & 0xff) | ((data[i + 1] & 0xff) << 8) | ((data[i + 2] & 0xff) << 16) | (data[i + 3] << 24);
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13);
h1 = h1 * 5 + 0xe6546b64;
}
// tail
int k1 = 0;
switch(len & 0x03) {
case 3:
k1 = (data[roundedEnd + 2] & 0xff) << 16;
// fallthrough
case 2:
k1 |= (data[roundedEnd + 1] & 0xff) << 8;
// fallthrough
case 1:
k1 |= data[roundedEnd] & 0xff;
k1 *= c1;
k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
default:
}
// finalization
h1 ^= len;
// fmix(h1);
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
return h1;
} | [
"public",
"static",
"int",
"murmurhash3x8632",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
",",
"int",
"len",
",",
"int",
"seed",
")",
"{",
"int",
"c1",
"=",
"0xcc9e2d51",
";",
"int",
"c2",
"=",
"0x1b873593",
";",
"int",
"h1",
"=",
"seed",
... | This code is public domain.
The MurmurHash3 algorithm was created by Austin Appleby and put into the public domain.
@see <a href="http://code.google.com/p/smhasher">http://code.google.com/p/smhasher</a>
@see <a href="https://github.com/yonik/java_util/blob/master/src/util/hash/MurmurHash3.java">https://github.com/yonik/java_util/blob/master/src/util/hash/MurmurHash3.java</a> | [
"This",
"code",
"is",
"public",
"domain",
"."
] | train | https://github.com/cloudfoundry/uaa/blob/e8df3d7060580c92d33461106399f9e4f36e3cd2/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtils.java#L75-L125 |
Viascom/groundwork | foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/util/QueryBuilder.java | QueryBuilder.buildQuery | public static String buildQuery(Map<String, String> entries, String encoding) throws FoxHttpRequestException {
if (entries.size() > 0) {
StringBuilder sb = new StringBuilder();
String dataString;
try {
for (Map.Entry<String, String> entry : entries.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), encoding));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append("&");
}
sb.deleteCharAt(sb.lastIndexOf("&"));
dataString = sb.toString();
} catch (UnsupportedEncodingException e) {
throw new FoxHttpRequestException(e);
}
return dataString;
} else {
return "";
}
} | java | public static String buildQuery(Map<String, String> entries, String encoding) throws FoxHttpRequestException {
if (entries.size() > 0) {
StringBuilder sb = new StringBuilder();
String dataString;
try {
for (Map.Entry<String, String> entry : entries.entrySet()) {
sb.append(URLEncoder.encode(entry.getKey(), encoding));
sb.append("=");
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append("&");
}
sb.deleteCharAt(sb.lastIndexOf("&"));
dataString = sb.toString();
} catch (UnsupportedEncodingException e) {
throw new FoxHttpRequestException(e);
}
return dataString;
} else {
return "";
}
} | [
"public",
"static",
"String",
"buildQuery",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"entries",
",",
"String",
"encoding",
")",
"throws",
"FoxHttpRequestException",
"{",
"if",
"(",
"entries",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"StringBuilder"... | Return a string of key/value pair's based on a map
@param entries
@param encoding
@return
@throws FoxHttpRequestException | [
"Return",
"a",
"string",
"of",
"key",
"/",
"value",
"pair",
"s",
"based",
"on",
"a",
"map"
] | train | https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/util/QueryBuilder.java#L42-L62 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/layout/GridBagLayoutBuilder.java | GridBagLayoutBuilder.appendRightLabel | public GridBagLayoutBuilder appendRightLabel(String labelKey, int colSpan) {
final JLabel label = createLabel(labelKey);
label.setHorizontalAlignment(SwingConstants.RIGHT);
return appendLabel(label, colSpan);
} | java | public GridBagLayoutBuilder appendRightLabel(String labelKey, int colSpan) {
final JLabel label = createLabel(labelKey);
label.setHorizontalAlignment(SwingConstants.RIGHT);
return appendLabel(label, colSpan);
} | [
"public",
"GridBagLayoutBuilder",
"appendRightLabel",
"(",
"String",
"labelKey",
",",
"int",
"colSpan",
")",
"{",
"final",
"JLabel",
"label",
"=",
"createLabel",
"(",
"labelKey",
")",
";",
"label",
".",
"setHorizontalAlignment",
"(",
"SwingConstants",
".",
"RIGHT"... | Appends a right-justified label to the end of the given line, using the
provided string as the key to look in the
{@link #setComponentFactory(ComponentFactory) ComponentFactory's}message
bundle for the text to use.
@param labelKey the key into the message bundle; if not found the key is used
as the text to display
@param colSpan the number of columns to span
@return "this" to make it easier to string together append calls | [
"Appends",
"a",
"right",
"-",
"justified",
"label",
"to",
"the",
"end",
"of",
"the",
"given",
"line",
"using",
"the",
"provided",
"string",
"as",
"the",
"key",
"to",
"look",
"in",
"the",
"{",
"@link",
"#setComponentFactory",
"(",
"ComponentFactory",
")",
"... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/layout/GridBagLayoutBuilder.java#L502-L506 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/FilterFileSystem.java | FilterFileSystem.copyFromLocalFile | public void copyFromLocalFile(boolean delSrc, Path src, Path dst)
throws IOException {
fs.copyFromLocalFile(delSrc, src, dst);
} | java | public void copyFromLocalFile(boolean delSrc, Path src, Path dst)
throws IOException {
fs.copyFromLocalFile(delSrc, src, dst);
} | [
"public",
"void",
"copyFromLocalFile",
"(",
"boolean",
"delSrc",
",",
"Path",
"src",
",",
"Path",
"dst",
")",
"throws",
"IOException",
"{",
"fs",
".",
"copyFromLocalFile",
"(",
"delSrc",
",",
"src",
",",
"dst",
")",
";",
"}"
] | The src file is on the local disk. Add it to FS at
the given dst name.
delSrc indicates if the source should be removed | [
"The",
"src",
"file",
"is",
"on",
"the",
"local",
"disk",
".",
"Add",
"it",
"to",
"FS",
"at",
"the",
"given",
"dst",
"name",
".",
"delSrc",
"indicates",
"if",
"the",
"source",
"should",
"be",
"removed"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FilterFileSystem.java#L311-L314 |
sporniket/core | sporniket-core-io/src/main/java/com/sporniket/libre/io/parser/properties/LineByLinePropertyParser.java | LineByLinePropertyParser.fireSingleLinePropertyParsedEvent | private void fireSingleLinePropertyParsedEvent(String name, String value)
{
SingleLinePropertyParsedEvent _event = new SingleLinePropertyParsedEvent(name, value);
for (PropertiesParsingListener _listener : getListeners())
{
_listener.onSingleLinePropertyParsed(_event);
}
} | java | private void fireSingleLinePropertyParsedEvent(String name, String value)
{
SingleLinePropertyParsedEvent _event = new SingleLinePropertyParsedEvent(name, value);
for (PropertiesParsingListener _listener : getListeners())
{
_listener.onSingleLinePropertyParsed(_event);
}
} | [
"private",
"void",
"fireSingleLinePropertyParsedEvent",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"SingleLinePropertyParsedEvent",
"_event",
"=",
"new",
"SingleLinePropertyParsedEvent",
"(",
"name",
",",
"value",
")",
";",
"for",
"(",
"PropertiesParsing... | Notify listeners that a single line property has been parsed.
@param name
property name.
@param value
property value. | [
"Notify",
"listeners",
"that",
"a",
"single",
"line",
"property",
"has",
"been",
"parsed",
"."
] | train | https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/parser/properties/LineByLinePropertyParser.java#L570-L577 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/font/FontLoader.java | FontLoader.getTypeface | public static Typeface getTypeface(Context ctx, Face type){
return getTypeface(ctx, "fonts/" + type.getFontFileName());
} | java | public static Typeface getTypeface(Context ctx, Face type){
return getTypeface(ctx, "fonts/" + type.getFontFileName());
} | [
"public",
"static",
"Typeface",
"getTypeface",
"(",
"Context",
"ctx",
",",
"Face",
"type",
")",
"{",
"return",
"getTypeface",
"(",
"ctx",
",",
"\"fonts/\"",
"+",
"type",
".",
"getFontFileName",
"(",
")",
")",
";",
"}"
] | Get a Roboto typeface for a given string type
@param ctx the application context
@param type the typeface type argument
@return the loaded typeface, or null | [
"Get",
"a",
"Roboto",
"typeface",
"for",
"a",
"given",
"string",
"type"
] | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/font/FontLoader.java#L104-L106 |
MenoData/Time4J | base/src/main/java/net/time4j/calendar/astro/JulianDay.java | JulianDay.ofEphemerisTime | public static JulianDay ofEphemerisTime(
CalendarDate date,
PlainTime time,
ZonalOffset offset
) {
long d = EpochDays.JULIAN_DAY_NUMBER.transform(date.getDaysSinceEpochUTC(), EpochDays.UTC);
double tod = time.get(PlainTime.NANO_OF_DAY) / (86400.0 * 1000000000L);
double jde = d - 0.5 + tod - offset.getIntegralAmount() / 86400.0;
return new JulianDay(jde, TimeScale.TT);
} | java | public static JulianDay ofEphemerisTime(
CalendarDate date,
PlainTime time,
ZonalOffset offset
) {
long d = EpochDays.JULIAN_DAY_NUMBER.transform(date.getDaysSinceEpochUTC(), EpochDays.UTC);
double tod = time.get(PlainTime.NANO_OF_DAY) / (86400.0 * 1000000000L);
double jde = d - 0.5 + tod - offset.getIntegralAmount() / 86400.0;
return new JulianDay(jde, TimeScale.TT);
} | [
"public",
"static",
"JulianDay",
"ofEphemerisTime",
"(",
"CalendarDate",
"date",
",",
"PlainTime",
"time",
",",
"ZonalOffset",
"offset",
")",
"{",
"long",
"d",
"=",
"EpochDays",
".",
"JULIAN_DAY_NUMBER",
".",
"transform",
"(",
"date",
".",
"getDaysSinceEpochUTC",
... | /*[deutsch]
<p>Erzeugt einen julianischen Tag auf der Zeitskala {@link TimeScale#TT},
manchmal auch <em>Julian Ephemeris Day</em> genannt. </p>
<p>Diese Art des julianischen Tages repräsentiert den aktuellen astronomischen Standard.
Die Zeit TT-2000-01-01T12:00Z entspricht JD(TT)2451545.0 </p>
@param date calendar date
@param time local time
@param offset timezone offset
@return JulianDay
@throws IllegalArgumentException if the Julian day of moment is not in supported range
@since 3.36/4.31 | [
"/",
"*",
"[",
"deutsch",
"]",
"<p",
">",
"Erzeugt",
"einen",
"julianischen",
"Tag",
"auf",
"der",
"Zeitskala",
"{",
"@link",
"TimeScale#TT",
"}",
"manchmal",
"auch",
"<em",
">",
"Julian",
"Ephemeris",
"Day<",
"/",
"em",
">",
"genannt",
".",
"<",
"/",
... | train | https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/calendar/astro/JulianDay.java#L219-L230 |
alkacon/opencms-core | src-setup/org/opencms/setup/CmsSetupBean.java | CmsSetupBean.copyFile | public void copyFile(String source, String target) {
try {
CmsFileUtil.copy(m_configRfsPath + source, m_configRfsPath + target);
} catch (IOException e) {
m_errors.add("Could not copy " + source + " to " + target + " \n");
m_errors.add(e.toString() + "\n");
}
} | java | public void copyFile(String source, String target) {
try {
CmsFileUtil.copy(m_configRfsPath + source, m_configRfsPath + target);
} catch (IOException e) {
m_errors.add("Could not copy " + source + " to " + target + " \n");
m_errors.add(e.toString() + "\n");
}
} | [
"public",
"void",
"copyFile",
"(",
"String",
"source",
",",
"String",
"target",
")",
"{",
"try",
"{",
"CmsFileUtil",
".",
"copy",
"(",
"m_configRfsPath",
"+",
"source",
",",
"m_configRfsPath",
"+",
"target",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",... | Copies a given file.<p>
@param source the source file
@param target the destination file | [
"Copies",
"a",
"given",
"file",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-setup/org/opencms/setup/CmsSetupBean.java#L411-L419 |
alkacon/opencms-core | src/org/opencms/db/generic/CmsUserQueryBuilder.java | CmsUserQueryBuilder.addSearchFilterCondition | protected void addSearchFilterCondition(
CmsSelectQuery select,
TableAlias users,
CmsUserSearchParameters searchParams) {
String searchFilter = searchParams.getSearchFilter();
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(searchFilter)) {
boolean caseInsensitive = !searchParams.isCaseSensitive();
if (caseInsensitive) {
searchFilter = searchFilter.toLowerCase();
}
CmsCompositeQueryFragment searchCondition = new CmsCompositeQueryFragment();
searchCondition.setSeparator(" OR ");
searchCondition.setPrefix("(");
searchCondition.setSuffix(")");
//use coalesce in case any of the name columns are null
String patternExprTemplate = generateConcat(
"COALESCE(%1$s, '')",
"' '",
"COALESCE(%2$s, '')",
"' '",
"COALESCE(%3$s, '')");
patternExprTemplate = wrapLower(patternExprTemplate, caseInsensitive);
String patternExpr = String.format(
patternExprTemplate,
users.column(colName()),
users.column(colFirstName()),
users.column(colLastName()));
String like = " LIKE ? ESCAPE '!' ";
String matchExpr = patternExpr + like;
searchFilter = "%" + CmsEncoder.escapeSqlLikePattern(searchFilter, '!') + '%';
searchCondition.add(new CmsSimpleQueryFragment(matchExpr, searchFilter));
for (SearchKey key : searchParams.getSearchKeys()) {
switch (key) {
case email:
searchCondition.add(
new CmsSimpleQueryFragment(
wrapLower(users.column(colEmail()), caseInsensitive) + like,
searchFilter));
break;
case orgUnit:
searchCondition.add(new CmsSimpleQueryFragment(
wrapLower(users.column(colOu()), caseInsensitive) + like,
searchFilter));
break;
default:
break;
}
}
select.addCondition(searchCondition);
}
} | java | protected void addSearchFilterCondition(
CmsSelectQuery select,
TableAlias users,
CmsUserSearchParameters searchParams) {
String searchFilter = searchParams.getSearchFilter();
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(searchFilter)) {
boolean caseInsensitive = !searchParams.isCaseSensitive();
if (caseInsensitive) {
searchFilter = searchFilter.toLowerCase();
}
CmsCompositeQueryFragment searchCondition = new CmsCompositeQueryFragment();
searchCondition.setSeparator(" OR ");
searchCondition.setPrefix("(");
searchCondition.setSuffix(")");
//use coalesce in case any of the name columns are null
String patternExprTemplate = generateConcat(
"COALESCE(%1$s, '')",
"' '",
"COALESCE(%2$s, '')",
"' '",
"COALESCE(%3$s, '')");
patternExprTemplate = wrapLower(patternExprTemplate, caseInsensitive);
String patternExpr = String.format(
patternExprTemplate,
users.column(colName()),
users.column(colFirstName()),
users.column(colLastName()));
String like = " LIKE ? ESCAPE '!' ";
String matchExpr = patternExpr + like;
searchFilter = "%" + CmsEncoder.escapeSqlLikePattern(searchFilter, '!') + '%';
searchCondition.add(new CmsSimpleQueryFragment(matchExpr, searchFilter));
for (SearchKey key : searchParams.getSearchKeys()) {
switch (key) {
case email:
searchCondition.add(
new CmsSimpleQueryFragment(
wrapLower(users.column(colEmail()), caseInsensitive) + like,
searchFilter));
break;
case orgUnit:
searchCondition.add(new CmsSimpleQueryFragment(
wrapLower(users.column(colOu()), caseInsensitive) + like,
searchFilter));
break;
default:
break;
}
}
select.addCondition(searchCondition);
}
} | [
"protected",
"void",
"addSearchFilterCondition",
"(",
"CmsSelectQuery",
"select",
",",
"TableAlias",
"users",
",",
"CmsUserSearchParameters",
"searchParams",
")",
"{",
"String",
"searchFilter",
"=",
"searchParams",
".",
"getSearchFilter",
"(",
")",
";",
"if",
"(",
"... | Adds a search condition to a query.<p>
@param select the query
@param users the user table alias
@param searchParams the search criteria | [
"Adds",
"a",
"search",
"condition",
"to",
"a",
"query",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsUserQueryBuilder.java#L284-L336 |
mlhartme/sushi | src/main/java/net/oneandone/sushi/io/Buffer.java | Buffer.copy | public long copy(InputStream in, OutputStream out, long max) throws IOException {
int chunk;
long all;
long remaining;
remaining = max;
all = 0;
while (remaining > 0) {
// cast is save because the buffer.length is an integer
chunk = in.read(buffer, 0, (int) Math.min(remaining, buffer.length));
if (chunk < 0) {
break;
}
out.write(buffer, 0, chunk);
all += chunk;
remaining -= chunk;
}
out.flush();
return all;
} | java | public long copy(InputStream in, OutputStream out, long max) throws IOException {
int chunk;
long all;
long remaining;
remaining = max;
all = 0;
while (remaining > 0) {
// cast is save because the buffer.length is an integer
chunk = in.read(buffer, 0, (int) Math.min(remaining, buffer.length));
if (chunk < 0) {
break;
}
out.write(buffer, 0, chunk);
all += chunk;
remaining -= chunk;
}
out.flush();
return all;
} | [
"public",
"long",
"copy",
"(",
"InputStream",
"in",
",",
"OutputStream",
"out",
",",
"long",
"max",
")",
"throws",
"IOException",
"{",
"int",
"chunk",
";",
"long",
"all",
";",
"long",
"remaining",
";",
"remaining",
"=",
"max",
";",
"all",
"=",
"0",
";"... | Copies up to max bytes.
@return number of bytes actually copied | [
"Copies",
"up",
"to",
"max",
"bytes",
"."
] | train | https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/io/Buffer.java#L165-L184 |
stratosphere/stratosphere | stratosphere-addons/spargel/src/main/java/eu/stratosphere/spargel/java/VertexCentricIteration.java | VertexCentricIteration.addBroadcastSetForUpdateFunction | public void addBroadcastSetForUpdateFunction(String name, DataSet<?> data) {
this.bcVarsUpdate.add(new Tuple2<String, DataSet<?>>(name, data));
} | java | public void addBroadcastSetForUpdateFunction(String name, DataSet<?> data) {
this.bcVarsUpdate.add(new Tuple2<String, DataSet<?>>(name, data));
} | [
"public",
"void",
"addBroadcastSetForUpdateFunction",
"(",
"String",
"name",
",",
"DataSet",
"<",
"?",
">",
"data",
")",
"{",
"this",
".",
"bcVarsUpdate",
".",
"add",
"(",
"new",
"Tuple2",
"<",
"String",
",",
"DataSet",
"<",
"?",
">",
">",
"(",
"name",
... | Adds a data set as a broadcast set to the vertex update function.
@param name The name under which the broadcast data is available in the vertex update function.
@param data The data set to be broadcasted. | [
"Adds",
"a",
"data",
"set",
"as",
"a",
"broadcast",
"set",
"to",
"the",
"vertex",
"update",
"function",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-addons/spargel/src/main/java/eu/stratosphere/spargel/java/VertexCentricIteration.java#L190-L192 |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java | CompoundDocument.getSIdChain | private SIdChain getSIdChain(final int pSId, final long pStreamSize) throws IOException {
SIdChain chain = new SIdChain();
int[] sat = isShortStream(pStreamSize) ? shortSAT : SAT;
int sid = pSId;
while (sid != END_OF_CHAIN_SID && sid != FREE_SID) {
chain.addSID(sid);
sid = sat[sid];
}
return chain;
} | java | private SIdChain getSIdChain(final int pSId, final long pStreamSize) throws IOException {
SIdChain chain = new SIdChain();
int[] sat = isShortStream(pStreamSize) ? shortSAT : SAT;
int sid = pSId;
while (sid != END_OF_CHAIN_SID && sid != FREE_SID) {
chain.addSID(sid);
sid = sat[sid];
}
return chain;
} | [
"private",
"SIdChain",
"getSIdChain",
"(",
"final",
"int",
"pSId",
",",
"final",
"long",
"pStreamSize",
")",
"throws",
"IOException",
"{",
"SIdChain",
"chain",
"=",
"new",
"SIdChain",
"(",
")",
";",
"int",
"[",
"]",
"sat",
"=",
"isShortStream",
"(",
"pStre... | Gets the SIdChain for the given stream Id
@param pSId the stream Id
@param pStreamSize the size of the stream, or -1 for system control streams
@return the SIdChain for the given stream Id
@throws IOException if an I/O exception occurs | [
"Gets",
"the",
"SIdChain",
"for",
"the",
"given",
"stream",
"Id"
] | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java#L414-L426 |
alkacon/opencms-core | src/org/opencms/db/CmsDriverManager.java | CmsDriverManager.checkDeletedParentFolder | private boolean checkDeletedParentFolder(CmsDbContext dbc, List<CmsResource> deletedFolders, CmsResource res) {
String parentPath = CmsResource.getParentFolder(res.getRootPath());
if (parentPath == null) {
// resource has no parent
return false;
}
CmsResource parent;
try {
parent = readResource(dbc, parentPath, CmsResourceFilter.ALL);
} catch (Exception e) {
// failure: if we cannot read the parent, we should not publish the resource
return false;
}
if (!parent.getState().isDeleted()) {
// parent is not deleted
return false;
}
for (int j = 0; j < deletedFolders.size(); j++) {
if ((deletedFolders.get(j)).getStructureId().equals(parent.getStructureId())) {
// parent is deleted, and it will get published
return true;
}
}
// parent is new, but it will not get published
return false;
} | java | private boolean checkDeletedParentFolder(CmsDbContext dbc, List<CmsResource> deletedFolders, CmsResource res) {
String parentPath = CmsResource.getParentFolder(res.getRootPath());
if (parentPath == null) {
// resource has no parent
return false;
}
CmsResource parent;
try {
parent = readResource(dbc, parentPath, CmsResourceFilter.ALL);
} catch (Exception e) {
// failure: if we cannot read the parent, we should not publish the resource
return false;
}
if (!parent.getState().isDeleted()) {
// parent is not deleted
return false;
}
for (int j = 0; j < deletedFolders.size(); j++) {
if ((deletedFolders.get(j)).getStructureId().equals(parent.getStructureId())) {
// parent is deleted, and it will get published
return true;
}
}
// parent is new, but it will not get published
return false;
} | [
"private",
"boolean",
"checkDeletedParentFolder",
"(",
"CmsDbContext",
"dbc",
",",
"List",
"<",
"CmsResource",
">",
"deletedFolders",
",",
"CmsResource",
"res",
")",
"{",
"String",
"parentPath",
"=",
"CmsResource",
".",
"getParentFolder",
"(",
"res",
".",
"getRoot... | Checks the parent of a resource during publishing.<p>
@param dbc the current database context
@param deletedFolders a list of deleted folders
@param res a resource to check the parent for
@return <code>true</code> if the parent resource will be deleted during publishing | [
"Checks",
"the",
"parent",
"of",
"a",
"resource",
"during",
"publishing",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L10730-L10761 |
VoltDB/voltdb | src/frontend/org/voltdb/importclient/kinesis/KinesisStreamImporterConfig.java | KinesisStreamImporterConfig.discoverShards | public static List<Shard> discoverShards(String regionName, String streamName, String accessKey, String secretKey,
String appName) {
try {
Region region = RegionUtils.getRegion(regionName);
if (region != null) {
final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonKinesis kinesisClient = new AmazonKinesisClient(credentials,
getClientConfigWithUserAgent(appName));
kinesisClient.setRegion(region);
DescribeStreamResult result = kinesisClient.describeStream(streamName);
if (!"ACTIVE".equals(result.getStreamDescription().getStreamStatus())) {
throw new IllegalArgumentException("Kinesis stream " + streamName + " is not active.");
}
return result.getStreamDescription().getShards();
}
} catch (ResourceNotFoundException e) {
LOGGER.warn("Kinesis stream " + streamName + " does not exist.", e);
} catch (Exception e) {
LOGGER.warn("Error found while describing the kinesis stream " + streamName, e);
}
return null;
} | java | public static List<Shard> discoverShards(String regionName, String streamName, String accessKey, String secretKey,
String appName) {
try {
Region region = RegionUtils.getRegion(regionName);
if (region != null) {
final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonKinesis kinesisClient = new AmazonKinesisClient(credentials,
getClientConfigWithUserAgent(appName));
kinesisClient.setRegion(region);
DescribeStreamResult result = kinesisClient.describeStream(streamName);
if (!"ACTIVE".equals(result.getStreamDescription().getStreamStatus())) {
throw new IllegalArgumentException("Kinesis stream " + streamName + " is not active.");
}
return result.getStreamDescription().getShards();
}
} catch (ResourceNotFoundException e) {
LOGGER.warn("Kinesis stream " + streamName + " does not exist.", e);
} catch (Exception e) {
LOGGER.warn("Error found while describing the kinesis stream " + streamName, e);
}
return null;
} | [
"public",
"static",
"List",
"<",
"Shard",
">",
"discoverShards",
"(",
"String",
"regionName",
",",
"String",
"streamName",
",",
"String",
"accessKey",
",",
"String",
"secretKey",
",",
"String",
"appName",
")",
"{",
"try",
"{",
"Region",
"region",
"=",
"Regio... | connect to kinesis stream to discover the shards on the stream
@param regionName The region name where the stream resides
@param streamName The kinesis stream name
@param accessKey The user access key
@param secretKey The user secret key
@param appName The name of stream application
@return a list of shards | [
"connect",
"to",
"kinesis",
"stream",
"to",
"discover",
"the",
"shards",
"on",
"the",
"stream"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/importclient/kinesis/KinesisStreamImporterConfig.java#L185-L207 |
jhalterman/failsafe | src/main/java/net/jodah/failsafe/RetryPolicy.java | RetryPolicy.canApplyDelayFn | public boolean canApplyDelayFn(R result, Throwable failure) {
return (delayResult == null || delayResult.equals(result)) && (delayFailure == null || (failure != null
&& delayFailure.isAssignableFrom(failure.getClass())));
} | java | public boolean canApplyDelayFn(R result, Throwable failure) {
return (delayResult == null || delayResult.equals(result)) && (delayFailure == null || (failure != null
&& delayFailure.isAssignableFrom(failure.getClass())));
} | [
"public",
"boolean",
"canApplyDelayFn",
"(",
"R",
"result",
",",
"Throwable",
"failure",
")",
"{",
"return",
"(",
"delayResult",
"==",
"null",
"||",
"delayResult",
".",
"equals",
"(",
"result",
")",
")",
"&&",
"(",
"delayFailure",
"==",
"null",
"||",
"(",
... | Returns whether any configured delay function can be applied for an execution result.
@see #withDelay(DelayFunction)
@see #withDelayOn(DelayFunction, Class)
@see #withDelayWhen(DelayFunction, Object) | [
"Returns",
"whether",
"any",
"configured",
"delay",
"function",
"can",
"be",
"applied",
"for",
"an",
"execution",
"result",
"."
] | train | https://github.com/jhalterman/failsafe/blob/65fcd3a82f7b232d2ff59bc525a59d693dd8e223/src/main/java/net/jodah/failsafe/RetryPolicy.java#L296-L299 |
stephanenicolas/toothpick | toothpick-runtime/src/main/java/toothpick/Toothpick.java | Toothpick.openScopes | public static Scope openScopes(Object... names) {
if (names == null) {
throw new IllegalArgumentException("null scope names are not allowed.");
}
if (names.length == 0) {
throw new IllegalArgumentException("Minimally, one scope name is required.");
}
ScopeNode lastScope = null;
ScopeNode previousScope = (ScopeNode) openScope(names[0], true);
for (int i = 1; i < names.length; i++) {
lastScope = (ScopeNode) openScope(names[i], false);
lastScope = previousScope.addChild(lastScope);
previousScope = lastScope;
}
return previousScope;
} | java | public static Scope openScopes(Object... names) {
if (names == null) {
throw new IllegalArgumentException("null scope names are not allowed.");
}
if (names.length == 0) {
throw new IllegalArgumentException("Minimally, one scope name is required.");
}
ScopeNode lastScope = null;
ScopeNode previousScope = (ScopeNode) openScope(names[0], true);
for (int i = 1; i < names.length; i++) {
lastScope = (ScopeNode) openScope(names[i], false);
lastScope = previousScope.addChild(lastScope);
previousScope = lastScope;
}
return previousScope;
} | [
"public",
"static",
"Scope",
"openScopes",
"(",
"Object",
"...",
"names",
")",
"{",
"if",
"(",
"names",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"null scope names are not allowed.\"",
")",
";",
"}",
"if",
"(",
"names",
".",
... | Opens multiple scopes in a row.
Opened scopes will be children of each other in left to right order (e.g. {@code
openScopes(a,b)} opens scopes {@code a} and {@code b}
and {@code b} is a child of {@code a}.
@param names of the scopes to open hierarchically.
@return the last opened scope, leaf node of the created subtree of scopes. | [
"Opens",
"multiple",
"scopes",
"in",
"a",
"row",
".",
"Opened",
"scopes",
"will",
"be",
"children",
"of",
"each",
"other",
"in",
"left",
"to",
"right",
"order",
"(",
"e",
".",
"g",
".",
"{",
"@code",
"openScopes",
"(",
"a",
"b",
")",
"}",
"opens",
... | train | https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/Toothpick.java#L54-L73 |
tvesalainen/bcc | src/main/java/org/vesalainen/bcc/MethodCompiler.java | MethodCompiler.putStaticField | public void putStaticField(Class<?> cls, String name) throws IOException
{
putStaticField(El.getField(cls, name));
} | java | public void putStaticField(Class<?> cls, String name) throws IOException
{
putStaticField(El.getField(cls, name));
} | [
"public",
"void",
"putStaticField",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"putStaticField",
"(",
"El",
".",
"getField",
"(",
"cls",
",",
"name",
")",
")",
";",
"}"
] | Set field in class
<p>Stack: ..., value => ...
@param cls
@param name
@throws IOException | [
"Set",
"field",
"in",
"class",
"<p",
">",
"Stack",
":",
"...",
"value",
"=",
">",
";",
"..."
] | train | https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/MethodCompiler.java#L1020-L1023 |
gocd/gocd | base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java | DirectoryScanner.isSymlink | private boolean isSymlink(File base, String path) {
return isSymlink(base, SelectorUtils.tokenizePath(path));
} | java | private boolean isSymlink(File base, String path) {
return isSymlink(base, SelectorUtils.tokenizePath(path));
} | [
"private",
"boolean",
"isSymlink",
"(",
"File",
"base",
",",
"String",
"path",
")",
"{",
"return",
"isSymlink",
"(",
"base",
",",
"SelectorUtils",
".",
"tokenizePath",
"(",
"path",
")",
")",
";",
"}"
] | Do we have to traverse a symlink when trying to reach path from
basedir?
@param base base File (dir).
@param path file path.
@since Ant 1.6 | [
"Do",
"we",
"have",
"to",
"traverse",
"a",
"symlink",
"when",
"trying",
"to",
"reach",
"path",
"from",
"basedir?"
] | train | https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/base/src/main/java/com/thoughtworks/go/util/DirectoryScanner.java#L1584-L1586 |
operasoftware/operaprestodriver | src/com/opera/core/systems/internal/WatirUtils.java | WatirUtils.textMatchesWithANY | public static boolean textMatchesWithANY(String haystack, String needle) {
haystack = haystack.trim();
needle = needle.trim();
// Make sure we escape every character that is considered to be a special character inside a
// regular expression. Matcher.quoteReplacement() takes care of '\\' and '$'.
needle = Matcher.quoteReplacement(needle);
String chars_to_be_escaped = ".|*?+(){}[]^";
for (char c : chars_to_be_escaped.toCharArray()) {
String regex = "\\" + c;
String replacement = "\\\\" + c;
needle = needle.replaceAll(regex, replacement);
}
String pattern = needle.replaceAll(ANY_MATCHER, "(?:.+)");
logger.finest("Looking for pattern '" + pattern + "' in '" + haystack + "'");
return haystack.matches(pattern);
} | java | public static boolean textMatchesWithANY(String haystack, String needle) {
haystack = haystack.trim();
needle = needle.trim();
// Make sure we escape every character that is considered to be a special character inside a
// regular expression. Matcher.quoteReplacement() takes care of '\\' and '$'.
needle = Matcher.quoteReplacement(needle);
String chars_to_be_escaped = ".|*?+(){}[]^";
for (char c : chars_to_be_escaped.toCharArray()) {
String regex = "\\" + c;
String replacement = "\\\\" + c;
needle = needle.replaceAll(regex, replacement);
}
String pattern = needle.replaceAll(ANY_MATCHER, "(?:.+)");
logger.finest("Looking for pattern '" + pattern + "' in '" + haystack + "'");
return haystack.matches(pattern);
} | [
"public",
"static",
"boolean",
"textMatchesWithANY",
"(",
"String",
"haystack",
",",
"String",
"needle",
")",
"{",
"haystack",
"=",
"haystack",
".",
"trim",
"(",
")",
";",
"needle",
"=",
"needle",
".",
"trim",
"(",
")",
";",
"// Make sure we escape every chara... | Compares haystack and needle taking into the account that the needle may contain any number of
ANY_MATCHER occurrences, that will be matched to any substring in haystack, i.e. "Show _ANY_
more..." will match anything like "Show 1 more...", "Show 2 more..." and so on.
@param haystack the text that will be compared, may not contain any ANY_MATCHER occurrence
@param needle the text that will be used for comparision, may contain any number of
ANY_MATCHER occurrences
@return a boolean indicating whether needle matched haystack. | [
"Compares",
"haystack",
"and",
"needle",
"taking",
"into",
"the",
"account",
"that",
"the",
"needle",
"may",
"contain",
"any",
"number",
"of",
"ANY_MATCHER",
"occurrences",
"that",
"will",
"be",
"matched",
"to",
"any",
"substring",
"in",
"haystack",
"i",
".",
... | train | https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/internal/WatirUtils.java#L133-L152 |
morimekta/utils | io-util/src/main/java/net/morimekta/util/FileWatcher.java | FileWatcher.addWatcher | @Deprecated
public void addWatcher(File file, Listener watcher) {
addWatcher(file.toPath(), watcher);
} | java | @Deprecated
public void addWatcher(File file, Listener watcher) {
addWatcher(file.toPath(), watcher);
} | [
"@",
"Deprecated",
"public",
"void",
"addWatcher",
"(",
"File",
"file",
",",
"Listener",
"watcher",
")",
"{",
"addWatcher",
"(",
"file",
".",
"toPath",
"(",
")",
",",
"watcher",
")",
";",
"}"
] | Start watching file path and notify watcher for updates on that file.
@param file The file path to watch.
@param watcher The watcher to be notified.
@deprecated Use {@link #addWatcher(Path, Listener)} | [
"Start",
"watching",
"file",
"path",
"and",
"notify",
"watcher",
"for",
"updates",
"on",
"that",
"file",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/FileWatcher.java#L176-L179 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java | JobOperations.createJob | public void createJob(JobAddParameter job, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
JobAddOptions options = new JobAddOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().jobs().add(job, options);
} | java | public void createJob(JobAddParameter job, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
JobAddOptions options = new JobAddOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().jobs().add(job, options);
} | [
"public",
"void",
"createJob",
"(",
"JobAddParameter",
"job",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"additionalBehaviors",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"JobAddOptions",
"options",
"=",
"new",
"JobAddOptions",
"(",
")",
"... | Adds a job to the Batch account.
@param job The job to be added.
@param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
@throws BatchErrorException Exception thrown when an error response is received from the Batch service.
@throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. | [
"Adds",
"a",
"job",
"to",
"the",
"Batch",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java#L316-L322 |
lucee/Lucee | core/src/main/java/lucee/runtime/op/Caster.java | Caster.toQuery | public static Query toQuery(Object o, Query defaultValue) {
if (o instanceof Query) return (Query) o;
else if (o instanceof ObjectWrap) {
return toQuery(((ObjectWrap) o).getEmbededObject(defaultValue), defaultValue);
}
return defaultValue;
} | java | public static Query toQuery(Object o, Query defaultValue) {
if (o instanceof Query) return (Query) o;
else if (o instanceof ObjectWrap) {
return toQuery(((ObjectWrap) o).getEmbededObject(defaultValue), defaultValue);
}
return defaultValue;
} | [
"public",
"static",
"Query",
"toQuery",
"(",
"Object",
"o",
",",
"Query",
"defaultValue",
")",
"{",
"if",
"(",
"o",
"instanceof",
"Query",
")",
"return",
"(",
"Query",
")",
"o",
";",
"else",
"if",
"(",
"o",
"instanceof",
"ObjectWrap",
")",
"{",
"return... | cast a Object to a Query Object
@param o Object to cast
@param defaultValue
@return casted Query Object | [
"cast",
"a",
"Object",
"to",
"a",
"Query",
"Object"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L3021-L3027 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java | ArrayFunctions.arrayContains | public static Expression arrayContains(String expression, Expression value) {
return arrayContains(x(expression), value);
} | java | public static Expression arrayContains(String expression, Expression value) {
return arrayContains(x(expression), value);
} | [
"public",
"static",
"Expression",
"arrayContains",
"(",
"String",
"expression",
",",
"Expression",
"value",
")",
"{",
"return",
"arrayContains",
"(",
"x",
"(",
"expression",
")",
",",
"value",
")",
";",
"}"
] | Returned expression results in true if the array contains value. | [
"Returned",
"expression",
"results",
"in",
"true",
"if",
"the",
"array",
"contains",
"value",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L118-L120 |
Unicon/cas-addons | src/main/java/net/unicon/cas/addons/support/ResourceChangeDetectingEventNotifier.java | ResourceChangeDetectingEventNotifier.notifyOfTheResourceChangeEventIfNecessary | public void notifyOfTheResourceChangeEventIfNecessary() {
final String currentResourceSha1 = this.resourceSha1Hex;
String newResourceSha1 = null;
try {
newResourceSha1 = new Sha1Hash(this.watchedResource.getFile()).toHex();
if (!newResourceSha1.equals(currentResourceSha1)) {
logger.debug("Resource: [{}] | Old Hash: [{}] | New Hash: [{}]", new Object[] {this.watchedResource.getURI(), currentResourceSha1, newResourceSha1});
synchronized (this.resourceSha1Hex) {
this.resourceSha1Hex = newResourceSha1;
this.applicationEventPublisher.publishEvent(new ResourceChangedEvent(this, this.watchedResource.getURI()));
}
}
}
catch (final Throwable e) {
//TODO: Possibly introduce an exception handling strategy?
logger.error("An exception is caught during 'watchedResource' access", e);
return;
}
} | java | public void notifyOfTheResourceChangeEventIfNecessary() {
final String currentResourceSha1 = this.resourceSha1Hex;
String newResourceSha1 = null;
try {
newResourceSha1 = new Sha1Hash(this.watchedResource.getFile()).toHex();
if (!newResourceSha1.equals(currentResourceSha1)) {
logger.debug("Resource: [{}] | Old Hash: [{}] | New Hash: [{}]", new Object[] {this.watchedResource.getURI(), currentResourceSha1, newResourceSha1});
synchronized (this.resourceSha1Hex) {
this.resourceSha1Hex = newResourceSha1;
this.applicationEventPublisher.publishEvent(new ResourceChangedEvent(this, this.watchedResource.getURI()));
}
}
}
catch (final Throwable e) {
//TODO: Possibly introduce an exception handling strategy?
logger.error("An exception is caught during 'watchedResource' access", e);
return;
}
} | [
"public",
"void",
"notifyOfTheResourceChangeEventIfNecessary",
"(",
")",
"{",
"final",
"String",
"currentResourceSha1",
"=",
"this",
".",
"resourceSha1Hex",
";",
"String",
"newResourceSha1",
"=",
"null",
";",
"try",
"{",
"newResourceSha1",
"=",
"new",
"Sha1Hash",
"(... | Compare the SHA1 digests (since last check and the latest) of the configured resource, and if change is detected,
publish the <code>ResourceChangeEvent</code> to ApplicationContext. | [
"Compare",
"the",
"SHA1",
"digests",
"(",
"since",
"last",
"check",
"and",
"the",
"latest",
")",
"of",
"the",
"configured",
"resource",
"and",
"if",
"change",
"is",
"detected",
"publish",
"the",
"<code",
">",
"ResourceChangeEvent<",
"/",
"code",
">",
"to",
... | train | https://github.com/Unicon/cas-addons/blob/9af2d4896e02d30622acec638539bfc41f45e480/src/main/java/net/unicon/cas/addons/support/ResourceChangeDetectingEventNotifier.java#L83-L101 |
facebookarchive/hadoop-20 | src/tools/org/apache/hadoop/tools/DistCp.java | DistCp.getChunkFilePaths | private static Path[] getChunkFilePaths(Configuration conf,
FileSystem dstfs, Path chunkFileDir, int chunkNum) throws IOException{
FileStatus [] chunkFileStatus = dstfs.listStatus(chunkFileDir);
HashSet <String> chunkFilePathSet = new HashSet<String>(chunkFileStatus.length);
for(FileStatus chunkfs:chunkFileStatus){
chunkFilePathSet.add(chunkfs.getPath().toUri().getPath());
}
List<Path> chunkFilePathList = new ArrayList<Path>();
Path verifiedPath = new Path(chunkFileDir, "verified");
boolean needVerification =
!chunkFilePathSet.contains(verifiedPath.toUri().getPath());
for(int i = 0; i < chunkNum; ++i) {
//make sure we add the chunk file in order,and the chunk file name is
//named in number
Path chunkFile = new Path(chunkFileDir, Integer.toString(i));
//make sure the chunk file is not missing
if(chunkFilePathSet.contains(chunkFile.toUri().getPath())) {
chunkFilePathList.add(chunkFile);
} else {
if (needVerification) {
throw new IOException("Chunk File: " + chunkFile.toUri().getPath() +
"doesn't exist!");
}
}
}
if (needVerification) {
// write the flag to indicate the map outputs have been verified.
FSDataOutputStream out = dstfs.create(verifiedPath);
out.close();
}
return chunkFilePathList.toArray(new Path[] {});
} | java | private static Path[] getChunkFilePaths(Configuration conf,
FileSystem dstfs, Path chunkFileDir, int chunkNum) throws IOException{
FileStatus [] chunkFileStatus = dstfs.listStatus(chunkFileDir);
HashSet <String> chunkFilePathSet = new HashSet<String>(chunkFileStatus.length);
for(FileStatus chunkfs:chunkFileStatus){
chunkFilePathSet.add(chunkfs.getPath().toUri().getPath());
}
List<Path> chunkFilePathList = new ArrayList<Path>();
Path verifiedPath = new Path(chunkFileDir, "verified");
boolean needVerification =
!chunkFilePathSet.contains(verifiedPath.toUri().getPath());
for(int i = 0; i < chunkNum; ++i) {
//make sure we add the chunk file in order,and the chunk file name is
//named in number
Path chunkFile = new Path(chunkFileDir, Integer.toString(i));
//make sure the chunk file is not missing
if(chunkFilePathSet.contains(chunkFile.toUri().getPath())) {
chunkFilePathList.add(chunkFile);
} else {
if (needVerification) {
throw new IOException("Chunk File: " + chunkFile.toUri().getPath() +
"doesn't exist!");
}
}
}
if (needVerification) {
// write the flag to indicate the map outputs have been verified.
FSDataOutputStream out = dstfs.create(verifiedPath);
out.close();
}
return chunkFilePathList.toArray(new Path[] {});
} | [
"private",
"static",
"Path",
"[",
"]",
"getChunkFilePaths",
"(",
"Configuration",
"conf",
",",
"FileSystem",
"dstfs",
",",
"Path",
"chunkFileDir",
",",
"int",
"chunkNum",
")",
"throws",
"IOException",
"{",
"FileStatus",
"[",
"]",
"chunkFileStatus",
"=",
"dstfs",... | go to the directory we created for the chunk files
the chunk files are named as 0, 1, 2, 3....
For example, if a file File1 is chopped into 3 chunks,
the we should have a directory /File1_chunkfiles, and
there are three files in that directory:
/File1_chunkfiles/0, /File1_chunkfiles/1, File1_chunkfiles/2
The returned chunkFilePath arrays contains the paths of
those chunks in sorted order. Also we can make sure there is
no missing chunks by checking the chunk file name .
For example, if we only have /File1_chunkfiles/0, File1_chunkfiles/2
we know that /File1_chunkfiles/1 is missing.
@param chunkFileDir the directory named with filename_chunkfiles
@return the paths to all the chunk files in the chunkFileDir
@throws IOException | [
"go",
"to",
"the",
"directory",
"we",
"created",
"for",
"the",
"chunk",
"files",
"the",
"chunk",
"files",
"are",
"named",
"as",
"0",
"1",
"2",
"3",
"....",
"For",
"example",
"if",
"a",
"file",
"File1",
"is",
"chopped",
"into",
"3",
"chunks",
"the",
"... | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/tools/org/apache/hadoop/tools/DistCp.java#L1692-L1723 |
ops4j/org.ops4j.pax.exam2 | containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/container/internal/DependenciesDeployer.java | DependenciesDeployer.writeDependenciesFeature | static void writeDependenciesFeature(Writer writer, ProvisionOption<?>... provisionOptions) {
XMLOutputFactory xof = XMLOutputFactory.newInstance();
xof.setProperty("javax.xml.stream.isRepairingNamespaces", true);
XMLStreamWriter sw = null;
try {
sw = xof.createXMLStreamWriter(writer);
sw.writeStartDocument("UTF-8", "1.0");
sw.setDefaultNamespace(KARAF_FEATURE_NS);
sw.writeCharacters("\n");
sw.writeStartElement("features");
sw.writeAttribute("name", "test-dependencies");
sw.writeCharacters("\n");
sw.writeStartElement("feature");
sw.writeAttribute("name", "test-dependencies");
sw.writeCharacters("\n");
for (ProvisionOption<?> provisionOption : provisionOptions) {
if (provisionOption.getURL().startsWith("link")
|| provisionOption.getURL().startsWith("scan-features")) {
// well those we've already handled at another location...
continue;
}
sw.writeStartElement("bundle");
if (provisionOption.getStartLevel() != null) {
sw.writeAttribute("start-level", provisionOption.getStartLevel().toString());
}
sw.writeCharacters(provisionOption.getURL());
endElement(sw);
}
endElement(sw);
endElement(sw);
sw.writeEndDocument();
}
catch (XMLStreamException e) {
throw new RuntimeException("Error writing feature " + e.getMessage(), e);
}
finally {
close(sw);
}
} | java | static void writeDependenciesFeature(Writer writer, ProvisionOption<?>... provisionOptions) {
XMLOutputFactory xof = XMLOutputFactory.newInstance();
xof.setProperty("javax.xml.stream.isRepairingNamespaces", true);
XMLStreamWriter sw = null;
try {
sw = xof.createXMLStreamWriter(writer);
sw.writeStartDocument("UTF-8", "1.0");
sw.setDefaultNamespace(KARAF_FEATURE_NS);
sw.writeCharacters("\n");
sw.writeStartElement("features");
sw.writeAttribute("name", "test-dependencies");
sw.writeCharacters("\n");
sw.writeStartElement("feature");
sw.writeAttribute("name", "test-dependencies");
sw.writeCharacters("\n");
for (ProvisionOption<?> provisionOption : provisionOptions) {
if (provisionOption.getURL().startsWith("link")
|| provisionOption.getURL().startsWith("scan-features")) {
// well those we've already handled at another location...
continue;
}
sw.writeStartElement("bundle");
if (provisionOption.getStartLevel() != null) {
sw.writeAttribute("start-level", provisionOption.getStartLevel().toString());
}
sw.writeCharacters(provisionOption.getURL());
endElement(sw);
}
endElement(sw);
endElement(sw);
sw.writeEndDocument();
}
catch (XMLStreamException e) {
throw new RuntimeException("Error writing feature " + e.getMessage(), e);
}
finally {
close(sw);
}
} | [
"static",
"void",
"writeDependenciesFeature",
"(",
"Writer",
"writer",
",",
"ProvisionOption",
"<",
"?",
">",
"...",
"provisionOptions",
")",
"{",
"XMLOutputFactory",
"xof",
"=",
"XMLOutputFactory",
".",
"newInstance",
"(",
")",
";",
"xof",
".",
"setProperty",
"... | Write a feature xml structure for test dependencies specified as ProvisionOption
in system to the given writer
@param writer where to write the feature xml
@param provisionOptions dependencies | [
"Write",
"a",
"feature",
"xml",
"structure",
"for",
"test",
"dependencies",
"specified",
"as",
"ProvisionOption",
"in",
"system",
"to",
"the",
"given",
"writer"
] | train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/container/internal/DependenciesDeployer.java#L142-L180 |
OpenHFT/Chronicle-Network | src/main/java/net/openhft/chronicle/network/connection/TcpChannelHub.java | TcpChannelHub.writeAsyncHeader | public void writeAsyncHeader(@NotNull Wire wire, String csp, long cid) {
assert outBytesLock().isHeldByCurrentThread();
wire.writeDocument(true, wireOut -> {
if (cid == 0)
wireOut.writeEventName(CoreFields.csp).text(csp);
else
wireOut.writeEventName(CoreFields.cid).int64(cid);
});
} | java | public void writeAsyncHeader(@NotNull Wire wire, String csp, long cid) {
assert outBytesLock().isHeldByCurrentThread();
wire.writeDocument(true, wireOut -> {
if (cid == 0)
wireOut.writeEventName(CoreFields.csp).text(csp);
else
wireOut.writeEventName(CoreFields.cid).int64(cid);
});
} | [
"public",
"void",
"writeAsyncHeader",
"(",
"@",
"NotNull",
"Wire",
"wire",
",",
"String",
"csp",
",",
"long",
"cid",
")",
"{",
"assert",
"outBytesLock",
"(",
")",
".",
"isHeldByCurrentThread",
"(",
")",
";",
"wire",
".",
"writeDocument",
"(",
"true",
",",
... | The writes the meta data to wire - the async version does not contain the tid
@param wire the wire that we will write to
@param csp provide either the csp or the cid
@param cid provide either the csp or the cid | [
"The",
"writes",
"the",
"meta",
"data",
"to",
"wire",
"-",
"the",
"async",
"version",
"does",
"not",
"contain",
"the",
"tid"
] | train | https://github.com/OpenHFT/Chronicle-Network/blob/b50d232a1763b1400d5438c7925dce845e5c387a/src/main/java/net/openhft/chronicle/network/connection/TcpChannelHub.java#L866-L875 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/time/JMTimeUtil.java | JMTimeUtil.getTime | public static String getTime(long epochTimestamp, String timeFormat,
ZoneId zoneId) {
return getTime(epochTimestamp, getDateTimeFormatter(timeFormat),
zoneId);
} | java | public static String getTime(long epochTimestamp, String timeFormat,
ZoneId zoneId) {
return getTime(epochTimestamp, getDateTimeFormatter(timeFormat),
zoneId);
} | [
"public",
"static",
"String",
"getTime",
"(",
"long",
"epochTimestamp",
",",
"String",
"timeFormat",
",",
"ZoneId",
"zoneId",
")",
"{",
"return",
"getTime",
"(",
"epochTimestamp",
",",
"getDateTimeFormatter",
"(",
"timeFormat",
")",
",",
"zoneId",
")",
";",
"}... | Gets time.
@param epochTimestamp the epoch timestamp
@param timeFormat the time format
@param zoneId the zone id
@return the time | [
"Gets",
"time",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/time/JMTimeUtil.java#L333-L337 |
nextreports/nextreports-engine | src/ro/nextreports/engine/chart/Chart.java | Chart.getI18nkeys | public List<String> getI18nkeys() {
if (i18nkeys == null) {
return new ArrayList<String>();
}
Collections.sort(i18nkeys, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Collator.getInstance().compare(o1, o2);
}
});
return i18nkeys;
} | java | public List<String> getI18nkeys() {
if (i18nkeys == null) {
return new ArrayList<String>();
}
Collections.sort(i18nkeys, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return Collator.getInstance().compare(o1, o2);
}
});
return i18nkeys;
} | [
"public",
"List",
"<",
"String",
">",
"getI18nkeys",
"(",
")",
"{",
"if",
"(",
"i18nkeys",
"==",
"null",
")",
"{",
"return",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"}",
"Collections",
".",
"sort",
"(",
"i18nkeys",
",",
"new",
"Compara... | Get keys for internationalized strings
@return list of keys for internationalized strings | [
"Get",
"keys",
"for",
"internationalized",
"strings"
] | train | https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/chart/Chart.java#L666-L678 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/TemplatedURLFormatter.java | TemplatedURLFormatter.initServletContext | public static void initServletContext( ServletContext servletContext, TemplatedURLFormatter formatter )
{
assert servletContext != null : "The ServletContext cannot be null.";
if ( servletContext == null )
{
throw new IllegalArgumentException( "The ServletContext cannot be null." );
}
servletContext.setAttribute( TEMPLATED_URL_FORMATTER_ATTR, formatter );
} | java | public static void initServletContext( ServletContext servletContext, TemplatedURLFormatter formatter )
{
assert servletContext != null : "The ServletContext cannot be null.";
if ( servletContext == null )
{
throw new IllegalArgumentException( "The ServletContext cannot be null." );
}
servletContext.setAttribute( TEMPLATED_URL_FORMATTER_ATTR, formatter );
} | [
"public",
"static",
"void",
"initServletContext",
"(",
"ServletContext",
"servletContext",
",",
"TemplatedURLFormatter",
"formatter",
")",
"{",
"assert",
"servletContext",
"!=",
"null",
":",
"\"The ServletContext cannot be null.\"",
";",
"if",
"(",
"servletContext",
"==",... | Adds a given TemplatedURLFormatter instance as an attribute on the ServletContext.
@param servletContext the current ServletContext.
@param formatter the TemplatedURLFormatter instance to add as an attribute of the context | [
"Adds",
"a",
"given",
"TemplatedURLFormatter",
"instance",
"as",
"an",
"attribute",
"on",
"the",
"ServletContext",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/core/urls/TemplatedURLFormatter.java#L95-L105 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java | SegmentsUtil.hashByWords | public static int hashByWords(MemorySegment[] segments, int offset, int numBytes) {
if (inFirstSegment(segments, offset, numBytes)) {
return MurmurHashUtil.hashBytesByWords(segments[0], offset, numBytes);
} else {
return hashMultiSegByWords(segments, offset, numBytes);
}
} | java | public static int hashByWords(MemorySegment[] segments, int offset, int numBytes) {
if (inFirstSegment(segments, offset, numBytes)) {
return MurmurHashUtil.hashBytesByWords(segments[0], offset, numBytes);
} else {
return hashMultiSegByWords(segments, offset, numBytes);
}
} | [
"public",
"static",
"int",
"hashByWords",
"(",
"MemorySegment",
"[",
"]",
"segments",
",",
"int",
"offset",
",",
"int",
"numBytes",
")",
"{",
"if",
"(",
"inFirstSegment",
"(",
"segments",
",",
"offset",
",",
"numBytes",
")",
")",
"{",
"return",
"MurmurHash... | hash segments to int, numBytes must be aligned to 4 bytes.
@param segments Source segments.
@param offset Source segments offset.
@param numBytes the number bytes to hash. | [
"hash",
"segments",
"to",
"int",
"numBytes",
"must",
"be",
"aligned",
"to",
"4",
"bytes",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/util/SegmentsUtil.java#L370-L376 |
apereo/person-directory | person-directory-impl/src/main/java/org/apereo/services/persondir/support/AbstractQueryPersonAttributeDao.java | AbstractQueryPersonAttributeDao.setResultAttributeMapping | public void setResultAttributeMapping(final Map<String, ?> resultAttributeMapping) {
final Map<String, Set<String>> parsedResultAttributeMapping = MultivaluedPersonAttributeUtils.parseAttributeToAttributeMapping(resultAttributeMapping);
if (parsedResultAttributeMapping.containsKey("")) {
throw new IllegalArgumentException("The map from attribute names to attributes must not have any empty keys.");
}
final Collection<String> userAttributes = MultivaluedPersonAttributeUtils.flattenCollection(parsedResultAttributeMapping.values());
this.resultAttributeMapping = parsedResultAttributeMapping;
this.possibleUserAttributes = new LinkedHashSet<>(userAttributes);
} | java | public void setResultAttributeMapping(final Map<String, ?> resultAttributeMapping) {
final Map<String, Set<String>> parsedResultAttributeMapping = MultivaluedPersonAttributeUtils.parseAttributeToAttributeMapping(resultAttributeMapping);
if (parsedResultAttributeMapping.containsKey("")) {
throw new IllegalArgumentException("The map from attribute names to attributes must not have any empty keys.");
}
final Collection<String> userAttributes = MultivaluedPersonAttributeUtils.flattenCollection(parsedResultAttributeMapping.values());
this.resultAttributeMapping = parsedResultAttributeMapping;
this.possibleUserAttributes = new LinkedHashSet<>(userAttributes);
} | [
"public",
"void",
"setResultAttributeMapping",
"(",
"final",
"Map",
"<",
"String",
",",
"?",
">",
"resultAttributeMapping",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"parsedResultAttributeMapping",
"=",
"MultivaluedPersonAttribu... | Set the {@link Map} to use for mapping from a data layer name to an attribute name or {@link Set} of attribute
names. Data layer names that are specified but have null mappings will use the column name for the attribute
name. Data layer names that are not specified as keys in this {@link Map} will be ignored.
<br>
The passed {@link Map} must have keys of type {@link String} and values of type {@link String} or a {@link Set}
of {@link String}.
@param resultAttributeMapping {@link Map} from column names to attribute names, may not be null.
@throws IllegalArgumentException If the {@link Map} doesn't follow the rules stated above.
@see MultivaluedPersonAttributeUtils#parseAttributeToAttributeMapping(Map) | [
"Set",
"the",
"{",
"@link",
"Map",
"}",
"to",
"use",
"for",
"mapping",
"from",
"a",
"data",
"layer",
"name",
"to",
"an",
"attribute",
"name",
"or",
"{",
"@link",
"Set",
"}",
"of",
"attribute",
"names",
".",
"Data",
"layer",
"names",
"that",
"are",
"s... | train | https://github.com/apereo/person-directory/blob/331200c0878aec202b8aff12a732402d6ba7681f/person-directory-impl/src/main/java/org/apereo/services/persondir/support/AbstractQueryPersonAttributeDao.java#L181-L192 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/WikipediaTemplateInfo.java | WikipediaTemplateInfo.getRevisionIdsNotContainingTemplateFragments | public List<Integer> getRevisionIdsNotContainingTemplateFragments(List<String> templateFragments) throws WikiApiException{
return getFragmentFilteredRevisionIds(templateFragments,false);
} | java | public List<Integer> getRevisionIdsNotContainingTemplateFragments(List<String> templateFragments) throws WikiApiException{
return getFragmentFilteredRevisionIds(templateFragments,false);
} | [
"public",
"List",
"<",
"Integer",
">",
"getRevisionIdsNotContainingTemplateFragments",
"(",
"List",
"<",
"String",
">",
"templateFragments",
")",
"throws",
"WikiApiException",
"{",
"return",
"getFragmentFilteredRevisionIds",
"(",
"templateFragments",
",",
"false",
")",
... | Returns a list containing the ids of all revisions that contain a
template the name of which starts with any of the given Strings.
@param templateFragments
the beginning of the templates that have to be matched
@return An list with the ids of the revisions that do not contain templates
beginning with any String in templateFragments
@throws WikiApiException
If there was any error retrieving the page object (most
likely if the template templates are corrupted) | [
"Returns",
"a",
"list",
"containing",
"the",
"ids",
"of",
"all",
"revisions",
"that",
"contain",
"a",
"template",
"the",
"name",
"of",
"which",
"starts",
"with",
"any",
"of",
"the",
"given",
"Strings",
"."
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/WikipediaTemplateInfo.java#L828-L830 |
zaproxy/zaproxy | src/ch/csnc/extension/httpclient/SSLContextManager.java | SSLContextManager.initPKCS11 | public int initPKCS11(PKCS11Configuration configuration, String kspassword)
throws IOException, KeyStoreException,
CertificateException, NoSuchAlgorithmException,
ClassNotFoundException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
if (!isProviderAvailable(PKCS11_PROVIDER_TYPE)) {
return -1;
}
Provider pkcs11 = createPKCS11Provider(configuration);
Security.addProvider(pkcs11);
// init the key store
KeyStore ks = getPKCS11KeyStore(pkcs11.getName());
ks.load(null, kspassword == null ? null : kspassword.toCharArray());
return addKeyStore(ks, "PKCS#11: " + configuration.getName(), ""); // do not store pin code
} | java | public int initPKCS11(PKCS11Configuration configuration, String kspassword)
throws IOException, KeyStoreException,
CertificateException, NoSuchAlgorithmException,
ClassNotFoundException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
if (!isProviderAvailable(PKCS11_PROVIDER_TYPE)) {
return -1;
}
Provider pkcs11 = createPKCS11Provider(configuration);
Security.addProvider(pkcs11);
// init the key store
KeyStore ks = getPKCS11KeyStore(pkcs11.getName());
ks.load(null, kspassword == null ? null : kspassword.toCharArray());
return addKeyStore(ks, "PKCS#11: " + configuration.getName(), ""); // do not store pin code
} | [
"public",
"int",
"initPKCS11",
"(",
"PKCS11Configuration",
"configuration",
",",
"String",
"kspassword",
")",
"throws",
"IOException",
",",
"KeyStoreException",
",",
"CertificateException",
",",
"NoSuchAlgorithmException",
",",
"ClassNotFoundException",
",",
"SecurityExcept... | /*
public int initCryptoApi() throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException{
Provider mscapi = new sun.security.mscapi.SunMSCAPI();
Security.addProvider(mscapi);
KeyStore ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null);
return addKeyStore(ks, "CryptoAPI", null); } | [
"/",
"*",
"public",
"int",
"initCryptoApi",
"()",
"throws",
"KeyStoreException",
"NoSuchAlgorithmException",
"CertificateException",
"IOException",
"{"
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/ch/csnc/extension/httpclient/SSLContextManager.java#L355-L374 |
spring-projects/spring-ldap | core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java | AbstractContextSource.setupAuthenticatedEnvironment | protected void setupAuthenticatedEnvironment(Hashtable<String, Object> env, String principal, String credentials) {
try {
authenticationStrategy.setupEnvironment(env, principal, credentials);
}
catch (NamingException e) {
throw LdapUtils.convertLdapException(e);
}
} | java | protected void setupAuthenticatedEnvironment(Hashtable<String, Object> env, String principal, String credentials) {
try {
authenticationStrategy.setupEnvironment(env, principal, credentials);
}
catch (NamingException e) {
throw LdapUtils.convertLdapException(e);
}
} | [
"protected",
"void",
"setupAuthenticatedEnvironment",
"(",
"Hashtable",
"<",
"String",
",",
"Object",
">",
"env",
",",
"String",
"principal",
",",
"String",
"credentials",
")",
"{",
"try",
"{",
"authenticationStrategy",
".",
"setupEnvironment",
"(",
"env",
",",
... | Default implementation of setting the environment up to be authenticated.
This method should typically NOT be overridden; any customization to the
authentication mechanism should be managed by setting a different
{@link DirContextAuthenticationStrategy} on this instance.
@param env the environment to modify.
@param principal the principal to authenticate with.
@param credentials the credentials to authenticate with.
@see DirContextAuthenticationStrategy
@see #setAuthenticationStrategy(DirContextAuthenticationStrategy) | [
"Default",
"implementation",
"of",
"setting",
"the",
"environment",
"up",
"to",
"be",
"authenticated",
".",
"This",
"method",
"should",
"typically",
"NOT",
"be",
"overridden",
";",
"any",
"customization",
"to",
"the",
"authentication",
"mechanism",
"should",
"be",... | train | https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java#L192-L199 |
marvinlabs/android-floatinglabel-widgets | library/src/main/java/com/marvinlabs/widget/floatinglabel/itempicker/AbstractPickerDialogFragment.java | AbstractPickerDialogFragment.buildCommonArgsBundle | protected static Bundle buildCommonArgsBundle(int pickerId, String title, String positiveButtonText, String negativeButtonText, boolean enableMultipleSelection, int[] selectedItemIndices) {
Bundle args = new Bundle();
args.putInt(ARG_PICKER_ID, pickerId);
args.putString(ARG_TITLE, title);
args.putString(ARG_POSITIVE_BUTTON_TEXT, positiveButtonText);
args.putString(ARG_NEGATIVE_BUTTON_TEXT, negativeButtonText);
args.putBoolean(ARG_ENABLE_MULTIPLE_SELECTION, enableMultipleSelection);
args.putIntArray(ARG_SELECTED_ITEMS_INDICES, selectedItemIndices);
return args;
} | java | protected static Bundle buildCommonArgsBundle(int pickerId, String title, String positiveButtonText, String negativeButtonText, boolean enableMultipleSelection, int[] selectedItemIndices) {
Bundle args = new Bundle();
args.putInt(ARG_PICKER_ID, pickerId);
args.putString(ARG_TITLE, title);
args.putString(ARG_POSITIVE_BUTTON_TEXT, positiveButtonText);
args.putString(ARG_NEGATIVE_BUTTON_TEXT, negativeButtonText);
args.putBoolean(ARG_ENABLE_MULTIPLE_SELECTION, enableMultipleSelection);
args.putIntArray(ARG_SELECTED_ITEMS_INDICES, selectedItemIndices);
return args;
} | [
"protected",
"static",
"Bundle",
"buildCommonArgsBundle",
"(",
"int",
"pickerId",
",",
"String",
"title",
",",
"String",
"positiveButtonText",
",",
"String",
"negativeButtonText",
",",
"boolean",
"enableMultipleSelection",
",",
"int",
"[",
"]",
"selectedItemIndices",
... | Utility method for implementations to create the base argument bundle
@param pickerId The id of the item picker
@param title The title for the dialog
@param positiveButtonText The text of the positive button
@param negativeButtonText The text of the negative button
@param enableMultipleSelection Whether or not to allow selecting multiple items
@param selectedItemIndices The positions of the items already selected
@return The arguments bundle | [
"Utility",
"method",
"for",
"implementations",
"to",
"create",
"the",
"base",
"argument",
"bundle"
] | train | https://github.com/marvinlabs/android-floatinglabel-widgets/blob/bb89889f1e75ed9b228b77d3ba895ceeeb41fe4f/library/src/main/java/com/marvinlabs/widget/floatinglabel/itempicker/AbstractPickerDialogFragment.java#L56-L65 |
yanzhenjie/AndServer | sample/src/main/java/com/yanzhenjie/andserver/sample/util/JsonUtils.java | JsonUtils.parseJson | public static <T> T parseJson(String json, Type type) {
return JSON.parseObject(json, type);
} | java | public static <T> T parseJson(String json, Type type) {
return JSON.parseObject(json, type);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"parseJson",
"(",
"String",
"json",
",",
"Type",
"type",
")",
"{",
"return",
"JSON",
".",
"parseObject",
"(",
"json",
",",
"type",
")",
";",
"}"
] | Parse json to object.
@param json json string.
@param type the type of object.
@param <T> type.
@return object. | [
"Parse",
"json",
"to",
"object",
"."
] | train | https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/sample/src/main/java/com/yanzhenjie/andserver/sample/util/JsonUtils.java#L79-L81 |
UrielCh/ovh-java-sdk | ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java | ApiOvhSms.serviceName_senders_sender_GET | public OvhSender serviceName_senders_sender_GET(String serviceName, String sender) throws IOException {
String qPath = "/sms/{serviceName}/senders/{sender}";
StringBuilder sb = path(qPath, serviceName, sender);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhSender.class);
} | java | public OvhSender serviceName_senders_sender_GET(String serviceName, String sender) throws IOException {
String qPath = "/sms/{serviceName}/senders/{sender}";
StringBuilder sb = path(qPath, serviceName, sender);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhSender.class);
} | [
"public",
"OvhSender",
"serviceName_senders_sender_GET",
"(",
"String",
"serviceName",
",",
"String",
"sender",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/sms/{serviceName}/senders/{sender}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
... | Get this object properties
REST: GET /sms/{serviceName}/senders/{sender}
@param serviceName [required] The internal name of your SMS offer
@param sender [required] The sms sender | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L182-L187 |
cdk/cdk | base/standard/src/main/java/org/openscience/cdk/geometry/BondTools.java | BondTools.closeEnoughToBond | public static boolean closeEnoughToBond(IAtom atom1, IAtom atom2, double distanceFudgeFactor) {
if (!atom1.equals(atom2)) {
double distanceBetweenAtoms = atom1.getPoint3d().distance(atom2.getPoint3d());
double bondingDistance = atom1.getCovalentRadius() + atom2.getCovalentRadius();
if (distanceBetweenAtoms <= (distanceFudgeFactor * bondingDistance)) {
return true;
}
}
return false;
} | java | public static boolean closeEnoughToBond(IAtom atom1, IAtom atom2, double distanceFudgeFactor) {
if (!atom1.equals(atom2)) {
double distanceBetweenAtoms = atom1.getPoint3d().distance(atom2.getPoint3d());
double bondingDistance = atom1.getCovalentRadius() + atom2.getCovalentRadius();
if (distanceBetweenAtoms <= (distanceFudgeFactor * bondingDistance)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"closeEnoughToBond",
"(",
"IAtom",
"atom1",
",",
"IAtom",
"atom2",
",",
"double",
"distanceFudgeFactor",
")",
"{",
"if",
"(",
"!",
"atom1",
".",
"equals",
"(",
"atom2",
")",
")",
"{",
"double",
"distanceBetweenAtoms",
"=",
"ato... | Returns true if the two atoms are within the distance fudge
factor of each other.
@param atom1 Description of Parameter
@param atom2 Description of Parameter
@param distanceFudgeFactor Description of Parameter
@return Description of the Returned Value
@cdk.keyword join-the-dots
@cdk.keyword bond creation | [
"Returns",
"true",
"if",
"the",
"two",
"atoms",
"are",
"within",
"the",
"distance",
"fudge",
"factor",
"of",
"each",
"other",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/geometry/BondTools.java#L133-L143 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasClassAdapter.java | AbstractRasClassAdapter.visitInnerClass | @Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
// Make sure the class is annotated.
ensureAnnotated();
if (name.equals(getClassInternalName())) {
StringBuilder sb = new StringBuilder();
sb.append(outerName);
sb.append("$");
sb.append(innerName);
isInnerClass = name.equals(sb.toString());
}
super.visitInnerClass(name, outerName, innerName, access);
} | java | @Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
// Make sure the class is annotated.
ensureAnnotated();
if (name.equals(getClassInternalName())) {
StringBuilder sb = new StringBuilder();
sb.append(outerName);
sb.append("$");
sb.append(innerName);
isInnerClass = name.equals(sb.toString());
}
super.visitInnerClass(name, outerName, innerName, access);
} | [
"@",
"Override",
"public",
"void",
"visitInnerClass",
"(",
"String",
"name",
",",
"String",
"outerName",
",",
"String",
"innerName",
",",
"int",
"access",
")",
"{",
"// Make sure the class is annotated.",
"ensureAnnotated",
"(",
")",
";",
"if",
"(",
"name",
".",... | Visit the information about an inner class. We use this to determine
whether or not the we're visiting an inner class. This callback is
also used to ensure that appropriate class level annotations exist. | [
"Visit",
"the",
"information",
"about",
"an",
"inner",
"class",
".",
"We",
"use",
"this",
"to",
"determine",
"whether",
"or",
"not",
"the",
"we",
"re",
"visiting",
"an",
"inner",
"class",
".",
"This",
"callback",
"is",
"also",
"used",
"to",
"ensure",
"th... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ras.instrument/src/com/ibm/ws/ras/instrument/internal/bci/AbstractRasClassAdapter.java#L176-L190 |
kaazing/gateway | util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java | Asn1Utils.encodeInteger | public static int encodeInteger(int value, ByteBuffer buf) {
int pos = buf.position();
int contentLength = 0;
do {
pos--;
buf.put(pos, (byte) (value & 0xff));
value >>>= 8;
contentLength++;
} while (value != 0);
buf.position(buf.position() - contentLength);
int headerLen = DerUtils.encodeIdAndLength(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_INTEGER_TAG_NUM,
contentLength, buf);
return headerLen + contentLength;
} | java | public static int encodeInteger(int value, ByteBuffer buf) {
int pos = buf.position();
int contentLength = 0;
do {
pos--;
buf.put(pos, (byte) (value & 0xff));
value >>>= 8;
contentLength++;
} while (value != 0);
buf.position(buf.position() - contentLength);
int headerLen = DerUtils.encodeIdAndLength(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_INTEGER_TAG_NUM,
contentLength, buf);
return headerLen + contentLength;
} | [
"public",
"static",
"int",
"encodeInteger",
"(",
"int",
"value",
",",
"ByteBuffer",
"buf",
")",
"{",
"int",
"pos",
"=",
"buf",
".",
"position",
"(",
")",
";",
"int",
"contentLength",
"=",
"0",
";",
"do",
"{",
"pos",
"--",
";",
"buf",
".",
"put",
"(... | Encode an ASN.1 INTEGER.
@param value
the value to be encoded
@param buf
the buffer with space to the left of current position where the value will be encoded
@return the length of the encoded data | [
"Encode",
"an",
"ASN",
".",
"1",
"INTEGER",
"."
] | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/util/src/main/java/org/kaazing/gateway/util/asn1/Asn1Utils.java#L330-L343 |
alkacon/opencms-core | src/org/opencms/ade/containerpage/CmsDetailOnlyContainerPageBuilder.java | CmsDetailOnlyContainerPageBuilder.buildContainerElementBean | private CmsContainerElementBean buildContainerElementBean(ContainerInfo cnt, CmsResource resource) {
I_CmsFormatterBean formatter = m_config.getFormatters(m_cms, resource).getDefaultFormatter(
cnt.getEffectiveType(),
cnt.getEffectiveWidth());
CmsUUID formatterId = formatter.getJspStructureId();
CmsContainerElementBean elementBean = new CmsContainerElementBean(
resource.getStructureId(),
formatterId,
new HashMap<String, String>(),
false);
return elementBean;
} | java | private CmsContainerElementBean buildContainerElementBean(ContainerInfo cnt, CmsResource resource) {
I_CmsFormatterBean formatter = m_config.getFormatters(m_cms, resource).getDefaultFormatter(
cnt.getEffectiveType(),
cnt.getEffectiveWidth());
CmsUUID formatterId = formatter.getJspStructureId();
CmsContainerElementBean elementBean = new CmsContainerElementBean(
resource.getStructureId(),
formatterId,
new HashMap<String, String>(),
false);
return elementBean;
} | [
"private",
"CmsContainerElementBean",
"buildContainerElementBean",
"(",
"ContainerInfo",
"cnt",
",",
"CmsResource",
"resource",
")",
"{",
"I_CmsFormatterBean",
"formatter",
"=",
"m_config",
".",
"getFormatters",
"(",
"m_cms",
",",
"resource",
")",
".",
"getDefaultFormat... | Builds the container element bean for a resource.<p>
@param cnt the container for the element resource
@param resource the resource
@return the container element bean | [
"Builds",
"the",
"container",
"element",
"bean",
"for",
"a",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/containerpage/CmsDetailOnlyContainerPageBuilder.java#L282-L294 |
gocd/gocd | server/src/main/java/com/thoughtworks/go/server/service/RestfulService.java | RestfulService.findJob | public JobIdentifier findJob(String pipelineName, String pipelineCounter, String stageName, String stageCounter, String buildName, Long buildId) {
JobConfigIdentifier jobConfigIdentifier = goConfigService.translateToActualCase(new JobConfigIdentifier(pipelineName, stageName, buildName));
PipelineIdentifier pipelineIdentifier;
if (JobIdentifier.LATEST.equalsIgnoreCase(pipelineCounter)) {
pipelineIdentifier = pipelineService.mostRecentPipelineIdentifier(jobConfigIdentifier.getPipelineName());
} else if (StringUtils.isNumeric(pipelineCounter)) {
pipelineIdentifier = pipelineService.findPipelineByNameAndCounter(pipelineName, Integer.parseInt(pipelineCounter)).getIdentifier();
} else {
throw new RuntimeException("Expected numeric pipeline counter but received '%s'" + pipelineCounter);
}
stageCounter = StringUtils.isEmpty(stageCounter) ? JobIdentifier.LATEST : stageCounter;
StageIdentifier stageIdentifier = translateStageCounter(pipelineIdentifier, jobConfigIdentifier.getStageName(), stageCounter);
JobIdentifier jobId;
if (buildId == null) {
jobId = jobResolverService.actualJobIdentifier(new JobIdentifier(stageIdentifier, jobConfigIdentifier.getJobName()));
} else {
jobId = new JobIdentifier(stageIdentifier, jobConfigIdentifier.getJobName(), buildId);
}
if (jobId == null) {
//fix for #5739
throw new RecordNotFoundException(String.format("Job '%s' not found in pipeline '%s' stage '%s'", buildName, pipelineName, stageName));
}
return jobId;
} | java | public JobIdentifier findJob(String pipelineName, String pipelineCounter, String stageName, String stageCounter, String buildName, Long buildId) {
JobConfigIdentifier jobConfigIdentifier = goConfigService.translateToActualCase(new JobConfigIdentifier(pipelineName, stageName, buildName));
PipelineIdentifier pipelineIdentifier;
if (JobIdentifier.LATEST.equalsIgnoreCase(pipelineCounter)) {
pipelineIdentifier = pipelineService.mostRecentPipelineIdentifier(jobConfigIdentifier.getPipelineName());
} else if (StringUtils.isNumeric(pipelineCounter)) {
pipelineIdentifier = pipelineService.findPipelineByNameAndCounter(pipelineName, Integer.parseInt(pipelineCounter)).getIdentifier();
} else {
throw new RuntimeException("Expected numeric pipeline counter but received '%s'" + pipelineCounter);
}
stageCounter = StringUtils.isEmpty(stageCounter) ? JobIdentifier.LATEST : stageCounter;
StageIdentifier stageIdentifier = translateStageCounter(pipelineIdentifier, jobConfigIdentifier.getStageName(), stageCounter);
JobIdentifier jobId;
if (buildId == null) {
jobId = jobResolverService.actualJobIdentifier(new JobIdentifier(stageIdentifier, jobConfigIdentifier.getJobName()));
} else {
jobId = new JobIdentifier(stageIdentifier, jobConfigIdentifier.getJobName(), buildId);
}
if (jobId == null) {
//fix for #5739
throw new RecordNotFoundException(String.format("Job '%s' not found in pipeline '%s' stage '%s'", buildName, pipelineName, stageName));
}
return jobId;
} | [
"public",
"JobIdentifier",
"findJob",
"(",
"String",
"pipelineName",
",",
"String",
"pipelineCounter",
",",
"String",
"stageName",
",",
"String",
"stageCounter",
",",
"String",
"buildName",
",",
"Long",
"buildId",
")",
"{",
"JobConfigIdentifier",
"jobConfigIdentifier"... | buildId should only be given when caller is absolutely sure about the job instance
(makes sense in agent-uploading artifacts/properties scenario because agent won't run a job if its copied over(it only executes real jobs)) -JJ
<p>
This does not return pipelineLabel | [
"buildId",
"should",
"only",
"be",
"given",
"when",
"caller",
"is",
"absolutely",
"sure",
"about",
"the",
"job",
"instance",
"(",
"makes",
"sense",
"in",
"agent",
"-",
"uploading",
"artifacts",
"/",
"properties",
"scenario",
"because",
"agent",
"won",
"t",
"... | train | https://github.com/gocd/gocd/blob/59a8480e23d6c06de39127635108dff57603cb71/server/src/main/java/com/thoughtworks/go/server/service/RestfulService.java#L46-L73 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/db/Context.java | Context.isTMNoTransaction | public static boolean isTMNoTransaction()
throws EFapsException
{
try {
return Context.TRANSMANAG.getStatus() == Status.STATUS_NO_TRANSACTION;
} catch (final SystemException e) {
throw new EFapsException(Context.class, "isTMNoTransaction.SystemException", e);
}
} | java | public static boolean isTMNoTransaction()
throws EFapsException
{
try {
return Context.TRANSMANAG.getStatus() == Status.STATUS_NO_TRANSACTION;
} catch (final SystemException e) {
throw new EFapsException(Context.class, "isTMNoTransaction.SystemException", e);
}
} | [
"public",
"static",
"boolean",
"isTMNoTransaction",
"(",
")",
"throws",
"EFapsException",
"{",
"try",
"{",
"return",
"Context",
".",
"TRANSMANAG",
".",
"getStatus",
"(",
")",
"==",
"Status",
".",
"STATUS_NO_TRANSACTION",
";",
"}",
"catch",
"(",
"final",
"Syste... | Is a transaction associated with a target object for transaction manager?
@return <i>true</i> if a transaction associated, otherwise <i>false</i>
@throws EFapsException if the status of the transaction manager could not
be evaluated
@see #TRANSMANAG | [
"Is",
"a",
"transaction",
"associated",
"with",
"a",
"target",
"object",
"for",
"transaction",
"manager?"
] | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/Context.java#L1147-L1155 |
looly/hutool | hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java | KeyUtil.generateKeyPair | public static KeyPair generateKeyPair(String algorithm, int keySize, byte[] seed) {
// SM2算法需要单独定义其曲线生成
if ("SM2".equalsIgnoreCase(algorithm)) {
final ECGenParameterSpec sm2p256v1 = new ECGenParameterSpec(SM2_DEFAULT_CURVE);
return generateKeyPair(algorithm, keySize, seed, sm2p256v1);
}
return generateKeyPair(algorithm, keySize, seed, (AlgorithmParameterSpec[]) null);
} | java | public static KeyPair generateKeyPair(String algorithm, int keySize, byte[] seed) {
// SM2算法需要单独定义其曲线生成
if ("SM2".equalsIgnoreCase(algorithm)) {
final ECGenParameterSpec sm2p256v1 = new ECGenParameterSpec(SM2_DEFAULT_CURVE);
return generateKeyPair(algorithm, keySize, seed, sm2p256v1);
}
return generateKeyPair(algorithm, keySize, seed, (AlgorithmParameterSpec[]) null);
} | [
"public",
"static",
"KeyPair",
"generateKeyPair",
"(",
"String",
"algorithm",
",",
"int",
"keySize",
",",
"byte",
"[",
"]",
"seed",
")",
"{",
"// SM2算法需要单独定义其曲线生成\r",
"if",
"(",
"\"SM2\"",
".",
"equalsIgnoreCase",
"(",
"algorithm",
")",
")",
"{",
"final",
"E... | 生成用于非对称加密的公钥和私钥<br>
密钥对生成算法见:https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyPairGenerator
@param algorithm 非对称加密算法
@param keySize 密钥模(modulus )长度
@param seed 种子
@return {@link KeyPair} | [
"生成用于非对称加密的公钥和私钥<br",
">",
"密钥对生成算法见:https",
":",
"//",
"docs",
".",
"oracle",
".",
"com",
"/",
"javase",
"/",
"7",
"/",
"docs",
"/",
"technotes",
"/",
"guides",
"/",
"security",
"/",
"StandardNames",
".",
"html#KeyPairGenerator"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java#L345-L353 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java | DefaultEntityManager.putDefaultCallback | private void putDefaultCallback(CallbackType callbackType, CallbackMetadata metadata) {
List<CallbackMetadata> metadataList = globalCallbacks.get(callbackType);
if (metadataList == null) {
metadataList = new ArrayList<>();
globalCallbacks.put(callbackType, metadataList);
}
metadataList.add(metadata);
} | java | private void putDefaultCallback(CallbackType callbackType, CallbackMetadata metadata) {
List<CallbackMetadata> metadataList = globalCallbacks.get(callbackType);
if (metadataList == null) {
metadataList = new ArrayList<>();
globalCallbacks.put(callbackType, metadataList);
}
metadataList.add(metadata);
} | [
"private",
"void",
"putDefaultCallback",
"(",
"CallbackType",
"callbackType",
",",
"CallbackMetadata",
"metadata",
")",
"{",
"List",
"<",
"CallbackMetadata",
">",
"metadataList",
"=",
"globalCallbacks",
".",
"get",
"(",
"callbackType",
")",
";",
"if",
"(",
"metada... | Puts/adds the given callback type and its metadata to the list of default listeners.
@param callbackType
the event type
@param metadata
the callback metadata | [
"Puts",
"/",
"adds",
"the",
"given",
"callback",
"type",
"and",
"its",
"metadata",
"to",
"the",
"list",
"of",
"default",
"listeners",
"."
] | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L423-L430 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.deleteCertificateAsync | public ServiceFuture<DeletedCertificateBundle> deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback<DeletedCertificateBundle> serviceCallback) {
return ServiceFuture.fromResponse(deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback);
} | java | public ServiceFuture<DeletedCertificateBundle> deleteCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback<DeletedCertificateBundle> serviceCallback) {
return ServiceFuture.fromResponse(deleteCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"DeletedCertificateBundle",
">",
"deleteCertificateAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"certificateName",
",",
"final",
"ServiceCallback",
"<",
"DeletedCertificateBundle",
">",
"serviceCallback",
")",
"{",
"return",
"Servi... | Deletes a certificate from a specified key vault.
Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used to remove individual versions of a certificate object. This operation requires the certificates/delete permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param certificateName The name of the certificate.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Deletes",
"a",
"certificate",
"from",
"a",
"specified",
"key",
"vault",
".",
"Deletes",
"all",
"versions",
"of",
"a",
"certificate",
"object",
"along",
"with",
"its",
"associated",
"policy",
".",
"Delete",
"certificate",
"cannot",
"be",
"used",
"to",
"remove"... | 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#L5339-L5341 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java | FactoryKernel.random2D_I32 | public static Kernel2D_S32 random2D_I32(int width , int offset, int min, int max, Random rand) {
Kernel2D_S32 ret = new Kernel2D_S32(width,offset);
int range = max - min;
for (int i = 0; i < ret.data.length; i++) {
ret.data[i] = rand.nextInt(range) + min;
}
return ret;
} | java | public static Kernel2D_S32 random2D_I32(int width , int offset, int min, int max, Random rand) {
Kernel2D_S32 ret = new Kernel2D_S32(width,offset);
int range = max - min;
for (int i = 0; i < ret.data.length; i++) {
ret.data[i] = rand.nextInt(range) + min;
}
return ret;
} | [
"public",
"static",
"Kernel2D_S32",
"random2D_I32",
"(",
"int",
"width",
",",
"int",
"offset",
",",
"int",
"min",
",",
"int",
"max",
",",
"Random",
"rand",
")",
"{",
"Kernel2D_S32",
"ret",
"=",
"new",
"Kernel2D_S32",
"(",
"width",
",",
"offset",
")",
";"... | Creates a random 2D kernel drawn from a uniform distribution.
@param width Kernel's width.
@param offset Offset for element zero in the kernel
@param min minimum value.
@param max maximum value.
@param rand Random number generator.
@return Randomized kernel. | [
"Creates",
"a",
"random",
"2D",
"kernel",
"drawn",
"from",
"a",
"uniform",
"distribution",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java#L277-L286 |
apiman/apiman | gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/api/auth/AuthFactory.java | AuthFactory.getAuth | public static AuthHandler getAuth(Vertx vertx, Router router, VertxEngineConfig apimanConfig) {
String type = apimanConfig.getAuth().getString("type", "NONE");
JsonObject authConfig = apimanConfig.getAuth().getJsonObject("config", new JsonObject());
switch(AuthType.getType(type)) {
case BASIC:
return BasicAuth.create(authConfig);
case NONE:
return NoneAuth.create();
case KEYCLOAK:
return KeycloakOAuthFactory.create(vertx, router, apimanConfig, authConfig);
default:
return NoneAuth.create();
}
} | java | public static AuthHandler getAuth(Vertx vertx, Router router, VertxEngineConfig apimanConfig) {
String type = apimanConfig.getAuth().getString("type", "NONE");
JsonObject authConfig = apimanConfig.getAuth().getJsonObject("config", new JsonObject());
switch(AuthType.getType(type)) {
case BASIC:
return BasicAuth.create(authConfig);
case NONE:
return NoneAuth.create();
case KEYCLOAK:
return KeycloakOAuthFactory.create(vertx, router, apimanConfig, authConfig);
default:
return NoneAuth.create();
}
} | [
"public",
"static",
"AuthHandler",
"getAuth",
"(",
"Vertx",
"vertx",
",",
"Router",
"router",
",",
"VertxEngineConfig",
"apimanConfig",
")",
"{",
"String",
"type",
"=",
"apimanConfig",
".",
"getAuth",
"(",
")",
".",
"getString",
"(",
"\"type\"",
",",
"\"NONE\"... | Creates an auth handler of the type indicated in the `auth` section of config.
@param vertx the vert.x instance
@param router the vert.x web router to protect
@param apimanConfig the apiman config
@return an auth handler | [
"Creates",
"an",
"auth",
"handler",
"of",
"the",
"type",
"indicated",
"in",
"the",
"auth",
"section",
"of",
"config",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/api/auth/AuthFactory.java#L54-L68 |
Bearded-Hen/Android-Bootstrap | AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapCircleThumbnail.java | BootstrapCircleThumbnail.updateImageState | protected void updateImageState() {
float viewWidth = getWidth();
float viewHeight = getHeight();
if ((int) viewWidth <= 0 || (int) viewHeight <= 0) {
return;
}
if (sourceBitmap != null) {
BitmapShader imageShader = new BitmapShader(sourceBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
imagePaint.setShader(imageShader);
// Scale the bitmap using a matrix, ensuring that it always matches the view bounds.
float bitmapWidth = sourceBitmap.getWidth();
float bitmapHeight = sourceBitmap.getHeight();
float scaleFactor = (bitmapWidth < bitmapHeight) ? bitmapWidth : bitmapHeight;
float xScale = viewWidth / scaleFactor;
float yScale = viewHeight / scaleFactor;
// Translate image to center crop (if it is not a perfect square bitmap)
float dx = 0;
float dy = 0;
if (bitmapWidth > bitmapHeight) {
dx = (viewWidth - bitmapWidth * xScale) * 0.5f;
}
else if (bitmapHeight > bitmapWidth) {
dy = (viewHeight - bitmapHeight * yScale) * 0.5f;
}
matrix.set(null);
matrix.setScale(xScale, yScale);
matrix.postTranslate((dx + 0.5f), (dy + 0.5f));
imageShader.setLocalMatrix(matrix);
imageRectF.set(0, 0, viewWidth, viewHeight);
}
updateBackground();
invalidate();
} | java | protected void updateImageState() {
float viewWidth = getWidth();
float viewHeight = getHeight();
if ((int) viewWidth <= 0 || (int) viewHeight <= 0) {
return;
}
if (sourceBitmap != null) {
BitmapShader imageShader = new BitmapShader(sourceBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
imagePaint.setShader(imageShader);
// Scale the bitmap using a matrix, ensuring that it always matches the view bounds.
float bitmapWidth = sourceBitmap.getWidth();
float bitmapHeight = sourceBitmap.getHeight();
float scaleFactor = (bitmapWidth < bitmapHeight) ? bitmapWidth : bitmapHeight;
float xScale = viewWidth / scaleFactor;
float yScale = viewHeight / scaleFactor;
// Translate image to center crop (if it is not a perfect square bitmap)
float dx = 0;
float dy = 0;
if (bitmapWidth > bitmapHeight) {
dx = (viewWidth - bitmapWidth * xScale) * 0.5f;
}
else if (bitmapHeight > bitmapWidth) {
dy = (viewHeight - bitmapHeight * yScale) * 0.5f;
}
matrix.set(null);
matrix.setScale(xScale, yScale);
matrix.postTranslate((dx + 0.5f), (dy + 0.5f));
imageShader.setLocalMatrix(matrix);
imageRectF.set(0, 0, viewWidth, viewHeight);
}
updateBackground();
invalidate();
} | [
"protected",
"void",
"updateImageState",
"(",
")",
"{",
"float",
"viewWidth",
"=",
"getWidth",
"(",
")",
";",
"float",
"viewHeight",
"=",
"getHeight",
"(",
")",
";",
"if",
"(",
"(",
"int",
")",
"viewWidth",
"<=",
"0",
"||",
"(",
"int",
")",
"viewHeight... | This method is called when the Circle Image needs to be recreated due to changes in size etc.
A Paint object uses a BitmapShader to draw a center-cropped, circular image onto the View
Canvas. A Matrix on the BitmapShader scales the original Bitmap to match the current view
bounds, avoiding any inefficiencies in duplicating Bitmaps.
<a href="http://www.curious-creature.com/2012/12/11/android-recipe-1-image-with-rounded-corners">
Further reading</a> | [
"This",
"method",
"is",
"called",
"when",
"the",
"Circle",
"Image",
"needs",
"to",
"be",
"recreated",
"due",
"to",
"changes",
"in",
"size",
"etc",
".",
"A",
"Paint",
"object",
"uses",
"a",
"BitmapShader",
"to",
"draw",
"a",
"center",
"-",
"cropped",
"cir... | train | https://github.com/Bearded-Hen/Android-Bootstrap/blob/b3d62cc1847e26d420c53c92665a4fe1e6ee7ecf/AndroidBootstrap/src/main/java/com/beardedhen/androidbootstrap/BootstrapCircleThumbnail.java#L81-L121 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java | ApiOvhEmailpro.service_account_email_sendOnBehalfTo_allowedAccountId_GET | public OvhAccountSendOnBehalfTo service_account_email_sendOnBehalfTo_allowedAccountId_GET(String service, String email, Long allowedAccountId) throws IOException {
String qPath = "/email/pro/{service}/account/{email}/sendOnBehalfTo/{allowedAccountId}";
StringBuilder sb = path(qPath, service, email, allowedAccountId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAccountSendOnBehalfTo.class);
} | java | public OvhAccountSendOnBehalfTo service_account_email_sendOnBehalfTo_allowedAccountId_GET(String service, String email, Long allowedAccountId) throws IOException {
String qPath = "/email/pro/{service}/account/{email}/sendOnBehalfTo/{allowedAccountId}";
StringBuilder sb = path(qPath, service, email, allowedAccountId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAccountSendOnBehalfTo.class);
} | [
"public",
"OvhAccountSendOnBehalfTo",
"service_account_email_sendOnBehalfTo_allowedAccountId_GET",
"(",
"String",
"service",
",",
"String",
"email",
",",
"Long",
"allowedAccountId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/pro/{service}/account/{emai... | Get this object properties
REST: GET /email/pro/{service}/account/{email}/sendOnBehalfTo/{allowedAccountId}
@param service [required] The internal name of your pro organization
@param email [required] Default email for this mailbox
@param allowedAccountId [required] Account id to give send on behalf to
API beta | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java#L575-L580 |
VoltDB/voltdb | src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java | JDBC4CallableStatement.getBigDecimal | @Override
@Deprecated
public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException
{
checkClosed();
throw SQLError.noSupport();
} | java | @Override
@Deprecated
public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException
{
checkClosed();
throw SQLError.noSupport();
} | [
"@",
"Override",
"@",
"Deprecated",
"public",
"BigDecimal",
"getBigDecimal",
"(",
"int",
"parameterIndex",
",",
"int",
"scale",
")",
"throws",
"SQLException",
"{",
"checkClosed",
"(",
")",
";",
"throw",
"SQLError",
".",
"noSupport",
"(",
")",
";",
"}"
] | Deprecated. use getBigDecimal(int parameterIndex) or getBigDecimal(String parameterName) | [
"Deprecated",
".",
"use",
"getBigDecimal",
"(",
"int",
"parameterIndex",
")",
"or",
"getBigDecimal",
"(",
"String",
"parameterName",
")"
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L70-L76 |
Jasig/uPortal | uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/GroupService.java | GroupService.getGroupMember | public static IGroupMember getGroupMember(String key, Class<?> type) throws GroupsException {
/*
* WARNING: The 'type' parameter is not the leafType; you're obligated
* to say whether you want a group or a non-group (i.e. some type of
* entity). In fact, the underlying implementation blindly instantiates
* whatever you tell it to.
*/
LOGGER.trace("Invoking getEntity for key='{}', type='{}'", key, type);
return instance().igetGroupMember(key, type);
} | java | public static IGroupMember getGroupMember(String key, Class<?> type) throws GroupsException {
/*
* WARNING: The 'type' parameter is not the leafType; you're obligated
* to say whether you want a group or a non-group (i.e. some type of
* entity). In fact, the underlying implementation blindly instantiates
* whatever you tell it to.
*/
LOGGER.trace("Invoking getEntity for key='{}', type='{}'", key, type);
return instance().igetGroupMember(key, type);
} | [
"public",
"static",
"IGroupMember",
"getGroupMember",
"(",
"String",
"key",
",",
"Class",
"<",
"?",
">",
"type",
")",
"throws",
"GroupsException",
"{",
"/*\n * WARNING: The 'type' parameter is not the leafType; you're obligated\n * to say whether you want a group ... | Returns an <code> IGroupMember </code> representing either a group or a portal entity. If the
parm <code> type </code> is the group type, the <code> IGroupMember </code> is an <code>
IEntityGroup </code> else it is an <code> IEntity </code> . | [
"Returns",
"an",
"<code",
">",
"IGroupMember",
"<",
"/",
"code",
">",
"representing",
"either",
"a",
"group",
"or",
"a",
"portal",
"entity",
".",
"If",
"the",
"parm",
"<code",
">",
"type",
"<",
"/",
"code",
">",
"is",
"the",
"group",
"type",
"the",
"... | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/GroupService.java#L171-L181 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/predicate/PropertyReference.java | PropertyReference.propertyRef | public static P<Object> propertyRef(Compare p,String columnName){
return new RefP(p, new PropertyReference(columnName));
} | java | public static P<Object> propertyRef(Compare p,String columnName){
return new RefP(p, new PropertyReference(columnName));
} | [
"public",
"static",
"P",
"<",
"Object",
">",
"propertyRef",
"(",
"Compare",
"p",
",",
"String",
"columnName",
")",
"{",
"return",
"new",
"RefP",
"(",
"p",
",",
"new",
"PropertyReference",
"(",
"columnName",
")",
")",
";",
"}"
] | build a predicate from a compare operation and a column name
@param p
@param columnName
@return | [
"build",
"a",
"predicate",
"from",
"a",
"compare",
"operation",
"and",
"a",
"column",
"name"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/predicate/PropertyReference.java#L39-L41 |
linkedin/dexmaker | dexmaker/src/main/java/com/android/dx/Code.java | Code.aget | public void aget(Local<?> target, Local<?> array, Local<Integer> index) {
addInstruction(new ThrowingInsn(Rops.opAget(target.type.ropType), sourcePosition,
RegisterSpecList.make(array.spec(), index.spec()), catches));
moveResult(target, true);
} | java | public void aget(Local<?> target, Local<?> array, Local<Integer> index) {
addInstruction(new ThrowingInsn(Rops.opAget(target.type.ropType), sourcePosition,
RegisterSpecList.make(array.spec(), index.spec()), catches));
moveResult(target, true);
} | [
"public",
"void",
"aget",
"(",
"Local",
"<",
"?",
">",
"target",
",",
"Local",
"<",
"?",
">",
"array",
",",
"Local",
"<",
"Integer",
">",
"index",
")",
"{",
"addInstruction",
"(",
"new",
"ThrowingInsn",
"(",
"Rops",
".",
"opAget",
"(",
"target",
".",... | Assigns the element at {@code index} in {@code array} to {@code target}. | [
"Assigns",
"the",
"element",
"at",
"{"
] | train | https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L803-L807 |
aws/aws-sdk-java | aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/AccountSettings.java | AccountSettings.withMaxSlots | public AccountSettings withMaxSlots(java.util.Map<String, Integer> maxSlots) {
setMaxSlots(maxSlots);
return this;
} | java | public AccountSettings withMaxSlots(java.util.Map<String, Integer> maxSlots) {
setMaxSlots(maxSlots);
return this;
} | [
"public",
"AccountSettings",
"withMaxSlots",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"Integer",
">",
"maxSlots",
")",
"{",
"setMaxSlots",
"(",
"maxSlots",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
<code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs returned by
the <code>ListOfferings</code> command.
</p>
@param maxSlots
The maximum number of device slots that the AWS account can purchase. Each maximum is expressed as an
<code>offering-id:number</code> pair, where the <code>offering-id</code> represents one of the IDs
returned by the <code>ListOfferings</code> command.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"maximum",
"number",
"of",
"device",
"slots",
"that",
"the",
"AWS",
"account",
"can",
"purchase",
".",
"Each",
"maximum",
"is",
"expressed",
"as",
"an",
"<code",
">",
"offering",
"-",
"id",
":",
"number<",
"/",
"code",
">",
"pair",
"w... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/AccountSettings.java#L377-L380 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.readFolder | public CmsFolder readFolder(String resourcename, CmsResourceFilter filter) throws CmsException {
return m_securityManager.readFolder(m_context, addSiteRoot(resourcename), filter);
} | java | public CmsFolder readFolder(String resourcename, CmsResourceFilter filter) throws CmsException {
return m_securityManager.readFolder(m_context, addSiteRoot(resourcename), filter);
} | [
"public",
"CmsFolder",
"readFolder",
"(",
"String",
"resourcename",
",",
"CmsResourceFilter",
"filter",
")",
"throws",
"CmsException",
"{",
"return",
"m_securityManager",
".",
"readFolder",
"(",
"m_context",
",",
"addSiteRoot",
"(",
"resourcename",
")",
",",
"filter... | Reads a folder resource from the VFS,
using the specified resource filter.<p>
The specified filter controls what kind of resources should be "found"
during the read operation. This will depend on the application. For example,
using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently
"valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code>
will ignore the date release / date expired information of the resource.<p>
@param resourcename the name of the folder resource to read (full current site relative path)
@param filter the resource filter to use while reading
@return the folder resource that was read
@throws CmsException if the resource could not be read for any reason
@see #readResource(String, CmsResourceFilter) | [
"Reads",
"a",
"folder",
"resource",
"from",
"the",
"VFS",
"using",
"the",
"specified",
"resource",
"filter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L2603-L2606 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BooleanExtensions.java | BooleanExtensions.operator_greaterEqualsThan | @Pure
@Inline(value = "($3.compare($1, $2) >= 0)", imported = Booleans.class)
public static boolean operator_greaterEqualsThan(boolean a, boolean b) {
return Booleans.compare(a, b) >= 0;
} | java | @Pure
@Inline(value = "($3.compare($1, $2) >= 0)", imported = Booleans.class)
public static boolean operator_greaterEqualsThan(boolean a, boolean b) {
return Booleans.compare(a, b) >= 0;
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"($3.compare($1, $2) >= 0)\"",
",",
"imported",
"=",
"Booleans",
".",
"class",
")",
"public",
"static",
"boolean",
"operator_greaterEqualsThan",
"(",
"boolean",
"a",
",",
"boolean",
"b",
")",
"{",
"return",
"Boo... | The binary <code>greaterEqualsThan</code> operator for boolean values.
{@code false} is considered less than {@code true}.
@see Boolean#compareTo(Boolean)
@see Booleans#compare(boolean, boolean)
@param a a boolean.
@param b another boolean.
@return <code>Booleans.compare(a, b)>=0</code>
@since 2.4 | [
"The",
"binary",
"<code",
">",
"greaterEqualsThan<",
"/",
"code",
">",
"operator",
"for",
"boolean",
"values",
".",
"{",
"@code",
"false",
"}",
"is",
"considered",
"less",
"than",
"{",
"@code",
"true",
"}",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/BooleanExtensions.java#L171-L175 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkManagerImpl.java | WorkManagerImpl.doWork | @Override
public void doWork(
Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener) throws WorkException {
try {
beforeRunCheck(work, workListener, startTimeout);
new WorkProxy(work, startTimeout, execContext, workListener, bootstrapContext, runningWork, false).call();
} catch (WorkException ex) {
throw ex;
} catch (Throwable t) {
WorkRejectedException wrex = new WorkRejectedException(t);
wrex.setErrorCode(WorkException.INTERNAL);
if (workListener != null)
workListener.workRejected(new WorkEvent(work, WorkEvent.WORK_REJECTED, work, wrex));
throw wrex;
}
} | java | @Override
public void doWork(
Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener) throws WorkException {
try {
beforeRunCheck(work, workListener, startTimeout);
new WorkProxy(work, startTimeout, execContext, workListener, bootstrapContext, runningWork, false).call();
} catch (WorkException ex) {
throw ex;
} catch (Throwable t) {
WorkRejectedException wrex = new WorkRejectedException(t);
wrex.setErrorCode(WorkException.INTERNAL);
if (workListener != null)
workListener.workRejected(new WorkEvent(work, WorkEvent.WORK_REJECTED, work, wrex));
throw wrex;
}
} | [
"@",
"Override",
"public",
"void",
"doWork",
"(",
"Work",
"work",
",",
"long",
"startTimeout",
",",
"ExecutionContext",
"execContext",
",",
"WorkListener",
"workListener",
")",
"throws",
"WorkException",
"{",
"try",
"{",
"beforeRunCheck",
"(",
"work",
",",
"work... | This method does not return until the work is completed as the caller
expects to wait until the work is completed before getting control back.
This method accomplishes this by NOT spinning a thread.
@pre providerId != null
@param work
@param startTimeout
@param execContext
@param workListener
@throws WorkException
@see <a
href="http://java.sun.com/j2ee/1.4/docs/api/javax/resource/spi/work/WorkManager.html#doWork(com.ibm.javarx.spi.work.Work, long, com.ibm.javarx.spi.work.ExecutionContext, com.ibm.javarx.spi.work.WorkListener)">
com.ibm.javarx.spi.work.WorkManager.doWork(Work, long, ExecutionContext, WorkListener)</a> | [
"This",
"method",
"does",
"not",
"return",
"until",
"the",
"work",
"is",
"completed",
"as",
"the",
"caller",
"expects",
"to",
"wait",
"until",
"the",
"work",
"is",
"completed",
"before",
"getting",
"control",
"back",
".",
"This",
"method",
"accomplishes",
"t... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca/src/com/ibm/ws/jca/internal/WorkManagerImpl.java#L102-L122 |
Alluxio/alluxio | core/server/common/src/main/java/alluxio/StorageTierAssoc.java | StorageTierAssoc.interpretOrdinal | static int interpretOrdinal(int ordinal, int numTiers) {
if (ordinal >= 0) {
return Math.min(ordinal, numTiers - 1);
}
return Math.max(numTiers + ordinal, 0);
} | java | static int interpretOrdinal(int ordinal, int numTiers) {
if (ordinal >= 0) {
return Math.min(ordinal, numTiers - 1);
}
return Math.max(numTiers + ordinal, 0);
} | [
"static",
"int",
"interpretOrdinal",
"(",
"int",
"ordinal",
",",
"int",
"numTiers",
")",
"{",
"if",
"(",
"ordinal",
">=",
"0",
")",
"{",
"return",
"Math",
".",
"min",
"(",
"ordinal",
",",
"numTiers",
"-",
"1",
")",
";",
"}",
"return",
"Math",
".",
... | Interprets a tier ordinal given the number of tiers.
Non-negative values identify tiers starting from top going down (0 identifies the first tier,
1 identifies the second tier, and so on). If the provided value is greater than the number
of tiers, it identifies the last tier. Negative values identify tiers starting from the bottom
going up (-1 identifies the last tier, -2 identifies the second to last tier, and so on). If
the absolute value of the provided value is greater than the number of tiers, it identifies
the first tier.
@param ordinal the storage tier ordinal to interpret
@param numTiers the number of storage tiers
@return a valid tier ordinal | [
"Interprets",
"a",
"tier",
"ordinal",
"given",
"the",
"number",
"of",
"tiers",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/StorageTierAssoc.java#L50-L55 |
jhy/jsoup | src/main/java/org/jsoup/safety/Whitelist.java | Whitelist.addProtocols | public Whitelist addProtocols(String tag, String attribute, String... protocols) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
Validate.notNull(protocols);
TagName tagName = TagName.valueOf(tag);
AttributeKey attrKey = AttributeKey.valueOf(attribute);
Map<AttributeKey, Set<Protocol>> attrMap;
Set<Protocol> protSet;
if (this.protocols.containsKey(tagName)) {
attrMap = this.protocols.get(tagName);
} else {
attrMap = new HashMap<>();
this.protocols.put(tagName, attrMap);
}
if (attrMap.containsKey(attrKey)) {
protSet = attrMap.get(attrKey);
} else {
protSet = new HashSet<>();
attrMap.put(attrKey, protSet);
}
for (String protocol : protocols) {
Validate.notEmpty(protocol);
Protocol prot = Protocol.valueOf(protocol);
protSet.add(prot);
}
return this;
} | java | public Whitelist addProtocols(String tag, String attribute, String... protocols) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
Validate.notNull(protocols);
TagName tagName = TagName.valueOf(tag);
AttributeKey attrKey = AttributeKey.valueOf(attribute);
Map<AttributeKey, Set<Protocol>> attrMap;
Set<Protocol> protSet;
if (this.protocols.containsKey(tagName)) {
attrMap = this.protocols.get(tagName);
} else {
attrMap = new HashMap<>();
this.protocols.put(tagName, attrMap);
}
if (attrMap.containsKey(attrKey)) {
protSet = attrMap.get(attrKey);
} else {
protSet = new HashSet<>();
attrMap.put(attrKey, protSet);
}
for (String protocol : protocols) {
Validate.notEmpty(protocol);
Protocol prot = Protocol.valueOf(protocol);
protSet.add(prot);
}
return this;
} | [
"public",
"Whitelist",
"addProtocols",
"(",
"String",
"tag",
",",
"String",
"attribute",
",",
"String",
"...",
"protocols",
")",
"{",
"Validate",
".",
"notEmpty",
"(",
"tag",
")",
";",
"Validate",
".",
"notEmpty",
"(",
"attribute",
")",
";",
"Validate",
".... | Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to
URLs with the defined protocol.
<p>
E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code>
</p>
<p>
To allow a link to an in-page URL anchor (i.e. <code><a href="#anchor"></code>, add a <code>#</code>:<br>
E.g.: <code>addProtocols("a", "href", "#")</code>
</p>
@param tag Tag the URL protocol is for
@param attribute Attribute name
@param protocols List of valid protocols
@return this, for chaining | [
"Add",
"allowed",
"URL",
"protocols",
"for",
"an",
"element",
"s",
"URL",
"attribute",
".",
"This",
"restricts",
"the",
"possible",
"values",
"of",
"the",
"attribute",
"to",
"URLs",
"with",
"the",
"defined",
"protocol",
".",
"<p",
">",
"E",
".",
"g",
"."... | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/safety/Whitelist.java#L410-L438 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPBatchClientConnectionInterceptor.java | HTTPBatchClientConnectionInterceptor.prepareHttpRequest | private <T extends CloseableHttpClient> HttpRequestBase prepareHttpRequest(RequestElements intuitRequest) throws FMSException
{
//setTimeout(client, intuitRequest.getContext());
HttpRequestBase httpRequest = extractMethod(intuitRequest, extractURI(intuitRequest));
// populate the headers to HttpRequestBase
populateRequestHeaders(httpRequest, intuitRequest.getRequestHeaders());
// authorize the request
authorizeRequest(intuitRequest.getContext(), httpRequest);
LOG.debug("Request URI : " + httpRequest.getURI());
LOG.debug("Http Method : " + httpRequest.getMethod());
return httpRequest;
} | java | private <T extends CloseableHttpClient> HttpRequestBase prepareHttpRequest(RequestElements intuitRequest) throws FMSException
{
//setTimeout(client, intuitRequest.getContext());
HttpRequestBase httpRequest = extractMethod(intuitRequest, extractURI(intuitRequest));
// populate the headers to HttpRequestBase
populateRequestHeaders(httpRequest, intuitRequest.getRequestHeaders());
// authorize the request
authorizeRequest(intuitRequest.getContext(), httpRequest);
LOG.debug("Request URI : " + httpRequest.getURI());
LOG.debug("Http Method : " + httpRequest.getMethod());
return httpRequest;
} | [
"private",
"<",
"T",
"extends",
"CloseableHttpClient",
">",
"HttpRequestBase",
"prepareHttpRequest",
"(",
"RequestElements",
"intuitRequest",
")",
"throws",
"FMSException",
"{",
"//setTimeout(client, intuitRequest.getContext());",
"HttpRequestBase",
"httpRequest",
"=",
"extract... | Returns httpRequest instance with configured fields
@param intuitRequest
@param client
@param <T>
@return
@throws FMSException | [
"Returns",
"httpRequest",
"instance",
"with",
"configured",
"fields"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/HTTPBatchClientConnectionInterceptor.java#L230-L245 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/exporter/ExplodedExporterDelegate.java | ExplodedExporterDelegate.processArchiveAsset | private void processArchiveAsset(File parentDirectory, ArchiveAsset nestedArchiveAsset) {
// Get the nested archive
Archive<?> nestedArchive = nestedArchiveAsset.getArchive();
nestedArchive.as(ExplodedExporter.class).exportExploded(parentDirectory);
} | java | private void processArchiveAsset(File parentDirectory, ArchiveAsset nestedArchiveAsset) {
// Get the nested archive
Archive<?> nestedArchive = nestedArchiveAsset.getArchive();
nestedArchive.as(ExplodedExporter.class).exportExploded(parentDirectory);
} | [
"private",
"void",
"processArchiveAsset",
"(",
"File",
"parentDirectory",
",",
"ArchiveAsset",
"nestedArchiveAsset",
")",
"{",
"// Get the nested archive",
"Archive",
"<",
"?",
">",
"nestedArchive",
"=",
"nestedArchiveAsset",
".",
"getArchive",
"(",
")",
";",
"nestedA... | Processes a nested archive by delegating to the ExplodedArchiveExporter
@param parentDirectory
@param nestedArchiveAsset | [
"Processes",
"a",
"nested",
"archive",
"by",
"delegating",
"to",
"the",
"ExplodedArchiveExporter"
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/exporter/ExplodedExporterDelegate.java#L165-L169 |
moparisthebest/beehive | beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventNotifier.java | EventNotifier.removeListener | synchronized public void removeListener(Object listener)
{
if (!_listeners.contains(listener))
throw new IllegalStateException("Invalid listener, not currently registered");
_listeners.remove(listener);
} | java | synchronized public void removeListener(Object listener)
{
if (!_listeners.contains(listener))
throw new IllegalStateException("Invalid listener, not currently registered");
_listeners.remove(listener);
} | [
"synchronized",
"public",
"void",
"removeListener",
"(",
"Object",
"listener",
")",
"{",
"if",
"(",
"!",
"_listeners",
".",
"contains",
"(",
"listener",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Invalid listener, not currently registered\"",
")",
";... | Remove an existing callback event listener for this EventNotifier | [
"Remove",
"an",
"existing",
"callback",
"event",
"listener",
"for",
"this",
"EventNotifier"
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/EventNotifier.java#L41-L47 |
gosu-lang/gosu-lang | gosu-ant-tools/src/main/java/gosu/tools/ant/Gosuc.java | Gosuc.asFiles | private List<File> asFiles(File srcDir, String[] files, FileNameMapper m) {
List<File> newFiles = new ArrayList<>();
for(String file : files) {
boolean hasMatchingExtension = m.mapFileName(file) != null; //use mapFileName as a check to validate if the source file extension is recognized by the mapper or not
if(hasMatchingExtension) {
newFiles.add(new File(srcDir, file));
}
}
return newFiles;
} | java | private List<File> asFiles(File srcDir, String[] files, FileNameMapper m) {
List<File> newFiles = new ArrayList<>();
for(String file : files) {
boolean hasMatchingExtension = m.mapFileName(file) != null; //use mapFileName as a check to validate if the source file extension is recognized by the mapper or not
if(hasMatchingExtension) {
newFiles.add(new File(srcDir, file));
}
}
return newFiles;
} | [
"private",
"List",
"<",
"File",
">",
"asFiles",
"(",
"File",
"srcDir",
",",
"String",
"[",
"]",
"files",
",",
"FileNameMapper",
"m",
")",
"{",
"List",
"<",
"File",
">",
"newFiles",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"String",
... | Converts an array of relative String filenames to a {@code List<File>}
@param srcDir The root directory of all files
@param files All files are relative to srcDir
@return a List of Files by joining srcDir to each file | [
"Converts",
"an",
"array",
"of",
"relative",
"String",
"filenames",
"to",
"a",
"{"
] | train | https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-ant-tools/src/main/java/gosu/tools/ant/Gosuc.java#L242-L251 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/seo/CmsSeoOptionsDialog.java | CmsSeoOptionsDialog.loadAliases | public static void loadAliases(final CmsUUID structureId, final AsyncCallback<List<CmsAliasBean>> callback) {
final CmsRpcAction<List<CmsAliasBean>> action = new CmsRpcAction<List<CmsAliasBean>>() {
@Override
public void execute() {
start(200, true);
CmsCoreProvider.getVfsService().getAliasesForPage(structureId, this);
}
@Override
protected void onResponse(List<CmsAliasBean> result) {
stop(false);
callback.onSuccess(result);
}
};
action.execute();
} | java | public static void loadAliases(final CmsUUID structureId, final AsyncCallback<List<CmsAliasBean>> callback) {
final CmsRpcAction<List<CmsAliasBean>> action = new CmsRpcAction<List<CmsAliasBean>>() {
@Override
public void execute() {
start(200, true);
CmsCoreProvider.getVfsService().getAliasesForPage(structureId, this);
}
@Override
protected void onResponse(List<CmsAliasBean> result) {
stop(false);
callback.onSuccess(result);
}
};
action.execute();
} | [
"public",
"static",
"void",
"loadAliases",
"(",
"final",
"CmsUUID",
"structureId",
",",
"final",
"AsyncCallback",
"<",
"List",
"<",
"CmsAliasBean",
">",
">",
"callback",
")",
"{",
"final",
"CmsRpcAction",
"<",
"List",
"<",
"CmsAliasBean",
">",
">",
"action",
... | Loads the aliases for a given page.<p>
@param structureId the structure id of the page
@param callback the callback for the loaded aliases | [
"Loads",
"the",
"aliases",
"for",
"a",
"given",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/seo/CmsSeoOptionsDialog.java#L186-L205 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/CapabilityRegistry.java | CapabilityRegistry.removePossibleCapability | @Override
public CapabilityRegistration<?> removePossibleCapability(Capability capability, PathAddress registrationPoint) {
CapabilityId capabilityId = new CapabilityId(capability.getName(), CapabilityScope.GLOBAL);
CapabilityRegistration<?> removed = null;
writeLock.lock();
try {
CapabilityRegistration<?> candidate = possibleCapabilities.get(capabilityId);
if (candidate != null) {
RegistrationPoint rp = new RegistrationPoint(registrationPoint, null);
if (candidate.removeRegistrationPoint(rp)) {
if (candidate.getRegistrationPointCount() == 0) {
removed = possibleCapabilities.remove(capabilityId);
} else {
removed = candidate;
}
}
}
if (removed != null) {
modified = true;
}
return removed;
} finally {
writeLock.unlock();
}
} | java | @Override
public CapabilityRegistration<?> removePossibleCapability(Capability capability, PathAddress registrationPoint) {
CapabilityId capabilityId = new CapabilityId(capability.getName(), CapabilityScope.GLOBAL);
CapabilityRegistration<?> removed = null;
writeLock.lock();
try {
CapabilityRegistration<?> candidate = possibleCapabilities.get(capabilityId);
if (candidate != null) {
RegistrationPoint rp = new RegistrationPoint(registrationPoint, null);
if (candidate.removeRegistrationPoint(rp)) {
if (candidate.getRegistrationPointCount() == 0) {
removed = possibleCapabilities.remove(capabilityId);
} else {
removed = candidate;
}
}
}
if (removed != null) {
modified = true;
}
return removed;
} finally {
writeLock.unlock();
}
} | [
"@",
"Override",
"public",
"CapabilityRegistration",
"<",
"?",
">",
"removePossibleCapability",
"(",
"Capability",
"capability",
",",
"PathAddress",
"registrationPoint",
")",
"{",
"CapabilityId",
"capabilityId",
"=",
"new",
"CapabilityId",
"(",
"capability",
".",
"get... | Remove a previously registered capability if all registration points for it have been removed.
@param capability the capability. Cannot be {@code null}
@param registrationPoint the specific registration point that is being removed
@return the capability that was removed, or {@code null} if no matching capability was registered or other
registration points for the capability still exist | [
"Remove",
"a",
"previously",
"registered",
"capability",
"if",
"all",
"registration",
"points",
"for",
"it",
"have",
"been",
"removed",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/CapabilityRegistry.java#L595-L620 |
igniterealtime/Smack | smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TranscriptManager.java | TranscriptManager.getTranscripts | public Transcripts getTranscripts(EntityBareJid workgroupJID, Jid userID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
Transcripts request = new Transcripts(userID);
request.setTo(workgroupJID);
Transcripts response = connection.createStanzaCollectorAndSend(request).nextResultOrThrow();
return response;
} | java | public Transcripts getTranscripts(EntityBareJid workgroupJID, Jid userID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
Transcripts request = new Transcripts(userID);
request.setTo(workgroupJID);
Transcripts response = connection.createStanzaCollectorAndSend(request).nextResultOrThrow();
return response;
} | [
"public",
"Transcripts",
"getTranscripts",
"(",
"EntityBareJid",
"workgroupJID",
",",
"Jid",
"userID",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",
"Transcripts",
"request",
"=",
"new",
... | Returns the transcripts of a given user. The answer will contain the complete history of
conversations that a user had.
@param userID the id of the user to get his conversations.
@param workgroupJID the JID of the workgroup that will process the request.
@return the transcripts of a given user.
@throws XMPPErrorException
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException | [
"Returns",
"the",
"transcripts",
"of",
"a",
"given",
"user",
".",
"The",
"answer",
"will",
"contain",
"the",
"complete",
"history",
"of",
"conversations",
"that",
"a",
"user",
"had",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/TranscriptManager.java#L75-L80 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/os/BundleUtils.java | BundleUtils.optFloatArray | @Nullable
public static float[] optFloatArray(@Nullable Bundle bundle, @Nullable String key) {
return optFloatArray(bundle, key, new float[0]);
} | java | @Nullable
public static float[] optFloatArray(@Nullable Bundle bundle, @Nullable String key) {
return optFloatArray(bundle, key, new float[0]);
} | [
"@",
"Nullable",
"public",
"static",
"float",
"[",
"]",
"optFloatArray",
"(",
"@",
"Nullable",
"Bundle",
"bundle",
",",
"@",
"Nullable",
"String",
"key",
")",
"{",
"return",
"optFloatArray",
"(",
"bundle",
",",
"key",
",",
"new",
"float",
"[",
"0",
"]",
... | Returns a optional float array value. In other words, returns the value mapped by key if it exists and is a float array.
The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null.
@param bundle a bundle. If the bundle is null, this method will return null.
@param key a key for the value.
@return a float array value if exists, null otherwise.
@see android.os.Bundle#getFloatArray(String) | [
"Returns",
"a",
"optional",
"float",
"array",
"value",
".",
"In",
"other",
"words",
"returns",
"the",
"value",
"mapped",
"by",
"key",
"if",
"it",
"exists",
"and",
"is",
"a",
"float",
"array",
".",
"The",
"bundle",
"argument",
"is",
"allowed",
"to",
"be",... | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L511-L514 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/HFClient.java | HFClient.newChannel | public Channel newChannel(String name, Orderer orderer, ChannelConfiguration channelConfiguration,
byte[]... channelConfigurationSignatures) throws TransactionException, InvalidArgumentException {
clientCheck();
if (Utils.isNullOrEmpty(name)) {
throw new InvalidArgumentException("Channel name can not be null or empty string.");
}
synchronized (channels) {
if (channels.containsKey(name)) {
throw new InvalidArgumentException(format("Channel by the name %s already exits", name));
}
logger.trace("Creating channel :" + name);
Channel newChannel = Channel.createNewInstance(name, this, orderer, channelConfiguration,
channelConfigurationSignatures);
channels.put(name, newChannel);
return newChannel;
}
} | java | public Channel newChannel(String name, Orderer orderer, ChannelConfiguration channelConfiguration,
byte[]... channelConfigurationSignatures) throws TransactionException, InvalidArgumentException {
clientCheck();
if (Utils.isNullOrEmpty(name)) {
throw new InvalidArgumentException("Channel name can not be null or empty string.");
}
synchronized (channels) {
if (channels.containsKey(name)) {
throw new InvalidArgumentException(format("Channel by the name %s already exits", name));
}
logger.trace("Creating channel :" + name);
Channel newChannel = Channel.createNewInstance(name, this, orderer, channelConfiguration,
channelConfigurationSignatures);
channels.put(name, newChannel);
return newChannel;
}
} | [
"public",
"Channel",
"newChannel",
"(",
"String",
"name",
",",
"Orderer",
"orderer",
",",
"ChannelConfiguration",
"channelConfiguration",
",",
"byte",
"[",
"]",
"...",
"channelConfigurationSignatures",
")",
"throws",
"TransactionException",
",",
"InvalidArgumentException"... | Create a new channel
@param name The channel's name
@param orderer Orderer to create the channel with.
@param channelConfiguration Channel configuration data.
@param channelConfigurationSignatures byte arrays containing ConfigSignature's proto serialized.
See {@link Channel#getChannelConfigurationSignature} on how to create
@return a new channel.
@throws TransactionException
@throws InvalidArgumentException | [
"Create",
"a",
"new",
"channel"
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/HFClient.java#L264-L288 |
d-michail/jheaps | src/main/java/org/jheaps/tree/FibonacciHeap.java | FibonacciHeap.link | private void link(Node<K, V> y, Node<K, V> x) {
// remove from root list
y.prev.next = y.next;
y.next.prev = y.prev;
// one less root
roots--;
// clear if marked
y.mark = false;
// hang as x's child
x.degree++;
y.parent = x;
Node<K, V> child = x.child;
if (child == null) {
x.child = y;
y.next = y;
y.prev = y;
} else {
y.prev = child;
y.next = child.next;
child.next = y;
y.next.prev = y;
}
} | java | private void link(Node<K, V> y, Node<K, V> x) {
// remove from root list
y.prev.next = y.next;
y.next.prev = y.prev;
// one less root
roots--;
// clear if marked
y.mark = false;
// hang as x's child
x.degree++;
y.parent = x;
Node<K, V> child = x.child;
if (child == null) {
x.child = y;
y.next = y;
y.prev = y;
} else {
y.prev = child;
y.next = child.next;
child.next = y;
y.next.prev = y;
}
} | [
"private",
"void",
"link",
"(",
"Node",
"<",
"K",
",",
"V",
">",
"y",
",",
"Node",
"<",
"K",
",",
"V",
">",
"x",
")",
"{",
"// remove from root list",
"y",
".",
"prev",
".",
"next",
"=",
"y",
".",
"next",
";",
"y",
".",
"next",
".",
"prev",
"... | /*
Remove node y from the root list and make it a child of x. Degree of x
increases by 1 and y is unmarked if marked. | [
"/",
"*",
"Remove",
"node",
"y",
"from",
"the",
"root",
"list",
"and",
"make",
"it",
"a",
"child",
"of",
"x",
".",
"Degree",
"of",
"x",
"increases",
"by",
"1",
"and",
"y",
"is",
"unmarked",
"if",
"marked",
"."
] | train | https://github.com/d-michail/jheaps/blob/7146451dd6591c2a8559dc564c9c40428c4a2c10/src/main/java/org/jheaps/tree/FibonacciHeap.java#L630-L656 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/admin/index/Index.java | Index.getSearch | public static ISearch getSearch()
throws EFapsException
{
ISearch ret = null;
if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXSEARCHCLASS)) {
final String clazzname = EFapsSystemConfiguration.get().getAttributeValue(
KernelSettings.INDEXSEARCHCLASS);
try {
final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance());
ret = (ISearch) clazz.newInstance();
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new EFapsException(Index.class, "Could not instanciate IDirectoryProvider", e);
}
} else {
ret = new ISearch()
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The query. */
private String query;
@Override
public void setQuery(final String _query)
{
this.query = _query;
}
@Override
public String getQuery()
{
return this.query;
}
};
}
return ret;
} | java | public static ISearch getSearch()
throws EFapsException
{
ISearch ret = null;
if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXSEARCHCLASS)) {
final String clazzname = EFapsSystemConfiguration.get().getAttributeValue(
KernelSettings.INDEXSEARCHCLASS);
try {
final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance());
ret = (ISearch) clazz.newInstance();
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new EFapsException(Index.class, "Could not instanciate IDirectoryProvider", e);
}
} else {
ret = new ISearch()
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The query. */
private String query;
@Override
public void setQuery(final String _query)
{
this.query = _query;
}
@Override
public String getQuery()
{
return this.query;
}
};
}
return ret;
} | [
"public",
"static",
"ISearch",
"getSearch",
"(",
")",
"throws",
"EFapsException",
"{",
"ISearch",
"ret",
"=",
"null",
";",
"if",
"(",
"EFapsSystemConfiguration",
".",
"get",
"(",
")",
".",
"containsAttributeValue",
"(",
"KernelSettings",
".",
"INDEXSEARCHCLASS",
... | Gets the directory.
@return the directory
@throws EFapsException on error | [
"Gets",
"the",
"directory",
"."
] | train | https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/index/Index.java#L177-L213 |
ivanceras/orm | src/main/java/com/ivanceras/db/server/util/DAOGenerator.java | DAOGenerator.startUncurated | public void startUncurated(Configuration conf) throws Exception{
IDatabaseDev db = (IDatabaseDev) em.getDB();//TODO make sure DB platform can be used for development
ModelDefinitionProvider provider = new ModelDefinitionProvider(db, conf.dbUser, null, conf.includeSchema);
ModelDef[] origModelList = provider.getTableDefinitions();
//TODO: proper support for explicit ModelDefinitions
ModelDef[] withExplecitList = overrideModelDefFromExplicit(origModelList, explicitMeta);
ModelDef[] modelList = withExplecitList;
ModelDef[] modelListOwned = setModelOwners(modelList, tableGroups);
ModelDef[] modelListChilded = setDirectChildren(modelListOwned);
new ModelMetaDataGenerator().start(modelListChilded, conf);
} | java | public void startUncurated(Configuration conf) throws Exception{
IDatabaseDev db = (IDatabaseDev) em.getDB();//TODO make sure DB platform can be used for development
ModelDefinitionProvider provider = new ModelDefinitionProvider(db, conf.dbUser, null, conf.includeSchema);
ModelDef[] origModelList = provider.getTableDefinitions();
//TODO: proper support for explicit ModelDefinitions
ModelDef[] withExplecitList = overrideModelDefFromExplicit(origModelList, explicitMeta);
ModelDef[] modelList = withExplecitList;
ModelDef[] modelListOwned = setModelOwners(modelList, tableGroups);
ModelDef[] modelListChilded = setDirectChildren(modelListOwned);
new ModelMetaDataGenerator().start(modelListChilded, conf);
} | [
"public",
"void",
"startUncurated",
"(",
"Configuration",
"conf",
")",
"throws",
"Exception",
"{",
"IDatabaseDev",
"db",
"=",
"(",
"IDatabaseDev",
")",
"em",
".",
"getDB",
"(",
")",
";",
"//TODO make sure DB platform can be used for development",
"ModelDefinitionProvide... | Curated will correct The ModelDef
@param curated
@throws Exception | [
"Curated",
"will",
"correct",
"The",
"ModelDef"
] | train | https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/server/util/DAOGenerator.java#L59-L72 |
jbossas/jboss-invocation | src/main/java/org/jboss/invocation/proxy/ProxyFactory.java | ProxyFactory.getInvocationHandler | public InvocationHandler getInvocationHandler(Object proxy) {
Field field = getInvocationHandlerField();
try {
return (InvocationHandler) field.get(proxy);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Object is not a proxy of correct type", e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | java | public InvocationHandler getInvocationHandler(Object proxy) {
Field field = getInvocationHandlerField();
try {
return (InvocationHandler) field.get(proxy);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Object is not a proxy of correct type", e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | [
"public",
"InvocationHandler",
"getInvocationHandler",
"(",
"Object",
"proxy",
")",
"{",
"Field",
"field",
"=",
"getInvocationHandlerField",
"(",
")",
";",
"try",
"{",
"return",
"(",
"InvocationHandler",
")",
"field",
".",
"get",
"(",
"proxy",
")",
";",
"}",
... | Returns the invocation handler for a proxy created from this factory.
@param proxy the proxy
@return the invocation handler | [
"Returns",
"the",
"invocation",
"handler",
"for",
"a",
"proxy",
"created",
"from",
"this",
"factory",
"."
] | train | https://github.com/jbossas/jboss-invocation/blob/f72586a554264cbc78fcdad9fdd3e84b833249c9/src/main/java/org/jboss/invocation/proxy/ProxyFactory.java#L375-L384 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/lang/Strings.java | Strings.removeWord | public static String removeWord(final String host, final String word) {
return removeWord(host, word, DELIMITER);
} | java | public static String removeWord(final String host, final String word) {
return removeWord(host, word, DELIMITER);
} | [
"public",
"static",
"String",
"removeWord",
"(",
"final",
"String",
"host",
",",
"final",
"String",
"word",
")",
"{",
"return",
"removeWord",
"(",
"host",
",",
"word",
",",
"DELIMITER",
")",
";",
"}"
] | <p>
removeWord.
</p>
@param host
a {@link java.lang.String} object.
@param word
a {@link java.lang.String} object.
@return a {@link java.lang.String} object. | [
"<p",
">",
"removeWord",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/Strings.java#L630-L633 |
lessthanoptimal/BoofCV | examples/src/main/java/boofcv/examples/imageprocessing/ExamplePlanarImages.java | ExamplePlanarImages.pixelAccess | public static void pixelAccess( BufferedImage input ) {
// convert the BufferedImage into a Planar
Planar<GrayU8> image = ConvertBufferedImage.convertFromPlanar(input,null,true,GrayU8.class);
int x = 10, y = 10;
// to access a pixel you first access the gray image for the each band
for( int i = 0; i < image.getNumBands(); i++ )
System.out.println("Original "+i+" = "+image.getBand(i).get(x,y));
// change the value in each band
for( int i = 0; i < image.getNumBands(); i++ )
image.getBand(i).set(x, y, 100 + i);
// to access a pixel you first access the gray image for the each band
for( int i = 0; i < image.getNumBands(); i++ )
System.out.println("Result "+i+" = "+image.getBand(i).get(x,y));
}
/**
* There is no real perfect way that everyone agrees on for converting color images into gray scale
* images. Two examples of how to convert a Planar image into a gray scale image are shown
* in this example.
*/
public static void convertToGray( BufferedImage input ) {
// convert the BufferedImage into a Planar
Planar<GrayU8> image = ConvertBufferedImage.convertFromPlanar(input,null,true,GrayU8.class);
GrayU8 gray = new GrayU8( image.width,image.height);
// creates a gray scale image by averaging intensity value across pixels
ConvertImage.average(image, gray);
BufferedImage outputAve = ConvertBufferedImage.convertTo(gray,null);
// convert to gray scale but weigh each color band based on how human vision works
ColorRgb.rgbToGray_Weighted(image, gray);
BufferedImage outputWeighted = ConvertBufferedImage.convertTo(gray,null);
// create an output image just from the first band
BufferedImage outputBand0 = ConvertBufferedImage.convertTo(image.getBand(0),null);
gui.addImage(outputAve,"Gray Averaged");
gui.addImage(outputWeighted,"Gray Weighted");
gui.addImage(outputBand0,"Band 0");
}
public static void main( String args[] ) {
BufferedImage input = UtilImageIO.loadImage(UtilIO.pathExample("apartment_building_02.jpg"));
// Uncomment lines below to run each example
ExamplePlanarImages.independent(input);
ExamplePlanarImages.pixelAccess(input);
ExamplePlanarImages.convertToGray(input);
ShowImages.showWindow(gui,"Color Planar Image Examples",true);
}
} | java | public static void pixelAccess( BufferedImage input ) {
// convert the BufferedImage into a Planar
Planar<GrayU8> image = ConvertBufferedImage.convertFromPlanar(input,null,true,GrayU8.class);
int x = 10, y = 10;
// to access a pixel you first access the gray image for the each band
for( int i = 0; i < image.getNumBands(); i++ )
System.out.println("Original "+i+" = "+image.getBand(i).get(x,y));
// change the value in each band
for( int i = 0; i < image.getNumBands(); i++ )
image.getBand(i).set(x, y, 100 + i);
// to access a pixel you first access the gray image for the each band
for( int i = 0; i < image.getNumBands(); i++ )
System.out.println("Result "+i+" = "+image.getBand(i).get(x,y));
}
/**
* There is no real perfect way that everyone agrees on for converting color images into gray scale
* images. Two examples of how to convert a Planar image into a gray scale image are shown
* in this example.
*/
public static void convertToGray( BufferedImage input ) {
// convert the BufferedImage into a Planar
Planar<GrayU8> image = ConvertBufferedImage.convertFromPlanar(input,null,true,GrayU8.class);
GrayU8 gray = new GrayU8( image.width,image.height);
// creates a gray scale image by averaging intensity value across pixels
ConvertImage.average(image, gray);
BufferedImage outputAve = ConvertBufferedImage.convertTo(gray,null);
// convert to gray scale but weigh each color band based on how human vision works
ColorRgb.rgbToGray_Weighted(image, gray);
BufferedImage outputWeighted = ConvertBufferedImage.convertTo(gray,null);
// create an output image just from the first band
BufferedImage outputBand0 = ConvertBufferedImage.convertTo(image.getBand(0),null);
gui.addImage(outputAve,"Gray Averaged");
gui.addImage(outputWeighted,"Gray Weighted");
gui.addImage(outputBand0,"Band 0");
}
public static void main( String args[] ) {
BufferedImage input = UtilImageIO.loadImage(UtilIO.pathExample("apartment_building_02.jpg"));
// Uncomment lines below to run each example
ExamplePlanarImages.independent(input);
ExamplePlanarImages.pixelAccess(input);
ExamplePlanarImages.convertToGray(input);
ShowImages.showWindow(gui,"Color Planar Image Examples",true);
}
} | [
"public",
"static",
"void",
"pixelAccess",
"(",
"BufferedImage",
"input",
")",
"{",
"// convert the BufferedImage into a Planar",
"Planar",
"<",
"GrayU8",
">",
"image",
"=",
"ConvertBufferedImage",
".",
"convertFromPlanar",
"(",
"input",
",",
"null",
",",
"true",
",... | Values of pixels can be read and modified by accessing the internal {@link ImageGray}. | [
"Values",
"of",
"pixels",
"can",
"be",
"read",
"and",
"modified",
"by",
"accessing",
"the",
"internal",
"{"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/imageprocessing/ExamplePlanarImages.java#L86-L143 |
wildfly/wildfly-core | cli/src/main/java/org/jboss/as/cli/gui/CommandExecutor.java | CommandExecutor.doCommand | public synchronized ModelNode doCommand(String command) throws CommandFormatException, IOException {
ModelNode request = cmdCtx.buildRequest(command);
return execute(request, isSlowCommand(command)).getResponseNode();
} | java | public synchronized ModelNode doCommand(String command) throws CommandFormatException, IOException {
ModelNode request = cmdCtx.buildRequest(command);
return execute(request, isSlowCommand(command)).getResponseNode();
} | [
"public",
"synchronized",
"ModelNode",
"doCommand",
"(",
"String",
"command",
")",
"throws",
"CommandFormatException",
",",
"IOException",
"{",
"ModelNode",
"request",
"=",
"cmdCtx",
".",
"buildRequest",
"(",
"command",
")",
";",
"return",
"execute",
"(",
"request... | Submit a command to the server.
@param command The CLI command
@return The DMR response as a ModelNode
@throws CommandFormatException
@throws IOException | [
"Submit",
"a",
"command",
"to",
"the",
"server",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/gui/CommandExecutor.java#L75-L78 |
kaazing/gateway | security/src/main/java/org/kaazing/gateway/security/auth/context/DefaultLoginContextFactory.java | DefaultLoginContextFactory.createLoginContext | protected LoginContext createLoginContext(CallbackHandler handler, final DefaultLoginResult loginResult)
throws LoginException {
return createLoginContext(null, handler, loginResult);
} | java | protected LoginContext createLoginContext(CallbackHandler handler, final DefaultLoginResult loginResult)
throws LoginException {
return createLoginContext(null, handler, loginResult);
} | [
"protected",
"LoginContext",
"createLoginContext",
"(",
"CallbackHandler",
"handler",
",",
"final",
"DefaultLoginResult",
"loginResult",
")",
"throws",
"LoginException",
"{",
"return",
"createLoginContext",
"(",
"null",
",",
"handler",
",",
"loginResult",
")",
";",
"}... | For login context providers that can abstract their tokens into a CallbackHandler
that understands their token, this is a utility method that can be called to construct a create login.
@param handler the callback handler that can understand
@return a login context
@throws LoginException when a login context cannot be created | [
"For",
"login",
"context",
"providers",
"that",
"can",
"abstract",
"their",
"tokens",
"into",
"a",
"CallbackHandler",
"that",
"understands",
"their",
"token",
"this",
"is",
"a",
"utility",
"method",
"that",
"can",
"be",
"called",
"to",
"construct",
"a",
"creat... | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/security/src/main/java/org/kaazing/gateway/security/auth/context/DefaultLoginContextFactory.java#L205-L208 |
primefaces/primefaces | src/main/java/org/primefaces/util/ComponentTraversalUtils.java | ComponentTraversalUtils.firstWithId | public static UIComponent firstWithId(String id, UIComponent base) {
if (id.equals(base.getId())) {
return base;
}
UIComponent result = null;
Iterator<UIComponent> kids = base.getFacetsAndChildren();
while (kids.hasNext() && (result == null)) {
UIComponent kid = kids.next();
if (id.equals(kid.getId())) {
result = kid;
break;
}
result = firstWithId(id, kid);
if (result != null) {
break;
}
}
return result;
} | java | public static UIComponent firstWithId(String id, UIComponent base) {
if (id.equals(base.getId())) {
return base;
}
UIComponent result = null;
Iterator<UIComponent> kids = base.getFacetsAndChildren();
while (kids.hasNext() && (result == null)) {
UIComponent kid = kids.next();
if (id.equals(kid.getId())) {
result = kid;
break;
}
result = firstWithId(id, kid);
if (result != null) {
break;
}
}
return result;
} | [
"public",
"static",
"UIComponent",
"firstWithId",
"(",
"String",
"id",
",",
"UIComponent",
"base",
")",
"{",
"if",
"(",
"id",
".",
"equals",
"(",
"base",
".",
"getId",
"(",
")",
")",
")",
"{",
"return",
"base",
";",
"}",
"UIComponent",
"result",
"=",
... | Finds the first component with the given id (NOT clientId!).
@param id The id.
@param base The base component to start the traversal.
@return The component or null. | [
"Finds",
"the",
"first",
"component",
"with",
"the",
"given",
"id",
"(",
"NOT",
"clientId!",
")",
"."
] | train | https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/util/ComponentTraversalUtils.java#L117-L137 |
jbundle/jbundle | thin/base/db/base/src/main/java/org/jbundle/thin/base/db/buff/BaseBuffer.java | BaseBuffer.getNextField | public int getNextField(FieldInfo field, boolean bDisplayOption, int iMoveMode) // Must be to call right Get calls
{
Object objNext = this.getNextData();
if (DATA_ERROR.equals(objNext))
return Constants.ERROR_RETURN; // EOF
if (DATA_EOF.equals(objNext))
return Constants.ERROR_RETURN; // EOF
if (DATA_SKIP.equals(objNext))
return Constants.NORMAL_RETURN; // Don't set this field
return field.setData(objNext, bDisplayOption, iMoveMode);
} | java | public int getNextField(FieldInfo field, boolean bDisplayOption, int iMoveMode) // Must be to call right Get calls
{
Object objNext = this.getNextData();
if (DATA_ERROR.equals(objNext))
return Constants.ERROR_RETURN; // EOF
if (DATA_EOF.equals(objNext))
return Constants.ERROR_RETURN; // EOF
if (DATA_SKIP.equals(objNext))
return Constants.NORMAL_RETURN; // Don't set this field
return field.setData(objNext, bDisplayOption, iMoveMode);
} | [
"public",
"int",
"getNextField",
"(",
"FieldInfo",
"field",
",",
"boolean",
"bDisplayOption",
",",
"int",
"iMoveMode",
")",
"// Must be to call right Get calls",
"{",
"Object",
"objNext",
"=",
"this",
".",
"getNextData",
"(",
")",
";",
"if",
"(",
"DATA_ERROR",
"... | Get the next field and fill it with data from this buffer.
You must override this method.
@param field The field to set.
@param bDisplayOption The display option for setting the field.
@param iMoveMove The move mode for setting the field.
@return The error code. | [
"Get",
"the",
"next",
"field",
"and",
"fill",
"it",
"with",
"data",
"from",
"this",
"buffer",
".",
"You",
"must",
"override",
"this",
"method",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/base/src/main/java/org/jbundle/thin/base/db/buff/BaseBuffer.java#L336-L346 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java | ForwardCurveInterpolation.addForward | private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {
double interpolationEntitiyTime;
RandomVariable interpolationEntityForwardValue;
switch(interpolationEntityForward) {
case FORWARD:
default:
interpolationEntitiyTime = fixingTime;
interpolationEntityForwardValue = forward;
break;
case FORWARD_TIMES_DISCOUNTFACTOR:
interpolationEntitiyTime = fixingTime;
interpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));
break;
case ZERO:
{
double paymentOffset = getPaymentOffset(fixingTime);
interpolationEntitiyTime = fixingTime+paymentOffset;
interpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);
break;
}
case DISCOUNTFACTOR:
{
double paymentOffset = getPaymentOffset(fixingTime);
interpolationEntitiyTime = fixingTime+paymentOffset;
interpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));
break;
}
}
super.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);
} | java | private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {
double interpolationEntitiyTime;
RandomVariable interpolationEntityForwardValue;
switch(interpolationEntityForward) {
case FORWARD:
default:
interpolationEntitiyTime = fixingTime;
interpolationEntityForwardValue = forward;
break;
case FORWARD_TIMES_DISCOUNTFACTOR:
interpolationEntitiyTime = fixingTime;
interpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));
break;
case ZERO:
{
double paymentOffset = getPaymentOffset(fixingTime);
interpolationEntitiyTime = fixingTime+paymentOffset;
interpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);
break;
}
case DISCOUNTFACTOR:
{
double paymentOffset = getPaymentOffset(fixingTime);
interpolationEntitiyTime = fixingTime+paymentOffset;
interpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));
break;
}
}
super.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);
} | [
"private",
"void",
"addForward",
"(",
"AnalyticModel",
"model",
",",
"double",
"fixingTime",
",",
"RandomVariable",
"forward",
",",
"boolean",
"isParameter",
")",
"{",
"double",
"interpolationEntitiyTime",
";",
"RandomVariable",
"interpolationEntityForwardValue",
";",
"... | Add a forward to this curve.
@param model An analytic model providing a context. The discount curve (if needed) is obtained from this model.
@param fixingTime The given fixing time.
@param forward The given forward.
@param isParameter If true, then this point is server via {@link #getParameter()} and changed via {@link #setParameter(RandomVariable[])} and {@link #getCloneForParameter(RandomVariable[])}, i.e., it can be calibrated. | [
"Add",
"a",
"forward",
"to",
"this",
"curve",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java#L416-L445 |
SeleniumHQ/selenium | java/client/src/org/openqa/selenium/remote/RemoteWebDriverBuilder.java | RemoteWebDriverBuilder.oneOf | public RemoteWebDriverBuilder oneOf(Capabilities maybeThis, Capabilities... orOneOfThese) {
options.clear();
addAlternative(maybeThis);
for (Capabilities anOrOneOfThese : orOneOfThese) {
addAlternative(anOrOneOfThese);
}
return this;
} | java | public RemoteWebDriverBuilder oneOf(Capabilities maybeThis, Capabilities... orOneOfThese) {
options.clear();
addAlternative(maybeThis);
for (Capabilities anOrOneOfThese : orOneOfThese) {
addAlternative(anOrOneOfThese);
}
return this;
} | [
"public",
"RemoteWebDriverBuilder",
"oneOf",
"(",
"Capabilities",
"maybeThis",
",",
"Capabilities",
"...",
"orOneOfThese",
")",
"{",
"options",
".",
"clear",
"(",
")",
";",
"addAlternative",
"(",
"maybeThis",
")",
";",
"for",
"(",
"Capabilities",
"anOrOneOfThese",... | Clears the current set of alternative browsers and instead sets the list of possible choices to
the arguments given to this method. | [
"Clears",
"the",
"current",
"set",
"of",
"alternative",
"browsers",
"and",
"instead",
"sets",
"the",
"list",
"of",
"possible",
"choices",
"to",
"the",
"arguments",
"given",
"to",
"this",
"method",
"."
] | train | https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/remote/RemoteWebDriverBuilder.java#L106-L113 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.