repository_name
stringlengths 7
58
| func_path_in_repository
stringlengths 11
218
| func_name
stringlengths 4
140
| whole_func_string
stringlengths 153
5.32k
| language
stringclasses 1
value | func_code_string
stringlengths 72
4k
| func_code_tokens
sequencelengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
sequencelengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.java | EventCountCircuitBreaker.nextCheckIntervalData | private CheckIntervalData nextCheckIntervalData(final int increment,
final CheckIntervalData currentData, final State currentState, final long time) {
"""
Calculates the next {@code CheckIntervalData} object based on the current data and
the current state. The next data object takes the counter increment and the current
time into account.
@param increment the increment for the internal counter
@param currentData the current check data object
@param currentState the current state of the circuit breaker
@param time the current time
@return the updated {@code CheckIntervalData} object
"""
CheckIntervalData nextData;
if (stateStrategy(currentState).isCheckIntervalFinished(this, currentData, time)) {
nextData = new CheckIntervalData(increment, time);
} else {
nextData = currentData.increment(increment);
}
return nextData;
} | java | private CheckIntervalData nextCheckIntervalData(final int increment,
final CheckIntervalData currentData, final State currentState, final long time) {
CheckIntervalData nextData;
if (stateStrategy(currentState).isCheckIntervalFinished(this, currentData, time)) {
nextData = new CheckIntervalData(increment, time);
} else {
nextData = currentData.increment(increment);
}
return nextData;
} | [
"private",
"CheckIntervalData",
"nextCheckIntervalData",
"(",
"final",
"int",
"increment",
",",
"final",
"CheckIntervalData",
"currentData",
",",
"final",
"State",
"currentState",
",",
"final",
"long",
"time",
")",
"{",
"CheckIntervalData",
"nextData",
";",
"if",
"(",
"stateStrategy",
"(",
"currentState",
")",
".",
"isCheckIntervalFinished",
"(",
"this",
",",
"currentData",
",",
"time",
")",
")",
"{",
"nextData",
"=",
"new",
"CheckIntervalData",
"(",
"increment",
",",
"time",
")",
";",
"}",
"else",
"{",
"nextData",
"=",
"currentData",
".",
"increment",
"(",
"increment",
")",
";",
"}",
"return",
"nextData",
";",
"}"
] | Calculates the next {@code CheckIntervalData} object based on the current data and
the current state. The next data object takes the counter increment and the current
time into account.
@param increment the increment for the internal counter
@param currentData the current check data object
@param currentState the current state of the circuit breaker
@param time the current time
@return the updated {@code CheckIntervalData} object | [
"Calculates",
"the",
"next",
"{",
"@code",
"CheckIntervalData",
"}",
"object",
"based",
"on",
"the",
"current",
"data",
"and",
"the",
"current",
"state",
".",
"The",
"next",
"data",
"object",
"takes",
"the",
"counter",
"increment",
"and",
"the",
"current",
"time",
"into",
"account",
"."
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.java#L382-L391 |
hamnis/json-collection | src/main/java/net/hamnaberg/json/parser/CollectionParser.java | CollectionParser.parseTemplate | public Template parseTemplate(InputStream stream) throws IOException {
"""
Parses a JsonCollection from the given stream.
The stream is wrapped in a BufferedReader.
<p>
The stream is expected to be UTF-8 encoded.
@param stream the stream
@return a jsonCollection
@throws IOException
"""
return parseTemplate(new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8)));
} | java | public Template parseTemplate(InputStream stream) throws IOException {
return parseTemplate(new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8)));
} | [
"public",
"Template",
"parseTemplate",
"(",
"InputStream",
"stream",
")",
"throws",
"IOException",
"{",
"return",
"parseTemplate",
"(",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"stream",
",",
"Charsets",
".",
"UTF_8",
")",
")",
")",
";",
"}"
] | Parses a JsonCollection from the given stream.
The stream is wrapped in a BufferedReader.
<p>
The stream is expected to be UTF-8 encoded.
@param stream the stream
@return a jsonCollection
@throws IOException | [
"Parses",
"a",
"JsonCollection",
"from",
"the",
"given",
"stream",
".",
"The",
"stream",
"is",
"wrapped",
"in",
"a",
"BufferedReader",
".",
"<p",
">",
"The",
"stream",
"is",
"expected",
"to",
"be",
"UTF",
"-",
"8",
"encoded",
"."
] | train | https://github.com/hamnis/json-collection/blob/fbd4a1c6ab75b70b3b4cb981b608b395e9c8c180/src/main/java/net/hamnaberg/json/parser/CollectionParser.java#L89-L91 |
nextreports/nextreports-engine | src/ro/nextreports/engine/util/DateUtil.java | DateUtil.getLastNDay | public static Date getLastNDay(Date d, int n, int unitType) {
"""
Get date with n unitType before
@param d date
@param n number of units
@param unitType unit type : one of Calendar.DAY_OF_YEAR, Calendar.WEEK_OF_YEAR, Calendar.MONTH, Calendar.YEAR;
@return
"""
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(unitType, -n);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
} | java | public static Date getLastNDay(Date d, int n, int unitType) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(unitType, -n);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
} | [
"public",
"static",
"Date",
"getLastNDay",
"(",
"Date",
"d",
",",
"int",
"n",
",",
"int",
"unitType",
")",
"{",
"Calendar",
"cal",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"cal",
".",
"setTime",
"(",
"d",
")",
";",
"cal",
".",
"add",
"(",
"unitType",
",",
"-",
"n",
")",
";",
"cal",
".",
"set",
"(",
"Calendar",
".",
"HOUR_OF_DAY",
",",
"0",
")",
";",
"cal",
".",
"set",
"(",
"Calendar",
".",
"MINUTE",
",",
"0",
")",
";",
"cal",
".",
"set",
"(",
"Calendar",
".",
"SECOND",
",",
"0",
")",
";",
"cal",
".",
"set",
"(",
"Calendar",
".",
"MILLISECOND",
",",
"0",
")",
";",
"return",
"cal",
".",
"getTime",
"(",
")",
";",
"}"
] | Get date with n unitType before
@param d date
@param n number of units
@param unitType unit type : one of Calendar.DAY_OF_YEAR, Calendar.WEEK_OF_YEAR, Calendar.MONTH, Calendar.YEAR;
@return | [
"Get",
"date",
"with",
"n",
"unitType",
"before"
] | train | https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/DateUtil.java#L755-L764 |
pmwmedia/tinylog | benchmarks/src/main/java/org/tinylog/benchmarks/api/WritingBenchmark.java | WritingBenchmark.unbufferedRandomAccessFile | @Benchmark
@BenchmarkMode(Mode.AverageTime)
public void unbufferedRandomAccessFile(final Configuration configuration) throws IOException {
"""
Benchmarks direct writing via {@link RandomAccessFile} without using any kind of buffering.
@param configuration
Configuration with target file
@throws IOException
Failed to write to target file
"""
try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) {
for (long i = 0; i < LINES; ++i) {
file.write(DATA);
}
}
} | java | @Benchmark
@BenchmarkMode(Mode.AverageTime)
public void unbufferedRandomAccessFile(final Configuration configuration) throws IOException {
try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) {
for (long i = 0; i < LINES; ++i) {
file.write(DATA);
}
}
} | [
"@",
"Benchmark",
"@",
"BenchmarkMode",
"(",
"Mode",
".",
"AverageTime",
")",
"public",
"void",
"unbufferedRandomAccessFile",
"(",
"final",
"Configuration",
"configuration",
")",
"throws",
"IOException",
"{",
"try",
"(",
"RandomAccessFile",
"file",
"=",
"new",
"RandomAccessFile",
"(",
"configuration",
".",
"file",
",",
"\"rw\"",
")",
")",
"{",
"for",
"(",
"long",
"i",
"=",
"0",
";",
"i",
"<",
"LINES",
";",
"++",
"i",
")",
"{",
"file",
".",
"write",
"(",
"DATA",
")",
";",
"}",
"}",
"}"
] | Benchmarks direct writing via {@link RandomAccessFile} without using any kind of buffering.
@param configuration
Configuration with target file
@throws IOException
Failed to write to target file | [
"Benchmarks",
"direct",
"writing",
"via",
"{",
"@link",
"RandomAccessFile",
"}",
"without",
"using",
"any",
"kind",
"of",
"buffering",
"."
] | train | https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/benchmarks/src/main/java/org/tinylog/benchmarks/api/WritingBenchmark.java#L272-L280 |
meertensinstituut/mtas | src/main/java/mtas/analysis/token/MtasToken.java | MtasToken.setRealOffset | final public void setRealOffset(Integer start, Integer end) {
"""
Sets the real offset.
@param start the start
@param end the end
"""
if ((start == null) || (end == null)) {
// do nothing
} else if (start > end) {
throw new IllegalArgumentException(
"Start real offset after end real offset");
} else {
tokenRealOffset = new MtasOffset(start, end);
}
} | java | final public void setRealOffset(Integer start, Integer end) {
if ((start == null) || (end == null)) {
// do nothing
} else if (start > end) {
throw new IllegalArgumentException(
"Start real offset after end real offset");
} else {
tokenRealOffset = new MtasOffset(start, end);
}
} | [
"final",
"public",
"void",
"setRealOffset",
"(",
"Integer",
"start",
",",
"Integer",
"end",
")",
"{",
"if",
"(",
"(",
"start",
"==",
"null",
")",
"||",
"(",
"end",
"==",
"null",
")",
")",
"{",
"// do nothing",
"}",
"else",
"if",
"(",
"start",
">",
"end",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Start real offset after end real offset\"",
")",
";",
"}",
"else",
"{",
"tokenRealOffset",
"=",
"new",
"MtasOffset",
"(",
"start",
",",
"end",
")",
";",
"}",
"}"
] | Sets the real offset.
@param start the start
@param end the end | [
"Sets",
"the",
"real",
"offset",
"."
] | train | https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/analysis/token/MtasToken.java#L461-L470 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/web/JobmanagerInfoServlet.java | JobmanagerInfoServlet.writeJsonForJobs | private void writeJsonForJobs(PrintWriter wrt, List<RecentJobEvent> jobs) {
"""
Writes ManagementGraph as Json for all recent jobs
@param wrt
@param jobs
"""
try {
wrt.write("[");
// Loop Jobs
for (int i = 0; i < jobs.size(); i++) {
RecentJobEvent jobEvent = jobs.get(i);
writeJsonForJob(wrt, jobEvent);
//Write seperator between json objects
if(i != jobs.size() - 1) {
wrt.write(",");
}
}
wrt.write("]");
} catch (EofException eof) { // Connection closed by client
LOG.info("Info server for jobmanager: Connection closed by client, EofException");
} catch (IOException ioe) { // Connection closed by client
LOG.info("Info server for jobmanager: Connection closed by client, IOException");
}
} | java | private void writeJsonForJobs(PrintWriter wrt, List<RecentJobEvent> jobs) {
try {
wrt.write("[");
// Loop Jobs
for (int i = 0; i < jobs.size(); i++) {
RecentJobEvent jobEvent = jobs.get(i);
writeJsonForJob(wrt, jobEvent);
//Write seperator between json objects
if(i != jobs.size() - 1) {
wrt.write(",");
}
}
wrt.write("]");
} catch (EofException eof) { // Connection closed by client
LOG.info("Info server for jobmanager: Connection closed by client, EofException");
} catch (IOException ioe) { // Connection closed by client
LOG.info("Info server for jobmanager: Connection closed by client, IOException");
}
} | [
"private",
"void",
"writeJsonForJobs",
"(",
"PrintWriter",
"wrt",
",",
"List",
"<",
"RecentJobEvent",
">",
"jobs",
")",
"{",
"try",
"{",
"wrt",
".",
"write",
"(",
"\"[\"",
")",
";",
"// Loop Jobs",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"jobs",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"RecentJobEvent",
"jobEvent",
"=",
"jobs",
".",
"get",
"(",
"i",
")",
";",
"writeJsonForJob",
"(",
"wrt",
",",
"jobEvent",
")",
";",
"//Write seperator between json objects",
"if",
"(",
"i",
"!=",
"jobs",
".",
"size",
"(",
")",
"-",
"1",
")",
"{",
"wrt",
".",
"write",
"(",
"\",\"",
")",
";",
"}",
"}",
"wrt",
".",
"write",
"(",
"\"]\"",
")",
";",
"}",
"catch",
"(",
"EofException",
"eof",
")",
"{",
"// Connection closed by client",
"LOG",
".",
"info",
"(",
"\"Info server for jobmanager: Connection closed by client, EofException\"",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"// Connection closed by client\t",
"LOG",
".",
"info",
"(",
"\"Info server for jobmanager: Connection closed by client, IOException\"",
")",
";",
"}",
"}"
] | Writes ManagementGraph as Json for all recent jobs
@param wrt
@param jobs | [
"Writes",
"ManagementGraph",
"as",
"Json",
"for",
"all",
"recent",
"jobs"
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/web/JobmanagerInfoServlet.java#L119-L144 |
AltBeacon/android-beacon-library | lib/src/main/java/org/altbeacon/beacon/BeaconManager.java | BeaconManager.enableForegroundServiceScanning | public void enableForegroundServiceScanning(Notification notification, int notificationId)
throws IllegalStateException {
"""
Configures the library to use a foreground service for bacon scanning. This allows nearly
constant scanning on most Android versions to get around background limits, and displays an
icon to the user to indicate that the app is doing something in the background, even on
Android 8+. This will disable the user of the JobScheduler on Android 8 to do scans. Note
that this method does not by itself enable constant scanning. The scan intervals will work
as normal and must be configurd to specific values depending on how often you wish to scan.
@see #setForegroundScanPeriod(long)
@see #setForegroundBetweenScanPeriod(long)
This method requires a notification to display a message to the user about why the app is
scanning in the background. The notification must include an icon that will be displayed
in the top bar whenever the scanning service is running.
If the BeaconService is configured to run in a different process, this call will have no
effect.
@param notification - the notification that will be displayed when beacon scanning is active,
along with the icon that shows up in the status bar.
@throws IllegalStateException if called after consumers are already bound to the scanning
service
"""
if (isAnyConsumerBound()) {
throw new IllegalStateException("May not be called after consumers are already bound.");
}
if (notification == null) {
throw new NullPointerException("Notification cannot be null");
}
setEnableScheduledScanJobs(false);
mForegroundServiceNotification = notification;
mForegroundServiceNotificationId = notificationId;
} | java | public void enableForegroundServiceScanning(Notification notification, int notificationId)
throws IllegalStateException {
if (isAnyConsumerBound()) {
throw new IllegalStateException("May not be called after consumers are already bound.");
}
if (notification == null) {
throw new NullPointerException("Notification cannot be null");
}
setEnableScheduledScanJobs(false);
mForegroundServiceNotification = notification;
mForegroundServiceNotificationId = notificationId;
} | [
"public",
"void",
"enableForegroundServiceScanning",
"(",
"Notification",
"notification",
",",
"int",
"notificationId",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"isAnyConsumerBound",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"May not be called after consumers are already bound.\"",
")",
";",
"}",
"if",
"(",
"notification",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Notification cannot be null\"",
")",
";",
"}",
"setEnableScheduledScanJobs",
"(",
"false",
")",
";",
"mForegroundServiceNotification",
"=",
"notification",
";",
"mForegroundServiceNotificationId",
"=",
"notificationId",
";",
"}"
] | Configures the library to use a foreground service for bacon scanning. This allows nearly
constant scanning on most Android versions to get around background limits, and displays an
icon to the user to indicate that the app is doing something in the background, even on
Android 8+. This will disable the user of the JobScheduler on Android 8 to do scans. Note
that this method does not by itself enable constant scanning. The scan intervals will work
as normal and must be configurd to specific values depending on how often you wish to scan.
@see #setForegroundScanPeriod(long)
@see #setForegroundBetweenScanPeriod(long)
This method requires a notification to display a message to the user about why the app is
scanning in the background. The notification must include an icon that will be displayed
in the top bar whenever the scanning service is running.
If the BeaconService is configured to run in a different process, this call will have no
effect.
@param notification - the notification that will be displayed when beacon scanning is active,
along with the icon that shows up in the status bar.
@throws IllegalStateException if called after consumers are already bound to the scanning
service | [
"Configures",
"the",
"library",
"to",
"use",
"a",
"foreground",
"service",
"for",
"bacon",
"scanning",
".",
"This",
"allows",
"nearly",
"constant",
"scanning",
"on",
"most",
"Android",
"versions",
"to",
"get",
"around",
"background",
"limits",
"and",
"displays",
"an",
"icon",
"to",
"the",
"user",
"to",
"indicate",
"that",
"the",
"app",
"is",
"doing",
"something",
"in",
"the",
"background",
"even",
"on",
"Android",
"8",
"+",
".",
"This",
"will",
"disable",
"the",
"user",
"of",
"the",
"JobScheduler",
"on",
"Android",
"8",
"to",
"do",
"scans",
".",
"Note",
"that",
"this",
"method",
"does",
"not",
"by",
"itself",
"enable",
"constant",
"scanning",
".",
"The",
"scan",
"intervals",
"will",
"work",
"as",
"normal",
"and",
"must",
"be",
"configurd",
"to",
"specific",
"values",
"depending",
"on",
"how",
"often",
"you",
"wish",
"to",
"scan",
"."
] | train | https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/BeaconManager.java#L1393-L1404 |
leadware/jpersistence-tools | jpersistence-tools-api/src/main/java/net/leadware/persistence/tools/api/utils/RestrictionsContainer.java | RestrictionsContainer.addGt | public <Y extends Comparable<? super Y>> RestrictionsContainer addGt(String property, Y value) {
"""
Methode d'ajout de la restriction GT
@param property Nom de la Propriete
@param value Valeur de la propriete
@param <Y> Type de valeur
@return Conteneur
"""
// Ajout de la restriction
restrictions.add(new Gt<Y>(property, value));
// On retourne le conteneur
return this;
} | java | public <Y extends Comparable<? super Y>> RestrictionsContainer addGt(String property, Y value) {
// Ajout de la restriction
restrictions.add(new Gt<Y>(property, value));
// On retourne le conteneur
return this;
} | [
"public",
"<",
"Y",
"extends",
"Comparable",
"<",
"?",
"super",
"Y",
">",
">",
"RestrictionsContainer",
"addGt",
"(",
"String",
"property",
",",
"Y",
"value",
")",
"{",
"// Ajout de la restriction\r",
"restrictions",
".",
"add",
"(",
"new",
"Gt",
"<",
"Y",
">",
"(",
"property",
",",
"value",
")",
")",
";",
"// On retourne le conteneur\r",
"return",
"this",
";",
"}"
] | Methode d'ajout de la restriction GT
@param property Nom de la Propriete
@param value Valeur de la propriete
@param <Y> Type de valeur
@return Conteneur | [
"Methode",
"d",
"ajout",
"de",
"la",
"restriction",
"GT"
] | train | https://github.com/leadware/jpersistence-tools/blob/4c15372993584579d7dbb9b23dd4c0c0fdc9e789/jpersistence-tools-api/src/main/java/net/leadware/persistence/tools/api/utils/RestrictionsContainer.java#L137-L144 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/metadata/Utils.java | Utils.compareQNameLists | public static boolean compareQNameLists(List<QName> list1, List<QName> list2) {
"""
Compares two lists of QNames for equality.
@param list1
@param list2
@return true iff each list contains the same QName values in the same order
"""
if (list1 == list2)
return true;
if (list1 == null || list2 == null)
return false;
if (list1.size() != list2.size())
return false;
for (int i = 0; i < list1.size(); i++) {
if (!compareQNames(list1.get(i), list2.get(i)))
return false;
}
return true;
} | java | public static boolean compareQNameLists(List<QName> list1, List<QName> list2) {
if (list1 == list2)
return true;
if (list1 == null || list2 == null)
return false;
if (list1.size() != list2.size())
return false;
for (int i = 0; i < list1.size(); i++) {
if (!compareQNames(list1.get(i), list2.get(i)))
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"compareQNameLists",
"(",
"List",
"<",
"QName",
">",
"list1",
",",
"List",
"<",
"QName",
">",
"list2",
")",
"{",
"if",
"(",
"list1",
"==",
"list2",
")",
"return",
"true",
";",
"if",
"(",
"list1",
"==",
"null",
"||",
"list2",
"==",
"null",
")",
"return",
"false",
";",
"if",
"(",
"list1",
".",
"size",
"(",
")",
"!=",
"list2",
".",
"size",
"(",
")",
")",
"return",
"false",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"list1",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"compareQNames",
"(",
"list1",
".",
"get",
"(",
"i",
")",
",",
"list2",
".",
"get",
"(",
"i",
")",
")",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Compares two lists of QNames for equality.
@param list1
@param list2
@return true iff each list contains the same QName values in the same order | [
"Compares",
"two",
"lists",
"of",
"QNames",
"for",
"equality",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/metadata/Utils.java#L99-L113 |
cryptomator/cryptofs | src/main/java/org/cryptomator/cryptofs/ConflictResolver.java | ConflictResolver.renameConflictingFile | private Path renameConflictingFile(Path canonicalPath, Path conflictingPath, String ciphertext, String dirId, String dirPrefix) throws IOException {
"""
Resolves a conflict by renaming the conflicting file.
@param canonicalPath The path to the original (conflict-free) file.
@param conflictingPath The path to the potentially conflicting file.
@param ciphertext The (previously inflated) ciphertext name of the file without any preceeding directory prefix.
@param dirId The directory id of the file's parent directory.
@param dirPrefix The directory prefix (if the conflicting file is a directory file) or an empty string.
@return The new path after renaming the conflicting file.
@throws IOException
"""
try {
String cleartext = cryptor.fileNameCryptor().decryptFilename(ciphertext, dirId.getBytes(StandardCharsets.UTF_8));
Path alternativePath = canonicalPath;
for (int i = 1; Files.exists(alternativePath); i++) {
String alternativeCleartext = cleartext + " (Conflict " + i + ")";
String alternativeCiphertext = cryptor.fileNameCryptor().encryptFilename(alternativeCleartext, dirId.getBytes(StandardCharsets.UTF_8));
String alternativeCiphertextFileName = dirPrefix + alternativeCiphertext;
if (alternativeCiphertextFileName.length() > SHORT_NAMES_MAX_LENGTH) {
alternativeCiphertextFileName = longFileNameProvider.deflate(alternativeCiphertextFileName);
}
alternativePath = canonicalPath.resolveSibling(alternativeCiphertextFileName);
}
LOG.info("Moving conflicting file {} to {}", conflictingPath, alternativePath);
return Files.move(conflictingPath, alternativePath, StandardCopyOption.ATOMIC_MOVE);
} catch (AuthenticationFailedException e) {
// not decryptable, no need to resolve any kind of conflict
LOG.info("Found valid Base32 string, which is an unauthentic ciphertext: {}", conflictingPath);
return conflictingPath;
}
} | java | private Path renameConflictingFile(Path canonicalPath, Path conflictingPath, String ciphertext, String dirId, String dirPrefix) throws IOException {
try {
String cleartext = cryptor.fileNameCryptor().decryptFilename(ciphertext, dirId.getBytes(StandardCharsets.UTF_8));
Path alternativePath = canonicalPath;
for (int i = 1; Files.exists(alternativePath); i++) {
String alternativeCleartext = cleartext + " (Conflict " + i + ")";
String alternativeCiphertext = cryptor.fileNameCryptor().encryptFilename(alternativeCleartext, dirId.getBytes(StandardCharsets.UTF_8));
String alternativeCiphertextFileName = dirPrefix + alternativeCiphertext;
if (alternativeCiphertextFileName.length() > SHORT_NAMES_MAX_LENGTH) {
alternativeCiphertextFileName = longFileNameProvider.deflate(alternativeCiphertextFileName);
}
alternativePath = canonicalPath.resolveSibling(alternativeCiphertextFileName);
}
LOG.info("Moving conflicting file {} to {}", conflictingPath, alternativePath);
return Files.move(conflictingPath, alternativePath, StandardCopyOption.ATOMIC_MOVE);
} catch (AuthenticationFailedException e) {
// not decryptable, no need to resolve any kind of conflict
LOG.info("Found valid Base32 string, which is an unauthentic ciphertext: {}", conflictingPath);
return conflictingPath;
}
} | [
"private",
"Path",
"renameConflictingFile",
"(",
"Path",
"canonicalPath",
",",
"Path",
"conflictingPath",
",",
"String",
"ciphertext",
",",
"String",
"dirId",
",",
"String",
"dirPrefix",
")",
"throws",
"IOException",
"{",
"try",
"{",
"String",
"cleartext",
"=",
"cryptor",
".",
"fileNameCryptor",
"(",
")",
".",
"decryptFilename",
"(",
"ciphertext",
",",
"dirId",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"Path",
"alternativePath",
"=",
"canonicalPath",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"Files",
".",
"exists",
"(",
"alternativePath",
")",
";",
"i",
"++",
")",
"{",
"String",
"alternativeCleartext",
"=",
"cleartext",
"+",
"\" (Conflict \"",
"+",
"i",
"+",
"\")\"",
";",
"String",
"alternativeCiphertext",
"=",
"cryptor",
".",
"fileNameCryptor",
"(",
")",
".",
"encryptFilename",
"(",
"alternativeCleartext",
",",
"dirId",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"String",
"alternativeCiphertextFileName",
"=",
"dirPrefix",
"+",
"alternativeCiphertext",
";",
"if",
"(",
"alternativeCiphertextFileName",
".",
"length",
"(",
")",
">",
"SHORT_NAMES_MAX_LENGTH",
")",
"{",
"alternativeCiphertextFileName",
"=",
"longFileNameProvider",
".",
"deflate",
"(",
"alternativeCiphertextFileName",
")",
";",
"}",
"alternativePath",
"=",
"canonicalPath",
".",
"resolveSibling",
"(",
"alternativeCiphertextFileName",
")",
";",
"}",
"LOG",
".",
"info",
"(",
"\"Moving conflicting file {} to {}\"",
",",
"conflictingPath",
",",
"alternativePath",
")",
";",
"return",
"Files",
".",
"move",
"(",
"conflictingPath",
",",
"alternativePath",
",",
"StandardCopyOption",
".",
"ATOMIC_MOVE",
")",
";",
"}",
"catch",
"(",
"AuthenticationFailedException",
"e",
")",
"{",
"// not decryptable, no need to resolve any kind of conflict",
"LOG",
".",
"info",
"(",
"\"Found valid Base32 string, which is an unauthentic ciphertext: {}\"",
",",
"conflictingPath",
")",
";",
"return",
"conflictingPath",
";",
"}",
"}"
] | Resolves a conflict by renaming the conflicting file.
@param canonicalPath The path to the original (conflict-free) file.
@param conflictingPath The path to the potentially conflicting file.
@param ciphertext The (previously inflated) ciphertext name of the file without any preceeding directory prefix.
@param dirId The directory id of the file's parent directory.
@param dirPrefix The directory prefix (if the conflicting file is a directory file) or an empty string.
@return The new path after renaming the conflicting file.
@throws IOException | [
"Resolves",
"a",
"conflict",
"by",
"renaming",
"the",
"conflicting",
"file",
"."
] | train | https://github.com/cryptomator/cryptofs/blob/67fc1a4950dd1c150cd2e2c75bcabbeb7c9ac82e/src/main/java/org/cryptomator/cryptofs/ConflictResolver.java#L110-L130 |
fuinorg/objects4j | src/main/java/org/fuin/objects4j/ui/AnnotationAnalyzer.java | AnnotationAnalyzer.createClassInfo | public final ClassTextInfo createClassInfo(@NotNull final Class<?> clasz, @NotNull final Locale locale,
@NotNull final Class<? extends Annotation> annotationClasz) {
"""
Returns the text information for a given class.
@param clasz
Class.
@param locale
Locale to use.
@param annotationClasz
Type of annotation to find.
@return Label information - Never <code>null</code>.
"""
Contract.requireArgNotNull("clasz", clasz);
Contract.requireArgNotNull("locale", locale);
Contract.requireArgNotNull("annotationClasz", annotationClasz);
final Annotation annotation = clasz.getAnnotation(annotationClasz);
if (annotation == null) {
return null;
}
try {
final ResourceBundle bundle = getResourceBundle(annotation, locale, clasz);
final String text = getText(bundle, annotation, clasz.getSimpleName() + "." + annotationClasz.getSimpleName());
return new ClassTextInfo(clasz, text);
} catch (final MissingResourceException ex) {
if (getValue(annotation).equals("")) {
return new ClassTextInfo(clasz, null);
}
return new ClassTextInfo(clasz, getValue(annotation));
}
} | java | public final ClassTextInfo createClassInfo(@NotNull final Class<?> clasz, @NotNull final Locale locale,
@NotNull final Class<? extends Annotation> annotationClasz) {
Contract.requireArgNotNull("clasz", clasz);
Contract.requireArgNotNull("locale", locale);
Contract.requireArgNotNull("annotationClasz", annotationClasz);
final Annotation annotation = clasz.getAnnotation(annotationClasz);
if (annotation == null) {
return null;
}
try {
final ResourceBundle bundle = getResourceBundle(annotation, locale, clasz);
final String text = getText(bundle, annotation, clasz.getSimpleName() + "." + annotationClasz.getSimpleName());
return new ClassTextInfo(clasz, text);
} catch (final MissingResourceException ex) {
if (getValue(annotation).equals("")) {
return new ClassTextInfo(clasz, null);
}
return new ClassTextInfo(clasz, getValue(annotation));
}
} | [
"public",
"final",
"ClassTextInfo",
"createClassInfo",
"(",
"@",
"NotNull",
"final",
"Class",
"<",
"?",
">",
"clasz",
",",
"@",
"NotNull",
"final",
"Locale",
"locale",
",",
"@",
"NotNull",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClasz",
")",
"{",
"Contract",
".",
"requireArgNotNull",
"(",
"\"clasz\"",
",",
"clasz",
")",
";",
"Contract",
".",
"requireArgNotNull",
"(",
"\"locale\"",
",",
"locale",
")",
";",
"Contract",
".",
"requireArgNotNull",
"(",
"\"annotationClasz\"",
",",
"annotationClasz",
")",
";",
"final",
"Annotation",
"annotation",
"=",
"clasz",
".",
"getAnnotation",
"(",
"annotationClasz",
")",
";",
"if",
"(",
"annotation",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"final",
"ResourceBundle",
"bundle",
"=",
"getResourceBundle",
"(",
"annotation",
",",
"locale",
",",
"clasz",
")",
";",
"final",
"String",
"text",
"=",
"getText",
"(",
"bundle",
",",
"annotation",
",",
"clasz",
".",
"getSimpleName",
"(",
")",
"+",
"\".\"",
"+",
"annotationClasz",
".",
"getSimpleName",
"(",
")",
")",
";",
"return",
"new",
"ClassTextInfo",
"(",
"clasz",
",",
"text",
")",
";",
"}",
"catch",
"(",
"final",
"MissingResourceException",
"ex",
")",
"{",
"if",
"(",
"getValue",
"(",
"annotation",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"return",
"new",
"ClassTextInfo",
"(",
"clasz",
",",
"null",
")",
";",
"}",
"return",
"new",
"ClassTextInfo",
"(",
"clasz",
",",
"getValue",
"(",
"annotation",
")",
")",
";",
"}",
"}"
] | Returns the text information for a given class.
@param clasz
Class.
@param locale
Locale to use.
@param annotationClasz
Type of annotation to find.
@return Label information - Never <code>null</code>. | [
"Returns",
"the",
"text",
"information",
"for",
"a",
"given",
"class",
"."
] | train | https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/ui/AnnotationAnalyzer.java#L69-L92 |
astrapi69/mystic-crypt | crypt-data/src/main/java/de/alpharogroup/crypto/key/writer/PrivateKeyWriter.java | PrivateKeyWriter.writeInPemFormat | public static void writeInPemFormat(final PrivateKey privateKey, final @NonNull File file)
throws IOException {
"""
Write the given {@link PrivateKey} into the given {@link File}.
@param privateKey
the private key
@param file
the file to write in
@throws IOException
Signals that an I/O exception has occurred.
"""
KeyWriter.writeInPemFormat(privateKey, file);
} | java | public static void writeInPemFormat(final PrivateKey privateKey, final @NonNull File file)
throws IOException
{
KeyWriter.writeInPemFormat(privateKey, file);
} | [
"public",
"static",
"void",
"writeInPemFormat",
"(",
"final",
"PrivateKey",
"privateKey",
",",
"final",
"@",
"NonNull",
"File",
"file",
")",
"throws",
"IOException",
"{",
"KeyWriter",
".",
"writeInPemFormat",
"(",
"privateKey",
",",
"file",
")",
";",
"}"
] | Write the given {@link PrivateKey} into the given {@link File}.
@param privateKey
the private key
@param file
the file to write in
@throws IOException
Signals that an I/O exception has occurred. | [
"Write",
"the",
"given",
"{",
"@link",
"PrivateKey",
"}",
"into",
"the",
"given",
"{",
"@link",
"File",
"}",
"."
] | train | https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/key/writer/PrivateKeyWriter.java#L93-L97 |
datacleaner/DataCleaner | engine/env/spark/src/main/java/org/datacleaner/spark/utils/HadoopUtils.java | HadoopUtils.getDirectoryIfExists | private static File getDirectoryIfExists(final File existingCandidate, final String path) {
"""
Gets a candidate directory based on a file path, if it exists, and if it
another candidate hasn't already been resolved.
@param existingCandidate
an existing candidate directory. If this is non-null, it will
be returned immediately.
@param path
the path of a directory
@return a candidate directory, or null if none was resolved.
"""
if (existingCandidate != null) {
return existingCandidate;
}
if (!Strings.isNullOrEmpty(path)) {
final File directory = new File(path);
if (directory.exists() && directory.isDirectory()) {
return directory;
}
}
return null;
} | java | private static File getDirectoryIfExists(final File existingCandidate, final String path) {
if (existingCandidate != null) {
return existingCandidate;
}
if (!Strings.isNullOrEmpty(path)) {
final File directory = new File(path);
if (directory.exists() && directory.isDirectory()) {
return directory;
}
}
return null;
} | [
"private",
"static",
"File",
"getDirectoryIfExists",
"(",
"final",
"File",
"existingCandidate",
",",
"final",
"String",
"path",
")",
"{",
"if",
"(",
"existingCandidate",
"!=",
"null",
")",
"{",
"return",
"existingCandidate",
";",
"}",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"path",
")",
")",
"{",
"final",
"File",
"directory",
"=",
"new",
"File",
"(",
"path",
")",
";",
"if",
"(",
"directory",
".",
"exists",
"(",
")",
"&&",
"directory",
".",
"isDirectory",
"(",
")",
")",
"{",
"return",
"directory",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Gets a candidate directory based on a file path, if it exists, and if it
another candidate hasn't already been resolved.
@param existingCandidate
an existing candidate directory. If this is non-null, it will
be returned immediately.
@param path
the path of a directory
@return a candidate directory, or null if none was resolved. | [
"Gets",
"a",
"candidate",
"directory",
"based",
"on",
"a",
"file",
"path",
"if",
"it",
"exists",
"and",
"if",
"it",
"another",
"candidate",
"hasn",
"t",
"already",
"been",
"resolved",
"."
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/env/spark/src/main/java/org/datacleaner/spark/utils/HadoopUtils.java#L53-L64 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java | ByteConverter.float8 | public static void float8(byte[] target, int idx, double value) {
"""
Encodes a int value to the byte array.
@param target The byte array to encode to.
@param idx The starting index in the byte array.
@param value The value to encode.
"""
int8(target, idx, Double.doubleToRawLongBits(value));
} | java | public static void float8(byte[] target, int idx, double value) {
int8(target, idx, Double.doubleToRawLongBits(value));
} | [
"public",
"static",
"void",
"float8",
"(",
"byte",
"[",
"]",
"target",
",",
"int",
"idx",
",",
"double",
"value",
")",
"{",
"int8",
"(",
"target",
",",
"idx",
",",
"Double",
".",
"doubleToRawLongBits",
"(",
"value",
")",
")",
";",
"}"
] | Encodes a int value to the byte array.
@param target The byte array to encode to.
@param idx The starting index in the byte array.
@param value The value to encode. | [
"Encodes",
"a",
"int",
"value",
"to",
"the",
"byte",
"array",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/util/ByteConverter.java#L175-L177 |
bluelinelabs/Conductor | conductor/src/main/java/com/bluelinelabs/conductor/Router.java | Router.onRequestPermissionsResult | public void onRequestPermissionsResult(@NonNull String instanceId, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
"""
This should be called by the host Activity when its onRequestPermissionsResult method is called. The call will be forwarded
to the {@link Controller} with the instanceId passed in.
@param instanceId The instanceId of the Controller to which this result should be forwarded
@param requestCode The Activity's onRequestPermissionsResult requestCode
@param permissions The Activity's onRequestPermissionsResult permissions
@param grantResults The Activity's onRequestPermissionsResult grantResults
"""
Controller controller = getControllerWithInstanceId(instanceId);
if (controller != null) {
controller.requestPermissionsResult(requestCode, permissions, grantResults);
}
} | java | public void onRequestPermissionsResult(@NonNull String instanceId, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Controller controller = getControllerWithInstanceId(instanceId);
if (controller != null) {
controller.requestPermissionsResult(requestCode, permissions, grantResults);
}
} | [
"public",
"void",
"onRequestPermissionsResult",
"(",
"@",
"NonNull",
"String",
"instanceId",
",",
"int",
"requestCode",
",",
"@",
"NonNull",
"String",
"[",
"]",
"permissions",
",",
"@",
"NonNull",
"int",
"[",
"]",
"grantResults",
")",
"{",
"Controller",
"controller",
"=",
"getControllerWithInstanceId",
"(",
"instanceId",
")",
";",
"if",
"(",
"controller",
"!=",
"null",
")",
"{",
"controller",
".",
"requestPermissionsResult",
"(",
"requestCode",
",",
"permissions",
",",
"grantResults",
")",
";",
"}",
"}"
] | This should be called by the host Activity when its onRequestPermissionsResult method is called. The call will be forwarded
to the {@link Controller} with the instanceId passed in.
@param instanceId The instanceId of the Controller to which this result should be forwarded
@param requestCode The Activity's onRequestPermissionsResult requestCode
@param permissions The Activity's onRequestPermissionsResult permissions
@param grantResults The Activity's onRequestPermissionsResult grantResults | [
"This",
"should",
"be",
"called",
"by",
"the",
"host",
"Activity",
"when",
"its",
"onRequestPermissionsResult",
"method",
"is",
"called",
".",
"The",
"call",
"will",
"be",
"forwarded",
"to",
"the",
"{",
"@link",
"Controller",
"}",
"with",
"the",
"instanceId",
"passed",
"in",
"."
] | train | https://github.com/bluelinelabs/Conductor/blob/94c9121bb16f93b481954513a8e3905846829fb2/conductor/src/main/java/com/bluelinelabs/conductor/Router.java#L77-L82 |
stephanenicolas/robospice | robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java | SpiceManager.putDataInCache | public <T> Future<T> putDataInCache(final Object cacheKey, final T data) throws CacheSavingException, CacheCreationException {
"""
Put some new data in cache using cache key <i>requestCacheKey</i>. This
method doesn't perform any network processing, it just data in cache,
erasing any previsouly saved date in cache using the same class and key.
Don't call this method in the main thread because you could block it.
Instead, use the asynchronous version of this method:
{@link #putInCache(Class, Object, Object)}.
@param cacheKey
the key used to store and retrieve the result of the request
in the cache
@param data
the data to be saved in cache.
@return the data has it has been saved by an ObjectPersister in cache.
@throws CacheLoadingException
Exception thrown when a problem occurs while loading data
from cache.
"""
return executeCommand(new PutDataInCacheCommand<T>(this, data, cacheKey));
} | java | public <T> Future<T> putDataInCache(final Object cacheKey, final T data) throws CacheSavingException, CacheCreationException {
return executeCommand(new PutDataInCacheCommand<T>(this, data, cacheKey));
} | [
"public",
"<",
"T",
">",
"Future",
"<",
"T",
">",
"putDataInCache",
"(",
"final",
"Object",
"cacheKey",
",",
"final",
"T",
"data",
")",
"throws",
"CacheSavingException",
",",
"CacheCreationException",
"{",
"return",
"executeCommand",
"(",
"new",
"PutDataInCacheCommand",
"<",
"T",
">",
"(",
"this",
",",
"data",
",",
"cacheKey",
")",
")",
";",
"}"
] | Put some new data in cache using cache key <i>requestCacheKey</i>. This
method doesn't perform any network processing, it just data in cache,
erasing any previsouly saved date in cache using the same class and key.
Don't call this method in the main thread because you could block it.
Instead, use the asynchronous version of this method:
{@link #putInCache(Class, Object, Object)}.
@param cacheKey
the key used to store and retrieve the result of the request
in the cache
@param data
the data to be saved in cache.
@return the data has it has been saved by an ObjectPersister in cache.
@throws CacheLoadingException
Exception thrown when a problem occurs while loading data
from cache. | [
"Put",
"some",
"new",
"data",
"in",
"cache",
"using",
"cache",
"key",
"<i",
">",
"requestCacheKey<",
"/",
"i",
">",
".",
"This",
"method",
"doesn",
"t",
"perform",
"any",
"network",
"processing",
"it",
"just",
"data",
"in",
"cache",
"erasing",
"any",
"previsouly",
"saved",
"date",
"in",
"cache",
"using",
"the",
"same",
"class",
"and",
"key",
".",
"Don",
"t",
"call",
"this",
"method",
"in",
"the",
"main",
"thread",
"because",
"you",
"could",
"block",
"it",
".",
"Instead",
"use",
"the",
"asynchronous",
"version",
"of",
"this",
"method",
":",
"{"
] | train | https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java#L925-L927 |
michael-rapp/AndroidUtil | library/src/main/java/de/mrapp/android/util/FileUtil.java | FileUtil.createNewFile | public static void createNewFile(@NonNull final File file, final boolean overwrite)
throws IOException {
"""
Creates a new, empty file.
@param file
The file, which should be created, as an instance of the class {@link File}. The file
may not be null. If the file is a directory, an {@link IllegalArgumentException} will
be thrown
@param overwrite
True, if the file should be overwritten, if it does already exist, false otherwise
@throws IOException
The exception, which is thrown, if an error occurs while creating the file
"""
Condition.INSTANCE.ensureNotNull(file, "The file may not be null");
boolean result = file.createNewFile();
if (!result) {
if (overwrite) {
try {
delete(file);
createNewFile(file, false);
} catch (IOException e) {
throw new IOException("Failed to overwrite file \"" + file + "\"");
}
} else if (file.exists()) {
throw new IOException("File \"" + file + "\" does already exist");
} else {
throw new IllegalArgumentException("The file must not be a directory");
}
}
} | java | public static void createNewFile(@NonNull final File file, final boolean overwrite)
throws IOException {
Condition.INSTANCE.ensureNotNull(file, "The file may not be null");
boolean result = file.createNewFile();
if (!result) {
if (overwrite) {
try {
delete(file);
createNewFile(file, false);
} catch (IOException e) {
throw new IOException("Failed to overwrite file \"" + file + "\"");
}
} else if (file.exists()) {
throw new IOException("File \"" + file + "\" does already exist");
} else {
throw new IllegalArgumentException("The file must not be a directory");
}
}
} | [
"public",
"static",
"void",
"createNewFile",
"(",
"@",
"NonNull",
"final",
"File",
"file",
",",
"final",
"boolean",
"overwrite",
")",
"throws",
"IOException",
"{",
"Condition",
".",
"INSTANCE",
".",
"ensureNotNull",
"(",
"file",
",",
"\"The file may not be null\"",
")",
";",
"boolean",
"result",
"=",
"file",
".",
"createNewFile",
"(",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"if",
"(",
"overwrite",
")",
"{",
"try",
"{",
"delete",
"(",
"file",
")",
";",
"createNewFile",
"(",
"file",
",",
"false",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to overwrite file \\\"\"",
"+",
"file",
"+",
"\"\\\"\"",
")",
";",
"}",
"}",
"else",
"if",
"(",
"file",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"File \\\"\"",
"+",
"file",
"+",
"\"\\\" does already exist\"",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The file must not be a directory\"",
")",
";",
"}",
"}",
"}"
] | Creates a new, empty file.
@param file
The file, which should be created, as an instance of the class {@link File}. The file
may not be null. If the file is a directory, an {@link IllegalArgumentException} will
be thrown
@param overwrite
True, if the file should be overwritten, if it does already exist, false otherwise
@throws IOException
The exception, which is thrown, if an error occurs while creating the file | [
"Creates",
"a",
"new",
"empty",
"file",
"."
] | train | https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/FileUtil.java#L162-L181 |
intuit/QuickBooks-V3-Java-SDK | ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/SerializeInterceptor.java | SerializeInterceptor.getUploadFileContent | private byte[] getUploadFileContent(RequestElements requestElements) throws FMSException {
"""
Method to get the file content of the upload file based on the mime type
@param requestElements the request elements
@return byte[] the upload file content
@throws FMSException
"""
Attachable attachable = (Attachable) requestElements.getEntity();
InputStream docContent = requestElements.getUploadRequestElements().getDocContent();
// gets the mime value form the filename
String mime = getMime(attachable.getFileName(), ".");
// if null then gets the mime value from content-type of the file
mime = (mime != null) ? mime : getMime(attachable.getContentType(), "/");
if (isImageType(mime)) {
return getImageContent(docContent, mime);
} else {
return getContent(docContent);
}
} | java | private byte[] getUploadFileContent(RequestElements requestElements) throws FMSException {
Attachable attachable = (Attachable) requestElements.getEntity();
InputStream docContent = requestElements.getUploadRequestElements().getDocContent();
// gets the mime value form the filename
String mime = getMime(attachable.getFileName(), ".");
// if null then gets the mime value from content-type of the file
mime = (mime != null) ? mime : getMime(attachable.getContentType(), "/");
if (isImageType(mime)) {
return getImageContent(docContent, mime);
} else {
return getContent(docContent);
}
} | [
"private",
"byte",
"[",
"]",
"getUploadFileContent",
"(",
"RequestElements",
"requestElements",
")",
"throws",
"FMSException",
"{",
"Attachable",
"attachable",
"=",
"(",
"Attachable",
")",
"requestElements",
".",
"getEntity",
"(",
")",
";",
"InputStream",
"docContent",
"=",
"requestElements",
".",
"getUploadRequestElements",
"(",
")",
".",
"getDocContent",
"(",
")",
";",
"// gets the mime value form the filename",
"String",
"mime",
"=",
"getMime",
"(",
"attachable",
".",
"getFileName",
"(",
")",
",",
"\".\"",
")",
";",
"// if null then gets the mime value from content-type of the file",
"mime",
"=",
"(",
"mime",
"!=",
"null",
")",
"?",
"mime",
":",
"getMime",
"(",
"attachable",
".",
"getContentType",
"(",
")",
",",
"\"/\"",
")",
";",
"if",
"(",
"isImageType",
"(",
"mime",
")",
")",
"{",
"return",
"getImageContent",
"(",
"docContent",
",",
"mime",
")",
";",
"}",
"else",
"{",
"return",
"getContent",
"(",
"docContent",
")",
";",
"}",
"}"
] | Method to get the file content of the upload file based on the mime type
@param requestElements the request elements
@return byte[] the upload file content
@throws FMSException | [
"Method",
"to",
"get",
"the",
"file",
"content",
"of",
"the",
"upload",
"file",
"based",
"on",
"the",
"mime",
"type"
] | train | https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/SerializeInterceptor.java#L111-L124 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/internal/OperationFuture.java | OperationFuture.getStatus | public OperationStatus getStatus() {
"""
Get the current status of this operation.
Note that the operation status may change as the operation is tried and
potentially retried against the servers specified by the NodeLocator.
The interrupted status of the current thread is cleared by this method.
Inspect the returned OperationStatus to check whether an interruption has taken place.
@return OperationStatus
"""
if (status == null) {
try {
get();
} catch (InterruptedException e) {
status = new OperationStatus(false, "Interrupted", StatusCode.INTERRUPTED);
} catch (ExecutionException e) {
getLogger().warn("Error getting status of operation", e);
}
}
return status;
} | java | public OperationStatus getStatus() {
if (status == null) {
try {
get();
} catch (InterruptedException e) {
status = new OperationStatus(false, "Interrupted", StatusCode.INTERRUPTED);
} catch (ExecutionException e) {
getLogger().warn("Error getting status of operation", e);
}
}
return status;
} | [
"public",
"OperationStatus",
"getStatus",
"(",
")",
"{",
"if",
"(",
"status",
"==",
"null",
")",
"{",
"try",
"{",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"status",
"=",
"new",
"OperationStatus",
"(",
"false",
",",
"\"Interrupted\"",
",",
"StatusCode",
".",
"INTERRUPTED",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"getLogger",
"(",
")",
".",
"warn",
"(",
"\"Error getting status of operation\"",
",",
"e",
")",
";",
"}",
"}",
"return",
"status",
";",
"}"
] | Get the current status of this operation.
Note that the operation status may change as the operation is tried and
potentially retried against the servers specified by the NodeLocator.
The interrupted status of the current thread is cleared by this method.
Inspect the returned OperationStatus to check whether an interruption has taken place.
@return OperationStatus | [
"Get",
"the",
"current",
"status",
"of",
"this",
"operation",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/internal/OperationFuture.java#L245-L256 |
redkale/redkale | src/org/redkale/net/http/HttpRequest.java | HttpRequest.getLongParameter | public long getLongParameter(int radix, String name, long defaultValue) {
"""
获取指定的参数long值, 没有返回默认long值
@param radix 进制数
@param name 参数名
@param defaultValue 默认long值
@return 参数值
"""
parseBody();
return params.getLongValue(radix, name, defaultValue);
} | java | public long getLongParameter(int radix, String name, long defaultValue) {
parseBody();
return params.getLongValue(radix, name, defaultValue);
} | [
"public",
"long",
"getLongParameter",
"(",
"int",
"radix",
",",
"String",
"name",
",",
"long",
"defaultValue",
")",
"{",
"parseBody",
"(",
")",
";",
"return",
"params",
".",
"getLongValue",
"(",
"radix",
",",
"name",
",",
"defaultValue",
")",
";",
"}"
] | 获取指定的参数long值, 没有返回默认long值
@param radix 进制数
@param name 参数名
@param defaultValue 默认long值
@return 参数值 | [
"获取指定的参数long值",
"没有返回默认long值"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/net/http/HttpRequest.java#L1408-L1411 |
deeplearning4j/deeplearning4j | datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/WarpImageTransform.java | WarpImageTransform.doTransform | @Override
protected ImageWritable doTransform(ImageWritable image, Random random) {
"""
Takes an image and returns a transformed image.
Uses the random object in the case of random transformations.
@param image to transform, null == end of stream
@param random object to use (or null for deterministic)
@return transformed image
"""
if (image == null) {
return null;
}
Mat mat = converter.convert(image.getFrame());
Point2f src = new Point2f(4);
Point2f dst = new Point2f(4);
src.put(0, 0, mat.cols(), 0, mat.cols(), mat.rows(), 0, mat.rows());
for (int i = 0; i < 8; i++) {
dst.put(i, src.get(i) + deltas[i] * (random != null ? 2 * random.nextFloat() - 1 : 1));
}
Mat result = new Mat();
M = getPerspectiveTransform(src, dst);
warpPerspective(mat, result, M, mat.size(), interMode, borderMode, borderValue);
return new ImageWritable(converter.convert(result));
} | java | @Override
protected ImageWritable doTransform(ImageWritable image, Random random) {
if (image == null) {
return null;
}
Mat mat = converter.convert(image.getFrame());
Point2f src = new Point2f(4);
Point2f dst = new Point2f(4);
src.put(0, 0, mat.cols(), 0, mat.cols(), mat.rows(), 0, mat.rows());
for (int i = 0; i < 8; i++) {
dst.put(i, src.get(i) + deltas[i] * (random != null ? 2 * random.nextFloat() - 1 : 1));
}
Mat result = new Mat();
M = getPerspectiveTransform(src, dst);
warpPerspective(mat, result, M, mat.size(), interMode, borderMode, borderValue);
return new ImageWritable(converter.convert(result));
} | [
"@",
"Override",
"protected",
"ImageWritable",
"doTransform",
"(",
"ImageWritable",
"image",
",",
"Random",
"random",
")",
"{",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Mat",
"mat",
"=",
"converter",
".",
"convert",
"(",
"image",
".",
"getFrame",
"(",
")",
")",
";",
"Point2f",
"src",
"=",
"new",
"Point2f",
"(",
"4",
")",
";",
"Point2f",
"dst",
"=",
"new",
"Point2f",
"(",
"4",
")",
";",
"src",
".",
"put",
"(",
"0",
",",
"0",
",",
"mat",
".",
"cols",
"(",
")",
",",
"0",
",",
"mat",
".",
"cols",
"(",
")",
",",
"mat",
".",
"rows",
"(",
")",
",",
"0",
",",
"mat",
".",
"rows",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
")",
"{",
"dst",
".",
"put",
"(",
"i",
",",
"src",
".",
"get",
"(",
"i",
")",
"+",
"deltas",
"[",
"i",
"]",
"*",
"(",
"random",
"!=",
"null",
"?",
"2",
"*",
"random",
".",
"nextFloat",
"(",
")",
"-",
"1",
":",
"1",
")",
")",
";",
"}",
"Mat",
"result",
"=",
"new",
"Mat",
"(",
")",
";",
"M",
"=",
"getPerspectiveTransform",
"(",
"src",
",",
"dst",
")",
";",
"warpPerspective",
"(",
"mat",
",",
"result",
",",
"M",
",",
"mat",
".",
"size",
"(",
")",
",",
"interMode",
",",
"borderMode",
",",
"borderValue",
")",
";",
"return",
"new",
"ImageWritable",
"(",
"converter",
".",
"convert",
"(",
"result",
")",
")",
";",
"}"
] | Takes an image and returns a transformed image.
Uses the random object in the case of random transformations.
@param image to transform, null == end of stream
@param random object to use (or null for deterministic)
@return transformed image | [
"Takes",
"an",
"image",
"and",
"returns",
"a",
"transformed",
"image",
".",
"Uses",
"the",
"random",
"object",
"in",
"the",
"case",
"of",
"random",
"transformations",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/WarpImageTransform.java#L119-L137 |
json-path/JsonPath | json-path/src/main/java/com/jayway/jsonpath/internal/function/PathFunctionFactory.java | PathFunctionFactory.newFunction | public static PathFunction newFunction(String name) throws InvalidPathException {
"""
Returns the function by name or throws InvalidPathException if function not found.
@see #FUNCTIONS
@see PathFunction
@param name
The name of the function
@return
The implementation of a function
@throws InvalidPathException
"""
Class functionClazz = FUNCTIONS.get(name);
if(functionClazz == null){
throw new InvalidPathException("Function with name: " + name + " does not exist.");
} else {
try {
return (PathFunction)functionClazz.newInstance();
} catch (Exception e) {
throw new InvalidPathException("Function of name: " + name + " cannot be created", e);
}
}
} | java | public static PathFunction newFunction(String name) throws InvalidPathException {
Class functionClazz = FUNCTIONS.get(name);
if(functionClazz == null){
throw new InvalidPathException("Function with name: " + name + " does not exist.");
} else {
try {
return (PathFunction)functionClazz.newInstance();
} catch (Exception e) {
throw new InvalidPathException("Function of name: " + name + " cannot be created", e);
}
}
} | [
"public",
"static",
"PathFunction",
"newFunction",
"(",
"String",
"name",
")",
"throws",
"InvalidPathException",
"{",
"Class",
"functionClazz",
"=",
"FUNCTIONS",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"functionClazz",
"==",
"null",
")",
"{",
"throw",
"new",
"InvalidPathException",
"(",
"\"Function with name: \"",
"+",
"name",
"+",
"\" does not exist.\"",
")",
";",
"}",
"else",
"{",
"try",
"{",
"return",
"(",
"PathFunction",
")",
"functionClazz",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"InvalidPathException",
"(",
"\"Function of name: \"",
"+",
"name",
"+",
"\" cannot be created\"",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Returns the function by name or throws InvalidPathException if function not found.
@see #FUNCTIONS
@see PathFunction
@param name
The name of the function
@return
The implementation of a function
@throws InvalidPathException | [
"Returns",
"the",
"function",
"by",
"name",
"or",
"throws",
"InvalidPathException",
"if",
"function",
"not",
"found",
"."
] | train | https://github.com/json-path/JsonPath/blob/5a09489c3252b74bbf81992aadb3073be59c04f9/json-path/src/main/java/com/jayway/jsonpath/internal/function/PathFunctionFactory.java#L66-L77 |
Baidu-AIP/java-sdk | src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java | AipImageSearch.sameHqUpdateContSign | public JSONObject sameHqUpdateContSign(String contSign, HashMap<String, String> options) {
"""
相同图检索—更新接口
**更新图库中图片的摘要和分类信息(具体变量为brief、tags)**
@param contSign - 图片签名
@param options - 可选参数对象,key: value都为string类型
options - options列表:
brief 更新的摘要信息,最长256B。样例:{"name":"周杰伦", "id":"666"}
tags 1 - 65535范围内的整数,tag间以逗号分隔,最多2个tag。样例:"100,11" ;检索时可圈定分类维度进行检索
@return JSONObject
"""
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("cont_sign", contSign);
if (options != null) {
request.addBody(options);
}
request.setUri(ImageSearchConsts.SAME_HQ_UPDATE);
postOperation(request);
return requestServer(request);
} | java | public JSONObject sameHqUpdateContSign(String contSign, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("cont_sign", contSign);
if (options != null) {
request.addBody(options);
}
request.setUri(ImageSearchConsts.SAME_HQ_UPDATE);
postOperation(request);
return requestServer(request);
} | [
"public",
"JSONObject",
"sameHqUpdateContSign",
"(",
"String",
"contSign",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"options",
")",
"{",
"AipRequest",
"request",
"=",
"new",
"AipRequest",
"(",
")",
";",
"preOperation",
"(",
"request",
")",
";",
"request",
".",
"addBody",
"(",
"\"cont_sign\"",
",",
"contSign",
")",
";",
"if",
"(",
"options",
"!=",
"null",
")",
"{",
"request",
".",
"addBody",
"(",
"options",
")",
";",
"}",
"request",
".",
"setUri",
"(",
"ImageSearchConsts",
".",
"SAME_HQ_UPDATE",
")",
";",
"postOperation",
"(",
"request",
")",
";",
"return",
"requestServer",
"(",
"request",
")",
";",
"}"
] | 相同图检索—更新接口
**更新图库中图片的摘要和分类信息(具体变量为brief、tags)**
@param contSign - 图片签名
@param options - 可选参数对象,key: value都为string类型
options - options列表:
brief 更新的摘要信息,最长256B。样例:{"name":"周杰伦", "id":"666"}
tags 1 - 65535范围内的整数,tag间以逗号分隔,最多2个tag。样例:"100,11" ;检索时可圈定分类维度进行检索
@return JSONObject | [
"相同图检索—更新接口",
"**",
"更新图库中图片的摘要和分类信息(具体变量为brief、tags)",
"**"
] | train | https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java#L259-L270 |
Azure/azure-sdk-for-java | resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java | ResourcesInner.getById | public GenericResourceInner getById(String resourceId, String apiVersion) {
"""
Gets a resource by ID.
@param resourceId The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}
@param apiVersion The API version to use for the operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the GenericResourceInner object if successful.
"""
return getByIdWithServiceResponseAsync(resourceId, apiVersion).toBlocking().single().body();
} | java | public GenericResourceInner getById(String resourceId, String apiVersion) {
return getByIdWithServiceResponseAsync(resourceId, apiVersion).toBlocking().single().body();
} | [
"public",
"GenericResourceInner",
"getById",
"(",
"String",
"resourceId",
",",
"String",
"apiVersion",
")",
"{",
"return",
"getByIdWithServiceResponseAsync",
"(",
"resourceId",
",",
"apiVersion",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Gets a resource by ID.
@param resourceId The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name}
@param apiVersion The API version to use for the operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the GenericResourceInner object if successful. | [
"Gets",
"a",
"resource",
"by",
"ID",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L2390-L2392 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/TrueTypeFont.java | TrueTypeFont.getFontDescriptor | public float getFontDescriptor(int key, float fontSize) {
"""
Gets the font parameter identified by <CODE>key</CODE>. Valid values
for <CODE>key</CODE> are <CODE>ASCENT</CODE>, <CODE>CAPHEIGHT</CODE>, <CODE>DESCENT</CODE>
and <CODE>ITALICANGLE</CODE>.
@param key the parameter to be extracted
@param fontSize the font size in points
@return the parameter in points
"""
switch (key) {
case ASCENT:
return os_2.sTypoAscender * fontSize / head.unitsPerEm;
case CAPHEIGHT:
return os_2.sCapHeight * fontSize / head.unitsPerEm;
case DESCENT:
return os_2.sTypoDescender * fontSize / head.unitsPerEm;
case ITALICANGLE:
return (float)italicAngle;
case BBOXLLX:
return fontSize * head.xMin / head.unitsPerEm;
case BBOXLLY:
return fontSize * head.yMin / head.unitsPerEm;
case BBOXURX:
return fontSize * head.xMax / head.unitsPerEm;
case BBOXURY:
return fontSize * head.yMax / head.unitsPerEm;
case AWT_ASCENT:
return fontSize * hhea.Ascender / head.unitsPerEm;
case AWT_DESCENT:
return fontSize * hhea.Descender / head.unitsPerEm;
case AWT_LEADING:
return fontSize * hhea.LineGap / head.unitsPerEm;
case AWT_MAXADVANCE:
return fontSize * hhea.advanceWidthMax / head.unitsPerEm;
case UNDERLINE_POSITION:
return (underlinePosition - underlineThickness / 2) * fontSize / head.unitsPerEm;
case UNDERLINE_THICKNESS:
return underlineThickness * fontSize / head.unitsPerEm;
case STRIKETHROUGH_POSITION:
return os_2.yStrikeoutPosition * fontSize / head.unitsPerEm;
case STRIKETHROUGH_THICKNESS:
return os_2.yStrikeoutSize * fontSize / head.unitsPerEm;
case SUBSCRIPT_SIZE:
return os_2.ySubscriptYSize * fontSize / head.unitsPerEm;
case SUBSCRIPT_OFFSET:
return -os_2.ySubscriptYOffset * fontSize / head.unitsPerEm;
case SUPERSCRIPT_SIZE:
return os_2.ySuperscriptYSize * fontSize / head.unitsPerEm;
case SUPERSCRIPT_OFFSET:
return os_2.ySuperscriptYOffset * fontSize / head.unitsPerEm;
}
return 0;
} | java | public float getFontDescriptor(int key, float fontSize) {
switch (key) {
case ASCENT:
return os_2.sTypoAscender * fontSize / head.unitsPerEm;
case CAPHEIGHT:
return os_2.sCapHeight * fontSize / head.unitsPerEm;
case DESCENT:
return os_2.sTypoDescender * fontSize / head.unitsPerEm;
case ITALICANGLE:
return (float)italicAngle;
case BBOXLLX:
return fontSize * head.xMin / head.unitsPerEm;
case BBOXLLY:
return fontSize * head.yMin / head.unitsPerEm;
case BBOXURX:
return fontSize * head.xMax / head.unitsPerEm;
case BBOXURY:
return fontSize * head.yMax / head.unitsPerEm;
case AWT_ASCENT:
return fontSize * hhea.Ascender / head.unitsPerEm;
case AWT_DESCENT:
return fontSize * hhea.Descender / head.unitsPerEm;
case AWT_LEADING:
return fontSize * hhea.LineGap / head.unitsPerEm;
case AWT_MAXADVANCE:
return fontSize * hhea.advanceWidthMax / head.unitsPerEm;
case UNDERLINE_POSITION:
return (underlinePosition - underlineThickness / 2) * fontSize / head.unitsPerEm;
case UNDERLINE_THICKNESS:
return underlineThickness * fontSize / head.unitsPerEm;
case STRIKETHROUGH_POSITION:
return os_2.yStrikeoutPosition * fontSize / head.unitsPerEm;
case STRIKETHROUGH_THICKNESS:
return os_2.yStrikeoutSize * fontSize / head.unitsPerEm;
case SUBSCRIPT_SIZE:
return os_2.ySubscriptYSize * fontSize / head.unitsPerEm;
case SUBSCRIPT_OFFSET:
return -os_2.ySubscriptYOffset * fontSize / head.unitsPerEm;
case SUPERSCRIPT_SIZE:
return os_2.ySuperscriptYSize * fontSize / head.unitsPerEm;
case SUPERSCRIPT_OFFSET:
return os_2.ySuperscriptYOffset * fontSize / head.unitsPerEm;
}
return 0;
} | [
"public",
"float",
"getFontDescriptor",
"(",
"int",
"key",
",",
"float",
"fontSize",
")",
"{",
"switch",
"(",
"key",
")",
"{",
"case",
"ASCENT",
":",
"return",
"os_2",
".",
"sTypoAscender",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"CAPHEIGHT",
":",
"return",
"os_2",
".",
"sCapHeight",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"DESCENT",
":",
"return",
"os_2",
".",
"sTypoDescender",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"ITALICANGLE",
":",
"return",
"(",
"float",
")",
"italicAngle",
";",
"case",
"BBOXLLX",
":",
"return",
"fontSize",
"*",
"head",
".",
"xMin",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"BBOXLLY",
":",
"return",
"fontSize",
"*",
"head",
".",
"yMin",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"BBOXURX",
":",
"return",
"fontSize",
"*",
"head",
".",
"xMax",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"BBOXURY",
":",
"return",
"fontSize",
"*",
"head",
".",
"yMax",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"AWT_ASCENT",
":",
"return",
"fontSize",
"*",
"hhea",
".",
"Ascender",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"AWT_DESCENT",
":",
"return",
"fontSize",
"*",
"hhea",
".",
"Descender",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"AWT_LEADING",
":",
"return",
"fontSize",
"*",
"hhea",
".",
"LineGap",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"AWT_MAXADVANCE",
":",
"return",
"fontSize",
"*",
"hhea",
".",
"advanceWidthMax",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"UNDERLINE_POSITION",
":",
"return",
"(",
"underlinePosition",
"-",
"underlineThickness",
"/",
"2",
")",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"UNDERLINE_THICKNESS",
":",
"return",
"underlineThickness",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"STRIKETHROUGH_POSITION",
":",
"return",
"os_2",
".",
"yStrikeoutPosition",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"STRIKETHROUGH_THICKNESS",
":",
"return",
"os_2",
".",
"yStrikeoutSize",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"SUBSCRIPT_SIZE",
":",
"return",
"os_2",
".",
"ySubscriptYSize",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"SUBSCRIPT_OFFSET",
":",
"return",
"-",
"os_2",
".",
"ySubscriptYOffset",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"SUPERSCRIPT_SIZE",
":",
"return",
"os_2",
".",
"ySuperscriptYSize",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"case",
"SUPERSCRIPT_OFFSET",
":",
"return",
"os_2",
".",
"ySuperscriptYOffset",
"*",
"fontSize",
"/",
"head",
".",
"unitsPerEm",
";",
"}",
"return",
"0",
";",
"}"
] | Gets the font parameter identified by <CODE>key</CODE>. Valid values
for <CODE>key</CODE> are <CODE>ASCENT</CODE>, <CODE>CAPHEIGHT</CODE>, <CODE>DESCENT</CODE>
and <CODE>ITALICANGLE</CODE>.
@param key the parameter to be extracted
@param fontSize the font size in points
@return the parameter in points | [
"Gets",
"the",
"font",
"parameter",
"identified",
"by",
"<CODE",
">",
"key<",
"/",
"CODE",
">",
".",
"Valid",
"values",
"for",
"<CODE",
">",
"key<",
"/",
"CODE",
">",
"are",
"<CODE",
">",
"ASCENT<",
"/",
"CODE",
">",
"<CODE",
">",
"CAPHEIGHT<",
"/",
"CODE",
">",
"<CODE",
">",
"DESCENT<",
"/",
"CODE",
">",
"and",
"<CODE",
">",
"ITALICANGLE<",
"/",
"CODE",
">",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/TrueTypeFont.java#L1357-L1401 |
Appendium/objectlabkit | utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java | ConsoleMenu.getBoolean | public static boolean getBoolean(final String title, final boolean defaultValue) {
"""
Gets a boolean from the System.in
@param title
for the command line
@return boolean as selected by the user of the console app
"""
final String val = ConsoleMenu.selectOne(title, new String[] { "Yes", "No" },
new String[] { Boolean.TRUE.toString(), Boolean.FALSE.toString() }, defaultValue ? 1 : 2);
return Boolean.valueOf(val);
} | java | public static boolean getBoolean(final String title, final boolean defaultValue) {
final String val = ConsoleMenu.selectOne(title, new String[] { "Yes", "No" },
new String[] { Boolean.TRUE.toString(), Boolean.FALSE.toString() }, defaultValue ? 1 : 2);
return Boolean.valueOf(val);
} | [
"public",
"static",
"boolean",
"getBoolean",
"(",
"final",
"String",
"title",
",",
"final",
"boolean",
"defaultValue",
")",
"{",
"final",
"String",
"val",
"=",
"ConsoleMenu",
".",
"selectOne",
"(",
"title",
",",
"new",
"String",
"[",
"]",
"{",
"\"Yes\"",
",",
"\"No\"",
"}",
",",
"new",
"String",
"[",
"]",
"{",
"Boolean",
".",
"TRUE",
".",
"toString",
"(",
")",
",",
"Boolean",
".",
"FALSE",
".",
"toString",
"(",
")",
"}",
",",
"defaultValue",
"?",
"1",
":",
"2",
")",
";",
"return",
"Boolean",
".",
"valueOf",
"(",
"val",
")",
";",
"}"
] | Gets a boolean from the System.in
@param title
for the command line
@return boolean as selected by the user of the console app | [
"Gets",
"a",
"boolean",
"from",
"the",
"System",
".",
"in"
] | train | https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java#L244-L249 |
qspin/qtaste | kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java | TextUtilities.findWordStart | public static int findWordStart(String text, int pos, String noWordSep, boolean joinNonWordChars) {
"""
Locates the start of the word at the specified position.
@param text the text
@param pos The position
@param noWordSep Characters that are non-alphanumeric, but
should be treated as word characters anyway
@param joinNonWordChars Treat consecutive non-alphanumeric
characters as one word
"""
return findWordStart(text, pos, noWordSep, joinNonWordChars, false);
} | java | public static int findWordStart(String text, int pos, String noWordSep, boolean joinNonWordChars) {
return findWordStart(text, pos, noWordSep, joinNonWordChars, false);
} | [
"public",
"static",
"int",
"findWordStart",
"(",
"String",
"text",
",",
"int",
"pos",
",",
"String",
"noWordSep",
",",
"boolean",
"joinNonWordChars",
")",
"{",
"return",
"findWordStart",
"(",
"text",
",",
"pos",
",",
"noWordSep",
",",
"joinNonWordChars",
",",
"false",
")",
";",
"}"
] | Locates the start of the word at the specified position.
@param text the text
@param pos The position
@param noWordSep Characters that are non-alphanumeric, but
should be treated as word characters anyway
@param joinNonWordChars Treat consecutive non-alphanumeric
characters as one word | [
"Locates",
"the",
"start",
"of",
"the",
"word",
"at",
"the",
"specified",
"position",
"."
] | train | https://github.com/qspin/qtaste/blob/ba45d4d86eb29b92f157c6e98536dee2002ddfdc/kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java#L48-L50 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/util/POIUtils.java | POIUtils.getMergedRegion | public static CellRangeAddress getMergedRegion(final Sheet sheet, final int rowIdx, final int colIdx) {
"""
指定したセルのアドレスの結合情報を取得する。
@since 0.5
@param sheet シート情報
@param rowIdx 行番号
@param colIdx 列番号
@return 結合していない場合nullを返す。
"""
ArgUtils.notNull(sheet, "sheet");
final int num = sheet.getNumMergedRegions();
for(int i=0; i < num; i ++) {
final CellRangeAddress range = sheet.getMergedRegion(i);
if(range.isInRange(rowIdx, colIdx)) {
return range;
}
}
return null;
} | java | public static CellRangeAddress getMergedRegion(final Sheet sheet, final int rowIdx, final int colIdx) {
ArgUtils.notNull(sheet, "sheet");
final int num = sheet.getNumMergedRegions();
for(int i=0; i < num; i ++) {
final CellRangeAddress range = sheet.getMergedRegion(i);
if(range.isInRange(rowIdx, colIdx)) {
return range;
}
}
return null;
} | [
"public",
"static",
"CellRangeAddress",
"getMergedRegion",
"(",
"final",
"Sheet",
"sheet",
",",
"final",
"int",
"rowIdx",
",",
"final",
"int",
"colIdx",
")",
"{",
"ArgUtils",
".",
"notNull",
"(",
"sheet",
",",
"\"sheet\"",
")",
";",
"final",
"int",
"num",
"=",
"sheet",
".",
"getNumMergedRegions",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
")",
"{",
"final",
"CellRangeAddress",
"range",
"=",
"sheet",
".",
"getMergedRegion",
"(",
"i",
")",
";",
"if",
"(",
"range",
".",
"isInRange",
"(",
"rowIdx",
",",
"colIdx",
")",
")",
"{",
"return",
"range",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | 指定したセルのアドレスの結合情報を取得する。
@since 0.5
@param sheet シート情報
@param rowIdx 行番号
@param colIdx 列番号
@return 結合していない場合nullを返す。 | [
"指定したセルのアドレスの結合情報を取得する。"
] | train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/POIUtils.java#L364-L376 |
jenetics/jenetics | jenetics/src/main/java/io/jenetics/engine/Limits.java | Limits.bySteadyFitness | public static <C extends Comparable<? super C>>
Predicate<EvolutionResult<?, C>> bySteadyFitness(final int generations) {
"""
Return a predicate, which will truncate the evolution stream if no
better phenotype could be found after the given number of
{@code generations}.
<pre>{@code
final Phenotype<DoubleGene, Double> result = engine.stream()
// Truncate the evolution stream after 5 "steady" generations.
.limit(bySteadyFitness(5))
// The evolution will stop after maximal 100 generations.
.limit(100)
.collect(toBestPhenotype());
}</pre>
@param generations the number of <i>steady</i> generations
@param <C> the fitness type
@return a predicate which truncate the evolution stream if no better
phenotype could be found after a give number of
{@code generations}
@throws IllegalArgumentException if the generation is smaller than
one.
"""
return new SteadyFitnessLimit<>(generations);
} | java | public static <C extends Comparable<? super C>>
Predicate<EvolutionResult<?, C>> bySteadyFitness(final int generations) {
return new SteadyFitnessLimit<>(generations);
} | [
"public",
"static",
"<",
"C",
"extends",
"Comparable",
"<",
"?",
"super",
"C",
">",
">",
"Predicate",
"<",
"EvolutionResult",
"<",
"?",
",",
"C",
">",
">",
"bySteadyFitness",
"(",
"final",
"int",
"generations",
")",
"{",
"return",
"new",
"SteadyFitnessLimit",
"<>",
"(",
"generations",
")",
";",
"}"
] | Return a predicate, which will truncate the evolution stream if no
better phenotype could be found after the given number of
{@code generations}.
<pre>{@code
final Phenotype<DoubleGene, Double> result = engine.stream()
// Truncate the evolution stream after 5 "steady" generations.
.limit(bySteadyFitness(5))
// The evolution will stop after maximal 100 generations.
.limit(100)
.collect(toBestPhenotype());
}</pre>
@param generations the number of <i>steady</i> generations
@param <C> the fitness type
@return a predicate which truncate the evolution stream if no better
phenotype could be found after a give number of
{@code generations}
@throws IllegalArgumentException if the generation is smaller than
one. | [
"Return",
"a",
"predicate",
"which",
"will",
"truncate",
"the",
"evolution",
"stream",
"if",
"no",
"better",
"phenotype",
"could",
"be",
"found",
"after",
"the",
"given",
"number",
"of",
"{",
"@code",
"generations",
"}",
"."
] | train | https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/engine/Limits.java#L116-L119 |
OpenTSDB/opentsdb | src/tsd/HttpJsonSerializer.java | HttpJsonSerializer.formatQueryV1 | public ChannelBuffer formatQueryV1(final TSQuery data_query,
final List<DataPoints[]> results, final List<Annotation> globals) {
"""
Format the results from a timeseries data query
@param data_query The TSQuery object used to fetch the results
@param results The data fetched from storage
@param globals An optional list of global annotation objects
@return A ChannelBuffer object to pass on to the caller
"""
try {
return formatQueryAsyncV1(data_query, results, globals)
.joinUninterruptibly();
} catch (QueryException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Shouldn't be here", e);
}
} | java | public ChannelBuffer formatQueryV1(final TSQuery data_query,
final List<DataPoints[]> results, final List<Annotation> globals) {
try {
return formatQueryAsyncV1(data_query, results, globals)
.joinUninterruptibly();
} catch (QueryException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Shouldn't be here", e);
}
} | [
"public",
"ChannelBuffer",
"formatQueryV1",
"(",
"final",
"TSQuery",
"data_query",
",",
"final",
"List",
"<",
"DataPoints",
"[",
"]",
">",
"results",
",",
"final",
"List",
"<",
"Annotation",
">",
"globals",
")",
"{",
"try",
"{",
"return",
"formatQueryAsyncV1",
"(",
"data_query",
",",
"results",
",",
"globals",
")",
".",
"joinUninterruptibly",
"(",
")",
";",
"}",
"catch",
"(",
"QueryException",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Shouldn't be here\"",
",",
"e",
")",
";",
"}",
"}"
] | Format the results from a timeseries data query
@param data_query The TSQuery object used to fetch the results
@param results The data fetched from storage
@param globals An optional list of global annotation objects
@return A ChannelBuffer object to pass on to the caller | [
"Format",
"the",
"results",
"from",
"a",
"timeseries",
"data",
"query"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/HttpJsonSerializer.java#L620-L630 |
ldapchai/ldapchai | src/main/java/com/novell/ldapchai/util/ConfigObjectRecord.java | ConfigObjectRecord.parseString | public static ConfigObjectRecord parseString( final String input ) {
"""
Read a string value and convert to a {@code ConfigObjectRecord}.
@param input a complete config object record string including type, guids and payload.
@return A COR parsed from the <i>inputString</i>
"""
final ConfigObjectRecord cor = new ConfigObjectRecord();
try
{
cor.parseObjectRecord( input );
}
catch ( Exception e )
{
throw new IllegalArgumentException( "Data value is mailformed, invalid ConfigObjectRecord '" + input + "'" );
}
return cor;
} | java | public static ConfigObjectRecord parseString( final String input )
{
final ConfigObjectRecord cor = new ConfigObjectRecord();
try
{
cor.parseObjectRecord( input );
}
catch ( Exception e )
{
throw new IllegalArgumentException( "Data value is mailformed, invalid ConfigObjectRecord '" + input + "'" );
}
return cor;
} | [
"public",
"static",
"ConfigObjectRecord",
"parseString",
"(",
"final",
"String",
"input",
")",
"{",
"final",
"ConfigObjectRecord",
"cor",
"=",
"new",
"ConfigObjectRecord",
"(",
")",
";",
"try",
"{",
"cor",
".",
"parseObjectRecord",
"(",
"input",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Data value is mailformed, invalid ConfigObjectRecord '\"",
"+",
"input",
"+",
"\"'\"",
")",
";",
"}",
"return",
"cor",
";",
"}"
] | Read a string value and convert to a {@code ConfigObjectRecord}.
@param input a complete config object record string including type, guids and payload.
@return A COR parsed from the <i>inputString</i> | [
"Read",
"a",
"string",
"value",
"and",
"convert",
"to",
"a",
"{",
"@code",
"ConfigObjectRecord",
"}",
"."
] | train | https://github.com/ldapchai/ldapchai/blob/a6d4b5dbfa4e270db0ce70892512cbe39e64b874/src/main/java/com/novell/ldapchai/util/ConfigObjectRecord.java#L206-L218 |
auth0/auth0-java | src/main/java/com/auth0/client/auth/AuthAPI.java | AuthAPI.requestToken | public AuthRequest requestToken(String audience) {
"""
Creates a request to get a Token for the given audience using the 'Client Credentials' grant.
Default used realm is defined in the "API Authorization Settings" in the account's advanced settings in the Auth0 Dashboard.
<pre>
{@code
AuthAPI auth = new AuthAPI("me.auth0.com", "B3c6RYhk1v9SbIJcRIOwu62gIUGsnze", "2679NfkaBn62e6w5E8zNEzjr-yWfkaBne");
try {
TokenHolder result = auth.requestToken("https://myapi.me.auth0.com/users")
.setRealm("my-realm")
.execute();
} catch (Auth0Exception e) {
//Something happened
}
}
</pre>
@param audience the audience of the API to request access to.
@return a Request to configure and execute.
"""
Asserts.assertNotNull(audience, "audience");
String url = baseUrl
.newBuilder()
.addPathSegment(PATH_OAUTH)
.addPathSegment(PATH_TOKEN)
.build()
.toString();
TokenRequest request = new TokenRequest(client, url);
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_CLIENT_SECRET, clientSecret);
request.addParameter(KEY_GRANT_TYPE, "client_credentials");
request.addParameter(KEY_AUDIENCE, audience);
return request;
} | java | public AuthRequest requestToken(String audience) {
Asserts.assertNotNull(audience, "audience");
String url = baseUrl
.newBuilder()
.addPathSegment(PATH_OAUTH)
.addPathSegment(PATH_TOKEN)
.build()
.toString();
TokenRequest request = new TokenRequest(client, url);
request.addParameter(KEY_CLIENT_ID, clientId);
request.addParameter(KEY_CLIENT_SECRET, clientSecret);
request.addParameter(KEY_GRANT_TYPE, "client_credentials");
request.addParameter(KEY_AUDIENCE, audience);
return request;
} | [
"public",
"AuthRequest",
"requestToken",
"(",
"String",
"audience",
")",
"{",
"Asserts",
".",
"assertNotNull",
"(",
"audience",
",",
"\"audience\"",
")",
";",
"String",
"url",
"=",
"baseUrl",
".",
"newBuilder",
"(",
")",
".",
"addPathSegment",
"(",
"PATH_OAUTH",
")",
".",
"addPathSegment",
"(",
"PATH_TOKEN",
")",
".",
"build",
"(",
")",
".",
"toString",
"(",
")",
";",
"TokenRequest",
"request",
"=",
"new",
"TokenRequest",
"(",
"client",
",",
"url",
")",
";",
"request",
".",
"addParameter",
"(",
"KEY_CLIENT_ID",
",",
"clientId",
")",
";",
"request",
".",
"addParameter",
"(",
"KEY_CLIENT_SECRET",
",",
"clientSecret",
")",
";",
"request",
".",
"addParameter",
"(",
"KEY_GRANT_TYPE",
",",
"\"client_credentials\"",
")",
";",
"request",
".",
"addParameter",
"(",
"KEY_AUDIENCE",
",",
"audience",
")",
";",
"return",
"request",
";",
"}"
] | Creates a request to get a Token for the given audience using the 'Client Credentials' grant.
Default used realm is defined in the "API Authorization Settings" in the account's advanced settings in the Auth0 Dashboard.
<pre>
{@code
AuthAPI auth = new AuthAPI("me.auth0.com", "B3c6RYhk1v9SbIJcRIOwu62gIUGsnze", "2679NfkaBn62e6w5E8zNEzjr-yWfkaBne");
try {
TokenHolder result = auth.requestToken("https://myapi.me.auth0.com/users")
.setRealm("my-realm")
.execute();
} catch (Auth0Exception e) {
//Something happened
}
}
</pre>
@param audience the audience of the API to request access to.
@return a Request to configure and execute. | [
"Creates",
"a",
"request",
"to",
"get",
"a",
"Token",
"for",
"the",
"given",
"audience",
"using",
"the",
"Client",
"Credentials",
"grant",
".",
"Default",
"used",
"realm",
"is",
"defined",
"in",
"the",
"API",
"Authorization",
"Settings",
"in",
"the",
"account",
"s",
"advanced",
"settings",
"in",
"the",
"Auth0",
"Dashboard",
".",
"<pre",
">",
"{",
"@code",
"AuthAPI",
"auth",
"=",
"new",
"AuthAPI",
"(",
"me",
".",
"auth0",
".",
"com",
"B3c6RYhk1v9SbIJcRIOwu62gIUGsnze",
"2679NfkaBn62e6w5E8zNEzjr",
"-",
"yWfkaBne",
")",
";",
"try",
"{",
"TokenHolder",
"result",
"=",
"auth",
".",
"requestToken",
"(",
"https",
":",
"//",
"myapi",
".",
"me",
".",
"auth0",
".",
"com",
"/",
"users",
")",
".",
"setRealm",
"(",
"my",
"-",
"realm",
")",
".",
"execute",
"()",
";",
"}",
"catch",
"(",
"Auth0Exception",
"e",
")",
"{",
"//",
"Something",
"happened",
"}",
"}",
"<",
"/",
"pre",
">"
] | train | https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/auth/AuthAPI.java#L404-L419 |
tvesalainen/lpg | src/main/java/org/vesalainen/parser/util/CharInput.java | CharInput.getString | @Override
public String getString(long start, int length) {
"""
Returns string from buffer
@param start Start of input
@param length Length of input
@return
"""
if (length == 0)
{
return "";
}
if (array != null)
{
int ps = (int) (start % size);
int es = (int) ((start+length) % size);
if (ps < es)
{
return new String(array, ps, length);
}
else
{
StringBuilder sb = new StringBuilder();
sb.append(array, ps, size-ps);
sb.append(array, 0, es);
return sb.toString();
}
}
else
{
StringBuilder sb = new StringBuilder();
for (int ii=0;ii<length;ii++)
{
sb.append((char)get(start+ii));
}
return sb.toString();
}
} | java | @Override
public String getString(long start, int length)
{
if (length == 0)
{
return "";
}
if (array != null)
{
int ps = (int) (start % size);
int es = (int) ((start+length) % size);
if (ps < es)
{
return new String(array, ps, length);
}
else
{
StringBuilder sb = new StringBuilder();
sb.append(array, ps, size-ps);
sb.append(array, 0, es);
return sb.toString();
}
}
else
{
StringBuilder sb = new StringBuilder();
for (int ii=0;ii<length;ii++)
{
sb.append((char)get(start+ii));
}
return sb.toString();
}
} | [
"@",
"Override",
"public",
"String",
"getString",
"(",
"long",
"start",
",",
"int",
"length",
")",
"{",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
"\"\"",
";",
"}",
"if",
"(",
"array",
"!=",
"null",
")",
"{",
"int",
"ps",
"=",
"(",
"int",
")",
"(",
"start",
"%",
"size",
")",
";",
"int",
"es",
"=",
"(",
"int",
")",
"(",
"(",
"start",
"+",
"length",
")",
"%",
"size",
")",
";",
"if",
"(",
"ps",
"<",
"es",
")",
"{",
"return",
"new",
"String",
"(",
"array",
",",
"ps",
",",
"length",
")",
";",
"}",
"else",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"array",
",",
"ps",
",",
"size",
"-",
"ps",
")",
";",
"sb",
".",
"append",
"(",
"array",
",",
"0",
",",
"es",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}",
"else",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"length",
";",
"ii",
"++",
")",
"{",
"sb",
".",
"append",
"(",
"(",
"char",
")",
"get",
"(",
"start",
"+",
"ii",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | Returns string from buffer
@param start Start of input
@param length Length of input
@return | [
"Returns",
"string",
"from",
"buffer"
] | train | https://github.com/tvesalainen/lpg/blob/0917b8d295e9772b9f8a0affc258a08530cd567a/src/main/java/org/vesalainen/parser/util/CharInput.java#L154-L186 |
yatechorg/jedis-utils | src/main/java/org/yatech/jedis/utils/lua/LuaScriptBuilder.java | LuaScriptBuilder.endScriptReturn | public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) {
"""
End building the script, adding a return value statement
@param config the configuration for the script to build
@param value the value to return
@return the new {@link LuaScript} instance
"""
add(new LuaAstReturnStatement(argument(value)));
String scriptText = buildScriptText();
return new BasicLuaScript(scriptText, config);
} | java | public LuaScript endScriptReturn(LuaValue value, LuaScriptConfig config) {
add(new LuaAstReturnStatement(argument(value)));
String scriptText = buildScriptText();
return new BasicLuaScript(scriptText, config);
} | [
"public",
"LuaScript",
"endScriptReturn",
"(",
"LuaValue",
"value",
",",
"LuaScriptConfig",
"config",
")",
"{",
"add",
"(",
"new",
"LuaAstReturnStatement",
"(",
"argument",
"(",
"value",
")",
")",
")",
";",
"String",
"scriptText",
"=",
"buildScriptText",
"(",
")",
";",
"return",
"new",
"BasicLuaScript",
"(",
"scriptText",
",",
"config",
")",
";",
"}"
] | End building the script, adding a return value statement
@param config the configuration for the script to build
@param value the value to return
@return the new {@link LuaScript} instance | [
"End",
"building",
"the",
"script",
"adding",
"a",
"return",
"value",
"statement"
] | train | https://github.com/yatechorg/jedis-utils/blob/1951609fa6697df4f69be76e7d66b9284924bd97/src/main/java/org/yatech/jedis/utils/lua/LuaScriptBuilder.java#L100-L104 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/input/named/AbstractNamedInputHandler.java | AbstractNamedInputHandler.updateBean | protected T updateBean(T object, Map<String, Object> source) {
"""
Updates bean with values from source.
@param object Bean object to update
@param source Map which would be read
@return cloned bean with updated values
"""
T clone = copyProperties(object);
updateProperties(clone, source);
return clone;
} | java | protected T updateBean(T object, Map<String, Object> source) {
T clone = copyProperties(object);
updateProperties(clone, source);
return clone;
} | [
"protected",
"T",
"updateBean",
"(",
"T",
"object",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"source",
")",
"{",
"T",
"clone",
"=",
"copyProperties",
"(",
"object",
")",
";",
"updateProperties",
"(",
"clone",
",",
"source",
")",
";",
"return",
"clone",
";",
"}"
] | Updates bean with values from source.
@param object Bean object to update
@param source Map which would be read
@return cloned bean with updated values | [
"Updates",
"bean",
"with",
"values",
"from",
"source",
"."
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/input/named/AbstractNamedInputHandler.java#L88-L94 |
aoindustries/ao-taglib | src/main/java/com/aoindustries/taglib/AttributeUtils.java | AttributeUtils.resolveValue | public static <T> T resolveValue(Object value, Class<T> type, ELContext elContext) {
"""
Casts or evaluates an expression then casts to the provided type.
"""
if(value == null) {
return null;
} else if(value instanceof ValueExpression) {
return resolveValue((ValueExpression)value, type, elContext);
} else {
return type.cast(value);
}
} | java | public static <T> T resolveValue(Object value, Class<T> type, ELContext elContext) {
if(value == null) {
return null;
} else if(value instanceof ValueExpression) {
return resolveValue((ValueExpression)value, type, elContext);
} else {
return type.cast(value);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"resolveValue",
"(",
"Object",
"value",
",",
"Class",
"<",
"T",
">",
"type",
",",
"ELContext",
"elContext",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"ValueExpression",
")",
"{",
"return",
"resolveValue",
"(",
"(",
"ValueExpression",
")",
"value",
",",
"type",
",",
"elContext",
")",
";",
"}",
"else",
"{",
"return",
"type",
".",
"cast",
"(",
"value",
")",
";",
"}",
"}"
] | Casts or evaluates an expression then casts to the provided type. | [
"Casts",
"or",
"evaluates",
"an",
"expression",
"then",
"casts",
"to",
"the",
"provided",
"type",
"."
] | train | https://github.com/aoindustries/ao-taglib/blob/5670eba8485196bd42d31d3ff09a42deacb025f8/src/main/java/com/aoindustries/taglib/AttributeUtils.java#L61-L69 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-api/src/main/java/org/xwiki/component/util/ReflectionUtils.java | ReflectionUtils.getGenericClassType | public static Type getGenericClassType(Class clazz, Class filterClass) {
"""
Extract the real Type from the passed class. For example
<tt>public Class MyClass implements FilterClass<A, B>, SomeOtherClass<C></tt> will return
<tt>FilterClass<A, B>, SomeOtherClass<C></tt>.
@param clazz the class to extract from
@param filterClass the class of the generic type we're looking for
@return the real Type from the interfaces of the passed class, filtered by the passed filter class
@since 4.0M1
"""
for (Type type : clazz.getGenericInterfaces()) {
if (type == filterClass) {
return type;
} else if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
if (filterClass.isAssignableFrom((Class) pType.getRawType())) {
return type;
}
}
}
return null;
} | java | public static Type getGenericClassType(Class clazz, Class filterClass)
{
for (Type type : clazz.getGenericInterfaces()) {
if (type == filterClass) {
return type;
} else if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
if (filterClass.isAssignableFrom((Class) pType.getRawType())) {
return type;
}
}
}
return null;
} | [
"public",
"static",
"Type",
"getGenericClassType",
"(",
"Class",
"clazz",
",",
"Class",
"filterClass",
")",
"{",
"for",
"(",
"Type",
"type",
":",
"clazz",
".",
"getGenericInterfaces",
"(",
")",
")",
"{",
"if",
"(",
"type",
"==",
"filterClass",
")",
"{",
"return",
"type",
";",
"}",
"else",
"if",
"(",
"type",
"instanceof",
"ParameterizedType",
")",
"{",
"ParameterizedType",
"pType",
"=",
"(",
"ParameterizedType",
")",
"type",
";",
"if",
"(",
"filterClass",
".",
"isAssignableFrom",
"(",
"(",
"Class",
")",
"pType",
".",
"getRawType",
"(",
")",
")",
")",
"{",
"return",
"type",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Extract the real Type from the passed class. For example
<tt>public Class MyClass implements FilterClass<A, B>, SomeOtherClass<C></tt> will return
<tt>FilterClass<A, B>, SomeOtherClass<C></tt>.
@param clazz the class to extract from
@param filterClass the class of the generic type we're looking for
@return the real Type from the interfaces of the passed class, filtered by the passed filter class
@since 4.0M1 | [
"Extract",
"the",
"real",
"Type",
"from",
"the",
"passed",
"class",
".",
"For",
"example",
"<tt",
">",
"public",
"Class",
"MyClass",
"implements",
"FilterClass<",
";",
"A",
"B>",
";",
"SomeOtherClass<",
";",
"C>",
";",
"<",
"/",
"tt",
">",
"will",
"return",
"<tt",
">",
"FilterClass<",
";",
"A",
"B>",
";",
"SomeOtherClass<",
";",
"C>",
";",
"<",
"/",
"tt",
">",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-api/src/main/java/org/xwiki/component/util/ReflectionUtils.java#L267-L281 |
bozaro/git-lfs-java | gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java | Client.putObject | public boolean putObject(@NotNull final StreamProvider streamProvider, @NotNull final String hash, final long size) throws IOException {
"""
Upload object with specified hash and size.
@param streamProvider Object stream provider.
@param hash Object hash.
@param size Object size.
@return Return true is object is uploaded successfully and false if object is already uploaded.
@throws IOException On some errors.
"""
return putObject(streamProvider, new Meta(hash, size));
} | java | public boolean putObject(@NotNull final StreamProvider streamProvider, @NotNull final String hash, final long size) throws IOException {
return putObject(streamProvider, new Meta(hash, size));
} | [
"public",
"boolean",
"putObject",
"(",
"@",
"NotNull",
"final",
"StreamProvider",
"streamProvider",
",",
"@",
"NotNull",
"final",
"String",
"hash",
",",
"final",
"long",
"size",
")",
"throws",
"IOException",
"{",
"return",
"putObject",
"(",
"streamProvider",
",",
"new",
"Meta",
"(",
"hash",
",",
"size",
")",
")",
";",
"}"
] | Upload object with specified hash and size.
@param streamProvider Object stream provider.
@param hash Object hash.
@param size Object size.
@return Return true is object is uploaded successfully and false if object is already uploaded.
@throws IOException On some errors. | [
"Upload",
"object",
"with",
"specified",
"hash",
"and",
"size",
"."
] | train | https://github.com/bozaro/git-lfs-java/blob/ee05bf0472ee61bf362cf93d283e5ee5d44ef685/gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java#L202-L204 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/xml/hints/HintHandler.java | HintHandler.endElement | @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
"""
Handles the end element event.
@param uri the element's URI
@param localName the local name
@param qName the qualified name
@throws SAXException thrown if there is an exception processing the
element
"""
if (HINT.equals(qName) && rule != null) {
hintRules.add(rule);
rule = null;
}
} | java | @Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (HINT.equals(qName) && rule != null) {
hintRules.add(rule);
rule = null;
}
} | [
"@",
"Override",
"public",
"void",
"endElement",
"(",
"String",
"uri",
",",
"String",
"localName",
",",
"String",
"qName",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"HINT",
".",
"equals",
"(",
"qName",
")",
"&&",
"rule",
"!=",
"null",
")",
"{",
"hintRules",
".",
"add",
"(",
"rule",
")",
";",
"rule",
"=",
"null",
";",
"}",
"}"
] | Handles the end element event.
@param uri the element's URI
@param localName the local name
@param qName the qualified name
@throws SAXException thrown if there is an exception processing the
element | [
"Handles",
"the",
"end",
"element",
"event",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintHandler.java#L303-L309 |
apache/incubator-shardingsphere | sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java | ShardingRule.getLogicTableName | public String getLogicTableName(final String logicIndexName) {
"""
Get logic table name base on logic index name.
@param logicIndexName logic index name
@return logic table name
"""
for (TableRule each : tableRules) {
if (logicIndexName.equals(each.getLogicIndex())) {
return each.getLogicTable();
}
}
throw new ShardingConfigurationException("Cannot find logic table name with logic index name: '%s'", logicIndexName);
} | java | public String getLogicTableName(final String logicIndexName) {
for (TableRule each : tableRules) {
if (logicIndexName.equals(each.getLogicIndex())) {
return each.getLogicTable();
}
}
throw new ShardingConfigurationException("Cannot find logic table name with logic index name: '%s'", logicIndexName);
} | [
"public",
"String",
"getLogicTableName",
"(",
"final",
"String",
"logicIndexName",
")",
"{",
"for",
"(",
"TableRule",
"each",
":",
"tableRules",
")",
"{",
"if",
"(",
"logicIndexName",
".",
"equals",
"(",
"each",
".",
"getLogicIndex",
"(",
")",
")",
")",
"{",
"return",
"each",
".",
"getLogicTable",
"(",
")",
";",
"}",
"}",
"throw",
"new",
"ShardingConfigurationException",
"(",
"\"Cannot find logic table name with logic index name: '%s'\"",
",",
"logicIndexName",
")",
";",
"}"
] | Get logic table name base on logic index name.
@param logicIndexName logic index name
@return logic table name | [
"Get",
"logic",
"table",
"name",
"base",
"on",
"logic",
"index",
"name",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java#L372-L379 |
eclipse/xtext-lib | org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java | LongExtensions.operator_greaterThan | @Pure
@Inline(value="($1 > $2)", constantExpression=true)
public static boolean operator_greaterThan(long a, double b) {
"""
The binary <code>greaterThan</code> operator. This is the equivalent to the Java <code>></code> operator.
@param a a long.
@param b a double.
@return <code>a>b</code>
@since 2.3
"""
return a > b;
} | java | @Pure
@Inline(value="($1 > $2)", constantExpression=true)
public static boolean operator_greaterThan(long a, double b) {
return a > b;
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"($1 > $2)\"",
",",
"constantExpression",
"=",
"true",
")",
"public",
"static",
"boolean",
"operator_greaterThan",
"(",
"long",
"a",
",",
"double",
"b",
")",
"{",
"return",
"a",
">",
"b",
";",
"}"
] | The binary <code>greaterThan</code> operator. This is the equivalent to the Java <code>></code> operator.
@param a a long.
@param b a double.
@return <code>a>b</code>
@since 2.3 | [
"The",
"binary",
"<code",
">",
"greaterThan<",
"/",
"code",
">",
"operator",
".",
"This",
"is",
"the",
"equivalent",
"to",
"the",
"Java",
"<code",
">",
">",
";",
"<",
"/",
"code",
">",
"operator",
"."
] | train | https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/LongExtensions.java#L348-L352 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.writeResourceProjectLastModified | public void writeResourceProjectLastModified(CmsRequestContext context, CmsResource resource, CmsProject project)
throws CmsException {
"""
Writes the 'projectlastmodified' field of a resource record.<p>
@param context the current database context
@param resource the resource which should be modified
@param project the project whose project id should be written into the resource record
@throws CmsException if something goes wrong
"""
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkOfflineProject(dbc);
checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL);
m_driverManager.writeProjectLastModified(dbc, resource, project.getUuid());
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_WRITE_RESOURCE_1, context.getSitePath(resource)), e);
} finally {
dbc.clear();
}
} | java | public void writeResourceProjectLastModified(CmsRequestContext context, CmsResource resource, CmsProject project)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkOfflineProject(dbc);
checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL);
m_driverManager.writeProjectLastModified(dbc, resource, project.getUuid());
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_WRITE_RESOURCE_1, context.getSitePath(resource)), e);
} finally {
dbc.clear();
}
} | [
"public",
"void",
"writeResourceProjectLastModified",
"(",
"CmsRequestContext",
"context",
",",
"CmsResource",
"resource",
",",
"CmsProject",
"project",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"try",
"{",
"checkOfflineProject",
"(",
"dbc",
")",
";",
"checkPermissions",
"(",
"dbc",
",",
"resource",
",",
"CmsPermissionSet",
".",
"ACCESS_WRITE",
",",
"true",
",",
"CmsResourceFilter",
".",
"ALL",
")",
";",
"m_driverManager",
".",
"writeProjectLastModified",
"(",
"dbc",
",",
"resource",
",",
"project",
".",
"getUuid",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"dbc",
".",
"report",
"(",
"null",
",",
"Messages",
".",
"get",
"(",
")",
".",
"container",
"(",
"Messages",
".",
"ERR_WRITE_RESOURCE_1",
",",
"context",
".",
"getSitePath",
"(",
"resource",
")",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"dbc",
".",
"clear",
"(",
")",
";",
"}",
"}"
] | Writes the 'projectlastmodified' field of a resource record.<p>
@param context the current database context
@param resource the resource which should be modified
@param project the project whose project id should be written into the resource record
@throws CmsException if something goes wrong | [
"Writes",
"the",
"projectlastmodified",
"field",
"of",
"a",
"resource",
"record",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L6886-L6899 |
Azure/azure-sdk-for-java | kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java | DatabasesInner.listPrincipalsAsync | public Observable<List<DatabasePrincipalInner>> listPrincipalsAsync(String resourceGroupName, String clusterName, String databaseName) {
"""
Returns a list of database principals of the given Kusto cluster and database.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@param databaseName The name of the database in the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<DatabasePrincipalInner> object
"""
return listPrincipalsWithServiceResponseAsync(resourceGroupName, clusterName, databaseName).map(new Func1<ServiceResponse<List<DatabasePrincipalInner>>, List<DatabasePrincipalInner>>() {
@Override
public List<DatabasePrincipalInner> call(ServiceResponse<List<DatabasePrincipalInner>> response) {
return response.body();
}
});
} | java | public Observable<List<DatabasePrincipalInner>> listPrincipalsAsync(String resourceGroupName, String clusterName, String databaseName) {
return listPrincipalsWithServiceResponseAsync(resourceGroupName, clusterName, databaseName).map(new Func1<ServiceResponse<List<DatabasePrincipalInner>>, List<DatabasePrincipalInner>>() {
@Override
public List<DatabasePrincipalInner> call(ServiceResponse<List<DatabasePrincipalInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"DatabasePrincipalInner",
">",
">",
"listPrincipalsAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"String",
"databaseName",
")",
"{",
"return",
"listPrincipalsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
",",
"databaseName",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"List",
"<",
"DatabasePrincipalInner",
">",
">",
",",
"List",
"<",
"DatabasePrincipalInner",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"List",
"<",
"DatabasePrincipalInner",
">",
"call",
"(",
"ServiceResponse",
"<",
"List",
"<",
"DatabasePrincipalInner",
">",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Returns a list of database principals of the given Kusto cluster and database.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@param databaseName The name of the database in the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<DatabasePrincipalInner> object | [
"Returns",
"a",
"list",
"of",
"database",
"principals",
"of",
"the",
"given",
"Kusto",
"cluster",
"and",
"database",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java#L974-L981 |
Samsung/GearVRf | GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/thread/ExecutionChain.java | ExecutionChain.runOnMainThread | public <T, U> ExecutionChain runOnMainThread(Task<T, U> task) {
"""
Add a {@link Task} to be run on the
{@link MainThread#runOnMainThread(Runnable) main thread}. It will be run
after all Tasks added prior to this call.
@param task
{@code Task} to run
@return Reference to the {@code ExecutionChain}.
@throws IllegalStateException
if the chain of execution has already been {@link #execute()
started}.
"""
runOnThread(Context.Type.MAIN, task);
return this;
} | java | public <T, U> ExecutionChain runOnMainThread(Task<T, U> task) {
runOnThread(Context.Type.MAIN, task);
return this;
} | [
"public",
"<",
"T",
",",
"U",
">",
"ExecutionChain",
"runOnMainThread",
"(",
"Task",
"<",
"T",
",",
"U",
">",
"task",
")",
"{",
"runOnThread",
"(",
"Context",
".",
"Type",
".",
"MAIN",
",",
"task",
")",
";",
"return",
"this",
";",
"}"
] | Add a {@link Task} to be run on the
{@link MainThread#runOnMainThread(Runnable) main thread}. It will be run
after all Tasks added prior to this call.
@param task
{@code Task} to run
@return Reference to the {@code ExecutionChain}.
@throws IllegalStateException
if the chain of execution has already been {@link #execute()
started}. | [
"Add",
"a",
"{",
"@link",
"Task",
"}",
"to",
"be",
"run",
"on",
"the",
"{",
"@link",
"MainThread#runOnMainThread",
"(",
"Runnable",
")",
"main",
"thread",
"}",
".",
"It",
"will",
"be",
"run",
"after",
"all",
"Tasks",
"added",
"prior",
"to",
"this",
"call",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/thread/ExecutionChain.java#L268-L271 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/LocaleDisplayNames.java | LocaleDisplayNames.getInstance | public static LocaleDisplayNames getInstance(ULocale locale, DisplayContext... contexts) {
"""
Returns an instance of LocaleDisplayNames that returns names formatted for the provided locale,
using the provided DisplayContext settings
@param locale the display locale
@param contexts one or more context settings (e.g. for dialect
handling, capitalization, etc.
@return a LocaleDisplayNames instance
"""
LocaleDisplayNames result = null;
if (FACTORY_DISPLAYCONTEXT != null) {
try {
result = (LocaleDisplayNames) FACTORY_DISPLAYCONTEXT.invoke(null,
locale, contexts);
} catch (InvocationTargetException e) {
// fall through
} catch (IllegalAccessException e) {
// fall through
}
}
if (result == null) {
result = new LastResortLocaleDisplayNames(locale, contexts);
}
return result;
} | java | public static LocaleDisplayNames getInstance(ULocale locale, DisplayContext... contexts) {
LocaleDisplayNames result = null;
if (FACTORY_DISPLAYCONTEXT != null) {
try {
result = (LocaleDisplayNames) FACTORY_DISPLAYCONTEXT.invoke(null,
locale, contexts);
} catch (InvocationTargetException e) {
// fall through
} catch (IllegalAccessException e) {
// fall through
}
}
if (result == null) {
result = new LastResortLocaleDisplayNames(locale, contexts);
}
return result;
} | [
"public",
"static",
"LocaleDisplayNames",
"getInstance",
"(",
"ULocale",
"locale",
",",
"DisplayContext",
"...",
"contexts",
")",
"{",
"LocaleDisplayNames",
"result",
"=",
"null",
";",
"if",
"(",
"FACTORY_DISPLAYCONTEXT",
"!=",
"null",
")",
"{",
"try",
"{",
"result",
"=",
"(",
"LocaleDisplayNames",
")",
"FACTORY_DISPLAYCONTEXT",
".",
"invoke",
"(",
"null",
",",
"locale",
",",
"contexts",
")",
";",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"// fall through",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"// fall through",
"}",
"}",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"result",
"=",
"new",
"LastResortLocaleDisplayNames",
"(",
"locale",
",",
"contexts",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Returns an instance of LocaleDisplayNames that returns names formatted for the provided locale,
using the provided DisplayContext settings
@param locale the display locale
@param contexts one or more context settings (e.g. for dialect
handling, capitalization, etc.
@return a LocaleDisplayNames instance | [
"Returns",
"an",
"instance",
"of",
"LocaleDisplayNames",
"that",
"returns",
"names",
"formatted",
"for",
"the",
"provided",
"locale",
"using",
"the",
"provided",
"DisplayContext",
"settings"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/LocaleDisplayNames.java#L102-L118 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java | JvmTypesBuilder.newTypeRef | @Deprecated
public JvmTypeReference newTypeRef(EObject ctx, Class<?> clazz, JvmTypeReference... typeArgs) {
"""
Creates a new {@link JvmTypeReference} pointing to the given class and containing the given type arguments.
@param ctx
an EMF context, which is used to look up the {@link org.eclipse.xtext.common.types.JvmType} for the
given clazz.
@param clazz
the class the type reference shall point to.
@param typeArgs
type arguments
@return the newly created {@link JvmTypeReference}
@deprecated use {@link JvmTypeReferenceBuilder#typeRef(Class, JvmTypeReference...)}
"""
return references.getTypeForName(clazz, ctx, typeArgs);
} | java | @Deprecated
public JvmTypeReference newTypeRef(EObject ctx, Class<?> clazz, JvmTypeReference... typeArgs) {
return references.getTypeForName(clazz, ctx, typeArgs);
} | [
"@",
"Deprecated",
"public",
"JvmTypeReference",
"newTypeRef",
"(",
"EObject",
"ctx",
",",
"Class",
"<",
"?",
">",
"clazz",
",",
"JvmTypeReference",
"...",
"typeArgs",
")",
"{",
"return",
"references",
".",
"getTypeForName",
"(",
"clazz",
",",
"ctx",
",",
"typeArgs",
")",
";",
"}"
] | Creates a new {@link JvmTypeReference} pointing to the given class and containing the given type arguments.
@param ctx
an EMF context, which is used to look up the {@link org.eclipse.xtext.common.types.JvmType} for the
given clazz.
@param clazz
the class the type reference shall point to.
@param typeArgs
type arguments
@return the newly created {@link JvmTypeReference}
@deprecated use {@link JvmTypeReferenceBuilder#typeRef(Class, JvmTypeReference...)} | [
"Creates",
"a",
"new",
"{",
"@link",
"JvmTypeReference",
"}",
"pointing",
"to",
"the",
"given",
"class",
"and",
"containing",
"the",
"given",
"type",
"arguments",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java#L1298-L1301 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/content/CmsPropertyDelete.java | CmsPropertyDelete.actionDelete | public void actionDelete() throws JspException {
"""
Deletes the property definition.<p>
@throws JspException if problems including sub-elements occur
"""
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
try {
getCms().deletePropertyDefinition(getParamPropertyName());
// close the dialog
actionCloseDialog();
} catch (Throwable e) {
// error while deleting property definition, show error dialog
includeErrorpage(this, e);
}
} | java | public void actionDelete() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
try {
getCms().deletePropertyDefinition(getParamPropertyName());
// close the dialog
actionCloseDialog();
} catch (Throwable e) {
// error while deleting property definition, show error dialog
includeErrorpage(this, e);
}
} | [
"public",
"void",
"actionDelete",
"(",
")",
"throws",
"JspException",
"{",
"// save initialized instance of this class in request attribute for included sub-elements",
"getJsp",
"(",
")",
".",
"getRequest",
"(",
")",
".",
"setAttribute",
"(",
"SESSION_WORKPLACE_CLASS",
",",
"this",
")",
";",
"try",
"{",
"getCms",
"(",
")",
".",
"deletePropertyDefinition",
"(",
"getParamPropertyName",
"(",
")",
")",
";",
"// close the dialog",
"actionCloseDialog",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"// error while deleting property definition, show error dialog",
"includeErrorpage",
"(",
"this",
",",
"e",
")",
";",
"}",
"}"
] | Deletes the property definition.<p>
@throws JspException if problems including sub-elements occur | [
"Deletes",
"the",
"property",
"definition",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/content/CmsPropertyDelete.java#L101-L113 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLStatementCache.java | CQLStatementCache.getPreparedQuery | public PreparedStatement getPreparedQuery(String tableName, Query query) {
"""
Get the given prepared statement for the given table and query. Upon
first invocation for a given combo, the query is parsed and cached.
@param tableName Name of table to customize query for.
@param query Inquiry {@link Query}.
@return PreparedStatement for given combo.
"""
synchronized (m_prepQueryMap) {
Map<Query, PreparedStatement> statementMap = m_prepQueryMap.get(tableName);
if (statementMap == null) {
statementMap = new HashMap<>();
m_prepQueryMap.put(tableName, statementMap);
}
PreparedStatement prepState = statementMap.get(query);
if (prepState == null) {
prepState = prepareQuery(tableName, query);
statementMap.put(query, prepState);
}
return prepState;
}
} | java | public PreparedStatement getPreparedQuery(String tableName, Query query) {
synchronized (m_prepQueryMap) {
Map<Query, PreparedStatement> statementMap = m_prepQueryMap.get(tableName);
if (statementMap == null) {
statementMap = new HashMap<>();
m_prepQueryMap.put(tableName, statementMap);
}
PreparedStatement prepState = statementMap.get(query);
if (prepState == null) {
prepState = prepareQuery(tableName, query);
statementMap.put(query, prepState);
}
return prepState;
}
} | [
"public",
"PreparedStatement",
"getPreparedQuery",
"(",
"String",
"tableName",
",",
"Query",
"query",
")",
"{",
"synchronized",
"(",
"m_prepQueryMap",
")",
"{",
"Map",
"<",
"Query",
",",
"PreparedStatement",
">",
"statementMap",
"=",
"m_prepQueryMap",
".",
"get",
"(",
"tableName",
")",
";",
"if",
"(",
"statementMap",
"==",
"null",
")",
"{",
"statementMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"m_prepQueryMap",
".",
"put",
"(",
"tableName",
",",
"statementMap",
")",
";",
"}",
"PreparedStatement",
"prepState",
"=",
"statementMap",
".",
"get",
"(",
"query",
")",
";",
"if",
"(",
"prepState",
"==",
"null",
")",
"{",
"prepState",
"=",
"prepareQuery",
"(",
"tableName",
",",
"query",
")",
";",
"statementMap",
".",
"put",
"(",
"query",
",",
"prepState",
")",
";",
"}",
"return",
"prepState",
";",
"}",
"}"
] | Get the given prepared statement for the given table and query. Upon
first invocation for a given combo, the query is parsed and cached.
@param tableName Name of table to customize query for.
@param query Inquiry {@link Query}.
@return PreparedStatement for given combo. | [
"Get",
"the",
"given",
"prepared",
"statement",
"for",
"the",
"given",
"table",
"and",
"query",
".",
"Upon",
"first",
"invocation",
"for",
"a",
"given",
"combo",
"the",
"query",
"is",
"parsed",
"and",
"cached",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLStatementCache.java#L91-L105 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java | ManagedInstanceKeysInner.createOrUpdateAsync | public Observable<ManagedInstanceKeyInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) {
"""
Creates or updates a managed instance key.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param managedInstanceName The name of the managed instance.
@param keyName The name of the managed instance key to be operated on (updated or created).
@param parameters The requested managed instance key resource state.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).map(new Func1<ServiceResponse<ManagedInstanceKeyInner>, ManagedInstanceKeyInner>() {
@Override
public ManagedInstanceKeyInner call(ServiceResponse<ManagedInstanceKeyInner> response) {
return response.body();
}
});
} | java | public Observable<ManagedInstanceKeyInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, String keyName, ManagedInstanceKeyInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, keyName, parameters).map(new Func1<ServiceResponse<ManagedInstanceKeyInner>, ManagedInstanceKeyInner>() {
@Override
public ManagedInstanceKeyInner call(ServiceResponse<ManagedInstanceKeyInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ManagedInstanceKeyInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"managedInstanceName",
",",
"String",
"keyName",
",",
"ManagedInstanceKeyInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"managedInstanceName",
",",
"keyName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"ManagedInstanceKeyInner",
">",
",",
"ManagedInstanceKeyInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"ManagedInstanceKeyInner",
"call",
"(",
"ServiceResponse",
"<",
"ManagedInstanceKeyInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Creates or updates a managed instance key.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param managedInstanceName The name of the managed instance.
@param keyName The name of the managed instance key to be operated on (updated or created).
@param parameters The requested managed instance key resource state.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"a",
"managed",
"instance",
"key",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_10_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_10_01_preview/implementation/ManagedInstanceKeysInner.java#L473-L480 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java | HadoopUtils.getWriterFileSystem | public static FileSystem getWriterFileSystem(State state, int numBranches, int branchId)
throws IOException {
"""
Get a {@link FileSystem} object for the uri specified at {@link ConfigurationKeys#WRITER_FILE_SYSTEM_URI}.
@throws IOException
"""
return HadoopUtils.getOptionallyThrottledFileSystem(WriterUtils.getWriterFS(state, numBranches, branchId), state);
} | java | public static FileSystem getWriterFileSystem(State state, int numBranches, int branchId)
throws IOException {
return HadoopUtils.getOptionallyThrottledFileSystem(WriterUtils.getWriterFS(state, numBranches, branchId), state);
} | [
"public",
"static",
"FileSystem",
"getWriterFileSystem",
"(",
"State",
"state",
",",
"int",
"numBranches",
",",
"int",
"branchId",
")",
"throws",
"IOException",
"{",
"return",
"HadoopUtils",
".",
"getOptionallyThrottledFileSystem",
"(",
"WriterUtils",
".",
"getWriterFS",
"(",
"state",
",",
"numBranches",
",",
"branchId",
")",
",",
"state",
")",
";",
"}"
] | Get a {@link FileSystem} object for the uri specified at {@link ConfigurationKeys#WRITER_FILE_SYSTEM_URI}.
@throws IOException | [
"Get",
"a",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HadoopUtils.java#L995-L998 |
Scout24/appmon4j | spring/src/main/java/de/is24/util/monitoring/spring/MonitoringHandlerInterceptor.java | MonitoringHandlerInterceptor.afterCompletion | @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
"""
check, whether {@link #POST_HANDLE_TIME} is set, and {@link de.is24.util.monitoring.InApplicationMonitor#addTimerMeasurement(String, long, long) add timer measuremets} for post phase and complete request.
"""
long currentTime = System.currentTimeMillis();
String measurementPrefix = getPrefix(handler);
Object startTimeAttribute = getAndRemoveAttribute(request, START_TIME);
Object postHandleObject = getAndRemoveAttribute(request, POST_HANDLE_TIME);
if (startTimeAttribute == null) {
LOG.info("Could not find start_time. Something went wrong with handler: " + measurementPrefix);
monitor.incrementCounter(measurementPrefix + TIME_ERROR);
return;
}
long startTime = (Long) startTimeAttribute;
if (ex != null) {
monitor.addTimerMeasurement(measurementPrefix + ERROR, startTime, currentTime);
} else {
if (postHandleObject != null) {
long postHandleTime = (Long) postHandleObject;
monitor.addTimerMeasurement(measurementPrefix + RENDERING, postHandleTime, currentTime);
monitor.addTimerMeasurement(measurementPrefix + COMPLETE, startTime, currentTime);
}
}
} | java | @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
long currentTime = System.currentTimeMillis();
String measurementPrefix = getPrefix(handler);
Object startTimeAttribute = getAndRemoveAttribute(request, START_TIME);
Object postHandleObject = getAndRemoveAttribute(request, POST_HANDLE_TIME);
if (startTimeAttribute == null) {
LOG.info("Could not find start_time. Something went wrong with handler: " + measurementPrefix);
monitor.incrementCounter(measurementPrefix + TIME_ERROR);
return;
}
long startTime = (Long) startTimeAttribute;
if (ex != null) {
monitor.addTimerMeasurement(measurementPrefix + ERROR, startTime, currentTime);
} else {
if (postHandleObject != null) {
long postHandleTime = (Long) postHandleObject;
monitor.addTimerMeasurement(measurementPrefix + RENDERING, postHandleTime, currentTime);
monitor.addTimerMeasurement(measurementPrefix + COMPLETE, startTime, currentTime);
}
}
} | [
"@",
"Override",
"public",
"void",
"afterCompletion",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"Object",
"handler",
",",
"Exception",
"ex",
")",
"throws",
"Exception",
"{",
"long",
"currentTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"String",
"measurementPrefix",
"=",
"getPrefix",
"(",
"handler",
")",
";",
"Object",
"startTimeAttribute",
"=",
"getAndRemoveAttribute",
"(",
"request",
",",
"START_TIME",
")",
";",
"Object",
"postHandleObject",
"=",
"getAndRemoveAttribute",
"(",
"request",
",",
"POST_HANDLE_TIME",
")",
";",
"if",
"(",
"startTimeAttribute",
"==",
"null",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Could not find start_time. Something went wrong with handler: \"",
"+",
"measurementPrefix",
")",
";",
"monitor",
".",
"incrementCounter",
"(",
"measurementPrefix",
"+",
"TIME_ERROR",
")",
";",
"return",
";",
"}",
"long",
"startTime",
"=",
"(",
"Long",
")",
"startTimeAttribute",
";",
"if",
"(",
"ex",
"!=",
"null",
")",
"{",
"monitor",
".",
"addTimerMeasurement",
"(",
"measurementPrefix",
"+",
"ERROR",
",",
"startTime",
",",
"currentTime",
")",
";",
"}",
"else",
"{",
"if",
"(",
"postHandleObject",
"!=",
"null",
")",
"{",
"long",
"postHandleTime",
"=",
"(",
"Long",
")",
"postHandleObject",
";",
"monitor",
".",
"addTimerMeasurement",
"(",
"measurementPrefix",
"+",
"RENDERING",
",",
"postHandleTime",
",",
"currentTime",
")",
";",
"monitor",
".",
"addTimerMeasurement",
"(",
"measurementPrefix",
"+",
"COMPLETE",
",",
"startTime",
",",
"currentTime",
")",
";",
"}",
"}",
"}"
] | check, whether {@link #POST_HANDLE_TIME} is set, and {@link de.is24.util.monitoring.InApplicationMonitor#addTimerMeasurement(String, long, long) add timer measuremets} for post phase and complete request. | [
"check",
"whether",
"{"
] | train | https://github.com/Scout24/appmon4j/blob/a662e5123805ea455cfd01e1b9ae5d808f83529c/spring/src/main/java/de/is24/util/monitoring/spring/MonitoringHandlerInterceptor.java#L56-L82 |
CloudBees-community/syslog-java-client | src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java | LogManagerHelper.getStringProperty | public static String getStringProperty(@Nonnull LogManager manager, @Nullable String name, String defaultValue) {
"""
Visible version of {@link java.util.logging.LogManager#getStringProperty(String, String)}.
If the property is not defined we return the given default value.
"""
if (name == null) {
return defaultValue;
}
String val = manager.getProperty(name);
if (val == null) {
return defaultValue;
}
return val.trim();
} | java | public static String getStringProperty(@Nonnull LogManager manager, @Nullable String name, String defaultValue) {
if (name == null) {
return defaultValue;
}
String val = manager.getProperty(name);
if (val == null) {
return defaultValue;
}
return val.trim();
} | [
"public",
"static",
"String",
"getStringProperty",
"(",
"@",
"Nonnull",
"LogManager",
"manager",
",",
"@",
"Nullable",
"String",
"name",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"String",
"val",
"=",
"manager",
".",
"getProperty",
"(",
"name",
")",
";",
"if",
"(",
"val",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"return",
"val",
".",
"trim",
"(",
")",
";",
"}"
] | Visible version of {@link java.util.logging.LogManager#getStringProperty(String, String)}.
If the property is not defined we return the given default value. | [
"Visible",
"version",
"of",
"{",
"@link",
"java",
".",
"util",
".",
"logging",
".",
"LogManager#getStringProperty",
"(",
"String",
"String",
")",
"}",
"."
] | train | https://github.com/CloudBees-community/syslog-java-client/blob/41e01206e4ce17c6d225ffb443bf19792a3f3c3a/src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java#L117-L126 |
ahome-it/lienzo-core | src/main/java/com/ait/lienzo/client/core/util/Matrix.java | Matrix.times | public Matrix times(final Matrix B) {
"""
Returns C = A * B
@param B
@return new Matrix C
@throws GeometryException if the matrix dimensions don't match
"""
final Matrix A = this;
if (A.m_columns != B.m_rows)
{
throw new GeometryException("Illegal matrix dimensions");
}
final Matrix C = new Matrix(A.m_rows, B.m_columns);
for (int i = 0; i < C.m_rows; i++)
{
for (int j = 0; j < C.m_columns; j++)
{
for (int k = 0; k < A.m_columns; k++)
{
C.m_data[i][j] += (A.m_data[i][k] * B.m_data[k][j]);
}
}
}
return C;
} | java | public Matrix times(final Matrix B)
{
final Matrix A = this;
if (A.m_columns != B.m_rows)
{
throw new GeometryException("Illegal matrix dimensions");
}
final Matrix C = new Matrix(A.m_rows, B.m_columns);
for (int i = 0; i < C.m_rows; i++)
{
for (int j = 0; j < C.m_columns; j++)
{
for (int k = 0; k < A.m_columns; k++)
{
C.m_data[i][j] += (A.m_data[i][k] * B.m_data[k][j]);
}
}
}
return C;
} | [
"public",
"Matrix",
"times",
"(",
"final",
"Matrix",
"B",
")",
"{",
"final",
"Matrix",
"A",
"=",
"this",
";",
"if",
"(",
"A",
".",
"m_columns",
"!=",
"B",
".",
"m_rows",
")",
"{",
"throw",
"new",
"GeometryException",
"(",
"\"Illegal matrix dimensions\"",
")",
";",
"}",
"final",
"Matrix",
"C",
"=",
"new",
"Matrix",
"(",
"A",
".",
"m_rows",
",",
"B",
".",
"m_columns",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"C",
".",
"m_rows",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"C",
".",
"m_columns",
";",
"j",
"++",
")",
"{",
"for",
"(",
"int",
"k",
"=",
"0",
";",
"k",
"<",
"A",
".",
"m_columns",
";",
"k",
"++",
")",
"{",
"C",
".",
"m_data",
"[",
"i",
"]",
"[",
"j",
"]",
"+=",
"(",
"A",
".",
"m_data",
"[",
"i",
"]",
"[",
"k",
"]",
"*",
"B",
".",
"m_data",
"[",
"k",
"]",
"[",
"j",
"]",
")",
";",
"}",
"}",
"}",
"return",
"C",
";",
"}"
] | Returns C = A * B
@param B
@return new Matrix C
@throws GeometryException if the matrix dimensions don't match | [
"Returns",
"C",
"=",
"A",
"*",
"B"
] | train | https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/util/Matrix.java#L217-L238 |
wildfly-swarm-archive/ARCHIVE-wildfly-swarm | batch-jberet/api/src/main/java/org/wildfly/swarm/batch/jberet/BatchFraction.java | BatchFraction.defaultThreadPool | public BatchFraction defaultThreadPool(final String name, final int maxThreads, final int keepAliveTime, final TimeUnit keepAliveUnits) {
"""
Creates a new thread-pool and sets the created thread-pool as the default thread-pool for batch jobs.
@param name the maximum number of threads to set the pool to
@param keepAliveTime the time to keep threads alive
@param keepAliveUnits the time unit for the keep alive time
@return this fraction
"""
threadPool(name, maxThreads, keepAliveTime, keepAliveUnits);
return defaultThreadPool(name);
} | java | public BatchFraction defaultThreadPool(final String name, final int maxThreads, final int keepAliveTime, final TimeUnit keepAliveUnits) {
threadPool(name, maxThreads, keepAliveTime, keepAliveUnits);
return defaultThreadPool(name);
} | [
"public",
"BatchFraction",
"defaultThreadPool",
"(",
"final",
"String",
"name",
",",
"final",
"int",
"maxThreads",
",",
"final",
"int",
"keepAliveTime",
",",
"final",
"TimeUnit",
"keepAliveUnits",
")",
"{",
"threadPool",
"(",
"name",
",",
"maxThreads",
",",
"keepAliveTime",
",",
"keepAliveUnits",
")",
";",
"return",
"defaultThreadPool",
"(",
"name",
")",
";",
"}"
] | Creates a new thread-pool and sets the created thread-pool as the default thread-pool for batch jobs.
@param name the maximum number of threads to set the pool to
@param keepAliveTime the time to keep threads alive
@param keepAliveUnits the time unit for the keep alive time
@return this fraction | [
"Creates",
"a",
"new",
"thread",
"-",
"pool",
"and",
"sets",
"the",
"created",
"thread",
"-",
"pool",
"as",
"the",
"default",
"thread",
"-",
"pool",
"for",
"batch",
"jobs",
"."
] | train | https://github.com/wildfly-swarm-archive/ARCHIVE-wildfly-swarm/blob/28ef71bcfa743a7267666e0ed2919c37b356c09b/batch-jberet/api/src/main/java/org/wildfly/swarm/batch/jberet/BatchFraction.java#L155-L158 |
apache/flink | flink-filesystems/flink-hadoop-fs/src/main/java/org/apache/flink/runtime/fs/hdfs/HadoopRecoverableFsDataOutputStream.java | HadoopRecoverableFsDataOutputStream.waitUntilLeaseIsRevoked | private static boolean waitUntilLeaseIsRevoked(final FileSystem fs, final Path path) throws IOException {
"""
Called when resuming execution after a failure and waits until the lease
of the file we are resuming is free.
<p>The lease of the file we are resuming writing/committing to may still
belong to the process that failed previously and whose state we are
recovering.
@param path The path to the file we want to resume writing to.
"""
Preconditions.checkState(fs instanceof DistributedFileSystem);
final DistributedFileSystem dfs = (DistributedFileSystem) fs;
dfs.recoverLease(path);
final Deadline deadline = Deadline.now().plus(Duration.ofMillis(LEASE_TIMEOUT));
final StopWatch sw = new StopWatch();
sw.start();
boolean isClosed = dfs.isFileClosed(path);
while (!isClosed && deadline.hasTimeLeft()) {
try {
Thread.sleep(500L);
} catch (InterruptedException e1) {
throw new IOException("Recovering the lease failed: ", e1);
}
isClosed = dfs.isFileClosed(path);
}
return isClosed;
} | java | private static boolean waitUntilLeaseIsRevoked(final FileSystem fs, final Path path) throws IOException {
Preconditions.checkState(fs instanceof DistributedFileSystem);
final DistributedFileSystem dfs = (DistributedFileSystem) fs;
dfs.recoverLease(path);
final Deadline deadline = Deadline.now().plus(Duration.ofMillis(LEASE_TIMEOUT));
final StopWatch sw = new StopWatch();
sw.start();
boolean isClosed = dfs.isFileClosed(path);
while (!isClosed && deadline.hasTimeLeft()) {
try {
Thread.sleep(500L);
} catch (InterruptedException e1) {
throw new IOException("Recovering the lease failed: ", e1);
}
isClosed = dfs.isFileClosed(path);
}
return isClosed;
} | [
"private",
"static",
"boolean",
"waitUntilLeaseIsRevoked",
"(",
"final",
"FileSystem",
"fs",
",",
"final",
"Path",
"path",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkState",
"(",
"fs",
"instanceof",
"DistributedFileSystem",
")",
";",
"final",
"DistributedFileSystem",
"dfs",
"=",
"(",
"DistributedFileSystem",
")",
"fs",
";",
"dfs",
".",
"recoverLease",
"(",
"path",
")",
";",
"final",
"Deadline",
"deadline",
"=",
"Deadline",
".",
"now",
"(",
")",
".",
"plus",
"(",
"Duration",
".",
"ofMillis",
"(",
"LEASE_TIMEOUT",
")",
")",
";",
"final",
"StopWatch",
"sw",
"=",
"new",
"StopWatch",
"(",
")",
";",
"sw",
".",
"start",
"(",
")",
";",
"boolean",
"isClosed",
"=",
"dfs",
".",
"isFileClosed",
"(",
"path",
")",
";",
"while",
"(",
"!",
"isClosed",
"&&",
"deadline",
".",
"hasTimeLeft",
"(",
")",
")",
"{",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"500L",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e1",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Recovering the lease failed: \"",
",",
"e1",
")",
";",
"}",
"isClosed",
"=",
"dfs",
".",
"isFileClosed",
"(",
"path",
")",
";",
"}",
"return",
"isClosed",
";",
"}"
] | Called when resuming execution after a failure and waits until the lease
of the file we are resuming is free.
<p>The lease of the file we are resuming writing/committing to may still
belong to the process that failed previously and whose state we are
recovering.
@param path The path to the file we want to resume writing to. | [
"Called",
"when",
"resuming",
"execution",
"after",
"a",
"failure",
"and",
"waits",
"until",
"the",
"lease",
"of",
"the",
"file",
"we",
"are",
"resuming",
"is",
"free",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-hadoop-fs/src/main/java/org/apache/flink/runtime/fs/hdfs/HadoopRecoverableFsDataOutputStream.java#L321-L342 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/RunnableUtils.java | RunnableUtils.runWithSleep | public static boolean runWithSleep(long milliseconds, Runnable runnable) {
"""
Runs the given {@link Runnable} object and then causes the current, calling {@link Thread} to sleep
for the given number of milliseconds.
This utility method can be used to simulate a long running, expensive operation.
@param milliseconds a long value with the number of milliseconds for the current {@link Thread} to sleep.
@param runnable {@link Runnable} object to run; must not be {@literal null}.
@return a boolean value indicating whether the {@link Runnable} ran successfully
and whether the current {@link Thread} slept for the given number of milliseconds.
@throws IllegalArgumentException if milliseconds is less than equal to 0.
@see org.cp.elements.lang.concurrent.ThreadUtils#sleep(long, int)
@see java.lang.Runnable#run()
"""
Assert.isTrue(milliseconds > 0, "Milliseconds [%d] must be greater than 0", milliseconds);
runnable.run();
return ThreadUtils.sleep(milliseconds, 0);
} | java | public static boolean runWithSleep(long milliseconds, Runnable runnable) {
Assert.isTrue(milliseconds > 0, "Milliseconds [%d] must be greater than 0", milliseconds);
runnable.run();
return ThreadUtils.sleep(milliseconds, 0);
} | [
"public",
"static",
"boolean",
"runWithSleep",
"(",
"long",
"milliseconds",
",",
"Runnable",
"runnable",
")",
"{",
"Assert",
".",
"isTrue",
"(",
"milliseconds",
">",
"0",
",",
"\"Milliseconds [%d] must be greater than 0\"",
",",
"milliseconds",
")",
";",
"runnable",
".",
"run",
"(",
")",
";",
"return",
"ThreadUtils",
".",
"sleep",
"(",
"milliseconds",
",",
"0",
")",
";",
"}"
] | Runs the given {@link Runnable} object and then causes the current, calling {@link Thread} to sleep
for the given number of milliseconds.
This utility method can be used to simulate a long running, expensive operation.
@param milliseconds a long value with the number of milliseconds for the current {@link Thread} to sleep.
@param runnable {@link Runnable} object to run; must not be {@literal null}.
@return a boolean value indicating whether the {@link Runnable} ran successfully
and whether the current {@link Thread} slept for the given number of milliseconds.
@throws IllegalArgumentException if milliseconds is less than equal to 0.
@see org.cp.elements.lang.concurrent.ThreadUtils#sleep(long, int)
@see java.lang.Runnable#run() | [
"Runs",
"the",
"given",
"{",
"@link",
"Runnable",
"}",
"object",
"and",
"then",
"causes",
"the",
"current",
"calling",
"{",
"@link",
"Thread",
"}",
"to",
"sleep",
"for",
"the",
"given",
"number",
"of",
"milliseconds",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/RunnableUtils.java#L50-L57 |
tvesalainen/util | util/src/main/java/org/vesalainen/nio/Splitter.java | Splitter.split | public int split(T obj, int start, int length) throws IOException {
"""
Calls either of two op methods depending on start + length > size. If so
calls op with 5 parameters, otherwise op with 3 parameters.
@param obj
@param start
@param length
@return
@throws IOException
"""
int count = 0;
if (length > 0)
{
int end = (start + length) % size;
if (start < end)
{
count = op(obj, start, end);
}
else
{
if (end > 0)
{
count = op(obj, start, size, 0, end);
}
else
{
count = op(obj, start, size);
}
}
}
assert count <= length;
return count;
} | java | public int split(T obj, int start, int length) throws IOException
{
int count = 0;
if (length > 0)
{
int end = (start + length) % size;
if (start < end)
{
count = op(obj, start, end);
}
else
{
if (end > 0)
{
count = op(obj, start, size, 0, end);
}
else
{
count = op(obj, start, size);
}
}
}
assert count <= length;
return count;
} | [
"public",
"int",
"split",
"(",
"T",
"obj",
",",
"int",
"start",
",",
"int",
"length",
")",
"throws",
"IOException",
"{",
"int",
"count",
"=",
"0",
";",
"if",
"(",
"length",
">",
"0",
")",
"{",
"int",
"end",
"=",
"(",
"start",
"+",
"length",
")",
"%",
"size",
";",
"if",
"(",
"start",
"<",
"end",
")",
"{",
"count",
"=",
"op",
"(",
"obj",
",",
"start",
",",
"end",
")",
";",
"}",
"else",
"{",
"if",
"(",
"end",
">",
"0",
")",
"{",
"count",
"=",
"op",
"(",
"obj",
",",
"start",
",",
"size",
",",
"0",
",",
"end",
")",
";",
"}",
"else",
"{",
"count",
"=",
"op",
"(",
"obj",
",",
"start",
",",
"size",
")",
";",
"}",
"}",
"}",
"assert",
"count",
"<=",
"length",
";",
"return",
"count",
";",
"}"
] | Calls either of two op methods depending on start + length > size. If so
calls op with 5 parameters, otherwise op with 3 parameters.
@param obj
@param start
@param length
@return
@throws IOException | [
"Calls",
"either",
"of",
"two",
"op",
"methods",
"depending",
"on",
"start",
"+",
"length",
">",
"size",
".",
"If",
"so",
"calls",
"op",
"with",
"5",
"parameters",
"otherwise",
"op",
"with",
"3",
"parameters",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/Splitter.java#L47-L71 |
carewebframework/carewebframework-core | org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandUtil.java | CommandUtil.associateCommand | public static void associateCommand(String commandName, BaseUIComponent component, BaseUIComponent commandTarget) {
"""
Associates a UI component with a command.
@param commandName Name of the command.
@param component Component to be associated.
@param commandTarget The target of the command event. A null value indicates that the
component itself will be the target.
"""
getCommand(commandName, true).bind(component, commandTarget);
} | java | public static void associateCommand(String commandName, BaseUIComponent component, BaseUIComponent commandTarget) {
getCommand(commandName, true).bind(component, commandTarget);
} | [
"public",
"static",
"void",
"associateCommand",
"(",
"String",
"commandName",
",",
"BaseUIComponent",
"component",
",",
"BaseUIComponent",
"commandTarget",
")",
"{",
"getCommand",
"(",
"commandName",
",",
"true",
")",
".",
"bind",
"(",
"component",
",",
"commandTarget",
")",
";",
"}"
] | Associates a UI component with a command.
@param commandName Name of the command.
@param component Component to be associated.
@param commandTarget The target of the command event. A null value indicates that the
component itself will be the target. | [
"Associates",
"a",
"UI",
"component",
"with",
"a",
"command",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandUtil.java#L188-L190 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/Step.java | Step.checkElementVisible | protected void checkElementVisible(PageElement pageElement, boolean displayed) throws FailureException {
"""
Checks if an html element (PageElement) is displayed.
@param pageElement
Is target element
@param displayed
Is target element supposed to be displayed
@throws FailureException
if the scenario encounters a functional error. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT} message
(with screenshot, with exception)
"""
if (displayed) {
try {
Context.waitUntil(ExpectedConditions.visibilityOfElementLocated(Utilities.getLocator(pageElement)));
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_ELEMENT_STILL_VISIBLE), true, pageElement.getPage().getCallBack());
}
} else {
try {
Context.waitUntil(ExpectedConditions.not(ExpectedConditions.visibilityOfElementLocated(Utilities.getLocator(pageElement))));
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_ELEMENT_STILL_VISIBLE), true, pageElement.getPage().getCallBack());
}
}
} | java | protected void checkElementVisible(PageElement pageElement, boolean displayed) throws FailureException {
if (displayed) {
try {
Context.waitUntil(ExpectedConditions.visibilityOfElementLocated(Utilities.getLocator(pageElement)));
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_ELEMENT_STILL_VISIBLE), true, pageElement.getPage().getCallBack());
}
} else {
try {
Context.waitUntil(ExpectedConditions.not(ExpectedConditions.visibilityOfElementLocated(Utilities.getLocator(pageElement))));
} catch (final Exception e) {
new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_ELEMENT_STILL_VISIBLE), true, pageElement.getPage().getCallBack());
}
}
} | [
"protected",
"void",
"checkElementVisible",
"(",
"PageElement",
"pageElement",
",",
"boolean",
"displayed",
")",
"throws",
"FailureException",
"{",
"if",
"(",
"displayed",
")",
"{",
"try",
"{",
"Context",
".",
"waitUntil",
"(",
"ExpectedConditions",
".",
"visibilityOfElementLocated",
"(",
"Utilities",
".",
"getLocator",
"(",
"pageElement",
")",
")",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"new",
"Result",
".",
"Failure",
"<>",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"Messages",
".",
"getMessage",
"(",
"Messages",
".",
"FAIL_MESSAGE_ELEMENT_STILL_VISIBLE",
")",
",",
"true",
",",
"pageElement",
".",
"getPage",
"(",
")",
".",
"getCallBack",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"try",
"{",
"Context",
".",
"waitUntil",
"(",
"ExpectedConditions",
".",
"not",
"(",
"ExpectedConditions",
".",
"visibilityOfElementLocated",
"(",
"Utilities",
".",
"getLocator",
"(",
"pageElement",
")",
")",
")",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"new",
"Result",
".",
"Failure",
"<>",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"Messages",
".",
"getMessage",
"(",
"Messages",
".",
"FAIL_MESSAGE_ELEMENT_STILL_VISIBLE",
")",
",",
"true",
",",
"pageElement",
".",
"getPage",
"(",
")",
".",
"getCallBack",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Checks if an html element (PageElement) is displayed.
@param pageElement
Is target element
@param displayed
Is target element supposed to be displayed
@throws FailureException
if the scenario encounters a functional error. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT} message
(with screenshot, with exception) | [
"Checks",
"if",
"an",
"html",
"element",
"(",
"PageElement",
")",
"is",
"displayed",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L399-L413 |
aws/aws-sdk-java | aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/Connector.java | Connector.withParameters | public Connector withParameters(java.util.Map<String, String> parameters) {
"""
The parameters or configuration that the connector uses.
@param parameters
The parameters or configuration that the connector uses.
@return Returns a reference to this object so that method calls can be chained together.
"""
setParameters(parameters);
return this;
} | java | public Connector withParameters(java.util.Map<String, String> parameters) {
setParameters(parameters);
return this;
} | [
"public",
"Connector",
"withParameters",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"setParameters",
"(",
"parameters",
")",
";",
"return",
"this",
";",
"}"
] | The parameters or configuration that the connector uses.
@param parameters
The parameters or configuration that the connector uses.
@return Returns a reference to this object so that method calls can be chained together. | [
"The",
"parameters",
"or",
"configuration",
"that",
"the",
"connector",
"uses",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/Connector.java#L143-L146 |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java | ApiOvhXdsl.serviceName_lines_number_diagnostic_run_POST | public OvhDiagnostic serviceName_lines_number_diagnostic_run_POST(String serviceName, String number, OvhCustomerActionsEnum[] actionsDone, OvhAnswers answers, OvhFaultTypeEnum faultType) throws IOException {
"""
Update and get advanced diagnostic of the line
REST: POST /xdsl/{serviceName}/lines/{number}/diagnostic/run
@param actionsDone [required] Customer possible actions
@param answers [required] Customer answers for line diagnostic
@param faultType [required] [default=noSync] Line diagnostic type. Depends of problem
@param serviceName [required] The internal name of your XDSL offer
@param number [required] The number of the line
"""
String qPath = "/xdsl/{serviceName}/lines/{number}/diagnostic/run";
StringBuilder sb = path(qPath, serviceName, number);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "actionsDone", actionsDone);
addBody(o, "answers", answers);
addBody(o, "faultType", faultType);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhDiagnostic.class);
} | java | public OvhDiagnostic serviceName_lines_number_diagnostic_run_POST(String serviceName, String number, OvhCustomerActionsEnum[] actionsDone, OvhAnswers answers, OvhFaultTypeEnum faultType) throws IOException {
String qPath = "/xdsl/{serviceName}/lines/{number}/diagnostic/run";
StringBuilder sb = path(qPath, serviceName, number);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "actionsDone", actionsDone);
addBody(o, "answers", answers);
addBody(o, "faultType", faultType);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhDiagnostic.class);
} | [
"public",
"OvhDiagnostic",
"serviceName_lines_number_diagnostic_run_POST",
"(",
"String",
"serviceName",
",",
"String",
"number",
",",
"OvhCustomerActionsEnum",
"[",
"]",
"actionsDone",
",",
"OvhAnswers",
"answers",
",",
"OvhFaultTypeEnum",
"faultType",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/xdsl/{serviceName}/lines/{number}/diagnostic/run\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"serviceName",
",",
"number",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"o",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"addBody",
"(",
"o",
",",
"\"actionsDone\"",
",",
"actionsDone",
")",
";",
"addBody",
"(",
"o",
",",
"\"answers\"",
",",
"answers",
")",
";",
"addBody",
"(",
"o",
",",
"\"faultType\"",
",",
"faultType",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"POST\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"o",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhDiagnostic",
".",
"class",
")",
";",
"}"
] | Update and get advanced diagnostic of the line
REST: POST /xdsl/{serviceName}/lines/{number}/diagnostic/run
@param actionsDone [required] Customer possible actions
@param answers [required] Customer answers for line diagnostic
@param faultType [required] [default=noSync] Line diagnostic type. Depends of problem
@param serviceName [required] The internal name of your XDSL offer
@param number [required] The number of the line | [
"Update",
"and",
"get",
"advanced",
"diagnostic",
"of",
"the",
"line"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L412-L421 |
bwkimmel/java-util | src/main/java/ca/eandb/util/sql/DbUtil.java | DbUtil.queryString | public static String queryString(Connection con, String def, String query, Object... param) throws SQLException {
"""
Runs a SQL query that returns a single <code>String</code> value.
@param con The <code>Connection</code> against which to run the query.
@param def The default value to return if the query returns no results.
@param query The SQL query to run.
@param param The parameters to the SQL query.
@return The value returned by the query, or <code>def</code> if the
query returns no results. It is assumed that the query
returns a result set consisting of a single row and column, and
that this value is a <code>String</code>. Any additional rows or
columns returned will be ignored.
@throws SQLException If an error occurs while attempting to communicate
with the database.
"""
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(query);
stmt.setMaxRows(1);
for (int i = 0; i < param.length; i++) {
stmt.setObject(i + 1, param[i]);
}
return queryString(stmt, def);
} finally {
close(stmt);
}
} | java | public static String queryString(Connection con, String def, String query, Object... param) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(query);
stmt.setMaxRows(1);
for (int i = 0; i < param.length; i++) {
stmt.setObject(i + 1, param[i]);
}
return queryString(stmt, def);
} finally {
close(stmt);
}
} | [
"public",
"static",
"String",
"queryString",
"(",
"Connection",
"con",
",",
"String",
"def",
",",
"String",
"query",
",",
"Object",
"...",
"param",
")",
"throws",
"SQLException",
"{",
"PreparedStatement",
"stmt",
"=",
"null",
";",
"try",
"{",
"stmt",
"=",
"con",
".",
"prepareStatement",
"(",
"query",
")",
";",
"stmt",
".",
"setMaxRows",
"(",
"1",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"param",
".",
"length",
";",
"i",
"++",
")",
"{",
"stmt",
".",
"setObject",
"(",
"i",
"+",
"1",
",",
"param",
"[",
"i",
"]",
")",
";",
"}",
"return",
"queryString",
"(",
"stmt",
",",
"def",
")",
";",
"}",
"finally",
"{",
"close",
"(",
"stmt",
")",
";",
"}",
"}"
] | Runs a SQL query that returns a single <code>String</code> value.
@param con The <code>Connection</code> against which to run the query.
@param def The default value to return if the query returns no results.
@param query The SQL query to run.
@param param The parameters to the SQL query.
@return The value returned by the query, or <code>def</code> if the
query returns no results. It is assumed that the query
returns a result set consisting of a single row and column, and
that this value is a <code>String</code>. Any additional rows or
columns returned will be ignored.
@throws SQLException If an error occurs while attempting to communicate
with the database. | [
"Runs",
"a",
"SQL",
"query",
"that",
"returns",
"a",
"single",
"<code",
">",
"String<",
"/",
"code",
">",
"value",
"."
] | train | https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/sql/DbUtil.java#L163-L175 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java | EscapedFunctions2.sqllocate | public static void sqllocate(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
"""
locate translation
@param buf The buffer to append into
@param parsedArgs arguments
@throws SQLException if something wrong happens
"""
if (parsedArgs.size() == 2) {
appendCall(buf, "position(", " in ", ")", parsedArgs);
} else if (parsedArgs.size() == 3) {
String tmp = "position(" + parsedArgs.get(0) + " in substring(" + parsedArgs.get(1) + " from "
+ parsedArgs.get(2) + "))";
buf.append("(")
.append(parsedArgs.get(2))
.append("*sign(")
.append(tmp)
.append(")+")
.append(tmp)
.append(")");
} else {
throw new PSQLException(GT.tr("{0} function takes two or three arguments.", "locate"),
PSQLState.SYNTAX_ERROR);
}
} | java | public static void sqllocate(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
if (parsedArgs.size() == 2) {
appendCall(buf, "position(", " in ", ")", parsedArgs);
} else if (parsedArgs.size() == 3) {
String tmp = "position(" + parsedArgs.get(0) + " in substring(" + parsedArgs.get(1) + " from "
+ parsedArgs.get(2) + "))";
buf.append("(")
.append(parsedArgs.get(2))
.append("*sign(")
.append(tmp)
.append(")+")
.append(tmp)
.append(")");
} else {
throw new PSQLException(GT.tr("{0} function takes two or three arguments.", "locate"),
PSQLState.SYNTAX_ERROR);
}
} | [
"public",
"static",
"void",
"sqllocate",
"(",
"StringBuilder",
"buf",
",",
"List",
"<",
"?",
"extends",
"CharSequence",
">",
"parsedArgs",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"parsedArgs",
".",
"size",
"(",
")",
"==",
"2",
")",
"{",
"appendCall",
"(",
"buf",
",",
"\"position(\"",
",",
"\" in \"",
",",
"\")\"",
",",
"parsedArgs",
")",
";",
"}",
"else",
"if",
"(",
"parsedArgs",
".",
"size",
"(",
")",
"==",
"3",
")",
"{",
"String",
"tmp",
"=",
"\"position(\"",
"+",
"parsedArgs",
".",
"get",
"(",
"0",
")",
"+",
"\" in substring(\"",
"+",
"parsedArgs",
".",
"get",
"(",
"1",
")",
"+",
"\" from \"",
"+",
"parsedArgs",
".",
"get",
"(",
"2",
")",
"+",
"\"))\"",
";",
"buf",
".",
"append",
"(",
"\"(\"",
")",
".",
"append",
"(",
"parsedArgs",
".",
"get",
"(",
"2",
")",
")",
".",
"append",
"(",
"\"*sign(\"",
")",
".",
"append",
"(",
"tmp",
")",
".",
"append",
"(",
"\")+\"",
")",
".",
"append",
"(",
"tmp",
")",
".",
"append",
"(",
"\")\"",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"PSQLException",
"(",
"GT",
".",
"tr",
"(",
"\"{0} function takes two or three arguments.\"",
",",
"\"locate\"",
")",
",",
"PSQLState",
".",
"SYNTAX_ERROR",
")",
";",
"}",
"}"
] | locate translation
@param buf The buffer to append into
@param parsedArgs arguments
@throws SQLException if something wrong happens | [
"locate",
"translation"
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L224-L241 |
JohnPersano/SuperToasts | library/src/main/java/com/github/johnpersano/supertoasts/library/SuperToast.java | SuperToast.onCreateView | @SuppressLint("InflateParams")
protected View onCreateView(Context context, LayoutInflater layoutInflater, int type) {
"""
Protected View that is overridden by the SuperActivityToast class.
"""
return layoutInflater.inflate(R.layout.supertoast, null);
} | java | @SuppressLint("InflateParams")
protected View onCreateView(Context context, LayoutInflater layoutInflater, int type) {
return layoutInflater.inflate(R.layout.supertoast, null);
} | [
"@",
"SuppressLint",
"(",
"\"InflateParams\"",
")",
"protected",
"View",
"onCreateView",
"(",
"Context",
"context",
",",
"LayoutInflater",
"layoutInflater",
",",
"int",
"type",
")",
"{",
"return",
"layoutInflater",
".",
"inflate",
"(",
"R",
".",
"layout",
".",
"supertoast",
",",
"null",
")",
";",
"}"
] | Protected View that is overridden by the SuperActivityToast class. | [
"Protected",
"View",
"that",
"is",
"overridden",
"by",
"the",
"SuperActivityToast",
"class",
"."
] | train | https://github.com/JohnPersano/SuperToasts/blob/5394db6a2f5c38410586d5d001d61f731da1132a/library/src/main/java/com/github/johnpersano/supertoasts/library/SuperToast.java#L154-L157 |
BlueBrain/bluima | modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/util/CountedNumberedSet.java | CountedNumberedSet.setCount | public void setCount(Object o,int c) {
"""
Assigns the specified object the specified count in the set.
@param o The object to be added or updated in the set.
@param c The count of the specified object.
"""
int[] nums = (int[]) cset.get(o);
if (nums != null) {
nums[0] = c;
}
else {
cset.put(o,new int[]{c,1});
}
} | java | public void setCount(Object o,int c) {
int[] nums = (int[]) cset.get(o);
if (nums != null) {
nums[0] = c;
}
else {
cset.put(o,new int[]{c,1});
}
} | [
"public",
"void",
"setCount",
"(",
"Object",
"o",
",",
"int",
"c",
")",
"{",
"int",
"[",
"]",
"nums",
"=",
"(",
"int",
"[",
"]",
")",
"cset",
".",
"get",
"(",
"o",
")",
";",
"if",
"(",
"nums",
"!=",
"null",
")",
"{",
"nums",
"[",
"0",
"]",
"=",
"c",
";",
"}",
"else",
"{",
"cset",
".",
"put",
"(",
"o",
",",
"new",
"int",
"[",
"]",
"{",
"c",
",",
"1",
"}",
")",
";",
"}",
"}"
] | Assigns the specified object the specified count in the set.
@param o The object to be added or updated in the set.
@param c The count of the specified object. | [
"Assigns",
"the",
"specified",
"object",
"the",
"specified",
"count",
"in",
"the",
"set",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/util/CountedNumberedSet.java#L70-L78 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFolder.java | BoxApiFolder.getAddToCollectionRequest | public BoxRequestsFolder.AddFolderToCollection getAddToCollectionRequest(String folderId, String collectionId) {
"""
Gets a request that adds a folder to a collection
@param folderId id of folder to add to collection
@param collectionId id of collection to add the folder to
@return request to add a folder to a collection
"""
BoxRequestsFolder.AddFolderToCollection request = new BoxRequestsFolder.AddFolderToCollection(folderId, collectionId, getFolderInfoUrl(folderId), mSession);
return request;
} | java | public BoxRequestsFolder.AddFolderToCollection getAddToCollectionRequest(String folderId, String collectionId) {
BoxRequestsFolder.AddFolderToCollection request = new BoxRequestsFolder.AddFolderToCollection(folderId, collectionId, getFolderInfoUrl(folderId), mSession);
return request;
} | [
"public",
"BoxRequestsFolder",
".",
"AddFolderToCollection",
"getAddToCollectionRequest",
"(",
"String",
"folderId",
",",
"String",
"collectionId",
")",
"{",
"BoxRequestsFolder",
".",
"AddFolderToCollection",
"request",
"=",
"new",
"BoxRequestsFolder",
".",
"AddFolderToCollection",
"(",
"folderId",
",",
"collectionId",
",",
"getFolderInfoUrl",
"(",
"folderId",
")",
",",
"mSession",
")",
";",
"return",
"request",
";",
"}"
] | Gets a request that adds a folder to a collection
@param folderId id of folder to add to collection
@param collectionId id of collection to add the folder to
@return request to add a folder to a collection | [
"Gets",
"a",
"request",
"that",
"adds",
"a",
"folder",
"to",
"a",
"collection"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFolder.java#L228-L231 |
jbundle/jbundle | model/base/src/main/java/org/jbundle/model/util/Util.java | Util.getPackageName | public static String getPackageName(String className, boolean resource) {
"""
Get the package name of this class name
@param className
@return
"""
String packageName = null;
if (className != null)
{
if (resource)
if (className.endsWith(PROPERTIES))
className = className.substring(0, className.length() - PROPERTIES.length());
if (className.lastIndexOf('.') != -1)
packageName = className.substring(0, className.lastIndexOf('.'));
}
return packageName;
} | java | public static String getPackageName(String className, boolean resource)
{
String packageName = null;
if (className != null)
{
if (resource)
if (className.endsWith(PROPERTIES))
className = className.substring(0, className.length() - PROPERTIES.length());
if (className.lastIndexOf('.') != -1)
packageName = className.substring(0, className.lastIndexOf('.'));
}
return packageName;
} | [
"public",
"static",
"String",
"getPackageName",
"(",
"String",
"className",
",",
"boolean",
"resource",
")",
"{",
"String",
"packageName",
"=",
"null",
";",
"if",
"(",
"className",
"!=",
"null",
")",
"{",
"if",
"(",
"resource",
")",
"if",
"(",
"className",
".",
"endsWith",
"(",
"PROPERTIES",
")",
")",
"className",
"=",
"className",
".",
"substring",
"(",
"0",
",",
"className",
".",
"length",
"(",
")",
"-",
"PROPERTIES",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"className",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
"!=",
"-",
"1",
")",
"packageName",
"=",
"className",
".",
"substring",
"(",
"0",
",",
"className",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
")",
";",
"}",
"return",
"packageName",
";",
"}"
] | Get the package name of this class name
@param className
@return | [
"Get",
"the",
"package",
"name",
"of",
"this",
"class",
"name"
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/model/base/src/main/java/org/jbundle/model/util/Util.java#L553-L565 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getCatInfo | public void getCatInfo(int[] ids, Callback<List<Cat>> callback) throws GuildWars2Exception, NullPointerException {
"""
For more info on cats API go <a href="https://wiki.guildwars2.com/wiki/API:2/cats">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of cat id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see Cat cat info
"""
isParamValid(new ParamChecker(ids));
gw2API.getCatInfo(processIds(ids)).enqueue(callback);
} | java | public void getCatInfo(int[] ids, Callback<List<Cat>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getCatInfo(processIds(ids)).enqueue(callback);
} | [
"public",
"void",
"getCatInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"Cat",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids",
")",
")",
";",
"gw2API",
".",
"getCatInfo",
"(",
"processIds",
"(",
"ids",
")",
")",
".",
"enqueue",
"(",
"callback",
")",
";",
"}"
] | For more info on cats API go <a href="https://wiki.guildwars2.com/wiki/API:2/cats">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of cat id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see Cat cat info | [
"For",
"more",
"info",
"on",
"cats",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"cats",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user",
"the",
"access",
"to",
"{",
"@link",
"Callback#onResponse",
"(",
"Call",
"Response",
")",
"}",
"and",
"{",
"@link",
"Callback#onFailure",
"(",
"Call",
"Throwable",
")",
"}",
"methods",
"for",
"custom",
"interactions"
] | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L659-L662 |
alkacon/opencms-core | src/org/opencms/staticexport/CmsLinkManager.java | CmsLinkManager.getOnlineLink | public String getOnlineLink(CmsObject cms, String resourceName) {
"""
Returns the online link for the given resource, with full server prefix.<p>
Like <code>http://site.enterprise.com:8080/index.html</code>.<p>
In case the resource name is a full root path, the site from the root path will be used.
Otherwise the resource is assumed to be in the current site set be the OpenCms user context.<p>
Please note that this method will always return the link as it will appear in the "Online"
project, that is after the resource has been published. In case you need a method that
just returns the link with the full server prefix, use {@link #getServerLink(CmsObject, String)}.<p>
@param cms the current OpenCms user context
@param resourceName the resource to generate the online link for
@return the online link for the given resource, with full server prefix
@see #getServerLink(CmsObject, String)
"""
return getOnlineLink(cms, resourceName, false);
} | java | public String getOnlineLink(CmsObject cms, String resourceName) {
return getOnlineLink(cms, resourceName, false);
} | [
"public",
"String",
"getOnlineLink",
"(",
"CmsObject",
"cms",
",",
"String",
"resourceName",
")",
"{",
"return",
"getOnlineLink",
"(",
"cms",
",",
"resourceName",
",",
"false",
")",
";",
"}"
] | Returns the online link for the given resource, with full server prefix.<p>
Like <code>http://site.enterprise.com:8080/index.html</code>.<p>
In case the resource name is a full root path, the site from the root path will be used.
Otherwise the resource is assumed to be in the current site set be the OpenCms user context.<p>
Please note that this method will always return the link as it will appear in the "Online"
project, that is after the resource has been published. In case you need a method that
just returns the link with the full server prefix, use {@link #getServerLink(CmsObject, String)}.<p>
@param cms the current OpenCms user context
@param resourceName the resource to generate the online link for
@return the online link for the given resource, with full server prefix
@see #getServerLink(CmsObject, String) | [
"Returns",
"the",
"online",
"link",
"for",
"the",
"given",
"resource",
"with",
"full",
"server",
"prefix",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L308-L311 |
xwiki/xwiki-commons | xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-default/src/main/java/org/xwiki/component/annotation/ComponentAnnotationLoader.java | ComponentAnnotationLoader.getGenericInterfaces | private Type[] getGenericInterfaces(Class<?> componentClass) {
"""
Helper method that generate a {@link RuntimeException} in case of a reflection error.
@param componentClass the component for which to return the interface types
@return the Types representing the interfaces directly implemented by the class or interface represented by this
object
@throws RuntimeException in case of a reflection error such as
{@link java.lang.reflect.MalformedParameterizedTypeException}
"""
Type[] interfaceTypes;
try {
interfaceTypes = componentClass.getGenericInterfaces();
} catch (Exception e) {
throw new RuntimeException(String.format("Failed to get interface for [%s]", componentClass.getName()), e);
}
return interfaceTypes;
} | java | private Type[] getGenericInterfaces(Class<?> componentClass)
{
Type[] interfaceTypes;
try {
interfaceTypes = componentClass.getGenericInterfaces();
} catch (Exception e) {
throw new RuntimeException(String.format("Failed to get interface for [%s]", componentClass.getName()), e);
}
return interfaceTypes;
} | [
"private",
"Type",
"[",
"]",
"getGenericInterfaces",
"(",
"Class",
"<",
"?",
">",
"componentClass",
")",
"{",
"Type",
"[",
"]",
"interfaceTypes",
";",
"try",
"{",
"interfaceTypes",
"=",
"componentClass",
".",
"getGenericInterfaces",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"Failed to get interface for [%s]\"",
",",
"componentClass",
".",
"getName",
"(",
")",
")",
",",
"e",
")",
";",
"}",
"return",
"interfaceTypes",
";",
"}"
] | Helper method that generate a {@link RuntimeException} in case of a reflection error.
@param componentClass the component for which to return the interface types
@return the Types representing the interfaces directly implemented by the class or interface represented by this
object
@throws RuntimeException in case of a reflection error such as
{@link java.lang.reflect.MalformedParameterizedTypeException} | [
"Helper",
"method",
"that",
"generate",
"a",
"{",
"@link",
"RuntimeException",
"}",
"in",
"case",
"of",
"a",
"reflection",
"error",
"."
] | train | https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-default/src/main/java/org/xwiki/component/annotation/ComponentAnnotationLoader.java#L397-L406 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/accounts/CmsEditUserAddInfoDialog.java | CmsEditUserAddInfoDialog.setInfo | public void setInfo(SortedMap<String, Object> addInfo) {
"""
Sets the modified additional information.<p>
@param addInfo the additional information to set
"""
m_addInfoEditable = new TreeMap<String, Object>(addInfo);
} | java | public void setInfo(SortedMap<String, Object> addInfo) {
m_addInfoEditable = new TreeMap<String, Object>(addInfo);
} | [
"public",
"void",
"setInfo",
"(",
"SortedMap",
"<",
"String",
",",
"Object",
">",
"addInfo",
")",
"{",
"m_addInfoEditable",
"=",
"new",
"TreeMap",
"<",
"String",
",",
"Object",
">",
"(",
"addInfo",
")",
";",
"}"
] | Sets the modified additional information.<p>
@param addInfo the additional information to set | [
"Sets",
"the",
"modified",
"additional",
"information",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/accounts/CmsEditUserAddInfoDialog.java#L257-L260 |
alexvasilkov/AndroidCommons | library/src/main/java/com/alexvasilkov/android/commons/prefs/PreferencesHelper.java | PreferencesHelper.getStringArray | @Nullable
public static String[] getStringArray(@NonNull SharedPreferences prefs,
@NonNull String key, @NonNull String delimiter) {
"""
Retrieves strings array stored as single string.
@param delimiter Delimiter used to split the string.
"""
return split(prefs.getString(key, null), delimiter);
} | java | @Nullable
public static String[] getStringArray(@NonNull SharedPreferences prefs,
@NonNull String key, @NonNull String delimiter) {
return split(prefs.getString(key, null), delimiter);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"[",
"]",
"getStringArray",
"(",
"@",
"NonNull",
"SharedPreferences",
"prefs",
",",
"@",
"NonNull",
"String",
"key",
",",
"@",
"NonNull",
"String",
"delimiter",
")",
"{",
"return",
"split",
"(",
"prefs",
".",
"getString",
"(",
"key",
",",
"null",
")",
",",
"delimiter",
")",
";",
"}"
] | Retrieves strings array stored as single string.
@param delimiter Delimiter used to split the string. | [
"Retrieves",
"strings",
"array",
"stored",
"as",
"single",
"string",
"."
] | train | https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/prefs/PreferencesHelper.java#L91-L95 |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java | KuberntesServiceUrlResourceProvider.getPort | private static int getPort(Service service, Annotation... qualifiers) {
"""
Find the the qualified container port of the target service
Uses java annotations first or returns the container port.
@param service
The target service.
@param qualifiers
The set of qualifiers.
@return Returns the resolved containerPort of '0' as a fallback.
"""
for (Annotation q : qualifiers) {
if (q instanceof Port) {
Port port = (Port) q;
if (port.value() > 0) {
return port.value();
}
}
}
ServicePort servicePort = findQualifiedServicePort(service, qualifiers);
if (servicePort != null) {
return servicePort.getPort();
}
return 0;
} | java | private static int getPort(Service service, Annotation... qualifiers) {
for (Annotation q : qualifiers) {
if (q instanceof Port) {
Port port = (Port) q;
if (port.value() > 0) {
return port.value();
}
}
}
ServicePort servicePort = findQualifiedServicePort(service, qualifiers);
if (servicePort != null) {
return servicePort.getPort();
}
return 0;
} | [
"private",
"static",
"int",
"getPort",
"(",
"Service",
"service",
",",
"Annotation",
"...",
"qualifiers",
")",
"{",
"for",
"(",
"Annotation",
"q",
":",
"qualifiers",
")",
"{",
"if",
"(",
"q",
"instanceof",
"Port",
")",
"{",
"Port",
"port",
"=",
"(",
"Port",
")",
"q",
";",
"if",
"(",
"port",
".",
"value",
"(",
")",
">",
"0",
")",
"{",
"return",
"port",
".",
"value",
"(",
")",
";",
"}",
"}",
"}",
"ServicePort",
"servicePort",
"=",
"findQualifiedServicePort",
"(",
"service",
",",
"qualifiers",
")",
";",
"if",
"(",
"servicePort",
"!=",
"null",
")",
"{",
"return",
"servicePort",
".",
"getPort",
"(",
")",
";",
"}",
"return",
"0",
";",
"}"
] | Find the the qualified container port of the target service
Uses java annotations first or returns the container port.
@param service
The target service.
@param qualifiers
The set of qualifiers.
@return Returns the resolved containerPort of '0' as a fallback. | [
"Find",
"the",
"the",
"qualified",
"container",
"port",
"of",
"the",
"target",
"service",
"Uses",
"java",
"annotations",
"first",
"or",
"returns",
"the",
"container",
"port",
"."
] | train | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java#L128-L143 |
banq/jdonframework | src/main/java/com/jdon/controller/service/WebServiceFactory.java | WebServiceFactory.getService | public Object getService(TargetMetaDef targetMetaDef, RequestWrapper request) {
"""
get a service instance the service must have a interface and implements
it.
"""
userTargetMetaDefFactory.createTargetMetaRequest(targetMetaDef, request.getContextHolder());
return webServiceAccessor.getService(request);
} | java | public Object getService(TargetMetaDef targetMetaDef, RequestWrapper request) {
userTargetMetaDefFactory.createTargetMetaRequest(targetMetaDef, request.getContextHolder());
return webServiceAccessor.getService(request);
} | [
"public",
"Object",
"getService",
"(",
"TargetMetaDef",
"targetMetaDef",
",",
"RequestWrapper",
"request",
")",
"{",
"userTargetMetaDefFactory",
".",
"createTargetMetaRequest",
"(",
"targetMetaDef",
",",
"request",
".",
"getContextHolder",
"(",
")",
")",
";",
"return",
"webServiceAccessor",
".",
"getService",
"(",
"request",
")",
";",
"}"
] | get a service instance the service must have a interface and implements
it. | [
"get",
"a",
"service",
"instance",
"the",
"service",
"must",
"have",
"a",
"interface",
"and",
"implements",
"it",
"."
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/controller/service/WebServiceFactory.java#L68-L71 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancersInner.java | LoadBalancersInner.updateTags | public LoadBalancerInner updateTags(String resourceGroupName, String loadBalancerName, Map<String, String> tags) {
"""
Updates a load balancer tags.
@param resourceGroupName The name of the resource group.
@param loadBalancerName The name of the load balancer.
@param tags Resource tags.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the LoadBalancerInner object if successful.
"""
return updateTagsWithServiceResponseAsync(resourceGroupName, loadBalancerName, tags).toBlocking().last().body();
} | java | public LoadBalancerInner updateTags(String resourceGroupName, String loadBalancerName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, loadBalancerName, tags).toBlocking().last().body();
} | [
"public",
"LoadBalancerInner",
"updateTags",
"(",
"String",
"resourceGroupName",
",",
"String",
"loadBalancerName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"return",
"updateTagsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"loadBalancerName",
",",
"tags",
")",
".",
"toBlocking",
"(",
")",
".",
"last",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
] | Updates a load balancer tags.
@param resourceGroupName The name of the resource group.
@param loadBalancerName The name of the load balancer.
@param tags Resource tags.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the LoadBalancerInner object if successful. | [
"Updates",
"a",
"load",
"balancer",
"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/LoadBalancersInner.java#L681-L683 |
looly/hutool | hutool-json/src/main/java/cn/hutool/json/JSONUtil.java | JSONUtil.toBean | public static <T> T toBean(String jsonString, Class<T> beanClass) {
"""
JSON字符串转为实体类对象,转换异常将被抛出
@param <T> Bean类型
@param jsonString JSON字符串
@param beanClass 实体类对象
@return 实体类对象
@since 3.1.2
"""
return toBean(parseObj(jsonString), beanClass);
} | java | public static <T> T toBean(String jsonString, Class<T> beanClass) {
return toBean(parseObj(jsonString), beanClass);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"toBean",
"(",
"String",
"jsonString",
",",
"Class",
"<",
"T",
">",
"beanClass",
")",
"{",
"return",
"toBean",
"(",
"parseObj",
"(",
"jsonString",
")",
",",
"beanClass",
")",
";",
"}"
] | JSON字符串转为实体类对象,转换异常将被抛出
@param <T> Bean类型
@param jsonString JSON字符串
@param beanClass 实体类对象
@return 实体类对象
@since 3.1.2 | [
"JSON字符串转为实体类对象,转换异常将被抛出"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-json/src/main/java/cn/hutool/json/JSONUtil.java#L330-L332 |
ops4j/org.ops4j.base | ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java | ResourceManager.getBaseResources | public static Resources getBaseResources( String baseName, Locale locale, ClassLoader classLoader ) {
"""
Retrieve resource with specified basename.
@param baseName the basename
@param classLoader the classLoader to load resources from
@param locale the locale of the resources requested.
@return the Resources
"""
synchronized( ResourceManager.class )
{
Resources resources = getCachedResource( baseName + "_" + locale.hashCode() );
if( null == resources )
{
resources = new Resources( baseName, locale, classLoader );
putCachedResource( baseName + "_" + locale.hashCode(), resources );
}
return resources;
}
} | java | public static Resources getBaseResources( String baseName, Locale locale, ClassLoader classLoader )
{
synchronized( ResourceManager.class )
{
Resources resources = getCachedResource( baseName + "_" + locale.hashCode() );
if( null == resources )
{
resources = new Resources( baseName, locale, classLoader );
putCachedResource( baseName + "_" + locale.hashCode(), resources );
}
return resources;
}
} | [
"public",
"static",
"Resources",
"getBaseResources",
"(",
"String",
"baseName",
",",
"Locale",
"locale",
",",
"ClassLoader",
"classLoader",
")",
"{",
"synchronized",
"(",
"ResourceManager",
".",
"class",
")",
"{",
"Resources",
"resources",
"=",
"getCachedResource",
"(",
"baseName",
"+",
"\"_\"",
"+",
"locale",
".",
"hashCode",
"(",
")",
")",
";",
"if",
"(",
"null",
"==",
"resources",
")",
"{",
"resources",
"=",
"new",
"Resources",
"(",
"baseName",
",",
"locale",
",",
"classLoader",
")",
";",
"putCachedResource",
"(",
"baseName",
"+",
"\"_\"",
"+",
"locale",
".",
"hashCode",
"(",
")",
",",
"resources",
")",
";",
"}",
"return",
"resources",
";",
"}",
"}"
] | Retrieve resource with specified basename.
@param baseName the basename
@param classLoader the classLoader to load resources from
@param locale the locale of the resources requested.
@return the Resources | [
"Retrieve",
"resource",
"with",
"specified",
"basename",
"."
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util/src/main/java/org/ops4j/util/i18n/ResourceManager.java#L96-L108 |
Wikidata/Wikidata-Toolkit | wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/Datamodel.java | Datamodel.makeFormIdValue | public static FormIdValue makeFormIdValue(String id, String siteIri) {
"""
Creates an {@link FormIdValue}.
@param id
a string of the form Ln...-Fm... where n... and m... are the string
representation of a positive integer number
@param siteIri
IRI to identify the site, usually the first part of the entity
IRI of the site this belongs to, e.g.,
"http://www.wikidata.org/entity/"
@return an {@link FormIdValue} corresponding to the input
"""
return factory.getFormIdValue(id, siteIri);
} | java | public static FormIdValue makeFormIdValue(String id, String siteIri) {
return factory.getFormIdValue(id, siteIri);
} | [
"public",
"static",
"FormIdValue",
"makeFormIdValue",
"(",
"String",
"id",
",",
"String",
"siteIri",
")",
"{",
"return",
"factory",
".",
"getFormIdValue",
"(",
"id",
",",
"siteIri",
")",
";",
"}"
] | Creates an {@link FormIdValue}.
@param id
a string of the form Ln...-Fm... where n... and m... are the string
representation of a positive integer number
@param siteIri
IRI to identify the site, usually the first part of the entity
IRI of the site this belongs to, e.g.,
"http://www.wikidata.org/entity/"
@return an {@link FormIdValue} corresponding to the input | [
"Creates",
"an",
"{",
"@link",
"FormIdValue",
"}",
"."
] | train | https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/Datamodel.java#L142-L144 |
litsec/swedish-eid-shibboleth-base | shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java | AbstractExternalAuthenticationController.servicesProcessRequest | protected void servicesProcessRequest(ProfileRequestContext<?, ?> profileRequestContext) throws ExternalAutenticationErrorCodeException {
"""
Invokes request processing for all installed services. Subclasses should override this method to invoke their own
services.
@param profileRequestContext
the request context
@throws ExternalAutenticationErrorCodeException
for errors during processing
"""
this.authnContextService.processRequest(profileRequestContext);
this.signSupportService.processRequest(profileRequestContext);
} | java | protected void servicesProcessRequest(ProfileRequestContext<?, ?> profileRequestContext) throws ExternalAutenticationErrorCodeException {
this.authnContextService.processRequest(profileRequestContext);
this.signSupportService.processRequest(profileRequestContext);
} | [
"protected",
"void",
"servicesProcessRequest",
"(",
"ProfileRequestContext",
"<",
"?",
",",
"?",
">",
"profileRequestContext",
")",
"throws",
"ExternalAutenticationErrorCodeException",
"{",
"this",
".",
"authnContextService",
".",
"processRequest",
"(",
"profileRequestContext",
")",
";",
"this",
".",
"signSupportService",
".",
"processRequest",
"(",
"profileRequestContext",
")",
";",
"}"
] | Invokes request processing for all installed services. Subclasses should override this method to invoke their own
services.
@param profileRequestContext
the request context
@throws ExternalAutenticationErrorCodeException
for errors during processing | [
"Invokes",
"request",
"processing",
"for",
"all",
"installed",
"services",
".",
"Subclasses",
"should",
"override",
"this",
"method",
"to",
"invoke",
"their",
"own",
"services",
"."
] | train | https://github.com/litsec/swedish-eid-shibboleth-base/blob/aaaa467ff61f07d7dfa31627fb36851a37da6804/shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java#L226-L229 |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.gainPrincipalFromAlias | private String gainPrincipalFromAlias(String alias, KeyStore keystore) throws Exception {
"""
Private method for gaining X500Principal from keystore according its alias.
@param alias alias of principal
@param keystore KeyStore which is used by this policy file
@return name of gained X500Principal
@throws Exception when there was any problem during gaining Principal
"""
if (keystore == null) {
return null;
}
if (!keystore.containsAlias(alias)) {
return null;
}
Certificate certificate = keystore.getCertificate(alias);
if (certificate == null || !(certificate instanceof X509Certificate)) {
return null;
}
X509Certificate x509Certificate = (X509Certificate) certificate;
X500Principal principal = new X500Principal(x509Certificate.getSubjectX500Principal().toString());
return principal.getName();
} | java | private String gainPrincipalFromAlias(String alias, KeyStore keystore) throws Exception {
if (keystore == null) {
return null;
}
if (!keystore.containsAlias(alias)) {
return null;
}
Certificate certificate = keystore.getCertificate(alias);
if (certificate == null || !(certificate instanceof X509Certificate)) {
return null;
}
X509Certificate x509Certificate = (X509Certificate) certificate;
X500Principal principal = new X500Principal(x509Certificate.getSubjectX500Principal().toString());
return principal.getName();
} | [
"private",
"String",
"gainPrincipalFromAlias",
"(",
"String",
"alias",
",",
"KeyStore",
"keystore",
")",
"throws",
"Exception",
"{",
"if",
"(",
"keystore",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"keystore",
".",
"containsAlias",
"(",
"alias",
")",
")",
"{",
"return",
"null",
";",
"}",
"Certificate",
"certificate",
"=",
"keystore",
".",
"getCertificate",
"(",
"alias",
")",
";",
"if",
"(",
"certificate",
"==",
"null",
"||",
"!",
"(",
"certificate",
"instanceof",
"X509Certificate",
")",
")",
"{",
"return",
"null",
";",
"}",
"X509Certificate",
"x509Certificate",
"=",
"(",
"X509Certificate",
")",
"certificate",
";",
"X500Principal",
"principal",
"=",
"new",
"X500Principal",
"(",
"x509Certificate",
".",
"getSubjectX500Principal",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"return",
"principal",
".",
"getName",
"(",
")",
";",
"}"
] | Private method for gaining X500Principal from keystore according its alias.
@param alias alias of principal
@param keystore KeyStore which is used by this policy file
@return name of gained X500Principal
@throws Exception when there was any problem during gaining Principal | [
"Private",
"method",
"for",
"gaining",
"X500Principal",
"from",
"keystore",
"according",
"its",
"alias",
"."
] | train | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L714-L730 |
Alluxio/alluxio | shell/src/main/java/alluxio/cli/fs/command/CpCommand.java | CpCommand.asyncCopyLocalPath | private void asyncCopyLocalPath(CopyThreadPoolExecutor pool, AlluxioURI srcPath,
AlluxioURI dstPath) throws InterruptedException {
"""
Asynchronously copies a file or directory specified by srcPath from the local filesystem to
dstPath in the Alluxio filesystem space, assuming dstPath does not exist.
@param srcPath the {@link AlluxioURI} of the source file in the local filesystem
@param dstPath the {@link AlluxioURI} of the destination
@throws InterruptedException when failed to send messages to the pool
"""
File src = new File(srcPath.getPath());
if (!src.isDirectory()) {
pool.submit(() -> {
try {
copyFromLocalFile(srcPath, dstPath);
pool.succeed(srcPath, dstPath);
} catch (Exception e) {
pool.fail(srcPath, dstPath, e);
}
return null;
});
} else {
try {
mFileSystem.createDirectory(dstPath);
} catch (Exception e) {
pool.fail(srcPath, dstPath, e);
return;
}
File[] fileList = src.listFiles();
if (fileList == null) {
pool.fail(srcPath, dstPath,
new IOException(String.format("Failed to list directory %s.", src)));
return;
}
for (File srcFile : fileList) {
AlluxioURI newURI = new AlluxioURI(dstPath, new AlluxioURI(srcFile.getName()));
asyncCopyLocalPath(pool,
new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), srcFile.getPath()),
newURI);
}
}
} | java | private void asyncCopyLocalPath(CopyThreadPoolExecutor pool, AlluxioURI srcPath,
AlluxioURI dstPath) throws InterruptedException {
File src = new File(srcPath.getPath());
if (!src.isDirectory()) {
pool.submit(() -> {
try {
copyFromLocalFile(srcPath, dstPath);
pool.succeed(srcPath, dstPath);
} catch (Exception e) {
pool.fail(srcPath, dstPath, e);
}
return null;
});
} else {
try {
mFileSystem.createDirectory(dstPath);
} catch (Exception e) {
pool.fail(srcPath, dstPath, e);
return;
}
File[] fileList = src.listFiles();
if (fileList == null) {
pool.fail(srcPath, dstPath,
new IOException(String.format("Failed to list directory %s.", src)));
return;
}
for (File srcFile : fileList) {
AlluxioURI newURI = new AlluxioURI(dstPath, new AlluxioURI(srcFile.getName()));
asyncCopyLocalPath(pool,
new AlluxioURI(srcPath.getScheme(), srcPath.getAuthority(), srcFile.getPath()),
newURI);
}
}
} | [
"private",
"void",
"asyncCopyLocalPath",
"(",
"CopyThreadPoolExecutor",
"pool",
",",
"AlluxioURI",
"srcPath",
",",
"AlluxioURI",
"dstPath",
")",
"throws",
"InterruptedException",
"{",
"File",
"src",
"=",
"new",
"File",
"(",
"srcPath",
".",
"getPath",
"(",
")",
")",
";",
"if",
"(",
"!",
"src",
".",
"isDirectory",
"(",
")",
")",
"{",
"pool",
".",
"submit",
"(",
"(",
")",
"->",
"{",
"try",
"{",
"copyFromLocalFile",
"(",
"srcPath",
",",
"dstPath",
")",
";",
"pool",
".",
"succeed",
"(",
"srcPath",
",",
"dstPath",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"pool",
".",
"fail",
"(",
"srcPath",
",",
"dstPath",
",",
"e",
")",
";",
"}",
"return",
"null",
";",
"}",
")",
";",
"}",
"else",
"{",
"try",
"{",
"mFileSystem",
".",
"createDirectory",
"(",
"dstPath",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"pool",
".",
"fail",
"(",
"srcPath",
",",
"dstPath",
",",
"e",
")",
";",
"return",
";",
"}",
"File",
"[",
"]",
"fileList",
"=",
"src",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"fileList",
"==",
"null",
")",
"{",
"pool",
".",
"fail",
"(",
"srcPath",
",",
"dstPath",
",",
"new",
"IOException",
"(",
"String",
".",
"format",
"(",
"\"Failed to list directory %s.\"",
",",
"src",
")",
")",
")",
";",
"return",
";",
"}",
"for",
"(",
"File",
"srcFile",
":",
"fileList",
")",
"{",
"AlluxioURI",
"newURI",
"=",
"new",
"AlluxioURI",
"(",
"dstPath",
",",
"new",
"AlluxioURI",
"(",
"srcFile",
".",
"getName",
"(",
")",
")",
")",
";",
"asyncCopyLocalPath",
"(",
"pool",
",",
"new",
"AlluxioURI",
"(",
"srcPath",
".",
"getScheme",
"(",
")",
",",
"srcPath",
".",
"getAuthority",
"(",
")",
",",
"srcFile",
".",
"getPath",
"(",
")",
")",
",",
"newURI",
")",
";",
"}",
"}",
"}"
] | Asynchronously copies a file or directory specified by srcPath from the local filesystem to
dstPath in the Alluxio filesystem space, assuming dstPath does not exist.
@param srcPath the {@link AlluxioURI} of the source file in the local filesystem
@param dstPath the {@link AlluxioURI} of the destination
@throws InterruptedException when failed to send messages to the pool | [
"Asynchronously",
"copies",
"a",
"file",
"or",
"directory",
"specified",
"by",
"srcPath",
"from",
"the",
"local",
"filesystem",
"to",
"dstPath",
"in",
"the",
"Alluxio",
"filesystem",
"space",
"assuming",
"dstPath",
"does",
"not",
"exist",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/CpCommand.java#L632-L665 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/JMSServices.java | JMSServices.broadcastTextMessage | public void broadcastTextMessage(String topicName, String textMessage, int delaySeconds)
throws NamingException, JMSException, ServiceLocatorException {
"""
Sends the passed in text message to a local topic
@param topicName
@param pMessage
@param delaySeconds
@throws ServiceLocatorException
"""
if (mdwMessageProducer != null) {
mdwMessageProducer.broadcastMessageToTopic(topicName, textMessage);
}
else {
TopicConnectionFactory tFactory = null;
TopicConnection tConnection = null;
TopicSession tSession = null;
TopicPublisher tPublisher = null;
try {
// if (logger.isDebugEnabled()) logger.debug("broadcast JMS
// message: " +
// textMessage);
// cannot log above - causing recursive broadcasting
tFactory = getTopicConnectionFactory(null);
tConnection = tFactory.createTopicConnection();
tSession = tConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = getTopic(topicName);
tPublisher = tSession.createPublisher(topic);
// TODO: platform-independent delay
// WLMessageProducer wlMessageProducer =
// (WLMessageProducer)tPublisher;
// long delayInMilliSec = 0;
// if(pMinDelay > 0){
// delayInMilliSec = delaySeconds*1000;
// }
// wlMessageProducer.setTimeToDeliver(delayInMilliSec);
TextMessage message = tSession.createTextMessage();
tConnection.start();
message.setText(textMessage);
tPublisher.publish(message, DeliveryMode.PERSISTENT,
TextMessage.DEFAULT_DELIVERY_MODE, TextMessage.DEFAULT_TIME_TO_LIVE);
// }catch(ServiceLocatorException ex){
// ex.printStackTrace();
// never log exception here!!! infinite loop when publishing log
// messages
// throw new JMSException(ex.getMessage());
}
finally {
closeResources(tConnection, tSession, tPublisher);
}
}
} | java | public void broadcastTextMessage(String topicName, String textMessage, int delaySeconds)
throws NamingException, JMSException, ServiceLocatorException {
if (mdwMessageProducer != null) {
mdwMessageProducer.broadcastMessageToTopic(topicName, textMessage);
}
else {
TopicConnectionFactory tFactory = null;
TopicConnection tConnection = null;
TopicSession tSession = null;
TopicPublisher tPublisher = null;
try {
// if (logger.isDebugEnabled()) logger.debug("broadcast JMS
// message: " +
// textMessage);
// cannot log above - causing recursive broadcasting
tFactory = getTopicConnectionFactory(null);
tConnection = tFactory.createTopicConnection();
tSession = tConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = getTopic(topicName);
tPublisher = tSession.createPublisher(topic);
// TODO: platform-independent delay
// WLMessageProducer wlMessageProducer =
// (WLMessageProducer)tPublisher;
// long delayInMilliSec = 0;
// if(pMinDelay > 0){
// delayInMilliSec = delaySeconds*1000;
// }
// wlMessageProducer.setTimeToDeliver(delayInMilliSec);
TextMessage message = tSession.createTextMessage();
tConnection.start();
message.setText(textMessage);
tPublisher.publish(message, DeliveryMode.PERSISTENT,
TextMessage.DEFAULT_DELIVERY_MODE, TextMessage.DEFAULT_TIME_TO_LIVE);
// }catch(ServiceLocatorException ex){
// ex.printStackTrace();
// never log exception here!!! infinite loop when publishing log
// messages
// throw new JMSException(ex.getMessage());
}
finally {
closeResources(tConnection, tSession, tPublisher);
}
}
} | [
"public",
"void",
"broadcastTextMessage",
"(",
"String",
"topicName",
",",
"String",
"textMessage",
",",
"int",
"delaySeconds",
")",
"throws",
"NamingException",
",",
"JMSException",
",",
"ServiceLocatorException",
"{",
"if",
"(",
"mdwMessageProducer",
"!=",
"null",
")",
"{",
"mdwMessageProducer",
".",
"broadcastMessageToTopic",
"(",
"topicName",
",",
"textMessage",
")",
";",
"}",
"else",
"{",
"TopicConnectionFactory",
"tFactory",
"=",
"null",
";",
"TopicConnection",
"tConnection",
"=",
"null",
";",
"TopicSession",
"tSession",
"=",
"null",
";",
"TopicPublisher",
"tPublisher",
"=",
"null",
";",
"try",
"{",
"// if (logger.isDebugEnabled()) logger.debug(\"broadcast JMS",
"// message: \" +",
"// textMessage);",
"// cannot log above - causing recursive broadcasting",
"tFactory",
"=",
"getTopicConnectionFactory",
"(",
"null",
")",
";",
"tConnection",
"=",
"tFactory",
".",
"createTopicConnection",
"(",
")",
";",
"tSession",
"=",
"tConnection",
".",
"createTopicSession",
"(",
"false",
",",
"Session",
".",
"AUTO_ACKNOWLEDGE",
")",
";",
"Topic",
"topic",
"=",
"getTopic",
"(",
"topicName",
")",
";",
"tPublisher",
"=",
"tSession",
".",
"createPublisher",
"(",
"topic",
")",
";",
"// TODO: platform-independent delay",
"// WLMessageProducer wlMessageProducer =",
"// (WLMessageProducer)tPublisher;",
"// long delayInMilliSec = 0;",
"// if(pMinDelay > 0){",
"// delayInMilliSec = delaySeconds*1000;",
"// }",
"// wlMessageProducer.setTimeToDeliver(delayInMilliSec);",
"TextMessage",
"message",
"=",
"tSession",
".",
"createTextMessage",
"(",
")",
";",
"tConnection",
".",
"start",
"(",
")",
";",
"message",
".",
"setText",
"(",
"textMessage",
")",
";",
"tPublisher",
".",
"publish",
"(",
"message",
",",
"DeliveryMode",
".",
"PERSISTENT",
",",
"TextMessage",
".",
"DEFAULT_DELIVERY_MODE",
",",
"TextMessage",
".",
"DEFAULT_TIME_TO_LIVE",
")",
";",
"// }catch(ServiceLocatorException ex){",
"// ex.printStackTrace();",
"// never log exception here!!! infinite loop when publishing log",
"// messages",
"// throw new JMSException(ex.getMessage());",
"}",
"finally",
"{",
"closeResources",
"(",
"tConnection",
",",
"tSession",
",",
"tPublisher",
")",
";",
"}",
"}",
"}"
] | Sends the passed in text message to a local topic
@param topicName
@param pMessage
@param delaySeconds
@throws ServiceLocatorException | [
"Sends",
"the",
"passed",
"in",
"text",
"message",
"to",
"a",
"local",
"topic"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/JMSServices.java#L299-L345 |
netty/netty | codec-haproxy/src/main/java/io/netty/handler/codec/haproxy/HAProxyMessageDecoder.java | HAProxyMessageDecoder.decodeLine | private ByteBuf decodeLine(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
"""
Create a frame out of the {@link ByteBuf} and return it.
Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
@param ctx the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
@param buffer the {@link ByteBuf} from which to read data
@return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
be created
"""
final int eol = findEndOfLine(buffer);
if (!discarding) {
if (eol >= 0) {
final int length = eol - buffer.readerIndex();
if (length > V1_MAX_LENGTH) {
buffer.readerIndex(eol + DELIMITER_LENGTH);
failOverLimit(ctx, length);
return null;
}
ByteBuf frame = buffer.readSlice(length);
buffer.skipBytes(DELIMITER_LENGTH);
return frame;
} else {
final int length = buffer.readableBytes();
if (length > V1_MAX_LENGTH) {
discardedBytes = length;
buffer.skipBytes(length);
discarding = true;
failOverLimit(ctx, "over " + discardedBytes);
}
return null;
}
} else {
if (eol >= 0) {
final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
buffer.readerIndex(eol + delimLength);
discardedBytes = 0;
discarding = false;
} else {
discardedBytes = buffer.readableBytes();
buffer.skipBytes(discardedBytes);
}
return null;
}
} | java | private ByteBuf decodeLine(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
final int eol = findEndOfLine(buffer);
if (!discarding) {
if (eol >= 0) {
final int length = eol - buffer.readerIndex();
if (length > V1_MAX_LENGTH) {
buffer.readerIndex(eol + DELIMITER_LENGTH);
failOverLimit(ctx, length);
return null;
}
ByteBuf frame = buffer.readSlice(length);
buffer.skipBytes(DELIMITER_LENGTH);
return frame;
} else {
final int length = buffer.readableBytes();
if (length > V1_MAX_LENGTH) {
discardedBytes = length;
buffer.skipBytes(length);
discarding = true;
failOverLimit(ctx, "over " + discardedBytes);
}
return null;
}
} else {
if (eol >= 0) {
final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
buffer.readerIndex(eol + delimLength);
discardedBytes = 0;
discarding = false;
} else {
discardedBytes = buffer.readableBytes();
buffer.skipBytes(discardedBytes);
}
return null;
}
} | [
"private",
"ByteBuf",
"decodeLine",
"(",
"ChannelHandlerContext",
"ctx",
",",
"ByteBuf",
"buffer",
")",
"throws",
"Exception",
"{",
"final",
"int",
"eol",
"=",
"findEndOfLine",
"(",
"buffer",
")",
";",
"if",
"(",
"!",
"discarding",
")",
"{",
"if",
"(",
"eol",
">=",
"0",
")",
"{",
"final",
"int",
"length",
"=",
"eol",
"-",
"buffer",
".",
"readerIndex",
"(",
")",
";",
"if",
"(",
"length",
">",
"V1_MAX_LENGTH",
")",
"{",
"buffer",
".",
"readerIndex",
"(",
"eol",
"+",
"DELIMITER_LENGTH",
")",
";",
"failOverLimit",
"(",
"ctx",
",",
"length",
")",
";",
"return",
"null",
";",
"}",
"ByteBuf",
"frame",
"=",
"buffer",
".",
"readSlice",
"(",
"length",
")",
";",
"buffer",
".",
"skipBytes",
"(",
"DELIMITER_LENGTH",
")",
";",
"return",
"frame",
";",
"}",
"else",
"{",
"final",
"int",
"length",
"=",
"buffer",
".",
"readableBytes",
"(",
")",
";",
"if",
"(",
"length",
">",
"V1_MAX_LENGTH",
")",
"{",
"discardedBytes",
"=",
"length",
";",
"buffer",
".",
"skipBytes",
"(",
"length",
")",
";",
"discarding",
"=",
"true",
";",
"failOverLimit",
"(",
"ctx",
",",
"\"over \"",
"+",
"discardedBytes",
")",
";",
"}",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"eol",
">=",
"0",
")",
"{",
"final",
"int",
"delimLength",
"=",
"buffer",
".",
"getByte",
"(",
"eol",
")",
"==",
"'",
"'",
"?",
"2",
":",
"1",
";",
"buffer",
".",
"readerIndex",
"(",
"eol",
"+",
"delimLength",
")",
";",
"discardedBytes",
"=",
"0",
";",
"discarding",
"=",
"false",
";",
"}",
"else",
"{",
"discardedBytes",
"=",
"buffer",
".",
"readableBytes",
"(",
")",
";",
"buffer",
".",
"skipBytes",
"(",
"discardedBytes",
")",
";",
"}",
"return",
"null",
";",
"}",
"}"
] | Create a frame out of the {@link ByteBuf} and return it.
Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
@param ctx the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
@param buffer the {@link ByteBuf} from which to read data
@return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could
be created | [
"Create",
"a",
"frame",
"out",
"of",
"the",
"{",
"@link",
"ByteBuf",
"}",
"and",
"return",
"it",
".",
"Based",
"on",
"code",
"from",
"{",
"@link",
"LineBasedFrameDecoder#decode",
"(",
"ChannelHandlerContext",
"ByteBuf",
")",
"}",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-haproxy/src/main/java/io/netty/handler/codec/haproxy/HAProxyMessageDecoder.java#L312-L347 |
VoltDB/voltdb | src/frontend/org/voltdb/ClientInterfaceHandleManager.java | ClientInterfaceHandleManager.makeThreadSafeCIHM | public static ClientInterfaceHandleManager makeThreadSafeCIHM(
boolean isAdmin, Connection connection, ClientInterfaceRepairCallback callback, AdmissionControlGroup acg) {
"""
Factory to make a threadsafe version of CIHM. This is used
exclusively by some internal CI adapters that don't have
the natural thread-safety protocol/design of VoltNetwork.
"""
return new ClientInterfaceHandleManager(isAdmin, connection, callback, acg) {
@Override
synchronized long getHandle(boolean isSinglePartition, int partitionId,
long clientHandle, int messageSize, long creationTimeNanos, String procName, long initiatorHSId,
boolean isShortCircuitRead) {
return super.getHandle(isSinglePartition, partitionId,
clientHandle, messageSize, creationTimeNanos, procName, initiatorHSId, isShortCircuitRead);
}
@Override
synchronized Iv2InFlight findHandle(long ciHandle) {
return super.findHandle(ciHandle);
}
@Override
synchronized Iv2InFlight removeHandle(long ciHandle) {
return super.removeHandle(ciHandle);
}
@Override
synchronized long getOutstandingTxns() {
return super.getOutstandingTxns();
}
@Override
synchronized void freeOutstandingTxns() {
super.freeOutstandingTxns();
}
@Override
synchronized List<Iv2InFlight> removeHandlesForPartitionAndInitiator(Integer partitionId,
Long initiatorHSId) {
return super.removeHandlesForPartitionAndInitiator(partitionId, initiatorHSId);
}
@Override
synchronized boolean shouldCheckThreadIdAssertion()
{
return false;
}
};
} | java | public static ClientInterfaceHandleManager makeThreadSafeCIHM(
boolean isAdmin, Connection connection, ClientInterfaceRepairCallback callback, AdmissionControlGroup acg)
{
return new ClientInterfaceHandleManager(isAdmin, connection, callback, acg) {
@Override
synchronized long getHandle(boolean isSinglePartition, int partitionId,
long clientHandle, int messageSize, long creationTimeNanos, String procName, long initiatorHSId,
boolean isShortCircuitRead) {
return super.getHandle(isSinglePartition, partitionId,
clientHandle, messageSize, creationTimeNanos, procName, initiatorHSId, isShortCircuitRead);
}
@Override
synchronized Iv2InFlight findHandle(long ciHandle) {
return super.findHandle(ciHandle);
}
@Override
synchronized Iv2InFlight removeHandle(long ciHandle) {
return super.removeHandle(ciHandle);
}
@Override
synchronized long getOutstandingTxns() {
return super.getOutstandingTxns();
}
@Override
synchronized void freeOutstandingTxns() {
super.freeOutstandingTxns();
}
@Override
synchronized List<Iv2InFlight> removeHandlesForPartitionAndInitiator(Integer partitionId,
Long initiatorHSId) {
return super.removeHandlesForPartitionAndInitiator(partitionId, initiatorHSId);
}
@Override
synchronized boolean shouldCheckThreadIdAssertion()
{
return false;
}
};
} | [
"public",
"static",
"ClientInterfaceHandleManager",
"makeThreadSafeCIHM",
"(",
"boolean",
"isAdmin",
",",
"Connection",
"connection",
",",
"ClientInterfaceRepairCallback",
"callback",
",",
"AdmissionControlGroup",
"acg",
")",
"{",
"return",
"new",
"ClientInterfaceHandleManager",
"(",
"isAdmin",
",",
"connection",
",",
"callback",
",",
"acg",
")",
"{",
"@",
"Override",
"synchronized",
"long",
"getHandle",
"(",
"boolean",
"isSinglePartition",
",",
"int",
"partitionId",
",",
"long",
"clientHandle",
",",
"int",
"messageSize",
",",
"long",
"creationTimeNanos",
",",
"String",
"procName",
",",
"long",
"initiatorHSId",
",",
"boolean",
"isShortCircuitRead",
")",
"{",
"return",
"super",
".",
"getHandle",
"(",
"isSinglePartition",
",",
"partitionId",
",",
"clientHandle",
",",
"messageSize",
",",
"creationTimeNanos",
",",
"procName",
",",
"initiatorHSId",
",",
"isShortCircuitRead",
")",
";",
"}",
"@",
"Override",
"synchronized",
"Iv2InFlight",
"findHandle",
"(",
"long",
"ciHandle",
")",
"{",
"return",
"super",
".",
"findHandle",
"(",
"ciHandle",
")",
";",
"}",
"@",
"Override",
"synchronized",
"Iv2InFlight",
"removeHandle",
"(",
"long",
"ciHandle",
")",
"{",
"return",
"super",
".",
"removeHandle",
"(",
"ciHandle",
")",
";",
"}",
"@",
"Override",
"synchronized",
"long",
"getOutstandingTxns",
"(",
")",
"{",
"return",
"super",
".",
"getOutstandingTxns",
"(",
")",
";",
"}",
"@",
"Override",
"synchronized",
"void",
"freeOutstandingTxns",
"(",
")",
"{",
"super",
".",
"freeOutstandingTxns",
"(",
")",
";",
"}",
"@",
"Override",
"synchronized",
"List",
"<",
"Iv2InFlight",
">",
"removeHandlesForPartitionAndInitiator",
"(",
"Integer",
"partitionId",
",",
"Long",
"initiatorHSId",
")",
"{",
"return",
"super",
".",
"removeHandlesForPartitionAndInitiator",
"(",
"partitionId",
",",
"initiatorHSId",
")",
";",
"}",
"@",
"Override",
"synchronized",
"boolean",
"shouldCheckThreadIdAssertion",
"(",
")",
"{",
"return",
"false",
";",
"}",
"}",
";",
"}"
] | Factory to make a threadsafe version of CIHM. This is used
exclusively by some internal CI adapters that don't have
the natural thread-safety protocol/design of VoltNetwork. | [
"Factory",
"to",
"make",
"a",
"threadsafe",
"version",
"of",
"CIHM",
".",
"This",
"is",
"used",
"exclusively",
"by",
"some",
"internal",
"CI",
"adapters",
"that",
"don",
"t",
"have",
"the",
"natural",
"thread",
"-",
"safety",
"protocol",
"/",
"design",
"of",
"VoltNetwork",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ClientInterfaceHandleManager.java#L131-L171 |
lucee/Lucee | core/src/main/java/lucee/transformer/library/function/FunctionLibFactory.java | FunctionLibFactory.setAttributes | private static void setAttributes(FunctionLib extFL, FunctionLib newFL) {
"""
copy attributes from old fld to the new
@param extFL
@param newFL
"""
newFL.setDescription(extFL.getDescription());
newFL.setDisplayName(extFL.getDisplayName());
newFL.setShortName(extFL.getShortName());
newFL.setUri(extFL.getUri());
newFL.setVersion(extFL.getVersion());
} | java | private static void setAttributes(FunctionLib extFL, FunctionLib newFL) {
newFL.setDescription(extFL.getDescription());
newFL.setDisplayName(extFL.getDisplayName());
newFL.setShortName(extFL.getShortName());
newFL.setUri(extFL.getUri());
newFL.setVersion(extFL.getVersion());
} | [
"private",
"static",
"void",
"setAttributes",
"(",
"FunctionLib",
"extFL",
",",
"FunctionLib",
"newFL",
")",
"{",
"newFL",
".",
"setDescription",
"(",
"extFL",
".",
"getDescription",
"(",
")",
")",
";",
"newFL",
".",
"setDisplayName",
"(",
"extFL",
".",
"getDisplayName",
"(",
")",
")",
";",
"newFL",
".",
"setShortName",
"(",
"extFL",
".",
"getShortName",
"(",
")",
")",
";",
"newFL",
".",
"setUri",
"(",
"extFL",
".",
"getUri",
"(",
")",
")",
";",
"newFL",
".",
"setVersion",
"(",
"extFL",
".",
"getVersion",
"(",
")",
")",
";",
"}"
] | copy attributes from old fld to the new
@param extFL
@param newFL | [
"copy",
"attributes",
"from",
"old",
"fld",
"to",
"the",
"new"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/library/function/FunctionLibFactory.java#L478-L484 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/asm/AsmUtils.java | AsmUtils.changeFieldAccess | public static Field changeFieldAccess(Class<?> clazz, String fieldName) {
"""
Changes the access level for the specified field for a class.
@param clazz the clazz
@param fieldName the field name
@return the field
"""
return changeFieldAccess(clazz, fieldName, fieldName, false);
} | java | public static Field changeFieldAccess(Class<?> clazz, String fieldName)
{
return changeFieldAccess(clazz, fieldName, fieldName, false);
} | [
"public",
"static",
"Field",
"changeFieldAccess",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"fieldName",
")",
"{",
"return",
"changeFieldAccess",
"(",
"clazz",
",",
"fieldName",
",",
"fieldName",
",",
"false",
")",
";",
"}"
] | Changes the access level for the specified field for a class.
@param clazz the clazz
@param fieldName the field name
@return the field | [
"Changes",
"the",
"access",
"level",
"for",
"the",
"specified",
"field",
"for",
"a",
"class",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/asm/AsmUtils.java#L312-L315 |
spring-projects/spring-social | spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java | OAuth2Template.getIntegerValue | private Long getIntegerValue(Map<String, Object> map, String key) {
"""
Retrieves object from map into an Integer, regardless of the object's actual type. Allows for flexibility in object type (eg, "3600" vs 3600).
"""
try {
return Long.valueOf(String.valueOf(map.get(key))); // normalize to String before creating integer value;
} catch (NumberFormatException e) {
return null;
}
} | java | private Long getIntegerValue(Map<String, Object> map, String key) {
try {
return Long.valueOf(String.valueOf(map.get(key))); // normalize to String before creating integer value;
} catch (NumberFormatException e) {
return null;
}
} | [
"private",
"Long",
"getIntegerValue",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"String",
"key",
")",
"{",
"try",
"{",
"return",
"Long",
".",
"valueOf",
"(",
"String",
".",
"valueOf",
"(",
"map",
".",
"get",
"(",
"key",
")",
")",
")",
";",
"// normalize to String before creating integer value;\t\t\t",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | Retrieves object from map into an Integer, regardless of the object's actual type. Allows for flexibility in object type (eg, "3600" vs 3600). | [
"Retrieves",
"object",
"from",
"map",
"into",
"an",
"Integer",
"regardless",
"of",
"the",
"object",
"s",
"actual",
"type",
".",
"Allows",
"for",
"flexibility",
"in",
"object",
"type",
"(",
"eg",
"3600",
"vs",
"3600",
")",
"."
] | train | https://github.com/spring-projects/spring-social/blob/e41cfecb288022b83c79413b58f52511c3c9d4fc/spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2Template.java#L313-L319 |
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/feature/color/HistogramFeatureOps.java | HistogramFeatureOps.histogram_F32 | public static void histogram_F32(Planar<GrayF32> image , Histogram_F64 histogram ) {
"""
Constructs an N-D histogram from a {@link Planar} {@link GrayF32} image.
@param image input image
@param histogram preconfigured histogram to store the output
"""
if (image.getNumBands() != histogram.getDimensions())
throw new IllegalArgumentException("Number of bands in the image and histogram must be the same");
if( !histogram.isRangeSet() )
throw new IllegalArgumentException("Must specify range along each dimension in histogram");
final int D = histogram.getDimensions();
int coordinate[] = new int[ D ];
histogram.fill(0);
for (int y = 0; y < image.getHeight(); y++) {
int imageIndex = image.getStartIndex() + y*image.getStride();
for (int x = 0; x < image.getWidth(); x++ , imageIndex++) {
for (int i = 0; i < D; i++) {
coordinate[i] = histogram.getDimensionIndex(i,image.getBand(i).data[imageIndex]);
}
int index = histogram.getIndex(coordinate);
histogram.value[index] += 1;
}
}
} | java | public static void histogram_F32(Planar<GrayF32> image , Histogram_F64 histogram )
{
if (image.getNumBands() != histogram.getDimensions())
throw new IllegalArgumentException("Number of bands in the image and histogram must be the same");
if( !histogram.isRangeSet() )
throw new IllegalArgumentException("Must specify range along each dimension in histogram");
final int D = histogram.getDimensions();
int coordinate[] = new int[ D ];
histogram.fill(0);
for (int y = 0; y < image.getHeight(); y++) {
int imageIndex = image.getStartIndex() + y*image.getStride();
for (int x = 0; x < image.getWidth(); x++ , imageIndex++) {
for (int i = 0; i < D; i++) {
coordinate[i] = histogram.getDimensionIndex(i,image.getBand(i).data[imageIndex]);
}
int index = histogram.getIndex(coordinate);
histogram.value[index] += 1;
}
}
} | [
"public",
"static",
"void",
"histogram_F32",
"(",
"Planar",
"<",
"GrayF32",
">",
"image",
",",
"Histogram_F64",
"histogram",
")",
"{",
"if",
"(",
"image",
".",
"getNumBands",
"(",
")",
"!=",
"histogram",
".",
"getDimensions",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Number of bands in the image and histogram must be the same\"",
")",
";",
"if",
"(",
"!",
"histogram",
".",
"isRangeSet",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Must specify range along each dimension in histogram\"",
")",
";",
"final",
"int",
"D",
"=",
"histogram",
".",
"getDimensions",
"(",
")",
";",
"int",
"coordinate",
"[",
"]",
"=",
"new",
"int",
"[",
"D",
"]",
";",
"histogram",
".",
"fill",
"(",
"0",
")",
";",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"image",
".",
"getHeight",
"(",
")",
";",
"y",
"++",
")",
"{",
"int",
"imageIndex",
"=",
"image",
".",
"getStartIndex",
"(",
")",
"+",
"y",
"*",
"image",
".",
"getStride",
"(",
")",
";",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"image",
".",
"getWidth",
"(",
")",
";",
"x",
"++",
",",
"imageIndex",
"++",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"D",
";",
"i",
"++",
")",
"{",
"coordinate",
"[",
"i",
"]",
"=",
"histogram",
".",
"getDimensionIndex",
"(",
"i",
",",
"image",
".",
"getBand",
"(",
"i",
")",
".",
"data",
"[",
"imageIndex",
"]",
")",
";",
"}",
"int",
"index",
"=",
"histogram",
".",
"getIndex",
"(",
"coordinate",
")",
";",
"histogram",
".",
"value",
"[",
"index",
"]",
"+=",
"1",
";",
"}",
"}",
"}"
] | Constructs an N-D histogram from a {@link Planar} {@link GrayF32} image.
@param image input image
@param histogram preconfigured histogram to store the output | [
"Constructs",
"an",
"N",
"-",
"D",
"histogram",
"from",
"a",
"{",
"@link",
"Planar",
"}",
"{",
"@link",
"GrayF32",
"}",
"image",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/color/HistogramFeatureOps.java#L131-L154 |
square/phrase | src/main/java/com/squareup/phrase/Phrase.java | Phrase.from | public static Phrase from(Resources r, @StringRes int patternResourceId) {
"""
Entry point into this API.
@throws IllegalArgumentException if pattern contains any syntax errors.
"""
return from(r.getText(patternResourceId));
} | java | public static Phrase from(Resources r, @StringRes int patternResourceId) {
return from(r.getText(patternResourceId));
} | [
"public",
"static",
"Phrase",
"from",
"(",
"Resources",
"r",
",",
"@",
"StringRes",
"int",
"patternResourceId",
")",
"{",
"return",
"from",
"(",
"r",
".",
"getText",
"(",
"patternResourceId",
")",
")",
";",
"}"
] | Entry point into this API.
@throws IllegalArgumentException if pattern contains any syntax errors. | [
"Entry",
"point",
"into",
"this",
"API",
"."
] | train | https://github.com/square/phrase/blob/d91f18e80790832db11b811c462f8e5cd492d97e/src/main/java/com/squareup/phrase/Phrase.java#L105-L107 |
pravega/pravega | client/src/main/java/io/pravega/client/netty/impl/ConnectionPoolImpl.java | ConnectionPoolImpl.getChannelInitializer | private ChannelInitializer<SocketChannel> getChannelInitializer(final PravegaNodeUri location,
final FlowHandler handler) {
"""
Create a Channel Initializer which is to to setup {@link ChannelPipeline}.
"""
final SslContext sslCtx = getSslContext();
return new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
if (clientConfig.isValidateHostName()) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
p.addLast(sslHandler);
}
p.addLast(
new ExceptionLoggingHandler(location.getEndpoint()),
new CommandEncoder(handler.getBatchSizeTracker()),
new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
new CommandDecoder(),
handler);
}
};
} | java | private ChannelInitializer<SocketChannel> getChannelInitializer(final PravegaNodeUri location,
final FlowHandler handler) {
final SslContext sslCtx = getSslContext();
return new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
if (clientConfig.isValidateHostName()) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
p.addLast(sslHandler);
}
p.addLast(
new ExceptionLoggingHandler(location.getEndpoint()),
new CommandEncoder(handler.getBatchSizeTracker()),
new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
new CommandDecoder(),
handler);
}
};
} | [
"private",
"ChannelInitializer",
"<",
"SocketChannel",
">",
"getChannelInitializer",
"(",
"final",
"PravegaNodeUri",
"location",
",",
"final",
"FlowHandler",
"handler",
")",
"{",
"final",
"SslContext",
"sslCtx",
"=",
"getSslContext",
"(",
")",
";",
"return",
"new",
"ChannelInitializer",
"<",
"SocketChannel",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"initChannel",
"(",
"SocketChannel",
"ch",
")",
"throws",
"Exception",
"{",
"ChannelPipeline",
"p",
"=",
"ch",
".",
"pipeline",
"(",
")",
";",
"if",
"(",
"sslCtx",
"!=",
"null",
")",
"{",
"SslHandler",
"sslHandler",
"=",
"sslCtx",
".",
"newHandler",
"(",
"ch",
".",
"alloc",
"(",
")",
",",
"location",
".",
"getEndpoint",
"(",
")",
",",
"location",
".",
"getPort",
"(",
")",
")",
";",
"if",
"(",
"clientConfig",
".",
"isValidateHostName",
"(",
")",
")",
"{",
"SSLEngine",
"sslEngine",
"=",
"sslHandler",
".",
"engine",
"(",
")",
";",
"SSLParameters",
"sslParameters",
"=",
"sslEngine",
".",
"getSSLParameters",
"(",
")",
";",
"sslParameters",
".",
"setEndpointIdentificationAlgorithm",
"(",
"\"HTTPS\"",
")",
";",
"sslEngine",
".",
"setSSLParameters",
"(",
"sslParameters",
")",
";",
"}",
"p",
".",
"addLast",
"(",
"sslHandler",
")",
";",
"}",
"p",
".",
"addLast",
"(",
"new",
"ExceptionLoggingHandler",
"(",
"location",
".",
"getEndpoint",
"(",
")",
")",
",",
"new",
"CommandEncoder",
"(",
"handler",
".",
"getBatchSizeTracker",
"(",
")",
")",
",",
"new",
"LengthFieldBasedFrameDecoder",
"(",
"WireCommands",
".",
"MAX_WIRECOMMAND_SIZE",
",",
"4",
",",
"4",
")",
",",
"new",
"CommandDecoder",
"(",
")",
",",
"handler",
")",
";",
"}",
"}",
";",
"}"
] | Create a Channel Initializer which is to to setup {@link ChannelPipeline}. | [
"Create",
"a",
"Channel",
"Initializer",
"which",
"is",
"to",
"to",
"setup",
"{"
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/netty/impl/ConnectionPoolImpl.java#L230-L257 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/json/JsonPathUtils.java | JsonPathUtils.evaluateAsString | public static String evaluateAsString(ReadContext readerContext, String jsonPathExpression) {
"""
Evaluate JsonPath expression using given read context and return result as string.
@param readerContext
@param jsonPathExpression
@return
"""
Object jsonPathResult = evaluate(readerContext, jsonPathExpression);
if (jsonPathResult instanceof JSONArray) {
return ((JSONArray) jsonPathResult).toJSONString();
} else if (jsonPathResult instanceof JSONObject) {
return ((JSONObject) jsonPathResult).toJSONString();
} else {
return Optional.ofNullable(jsonPathResult).map(Object::toString).orElse("null");
}
} | java | public static String evaluateAsString(ReadContext readerContext, String jsonPathExpression) {
Object jsonPathResult = evaluate(readerContext, jsonPathExpression);
if (jsonPathResult instanceof JSONArray) {
return ((JSONArray) jsonPathResult).toJSONString();
} else if (jsonPathResult instanceof JSONObject) {
return ((JSONObject) jsonPathResult).toJSONString();
} else {
return Optional.ofNullable(jsonPathResult).map(Object::toString).orElse("null");
}
} | [
"public",
"static",
"String",
"evaluateAsString",
"(",
"ReadContext",
"readerContext",
",",
"String",
"jsonPathExpression",
")",
"{",
"Object",
"jsonPathResult",
"=",
"evaluate",
"(",
"readerContext",
",",
"jsonPathExpression",
")",
";",
"if",
"(",
"jsonPathResult",
"instanceof",
"JSONArray",
")",
"{",
"return",
"(",
"(",
"JSONArray",
")",
"jsonPathResult",
")",
".",
"toJSONString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"jsonPathResult",
"instanceof",
"JSONObject",
")",
"{",
"return",
"(",
"(",
"JSONObject",
")",
"jsonPathResult",
")",
".",
"toJSONString",
"(",
")",
";",
"}",
"else",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"jsonPathResult",
")",
".",
"map",
"(",
"Object",
"::",
"toString",
")",
".",
"orElse",
"(",
"\"null\"",
")",
";",
"}",
"}"
] | Evaluate JsonPath expression using given read context and return result as string.
@param readerContext
@param jsonPathExpression
@return | [
"Evaluate",
"JsonPath",
"expression",
"using",
"given",
"read",
"context",
"and",
"return",
"result",
"as",
"string",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/json/JsonPathUtils.java#L122-L132 |
aws/aws-cloudtrail-processing-library | src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/AbstractEventSerializer.java | AbstractEventSerializer.parseSessionIssuer | private SessionIssuer parseSessionIssuer(SessionContext sessionContext) throws IOException {
"""
Parses the {@link SessionContext} object.
This runs only if the session is running with role-based or federated access permissions
(in other words, temporary credentials in IAM).
@param sessionContext
@return the session issuer object.
@throws IOException
"""
if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
throw new JsonParseException("Not a SessionIssuer object", jsonParser.getCurrentLocation());
}
SessionIssuer sessionIssuer = new SessionIssuer();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String key = jsonParser.getCurrentName();
switch (key) {
case "type":
sessionIssuer.add(CloudTrailEventField.type.name(), this.jsonParser.nextTextValue());
break;
case "principalId":
sessionIssuer.add(CloudTrailEventField.principalId.name(), this.jsonParser.nextTextValue());
break;
case "arn":
sessionIssuer.add(CloudTrailEventField.arn.name(), this.jsonParser.nextTextValue());
break;
case "accountId":
sessionIssuer.add(CloudTrailEventField.accountId.name(), this.jsonParser.nextTextValue());
break;
case "userName":
sessionIssuer.add(CloudTrailEventField.userName.name(), this.jsonParser.nextTextValue());
break;
default:
sessionIssuer.add(key, this.parseDefaultValue(key));
break;
}
}
return sessionIssuer;
} | java | private SessionIssuer parseSessionIssuer(SessionContext sessionContext) throws IOException {
if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
throw new JsonParseException("Not a SessionIssuer object", jsonParser.getCurrentLocation());
}
SessionIssuer sessionIssuer = new SessionIssuer();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String key = jsonParser.getCurrentName();
switch (key) {
case "type":
sessionIssuer.add(CloudTrailEventField.type.name(), this.jsonParser.nextTextValue());
break;
case "principalId":
sessionIssuer.add(CloudTrailEventField.principalId.name(), this.jsonParser.nextTextValue());
break;
case "arn":
sessionIssuer.add(CloudTrailEventField.arn.name(), this.jsonParser.nextTextValue());
break;
case "accountId":
sessionIssuer.add(CloudTrailEventField.accountId.name(), this.jsonParser.nextTextValue());
break;
case "userName":
sessionIssuer.add(CloudTrailEventField.userName.name(), this.jsonParser.nextTextValue());
break;
default:
sessionIssuer.add(key, this.parseDefaultValue(key));
break;
}
}
return sessionIssuer;
} | [
"private",
"SessionIssuer",
"parseSessionIssuer",
"(",
"SessionContext",
"sessionContext",
")",
"throws",
"IOException",
"{",
"if",
"(",
"jsonParser",
".",
"nextToken",
"(",
")",
"!=",
"JsonToken",
".",
"START_OBJECT",
")",
"{",
"throw",
"new",
"JsonParseException",
"(",
"\"Not a SessionIssuer object\"",
",",
"jsonParser",
".",
"getCurrentLocation",
"(",
")",
")",
";",
"}",
"SessionIssuer",
"sessionIssuer",
"=",
"new",
"SessionIssuer",
"(",
")",
";",
"while",
"(",
"jsonParser",
".",
"nextToken",
"(",
")",
"!=",
"JsonToken",
".",
"END_OBJECT",
")",
"{",
"String",
"key",
"=",
"jsonParser",
".",
"getCurrentName",
"(",
")",
";",
"switch",
"(",
"key",
")",
"{",
"case",
"\"type\"",
":",
"sessionIssuer",
".",
"add",
"(",
"CloudTrailEventField",
".",
"type",
".",
"name",
"(",
")",
",",
"this",
".",
"jsonParser",
".",
"nextTextValue",
"(",
")",
")",
";",
"break",
";",
"case",
"\"principalId\"",
":",
"sessionIssuer",
".",
"add",
"(",
"CloudTrailEventField",
".",
"principalId",
".",
"name",
"(",
")",
",",
"this",
".",
"jsonParser",
".",
"nextTextValue",
"(",
")",
")",
";",
"break",
";",
"case",
"\"arn\"",
":",
"sessionIssuer",
".",
"add",
"(",
"CloudTrailEventField",
".",
"arn",
".",
"name",
"(",
")",
",",
"this",
".",
"jsonParser",
".",
"nextTextValue",
"(",
")",
")",
";",
"break",
";",
"case",
"\"accountId\"",
":",
"sessionIssuer",
".",
"add",
"(",
"CloudTrailEventField",
".",
"accountId",
".",
"name",
"(",
")",
",",
"this",
".",
"jsonParser",
".",
"nextTextValue",
"(",
")",
")",
";",
"break",
";",
"case",
"\"userName\"",
":",
"sessionIssuer",
".",
"add",
"(",
"CloudTrailEventField",
".",
"userName",
".",
"name",
"(",
")",
",",
"this",
".",
"jsonParser",
".",
"nextTextValue",
"(",
")",
")",
";",
"break",
";",
"default",
":",
"sessionIssuer",
".",
"add",
"(",
"key",
",",
"this",
".",
"parseDefaultValue",
"(",
"key",
")",
")",
";",
"break",
";",
"}",
"}",
"return",
"sessionIssuer",
";",
"}"
] | Parses the {@link SessionContext} object.
This runs only if the session is running with role-based or federated access permissions
(in other words, temporary credentials in IAM).
@param sessionContext
@return the session issuer object.
@throws IOException | [
"Parses",
"the",
"{",
"@link",
"SessionContext",
"}",
"object",
".",
"This",
"runs",
"only",
"if",
"the",
"session",
"is",
"running",
"with",
"role",
"-",
"based",
"or",
"federated",
"access",
"permissions",
"(",
"in",
"other",
"words",
"temporary",
"credentials",
"in",
"IAM",
")",
"."
] | train | https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/serializer/AbstractEventSerializer.java#L347-L380 |
hdecarne/java-default | src/main/java/de/carne/io/IOUtil.java | IOUtil.copyStream | public static long copyStream(File dst, InputStream src) throws IOException {
"""
Copies all bytes from an {@linkplain InputStream} to a {@linkplain File}.
@param dst the {@linkplain File} to copy to.
@param src the {@linkplain InputStream} to copy from.
@return the number of copied bytes.
@throws IOException if an I/O error occurs.
"""
long copied;
try (FileOutputStream dstStream = new FileOutputStream(dst)) {
copied = copyStream(dstStream, src);
}
return copied;
} | java | public static long copyStream(File dst, InputStream src) throws IOException {
long copied;
try (FileOutputStream dstStream = new FileOutputStream(dst)) {
copied = copyStream(dstStream, src);
}
return copied;
} | [
"public",
"static",
"long",
"copyStream",
"(",
"File",
"dst",
",",
"InputStream",
"src",
")",
"throws",
"IOException",
"{",
"long",
"copied",
";",
"try",
"(",
"FileOutputStream",
"dstStream",
"=",
"new",
"FileOutputStream",
"(",
"dst",
")",
")",
"{",
"copied",
"=",
"copyStream",
"(",
"dstStream",
",",
"src",
")",
";",
"}",
"return",
"copied",
";",
"}"
] | Copies all bytes from an {@linkplain InputStream} to a {@linkplain File}.
@param dst the {@linkplain File} to copy to.
@param src the {@linkplain InputStream} to copy from.
@return the number of copied bytes.
@throws IOException if an I/O error occurs. | [
"Copies",
"all",
"bytes",
"from",
"an",
"{",
"@linkplain",
"InputStream",
"}",
"to",
"a",
"{",
"@linkplain",
"File",
"}",
"."
] | train | https://github.com/hdecarne/java-default/blob/ca16f6fdb0436e90e9e2df3106055e320bb3c9e3/src/main/java/de/carne/io/IOUtil.java#L101-L108 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/SnowflakeFileTransferAgent.java | SnowflakeFileTransferAgent.compressStreamWithGZIPNoDigest | private static InputStreamWithMetadata compressStreamWithGZIPNoDigest(
InputStream inputStream) throws SnowflakeSQLException {
"""
Compress an input stream with GZIP and return the result size, digest and
compressed stream.
@param inputStream
@return the compressed stream
@throws SnowflakeSQLException
@deprecated Can be removed when all accounts are encrypted
"""
try
{
FileBackedOutputStream tempStream =
new FileBackedOutputStream(MAX_BUFFER_SIZE, true);
CountingOutputStream countingStream =
new CountingOutputStream(tempStream);
// construct a gzip stream with sync_flush mode
GZIPOutputStream gzipStream;
gzipStream = new GZIPOutputStream(countingStream, true);
IOUtils.copy(inputStream, gzipStream);
inputStream.close();
gzipStream.finish();
gzipStream.flush();
countingStream.flush();
return new InputStreamWithMetadata(countingStream.getCount(),
null, tempStream);
}
catch (IOException ex)
{
logger.error("Exception compressing input stream", ex);
throw new SnowflakeSQLException(ex, SqlState.INTERNAL_ERROR,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
"error encountered for compression");
}
} | java | private static InputStreamWithMetadata compressStreamWithGZIPNoDigest(
InputStream inputStream) throws SnowflakeSQLException
{
try
{
FileBackedOutputStream tempStream =
new FileBackedOutputStream(MAX_BUFFER_SIZE, true);
CountingOutputStream countingStream =
new CountingOutputStream(tempStream);
// construct a gzip stream with sync_flush mode
GZIPOutputStream gzipStream;
gzipStream = new GZIPOutputStream(countingStream, true);
IOUtils.copy(inputStream, gzipStream);
inputStream.close();
gzipStream.finish();
gzipStream.flush();
countingStream.flush();
return new InputStreamWithMetadata(countingStream.getCount(),
null, tempStream);
}
catch (IOException ex)
{
logger.error("Exception compressing input stream", ex);
throw new SnowflakeSQLException(ex, SqlState.INTERNAL_ERROR,
ErrorCode.INTERNAL_ERROR.getMessageCode(),
"error encountered for compression");
}
} | [
"private",
"static",
"InputStreamWithMetadata",
"compressStreamWithGZIPNoDigest",
"(",
"InputStream",
"inputStream",
")",
"throws",
"SnowflakeSQLException",
"{",
"try",
"{",
"FileBackedOutputStream",
"tempStream",
"=",
"new",
"FileBackedOutputStream",
"(",
"MAX_BUFFER_SIZE",
",",
"true",
")",
";",
"CountingOutputStream",
"countingStream",
"=",
"new",
"CountingOutputStream",
"(",
"tempStream",
")",
";",
"// construct a gzip stream with sync_flush mode",
"GZIPOutputStream",
"gzipStream",
";",
"gzipStream",
"=",
"new",
"GZIPOutputStream",
"(",
"countingStream",
",",
"true",
")",
";",
"IOUtils",
".",
"copy",
"(",
"inputStream",
",",
"gzipStream",
")",
";",
"inputStream",
".",
"close",
"(",
")",
";",
"gzipStream",
".",
"finish",
"(",
")",
";",
"gzipStream",
".",
"flush",
"(",
")",
";",
"countingStream",
".",
"flush",
"(",
")",
";",
"return",
"new",
"InputStreamWithMetadata",
"(",
"countingStream",
".",
"getCount",
"(",
")",
",",
"null",
",",
"tempStream",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"logger",
".",
"error",
"(",
"\"Exception compressing input stream\"",
",",
"ex",
")",
";",
"throw",
"new",
"SnowflakeSQLException",
"(",
"ex",
",",
"SqlState",
".",
"INTERNAL_ERROR",
",",
"ErrorCode",
".",
"INTERNAL_ERROR",
".",
"getMessageCode",
"(",
")",
",",
"\"error encountered for compression\"",
")",
";",
"}",
"}"
] | Compress an input stream with GZIP and return the result size, digest and
compressed stream.
@param inputStream
@return the compressed stream
@throws SnowflakeSQLException
@deprecated Can be removed when all accounts are encrypted | [
"Compress",
"an",
"input",
"stream",
"with",
"GZIP",
"and",
"return",
"the",
"result",
"size",
"digest",
"and",
"compressed",
"stream",
"."
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeFileTransferAgent.java#L548-L586 |
fozziethebeat/S-Space | opt/src/main/java/edu/ucla/sspace/lra/LatentRelationalAnalysis.java | LatentRelationalAnalysis.getIndexOfPair | private static int getIndexOfPair(String value, Map<Integer, String> row_data) {
"""
returns the index of the String in the HashMap, or -1 if value was not found.
"""
for(Integer i : row_data.keySet()) {
if(row_data.get(i).equals(value)) {
return i.intValue();
}
}
return -1;
} | java | private static int getIndexOfPair(String value, Map<Integer, String> row_data) {
for(Integer i : row_data.keySet()) {
if(row_data.get(i).equals(value)) {
return i.intValue();
}
}
return -1;
} | [
"private",
"static",
"int",
"getIndexOfPair",
"(",
"String",
"value",
",",
"Map",
"<",
"Integer",
",",
"String",
">",
"row_data",
")",
"{",
"for",
"(",
"Integer",
"i",
":",
"row_data",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"row_data",
".",
"get",
"(",
"i",
")",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"i",
".",
"intValue",
"(",
")",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | returns the index of the String in the HashMap, or -1 if value was not found. | [
"returns",
"the",
"index",
"of",
"the",
"String",
"in",
"the",
"HashMap",
"or",
"-",
"1",
"if",
"value",
"was",
"not",
"found",
"."
] | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/opt/src/main/java/edu/ucla/sspace/lra/LatentRelationalAnalysis.java#L826-L833 |
biojava/biojava | biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatProperties.java | ProfeatProperties.getTransition | public static double getTransition(ProteinSequence sequence, ATTRIBUTE attribute, TRANSITION transition) throws Exception {
"""
An adaptor method which returns the number of transition between the specified groups for the given attribute with respect to the length of sequence.
@param sequence
a protein sequence consisting of non-ambiguous characters only
@param attribute
one of the seven attributes (Hydrophobicity, Volume, Polarity, Polarizability, Charge, SecondaryStructure or SolventAccessibility)
@param transition
the interested transition between the groups
@return
returns the number of transition between the specified groups for the given attribute with respect to the length of sequence.
@throws Exception
throws Exception if attribute or group are unknown
"""
return new ProfeatPropertiesImpl().getTransition(sequence, attribute, transition);
} | java | public static double getTransition(ProteinSequence sequence, ATTRIBUTE attribute, TRANSITION transition) throws Exception{
return new ProfeatPropertiesImpl().getTransition(sequence, attribute, transition);
} | [
"public",
"static",
"double",
"getTransition",
"(",
"ProteinSequence",
"sequence",
",",
"ATTRIBUTE",
"attribute",
",",
"TRANSITION",
"transition",
")",
"throws",
"Exception",
"{",
"return",
"new",
"ProfeatPropertiesImpl",
"(",
")",
".",
"getTransition",
"(",
"sequence",
",",
"attribute",
",",
"transition",
")",
";",
"}"
] | An adaptor method which returns the number of transition between the specified groups for the given attribute with respect to the length of sequence.
@param sequence
a protein sequence consisting of non-ambiguous characters only
@param attribute
one of the seven attributes (Hydrophobicity, Volume, Polarity, Polarizability, Charge, SecondaryStructure or SolventAccessibility)
@param transition
the interested transition between the groups
@return
returns the number of transition between the specified groups for the given attribute with respect to the length of sequence.
@throws Exception
throws Exception if attribute or group are unknown | [
"An",
"adaptor",
"method",
"which",
"returns",
"the",
"number",
"of",
"transition",
"between",
"the",
"specified",
"groups",
"for",
"the",
"given",
"attribute",
"with",
"respect",
"to",
"the",
"length",
"of",
"sequence",
"."
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatProperties.java#L94-L96 |
fcrepo3/fcrepo | fcrepo-server/src/main/java/org/fcrepo/server/utilities/StreamUtility.java | StreamUtility.pipeStream | public static void pipeStream(InputStream in, OutputStream out, int bufSize)
throws IOException {
"""
Copies the contents of an InputStream to an OutputStream, then closes
both.
@param in
The source stream.
@param out
The target stream.
@param bufSize
Number of bytes to attempt to copy at a time.
@throws IOException
If any sort of read/write error occurs on either stream.
"""
try {
byte[] buf = new byte[bufSize];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
logger.warn("Unable to close stream", e);
}
}
} | java | public static void pipeStream(InputStream in, OutputStream out, int bufSize)
throws IOException {
try {
byte[] buf = new byte[bufSize];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
logger.warn("Unable to close stream", e);
}
}
} | [
"public",
"static",
"void",
"pipeStream",
"(",
"InputStream",
"in",
",",
"OutputStream",
"out",
",",
"int",
"bufSize",
")",
"throws",
"IOException",
"{",
"try",
"{",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"bufSize",
"]",
";",
"int",
"len",
";",
"while",
"(",
"(",
"len",
"=",
"in",
".",
"read",
"(",
"buf",
")",
")",
">",
"0",
")",
"{",
"out",
".",
"write",
"(",
"buf",
",",
"0",
",",
"len",
")",
";",
"}",
"}",
"finally",
"{",
"try",
"{",
"in",
".",
"close",
"(",
")",
";",
"out",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Unable to close stream\"",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Copies the contents of an InputStream to an OutputStream, then closes
both.
@param in
The source stream.
@param out
The target stream.
@param bufSize
Number of bytes to attempt to copy at a time.
@throws IOException
If any sort of read/write error occurs on either stream. | [
"Copies",
"the",
"contents",
"of",
"an",
"InputStream",
"to",
"an",
"OutputStream",
"then",
"closes",
"both",
"."
] | train | https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/utilities/StreamUtility.java#L250-L266 |
structr/structr | structr-core/src/main/java/org/structr/core/entity/LinkedListNodeImpl.java | LinkedListNodeImpl.listInsertAfter | @Override
public void listInsertAfter(final T currentElement, final T newElement) throws FrameworkException {
"""
Inserts newElement after currentElement in the list defined by this
LinkedListManager.
@param currentElement the reference element
@param newElement the new element
"""
if (currentElement.getUuid().equals(newElement.getUuid())) {
throw new IllegalStateException("Cannot link a node to itself!");
}
final T next = listGetNext(currentElement);
if (next == null) {
linkNodes(getSiblingLinkType(), currentElement, newElement);
} else {
// unlink predecessor and successor
unlinkNodes(getSiblingLinkType(), currentElement, next);
// link predecessor to new element
linkNodes(getSiblingLinkType(), currentElement, newElement);
// dont create self link
if (!newElement.getUuid().equals(next.getUuid())) {
// link new element to successor
linkNodes(getSiblingLinkType(), newElement, next);
}
}
} | java | @Override
public void listInsertAfter(final T currentElement, final T newElement) throws FrameworkException {
if (currentElement.getUuid().equals(newElement.getUuid())) {
throw new IllegalStateException("Cannot link a node to itself!");
}
final T next = listGetNext(currentElement);
if (next == null) {
linkNodes(getSiblingLinkType(), currentElement, newElement);
} else {
// unlink predecessor and successor
unlinkNodes(getSiblingLinkType(), currentElement, next);
// link predecessor to new element
linkNodes(getSiblingLinkType(), currentElement, newElement);
// dont create self link
if (!newElement.getUuid().equals(next.getUuid())) {
// link new element to successor
linkNodes(getSiblingLinkType(), newElement, next);
}
}
} | [
"@",
"Override",
"public",
"void",
"listInsertAfter",
"(",
"final",
"T",
"currentElement",
",",
"final",
"T",
"newElement",
")",
"throws",
"FrameworkException",
"{",
"if",
"(",
"currentElement",
".",
"getUuid",
"(",
")",
".",
"equals",
"(",
"newElement",
".",
"getUuid",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot link a node to itself!\"",
")",
";",
"}",
"final",
"T",
"next",
"=",
"listGetNext",
"(",
"currentElement",
")",
";",
"if",
"(",
"next",
"==",
"null",
")",
"{",
"linkNodes",
"(",
"getSiblingLinkType",
"(",
")",
",",
"currentElement",
",",
"newElement",
")",
";",
"}",
"else",
"{",
"// unlink predecessor and successor",
"unlinkNodes",
"(",
"getSiblingLinkType",
"(",
")",
",",
"currentElement",
",",
"next",
")",
";",
"// link predecessor to new element",
"linkNodes",
"(",
"getSiblingLinkType",
"(",
")",
",",
"currentElement",
",",
"newElement",
")",
";",
"// dont create self link",
"if",
"(",
"!",
"newElement",
".",
"getUuid",
"(",
")",
".",
"equals",
"(",
"next",
".",
"getUuid",
"(",
")",
")",
")",
"{",
"// link new element to successor",
"linkNodes",
"(",
"getSiblingLinkType",
"(",
")",
",",
"newElement",
",",
"next",
")",
";",
"}",
"}",
"}"
] | Inserts newElement after currentElement in the list defined by this
LinkedListManager.
@param currentElement the reference element
@param newElement the new element | [
"Inserts",
"newElement",
"after",
"currentElement",
"in",
"the",
"list",
"defined",
"by",
"this",
"LinkedListManager",
"."
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/core/entity/LinkedListNodeImpl.java#L118-L144 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/AsyncMutateInBuilder.java | AsyncMutateInBuilder.arrayAddUnique | public <T> AsyncMutateInBuilder arrayAddUnique(String path, T value) {
"""
Insert a value in an existing array only if the value
isn't already contained in the array (by way of string comparison).
@param path the path to mutate in the JSON.
@param value the value to insert.
"""
this.mutationSpecs.add(new MutationSpec(Mutation.ARRAY_ADD_UNIQUE, path, value));
return this;
} | java | public <T> AsyncMutateInBuilder arrayAddUnique(String path, T value) {
this.mutationSpecs.add(new MutationSpec(Mutation.ARRAY_ADD_UNIQUE, path, value));
return this;
} | [
"public",
"<",
"T",
">",
"AsyncMutateInBuilder",
"arrayAddUnique",
"(",
"String",
"path",
",",
"T",
"value",
")",
"{",
"this",
".",
"mutationSpecs",
".",
"add",
"(",
"new",
"MutationSpec",
"(",
"Mutation",
".",
"ARRAY_ADD_UNIQUE",
",",
"path",
",",
"value",
")",
")",
";",
"return",
"this",
";",
"}"
] | Insert a value in an existing array only if the value
isn't already contained in the array (by way of string comparison).
@param path the path to mutate in the JSON.
@param value the value to insert. | [
"Insert",
"a",
"value",
"in",
"an",
"existing",
"array",
"only",
"if",
"the",
"value",
"isn",
"t",
"already",
"contained",
"in",
"the",
"array",
"(",
"by",
"way",
"of",
"string",
"comparison",
")",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/AsyncMutateInBuilder.java#L1196-L1199 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/TypeMaker.java | TypeMaker.typeArgumentsString | static String typeArgumentsString(DocEnv env, ClassType cl, boolean full) {
"""
Return the actual type arguments of a parameterized type as an
angle-bracketed string. Class name are qualified if "full" is true.
Return "" if there are no type arguments or we're hiding generics.
"""
if (env.legacyDoclet || cl.getTypeArguments().isEmpty()) {
return "";
}
StringBuilder s = new StringBuilder();
for (Type t : cl.getTypeArguments()) {
s.append(s.length() == 0 ? "<" : ", ");
s.append(getTypeString(env, t, full));
}
s.append(">");
return s.toString();
} | java | static String typeArgumentsString(DocEnv env, ClassType cl, boolean full) {
if (env.legacyDoclet || cl.getTypeArguments().isEmpty()) {
return "";
}
StringBuilder s = new StringBuilder();
for (Type t : cl.getTypeArguments()) {
s.append(s.length() == 0 ? "<" : ", ");
s.append(getTypeString(env, t, full));
}
s.append(">");
return s.toString();
} | [
"static",
"String",
"typeArgumentsString",
"(",
"DocEnv",
"env",
",",
"ClassType",
"cl",
",",
"boolean",
"full",
")",
"{",
"if",
"(",
"env",
".",
"legacyDoclet",
"||",
"cl",
".",
"getTypeArguments",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"\"\"",
";",
"}",
"StringBuilder",
"s",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Type",
"t",
":",
"cl",
".",
"getTypeArguments",
"(",
")",
")",
"{",
"s",
".",
"append",
"(",
"s",
".",
"length",
"(",
")",
"==",
"0",
"?",
"\"<\"",
":",
"\", \"",
")",
";",
"s",
".",
"append",
"(",
"getTypeString",
"(",
"env",
",",
"t",
",",
"full",
")",
")",
";",
"}",
"s",
".",
"append",
"(",
"\">\"",
")",
";",
"return",
"s",
".",
"toString",
"(",
")",
";",
"}"
] | Return the actual type arguments of a parameterized type as an
angle-bracketed string. Class name are qualified if "full" is true.
Return "" if there are no type arguments or we're hiding generics. | [
"Return",
"the",
"actual",
"type",
"arguments",
"of",
"a",
"parameterized",
"type",
"as",
"an",
"angle",
"-",
"bracketed",
"string",
".",
"Class",
"name",
"are",
"qualified",
"if",
"full",
"is",
"true",
".",
"Return",
"if",
"there",
"are",
"no",
"type",
"arguments",
"or",
"we",
"re",
"hiding",
"generics",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/TypeMaker.java#L202-L213 |
Subsets and Splits