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
listlengths 20
832
| func_documentation_string
stringlengths 61
2k
| func_documentation_tokens
listlengths 1
647
| split_name
stringclasses 1
value | func_code_url
stringlengths 102
339
|
---|---|---|---|---|---|---|---|---|---|---|
aggregateknowledge/java-hll | src/main/java/net/agkn/hll/serialization/BigEndianAscendingWordSerializer.java | BigEndianAscendingWordSerializer.writeWord | @Override
public void writeWord(final long word) {
"""
/* (non-Javadoc)
@see net.agkn.hll.serialization.IWordSerializer#writeWord(long)
@throws RuntimeException if the number of words written is greater than the
<code>wordCount</code> parameter in the constructor.
"""
if(wordsWritten == wordCount) {
throw new RuntimeException("Cannot write more words, backing array full!");
}
int bitsLeftInWord = wordLength;
while(bitsLeftInWord > 0) {
// Move to the next byte if the current one is fully packed.
if(bitsLeftInByte == 0) {
byteIndex++;
bitsLeftInByte = BITS_PER_BYTE;
}
final long consumedMask;
if(bitsLeftInWord == 64) {
consumedMask = ~0L;
} else {
consumedMask = ((1L << bitsLeftInWord) - 1L);
}
// Fix how many bits will be written in this cycle. Choose the
// smaller of the remaining bits in the word or byte.
final int numberOfBitsToWrite = Math.min(bitsLeftInByte, bitsLeftInWord);
final int bitsInByteRemainingAfterWrite = (bitsLeftInByte - numberOfBitsToWrite);
// In general, we write the highest bits of the word first, so we
// strip the highest bits that were consumed in previous cycles.
final long remainingBitsOfWordToWrite = (word & consumedMask);
final long bitsThatTheByteCanAccept;
// If there is more left in the word than can be written to this
// byte, shift off the bits that can't be written off the bottom.
if(bitsLeftInWord > numberOfBitsToWrite) {
bitsThatTheByteCanAccept = (remainingBitsOfWordToWrite >>> (bitsLeftInWord - bitsLeftInByte));
} else {
// If the byte can accept all remaining bits, there is no need
// to shift off the bits that won't be written in this cycle.
bitsThatTheByteCanAccept = remainingBitsOfWordToWrite;
}
// Align the word bits to write up against the byte bits that have
// already been written. This shift may do nothing if the remainder
// of the byte is being consumed in this cycle.
final long alignedBits = (bitsThatTheByteCanAccept << bitsInByteRemainingAfterWrite);
// Update the byte with the alignedBits.
bytes[byteIndex] |= (byte)alignedBits;
// Update state with bit count written.
bitsLeftInWord -= numberOfBitsToWrite;
bitsLeftInByte = bitsInByteRemainingAfterWrite;
}
wordsWritten ++;
} | java | @Override
public void writeWord(final long word) {
if(wordsWritten == wordCount) {
throw new RuntimeException("Cannot write more words, backing array full!");
}
int bitsLeftInWord = wordLength;
while(bitsLeftInWord > 0) {
// Move to the next byte if the current one is fully packed.
if(bitsLeftInByte == 0) {
byteIndex++;
bitsLeftInByte = BITS_PER_BYTE;
}
final long consumedMask;
if(bitsLeftInWord == 64) {
consumedMask = ~0L;
} else {
consumedMask = ((1L << bitsLeftInWord) - 1L);
}
// Fix how many bits will be written in this cycle. Choose the
// smaller of the remaining bits in the word or byte.
final int numberOfBitsToWrite = Math.min(bitsLeftInByte, bitsLeftInWord);
final int bitsInByteRemainingAfterWrite = (bitsLeftInByte - numberOfBitsToWrite);
// In general, we write the highest bits of the word first, so we
// strip the highest bits that were consumed in previous cycles.
final long remainingBitsOfWordToWrite = (word & consumedMask);
final long bitsThatTheByteCanAccept;
// If there is more left in the word than can be written to this
// byte, shift off the bits that can't be written off the bottom.
if(bitsLeftInWord > numberOfBitsToWrite) {
bitsThatTheByteCanAccept = (remainingBitsOfWordToWrite >>> (bitsLeftInWord - bitsLeftInByte));
} else {
// If the byte can accept all remaining bits, there is no need
// to shift off the bits that won't be written in this cycle.
bitsThatTheByteCanAccept = remainingBitsOfWordToWrite;
}
// Align the word bits to write up against the byte bits that have
// already been written. This shift may do nothing if the remainder
// of the byte is being consumed in this cycle.
final long alignedBits = (bitsThatTheByteCanAccept << bitsInByteRemainingAfterWrite);
// Update the byte with the alignedBits.
bytes[byteIndex] |= (byte)alignedBits;
// Update state with bit count written.
bitsLeftInWord -= numberOfBitsToWrite;
bitsLeftInByte = bitsInByteRemainingAfterWrite;
}
wordsWritten ++;
} | [
"@",
"Override",
"public",
"void",
"writeWord",
"(",
"final",
"long",
"word",
")",
"{",
"if",
"(",
"wordsWritten",
"==",
"wordCount",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot write more words, backing array full!\"",
")",
";",
"}",
"int",
"bitsLeftInWord",
"=",
"wordLength",
";",
"while",
"(",
"bitsLeftInWord",
">",
"0",
")",
"{",
"// Move to the next byte if the current one is fully packed.",
"if",
"(",
"bitsLeftInByte",
"==",
"0",
")",
"{",
"byteIndex",
"++",
";",
"bitsLeftInByte",
"=",
"BITS_PER_BYTE",
";",
"}",
"final",
"long",
"consumedMask",
";",
"if",
"(",
"bitsLeftInWord",
"==",
"64",
")",
"{",
"consumedMask",
"=",
"~",
"0L",
";",
"}",
"else",
"{",
"consumedMask",
"=",
"(",
"(",
"1L",
"<<",
"bitsLeftInWord",
")",
"-",
"1L",
")",
";",
"}",
"// Fix how many bits will be written in this cycle. Choose the",
"// smaller of the remaining bits in the word or byte.",
"final",
"int",
"numberOfBitsToWrite",
"=",
"Math",
".",
"min",
"(",
"bitsLeftInByte",
",",
"bitsLeftInWord",
")",
";",
"final",
"int",
"bitsInByteRemainingAfterWrite",
"=",
"(",
"bitsLeftInByte",
"-",
"numberOfBitsToWrite",
")",
";",
"// In general, we write the highest bits of the word first, so we",
"// strip the highest bits that were consumed in previous cycles.",
"final",
"long",
"remainingBitsOfWordToWrite",
"=",
"(",
"word",
"&",
"consumedMask",
")",
";",
"final",
"long",
"bitsThatTheByteCanAccept",
";",
"// If there is more left in the word than can be written to this",
"// byte, shift off the bits that can't be written off the bottom.",
"if",
"(",
"bitsLeftInWord",
">",
"numberOfBitsToWrite",
")",
"{",
"bitsThatTheByteCanAccept",
"=",
"(",
"remainingBitsOfWordToWrite",
">>>",
"(",
"bitsLeftInWord",
"-",
"bitsLeftInByte",
")",
")",
";",
"}",
"else",
"{",
"// If the byte can accept all remaining bits, there is no need",
"// to shift off the bits that won't be written in this cycle.",
"bitsThatTheByteCanAccept",
"=",
"remainingBitsOfWordToWrite",
";",
"}",
"// Align the word bits to write up against the byte bits that have",
"// already been written. This shift may do nothing if the remainder",
"// of the byte is being consumed in this cycle.",
"final",
"long",
"alignedBits",
"=",
"(",
"bitsThatTheByteCanAccept",
"<<",
"bitsInByteRemainingAfterWrite",
")",
";",
"// Update the byte with the alignedBits.",
"bytes",
"[",
"byteIndex",
"]",
"|=",
"(",
"byte",
")",
"alignedBits",
";",
"// Update state with bit count written.",
"bitsLeftInWord",
"-=",
"numberOfBitsToWrite",
";",
"bitsLeftInByte",
"=",
"bitsInByteRemainingAfterWrite",
";",
"}",
"wordsWritten",
"++",
";",
"}"
]
| /* (non-Javadoc)
@see net.agkn.hll.serialization.IWordSerializer#writeWord(long)
@throws RuntimeException if the number of words written is greater than the
<code>wordCount</code> parameter in the constructor. | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
]
| train | https://github.com/aggregateknowledge/java-hll/blob/1f4126e79a85b79581460c75bf1c1634b8a7402d/src/main/java/net/agkn/hll/serialization/BigEndianAscendingWordSerializer.java#L104-L160 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/fs/FileSystem.java | FileSystem.moveFromLocalFile | public void moveFromLocalFile(Path[] srcs, Path dst)
throws IOException {
"""
The src files is on the local disk. Add it to FS at
the given dst name, removing the source afterwards.
"""
copyFromLocalFile(true, true, false, srcs, dst);
} | java | public void moveFromLocalFile(Path[] srcs, Path dst)
throws IOException {
copyFromLocalFile(true, true, false, srcs, dst);
} | [
"public",
"void",
"moveFromLocalFile",
"(",
"Path",
"[",
"]",
"srcs",
",",
"Path",
"dst",
")",
"throws",
"IOException",
"{",
"copyFromLocalFile",
"(",
"true",
",",
"true",
",",
"false",
",",
"srcs",
",",
"dst",
")",
";",
"}"
]
| The src files is on the local disk. Add it to FS at
the given dst name, removing the source afterwards. | [
"The",
"src",
"files",
"is",
"on",
"the",
"local",
"disk",
".",
"Add",
"it",
"to",
"FS",
"at",
"the",
"given",
"dst",
"name",
"removing",
"the",
"source",
"afterwards",
"."
]
| train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileSystem.java#L1632-L1635 |
alkacon/opencms-core | src/org/opencms/workplace/editors/CmsEditor.java | CmsEditor.getFileEncoding | protected String getFileEncoding(CmsObject cms, String filename) {
"""
Helper method to determine the encoding of the given file in the VFS,
which must be set using the "content-encoding" property.<p>
@param cms the CmsObject
@param filename the name of the file which is to be checked
@return the encoding for the file
"""
try {
return cms.readPropertyObject(filename, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(
OpenCms.getSystemInfo().getDefaultEncoding());
} catch (CmsException e) {
return OpenCms.getSystemInfo().getDefaultEncoding();
}
} | java | protected String getFileEncoding(CmsObject cms, String filename) {
try {
return cms.readPropertyObject(filename, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, true).getValue(
OpenCms.getSystemInfo().getDefaultEncoding());
} catch (CmsException e) {
return OpenCms.getSystemInfo().getDefaultEncoding();
}
} | [
"protected",
"String",
"getFileEncoding",
"(",
"CmsObject",
"cms",
",",
"String",
"filename",
")",
"{",
"try",
"{",
"return",
"cms",
".",
"readPropertyObject",
"(",
"filename",
",",
"CmsPropertyDefinition",
".",
"PROPERTY_CONTENT_ENCODING",
",",
"true",
")",
".",
"getValue",
"(",
"OpenCms",
".",
"getSystemInfo",
"(",
")",
".",
"getDefaultEncoding",
"(",
")",
")",
";",
"}",
"catch",
"(",
"CmsException",
"e",
")",
"{",
"return",
"OpenCms",
".",
"getSystemInfo",
"(",
")",
".",
"getDefaultEncoding",
"(",
")",
";",
"}",
"}"
]
| Helper method to determine the encoding of the given file in the VFS,
which must be set using the "content-encoding" property.<p>
@param cms the CmsObject
@param filename the name of the file which is to be checked
@return the encoding for the file | [
"Helper",
"method",
"to",
"determine",
"the",
"encoding",
"of",
"the",
"given",
"file",
"in",
"the",
"VFS",
"which",
"must",
"be",
"set",
"using",
"the",
"content",
"-",
"encoding",
"property",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsEditor.java#L984-L992 |
groundupworks/wings | wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java | FacebookEndpoint.finishPublishPermissionsRequest | private boolean finishPublishPermissionsRequest(Activity activity, int requestCode, int resultCode, Intent data) {
"""
Finishes a {@link com.groundupworks.wings.facebook.FacebookEndpoint#startPublishPermissionsRequest(android.app.Activity, android.support.v4.app.Fragment)}.
@param activity the {@link Activity}.
@param requestCode the integer request code originally supplied to startActivityForResult(), allowing you to identify who
this result came from.
@param resultCode the integer result code returned by the child activity through its setResult().
@param data an Intent, which can return result data to the caller (various data can be attached to Intent
"extras").
@return true if publish permissions request is successful; false otherwise.
"""
boolean isSuccessful = false;
Session session = Session.getActiveSession();
// isOpened() must be called after onActivityResult().
if (session != null && session.onActivityResult(activity, requestCode, resultCode, data) && session.isOpened()
&& session.getPermissions().contains(PERMISSION_PUBLISH_ACTIONS)) {
isSuccessful = true;
}
return isSuccessful;
} | java | private boolean finishPublishPermissionsRequest(Activity activity, int requestCode, int resultCode, Intent data) {
boolean isSuccessful = false;
Session session = Session.getActiveSession();
// isOpened() must be called after onActivityResult().
if (session != null && session.onActivityResult(activity, requestCode, resultCode, data) && session.isOpened()
&& session.getPermissions().contains(PERMISSION_PUBLISH_ACTIONS)) {
isSuccessful = true;
}
return isSuccessful;
} | [
"private",
"boolean",
"finishPublishPermissionsRequest",
"(",
"Activity",
"activity",
",",
"int",
"requestCode",
",",
"int",
"resultCode",
",",
"Intent",
"data",
")",
"{",
"boolean",
"isSuccessful",
"=",
"false",
";",
"Session",
"session",
"=",
"Session",
".",
"getActiveSession",
"(",
")",
";",
"// isOpened() must be called after onActivityResult().",
"if",
"(",
"session",
"!=",
"null",
"&&",
"session",
".",
"onActivityResult",
"(",
"activity",
",",
"requestCode",
",",
"resultCode",
",",
"data",
")",
"&&",
"session",
".",
"isOpened",
"(",
")",
"&&",
"session",
".",
"getPermissions",
"(",
")",
".",
"contains",
"(",
"PERMISSION_PUBLISH_ACTIONS",
")",
")",
"{",
"isSuccessful",
"=",
"true",
";",
"}",
"return",
"isSuccessful",
";",
"}"
]
| Finishes a {@link com.groundupworks.wings.facebook.FacebookEndpoint#startPublishPermissionsRequest(android.app.Activity, android.support.v4.app.Fragment)}.
@param activity the {@link Activity}.
@param requestCode the integer request code originally supplied to startActivityForResult(), allowing you to identify who
this result came from.
@param resultCode the integer result code returned by the child activity through its setResult().
@param data an Intent, which can return result data to the caller (various data can be attached to Intent
"extras").
@return true if publish permissions request is successful; false otherwise. | [
"Finishes",
"a",
"{",
"@link",
"com",
".",
"groundupworks",
".",
"wings",
".",
"facebook",
".",
"FacebookEndpoint#startPublishPermissionsRequest",
"(",
"android",
".",
"app",
".",
"Activity",
"android",
".",
"support",
".",
"v4",
".",
"app",
".",
"Fragment",
")",
"}",
"."
]
| train | https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java#L429-L441 |
defei/codelogger-utils | src/main/java/org/codelogger/utils/MathUtils.java | MathUtils.isAliquot | public static <T extends Number> boolean isAliquot(final T dividend, final T divisor) {
"""
Judge divisor is an aliquot part of dividend.</br> 判断被除数是否能被除数整除。
@param dividend
number to be handled.被除数。
@param divisor
number to be handled.除数。
@return true if divisor is an aliquot part of dividend, otherwise
false.是否能被整除。
"""
return dividend.doubleValue() % divisor.doubleValue() == 0;
} | java | public static <T extends Number> boolean isAliquot(final T dividend, final T divisor) {
return dividend.doubleValue() % divisor.doubleValue() == 0;
} | [
"public",
"static",
"<",
"T",
"extends",
"Number",
">",
"boolean",
"isAliquot",
"(",
"final",
"T",
"dividend",
",",
"final",
"T",
"divisor",
")",
"{",
"return",
"dividend",
".",
"doubleValue",
"(",
")",
"%",
"divisor",
".",
"doubleValue",
"(",
")",
"==",
"0",
";",
"}"
]
| Judge divisor is an aliquot part of dividend.</br> 判断被除数是否能被除数整除。
@param dividend
number to be handled.被除数。
@param divisor
number to be handled.除数。
@return true if divisor is an aliquot part of dividend, otherwise
false.是否能被整除。 | [
"Judge",
"divisor",
"is",
"an",
"aliquot",
"part",
"of",
"dividend",
".",
"<",
"/",
"br",
">",
"判断被除数是否能被除数整除。"
]
| train | https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/MathUtils.java#L221-L224 |
google/truth | core/src/main/java/com/google/common/truth/MultimapSubject.java | MultimapSubject.advanceToFind | private static boolean advanceToFind(Iterator<?> iterator, Object value) {
"""
Advances the iterator until it either returns value, or has no more elements.
<p>Returns true if the value was found, false if the end was reached before finding it.
<p>This is basically the same as {@link Iterables#contains}, but where the contract explicitly
states that the iterator isn't advanced beyond the value if the value is found.
"""
while (iterator.hasNext()) {
if (Objects.equal(iterator.next(), value)) {
return true;
}
}
return false;
} | java | private static boolean advanceToFind(Iterator<?> iterator, Object value) {
while (iterator.hasNext()) {
if (Objects.equal(iterator.next(), value)) {
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"advanceToFind",
"(",
"Iterator",
"<",
"?",
">",
"iterator",
",",
"Object",
"value",
")",
"{",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"if",
"(",
"Objects",
".",
"equal",
"(",
"iterator",
".",
"next",
"(",
")",
",",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Advances the iterator until it either returns value, or has no more elements.
<p>Returns true if the value was found, false if the end was reached before finding it.
<p>This is basically the same as {@link Iterables#contains}, but where the contract explicitly
states that the iterator isn't advanced beyond the value if the value is found. | [
"Advances",
"the",
"iterator",
"until",
"it",
"either",
"returns",
"value",
"or",
"has",
"no",
"more",
"elements",
"."
]
| train | https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MultimapSubject.java#L425-L432 |
ksclarke/vertx-pairtree | src/main/java/info/freelibrary/pairtree/PairtreeUtils.java | PairtreeUtils.mapToPtPath | public static String mapToPtPath(final String aBasePath, final String aID) {
"""
Maps the supplied ID to a Pairtree path using the supplied base path.
@param aID An ID to map to a Pairtree path
@param aBasePath The base path to use in the mapping
@return The Pairtree path for the supplied ID
"""
return concat(aBasePath, mapToPtPath(aID), null);
} | java | public static String mapToPtPath(final String aBasePath, final String aID) {
return concat(aBasePath, mapToPtPath(aID), null);
} | [
"public",
"static",
"String",
"mapToPtPath",
"(",
"final",
"String",
"aBasePath",
",",
"final",
"String",
"aID",
")",
"{",
"return",
"concat",
"(",
"aBasePath",
",",
"mapToPtPath",
"(",
"aID",
")",
",",
"null",
")",
";",
"}"
]
| Maps the supplied ID to a Pairtree path using the supplied base path.
@param aID An ID to map to a Pairtree path
@param aBasePath The base path to use in the mapping
@return The Pairtree path for the supplied ID | [
"Maps",
"the",
"supplied",
"ID",
"to",
"a",
"Pairtree",
"path",
"using",
"the",
"supplied",
"base",
"path",
"."
]
| train | https://github.com/ksclarke/vertx-pairtree/blob/b2ea1e32057e5df262e9265540d346a732b718df/src/main/java/info/freelibrary/pairtree/PairtreeUtils.java#L164-L166 |
mediathekview/MLib | src/main/java/de/mediathekview/mlib/filmlisten/FilmlisteLesen.java | FilmlisteLesen.processFromWeb | private void processFromWeb(URL source, ListeFilme listeFilme) {
"""
Download a process a filmliste from the web.
@param source source url as string
@param listeFilme the list to read to
"""
Request.Builder builder = new Request.Builder().url(source);
builder.addHeader("User-Agent", Config.getUserAgent());
//our progress monitor callback
InputStreamProgressMonitor monitor = new InputStreamProgressMonitor() {
private int oldProgress = 0;
@Override
public void progress(long bytesRead, long size) {
final int iProgress = (int) (bytesRead * 100 / size);
if (iProgress != oldProgress) {
oldProgress = iProgress;
notifyProgress(source.toString(), iProgress);
}
}
};
try (Response response = MVHttpClient.getInstance().getHttpClient().newCall(builder.build()).execute();
ResponseBody body = response.body()) {
if (response.isSuccessful()) {
try (InputStream input = new ProgressMonitorInputStream(body.byteStream(), body.contentLength(), monitor)) {
try (InputStream is = selectDecompressor(source.toString(), input);
JsonParser jp = new JsonFactory().createParser(is)) {
readData(jp, listeFilme);
}
}
}
} catch (Exception ex) {
Log.errorLog(945123641, ex, "FilmListe: " + source);
listeFilme.clear();
}
} | java | private void processFromWeb(URL source, ListeFilme listeFilme) {
Request.Builder builder = new Request.Builder().url(source);
builder.addHeader("User-Agent", Config.getUserAgent());
//our progress monitor callback
InputStreamProgressMonitor monitor = new InputStreamProgressMonitor() {
private int oldProgress = 0;
@Override
public void progress(long bytesRead, long size) {
final int iProgress = (int) (bytesRead * 100 / size);
if (iProgress != oldProgress) {
oldProgress = iProgress;
notifyProgress(source.toString(), iProgress);
}
}
};
try (Response response = MVHttpClient.getInstance().getHttpClient().newCall(builder.build()).execute();
ResponseBody body = response.body()) {
if (response.isSuccessful()) {
try (InputStream input = new ProgressMonitorInputStream(body.byteStream(), body.contentLength(), monitor)) {
try (InputStream is = selectDecompressor(source.toString(), input);
JsonParser jp = new JsonFactory().createParser(is)) {
readData(jp, listeFilme);
}
}
}
} catch (Exception ex) {
Log.errorLog(945123641, ex, "FilmListe: " + source);
listeFilme.clear();
}
} | [
"private",
"void",
"processFromWeb",
"(",
"URL",
"source",
",",
"ListeFilme",
"listeFilme",
")",
"{",
"Request",
".",
"Builder",
"builder",
"=",
"new",
"Request",
".",
"Builder",
"(",
")",
".",
"url",
"(",
"source",
")",
";",
"builder",
".",
"addHeader",
"(",
"\"User-Agent\"",
",",
"Config",
".",
"getUserAgent",
"(",
")",
")",
";",
"//our progress monitor callback",
"InputStreamProgressMonitor",
"monitor",
"=",
"new",
"InputStreamProgressMonitor",
"(",
")",
"{",
"private",
"int",
"oldProgress",
"=",
"0",
";",
"@",
"Override",
"public",
"void",
"progress",
"(",
"long",
"bytesRead",
",",
"long",
"size",
")",
"{",
"final",
"int",
"iProgress",
"=",
"(",
"int",
")",
"(",
"bytesRead",
"*",
"100",
"/",
"size",
")",
";",
"if",
"(",
"iProgress",
"!=",
"oldProgress",
")",
"{",
"oldProgress",
"=",
"iProgress",
";",
"notifyProgress",
"(",
"source",
".",
"toString",
"(",
")",
",",
"iProgress",
")",
";",
"}",
"}",
"}",
";",
"try",
"(",
"Response",
"response",
"=",
"MVHttpClient",
".",
"getInstance",
"(",
")",
".",
"getHttpClient",
"(",
")",
".",
"newCall",
"(",
"builder",
".",
"build",
"(",
")",
")",
".",
"execute",
"(",
")",
";",
"ResponseBody",
"body",
"=",
"response",
".",
"body",
"(",
")",
")",
"{",
"if",
"(",
"response",
".",
"isSuccessful",
"(",
")",
")",
"{",
"try",
"(",
"InputStream",
"input",
"=",
"new",
"ProgressMonitorInputStream",
"(",
"body",
".",
"byteStream",
"(",
")",
",",
"body",
".",
"contentLength",
"(",
")",
",",
"monitor",
")",
")",
"{",
"try",
"(",
"InputStream",
"is",
"=",
"selectDecompressor",
"(",
"source",
".",
"toString",
"(",
")",
",",
"input",
")",
";",
"JsonParser",
"jp",
"=",
"new",
"JsonFactory",
"(",
")",
".",
"createParser",
"(",
"is",
")",
")",
"{",
"readData",
"(",
"jp",
",",
"listeFilme",
")",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"Log",
".",
"errorLog",
"(",
"945123641",
",",
"ex",
",",
"\"FilmListe: \"",
"+",
"source",
")",
";",
"listeFilme",
".",
"clear",
"(",
")",
";",
"}",
"}"
]
| Download a process a filmliste from the web.
@param source source url as string
@param listeFilme the list to read to | [
"Download",
"a",
"process",
"a",
"filmliste",
"from",
"the",
"web",
"."
]
| train | https://github.com/mediathekview/MLib/blob/01fd5791d87390fea7536275b8a2d4407fc00908/src/main/java/de/mediathekview/mlib/filmlisten/FilmlisteLesen.java#L230-L262 |
apache/incubator-druid | extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java | ApproximateHistogram.siftDown | private static void siftDown(int[] heap, int[] reverseIndex, int start, int end, float[] values) {
"""
Rebalances the min-heap by pushing values from the top down and simultaneously updating the reverse index
@param heap min-heap stored as indices into the array of values
@param reverseIndex reverse index from the array of values into the heap
@param start index to start re-balancing from
@param end index to stop re-balancing at
@param values values stored in the heap
"""
int root = start;
while (root * 2 + 1 <= end) {
int child = root * 2 + 1;
int swap = root;
if (values[heap[swap]] > values[heap[child]]) {
swap = child;
}
if (child + 1 <= end && values[heap[swap]] > values[heap[child + 1]]) {
swap = child + 1;
}
if (swap != root) {
// swap
int tmp = heap[swap];
heap[swap] = heap[root];
heap[root] = tmp;
// heap index from delta index
reverseIndex[heap[swap]] = swap;
reverseIndex[heap[root]] = root;
root = swap;
} else {
return;
}
}
} | java | private static void siftDown(int[] heap, int[] reverseIndex, int start, int end, float[] values)
{
int root = start;
while (root * 2 + 1 <= end) {
int child = root * 2 + 1;
int swap = root;
if (values[heap[swap]] > values[heap[child]]) {
swap = child;
}
if (child + 1 <= end && values[heap[swap]] > values[heap[child + 1]]) {
swap = child + 1;
}
if (swap != root) {
// swap
int tmp = heap[swap];
heap[swap] = heap[root];
heap[root] = tmp;
// heap index from delta index
reverseIndex[heap[swap]] = swap;
reverseIndex[heap[root]] = root;
root = swap;
} else {
return;
}
}
} | [
"private",
"static",
"void",
"siftDown",
"(",
"int",
"[",
"]",
"heap",
",",
"int",
"[",
"]",
"reverseIndex",
",",
"int",
"start",
",",
"int",
"end",
",",
"float",
"[",
"]",
"values",
")",
"{",
"int",
"root",
"=",
"start",
";",
"while",
"(",
"root",
"*",
"2",
"+",
"1",
"<=",
"end",
")",
"{",
"int",
"child",
"=",
"root",
"*",
"2",
"+",
"1",
";",
"int",
"swap",
"=",
"root",
";",
"if",
"(",
"values",
"[",
"heap",
"[",
"swap",
"]",
"]",
">",
"values",
"[",
"heap",
"[",
"child",
"]",
"]",
")",
"{",
"swap",
"=",
"child",
";",
"}",
"if",
"(",
"child",
"+",
"1",
"<=",
"end",
"&&",
"values",
"[",
"heap",
"[",
"swap",
"]",
"]",
">",
"values",
"[",
"heap",
"[",
"child",
"+",
"1",
"]",
"]",
")",
"{",
"swap",
"=",
"child",
"+",
"1",
";",
"}",
"if",
"(",
"swap",
"!=",
"root",
")",
"{",
"// swap",
"int",
"tmp",
"=",
"heap",
"[",
"swap",
"]",
";",
"heap",
"[",
"swap",
"]",
"=",
"heap",
"[",
"root",
"]",
";",
"heap",
"[",
"root",
"]",
"=",
"tmp",
";",
"// heap index from delta index",
"reverseIndex",
"[",
"heap",
"[",
"swap",
"]",
"]",
"=",
"swap",
";",
"reverseIndex",
"[",
"heap",
"[",
"root",
"]",
"]",
"=",
"root",
";",
"root",
"=",
"swap",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"}"
]
| Rebalances the min-heap by pushing values from the top down and simultaneously updating the reverse index
@param heap min-heap stored as indices into the array of values
@param reverseIndex reverse index from the array of values into the heap
@param start index to start re-balancing from
@param end index to stop re-balancing at
@param values values stored in the heap | [
"Rebalances",
"the",
"min",
"-",
"heap",
"by",
"pushing",
"values",
"from",
"the",
"top",
"down",
"and",
"simultaneously",
"updating",
"the",
"reverse",
"index"
]
| train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java#L1006-L1033 |
datasalt/pangool | core/src/main/java/com/datasalt/pangool/io/Mutator.java | Mutator.minusFields | public static Schema minusFields(String newName, Schema schema, String... minusFields) {
"""
Creates a new schema which has exactly the same fields as the input Schema minus the field names
that are specified as "minusFields". This is equivalent to calling {@link #subSetOf(Schema, String...)}
with the list of Fields that must remain, but instead here we specify the fields that should NOT remain.
<p>
The name of the schema is also specified as a parameter.
"""
List<Field> newSchema = new ArrayList<Field>();
l1: for(Field f: schema.getFields()) {
for(String minsField: minusFields) {
if(f.getName().equals(minsField)) {
continue l1;
}
}
newSchema.add(f);
}
return new Schema(newName, newSchema);
} | java | public static Schema minusFields(String newName, Schema schema, String... minusFields) {
List<Field> newSchema = new ArrayList<Field>();
l1: for(Field f: schema.getFields()) {
for(String minsField: minusFields) {
if(f.getName().equals(minsField)) {
continue l1;
}
}
newSchema.add(f);
}
return new Schema(newName, newSchema);
} | [
"public",
"static",
"Schema",
"minusFields",
"(",
"String",
"newName",
",",
"Schema",
"schema",
",",
"String",
"...",
"minusFields",
")",
"{",
"List",
"<",
"Field",
">",
"newSchema",
"=",
"new",
"ArrayList",
"<",
"Field",
">",
"(",
")",
";",
"l1",
":",
"for",
"(",
"Field",
"f",
":",
"schema",
".",
"getFields",
"(",
")",
")",
"{",
"for",
"(",
"String",
"minsField",
":",
"minusFields",
")",
"{",
"if",
"(",
"f",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"minsField",
")",
")",
"{",
"continue",
"l1",
";",
"}",
"}",
"newSchema",
".",
"add",
"(",
"f",
")",
";",
"}",
"return",
"new",
"Schema",
"(",
"newName",
",",
"newSchema",
")",
";",
"}"
]
| Creates a new schema which has exactly the same fields as the input Schema minus the field names
that are specified as "minusFields". This is equivalent to calling {@link #subSetOf(Schema, String...)}
with the list of Fields that must remain, but instead here we specify the fields that should NOT remain.
<p>
The name of the schema is also specified as a parameter. | [
"Creates",
"a",
"new",
"schema",
"which",
"has",
"exactly",
"the",
"same",
"fields",
"as",
"the",
"input",
"Schema",
"minus",
"the",
"field",
"names",
"that",
"are",
"specified",
"as",
"minusFields",
".",
"This",
"is",
"equivalent",
"to",
"calling",
"{"
]
| train | https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Mutator.java#L35-L46 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java | CacheProviderWrapper.setValue | @Override
public void setValue(com.ibm.ws.cache.EntryInfo entryInfo, Object value, boolean coordinate, boolean directive) {
"""
Puts an entry into the cache. If the entry already exists in the
cache, this method will ALSO update the same.
Called by DistributedNioMap (old ProxyCache)
Called by Cache.setEntry(cacheEntry, source)
@param entryInfo The EntryInfo object
@param value The value of the object
@param coordinate Indicates that the value should be set in other caches caching this value. (No effect on CoreCache)
@param directive boolean to indicate CACHE_NEW_CONTENT or USE_CACHED_VALUE
"""
final String methodName = "setValue()";
Object id = null;
if (entryInfo != null) {
id = entryInfo.getIdObject();
}
if (directive == DynaCacheConstants.VBC_CACHE_NEW_CONTENT) {
this.coreCache.put(entryInfo, value);
} else {
this.coreCache.touch(entryInfo.id, entryInfo.validatorExpirationTime, entryInfo.expirationTime);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " id=" + id + " directive=" + directive);
}
} | java | @Override
public void setValue(com.ibm.ws.cache.EntryInfo entryInfo, Object value, boolean coordinate, boolean directive) {
final String methodName = "setValue()";
Object id = null;
if (entryInfo != null) {
id = entryInfo.getIdObject();
}
if (directive == DynaCacheConstants.VBC_CACHE_NEW_CONTENT) {
this.coreCache.put(entryInfo, value);
} else {
this.coreCache.touch(entryInfo.id, entryInfo.validatorExpirationTime, entryInfo.expirationTime);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " cacheName=" + cacheName + " id=" + id + " directive=" + directive);
}
} | [
"@",
"Override",
"public",
"void",
"setValue",
"(",
"com",
".",
"ibm",
".",
"ws",
".",
"cache",
".",
"EntryInfo",
"entryInfo",
",",
"Object",
"value",
",",
"boolean",
"coordinate",
",",
"boolean",
"directive",
")",
"{",
"final",
"String",
"methodName",
"=",
"\"setValue()\"",
";",
"Object",
"id",
"=",
"null",
";",
"if",
"(",
"entryInfo",
"!=",
"null",
")",
"{",
"id",
"=",
"entryInfo",
".",
"getIdObject",
"(",
")",
";",
"}",
"if",
"(",
"directive",
"==",
"DynaCacheConstants",
".",
"VBC_CACHE_NEW_CONTENT",
")",
"{",
"this",
".",
"coreCache",
".",
"put",
"(",
"entryInfo",
",",
"value",
")",
";",
"}",
"else",
"{",
"this",
".",
"coreCache",
".",
"touch",
"(",
"entryInfo",
".",
"id",
",",
"entryInfo",
".",
"validatorExpirationTime",
",",
"entryInfo",
".",
"expirationTime",
")",
";",
"}",
"if",
"(",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"methodName",
"+",
"\" cacheName=\"",
"+",
"cacheName",
"+",
"\" id=\"",
"+",
"id",
"+",
"\" directive=\"",
"+",
"directive",
")",
";",
"}",
"}"
]
| Puts an entry into the cache. If the entry already exists in the
cache, this method will ALSO update the same.
Called by DistributedNioMap (old ProxyCache)
Called by Cache.setEntry(cacheEntry, source)
@param entryInfo The EntryInfo object
@param value The value of the object
@param coordinate Indicates that the value should be set in other caches caching this value. (No effect on CoreCache)
@param directive boolean to indicate CACHE_NEW_CONTENT or USE_CACHED_VALUE | [
"Puts",
"an",
"entry",
"into",
"the",
"cache",
".",
"If",
"the",
"entry",
"already",
"exists",
"in",
"the",
"cache",
"this",
"method",
"will",
"ALSO",
"update",
"the",
"same",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheProviderWrapper.java#L649-L664 |
kaazing/gateway | management/src/main/java/org/kaazing/gateway/management/jmx/JmxManagementService.java | JmxManagementService.handleNotification | @Override
public void handleNotification(Notification notification, Object handback) {
"""
NotificationListener support for connection open and closed notifications
"""
String notificationType = notification.getType();
if (notificationType.equals(JMXConnectionNotification.OPENED)) {
managementContext.incrementManagementSessionCount();
} else if (notificationType.equals(JMXConnectionNotification.CLOSED)) {
managementContext.decrementManagementSessionCount();
}
} | java | @Override
public void handleNotification(Notification notification, Object handback) {
String notificationType = notification.getType();
if (notificationType.equals(JMXConnectionNotification.OPENED)) {
managementContext.incrementManagementSessionCount();
} else if (notificationType.equals(JMXConnectionNotification.CLOSED)) {
managementContext.decrementManagementSessionCount();
}
} | [
"@",
"Override",
"public",
"void",
"handleNotification",
"(",
"Notification",
"notification",
",",
"Object",
"handback",
")",
"{",
"String",
"notificationType",
"=",
"notification",
".",
"getType",
"(",
")",
";",
"if",
"(",
"notificationType",
".",
"equals",
"(",
"JMXConnectionNotification",
".",
"OPENED",
")",
")",
"{",
"managementContext",
".",
"incrementManagementSessionCount",
"(",
")",
";",
"}",
"else",
"if",
"(",
"notificationType",
".",
"equals",
"(",
"JMXConnectionNotification",
".",
"CLOSED",
")",
")",
"{",
"managementContext",
".",
"decrementManagementSessionCount",
"(",
")",
";",
"}",
"}"
]
| NotificationListener support for connection open and closed notifications | [
"NotificationListener",
"support",
"for",
"connection",
"open",
"and",
"closed",
"notifications"
]
| train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/management/src/main/java/org/kaazing/gateway/management/jmx/JmxManagementService.java#L230-L238 |
kevinherron/opc-ua-stack | stack-core/src/main/java/com/digitalpetri/opcua/stack/core/util/CertificateUtil.java | CertificateUtil.decodeCertificates | public static List<X509Certificate> decodeCertificates(byte[] certificateBytes) throws UaException {
"""
Decode either a sequence of DER-encoded X.509 certificates or a PKCS#7 certificate chain.
@param certificateBytes the byte[] to decode from.
@return a {@link List} of certificates deocded from {@code certificateBytes}.
@throws UaException if decoding fails.
"""
Preconditions.checkNotNull(certificateBytes, "certificateBytes cannot be null");
CertificateFactory factory;
try {
factory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new UaException(StatusCodes.Bad_InternalError, e);
}
try {
Collection<? extends Certificate> certificates =
factory.generateCertificates(new ByteArrayInputStream(certificateBytes));
return certificates.stream()
.map(X509Certificate.class::cast)
.collect(Collectors.toList());
} catch (CertificateException e) {
throw new UaException(StatusCodes.Bad_CertificateInvalid, e);
}
} | java | public static List<X509Certificate> decodeCertificates(byte[] certificateBytes) throws UaException {
Preconditions.checkNotNull(certificateBytes, "certificateBytes cannot be null");
CertificateFactory factory;
try {
factory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new UaException(StatusCodes.Bad_InternalError, e);
}
try {
Collection<? extends Certificate> certificates =
factory.generateCertificates(new ByteArrayInputStream(certificateBytes));
return certificates.stream()
.map(X509Certificate.class::cast)
.collect(Collectors.toList());
} catch (CertificateException e) {
throw new UaException(StatusCodes.Bad_CertificateInvalid, e);
}
} | [
"public",
"static",
"List",
"<",
"X509Certificate",
">",
"decodeCertificates",
"(",
"byte",
"[",
"]",
"certificateBytes",
")",
"throws",
"UaException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"certificateBytes",
",",
"\"certificateBytes cannot be null\"",
")",
";",
"CertificateFactory",
"factory",
";",
"try",
"{",
"factory",
"=",
"CertificateFactory",
".",
"getInstance",
"(",
"\"X.509\"",
")",
";",
"}",
"catch",
"(",
"CertificateException",
"e",
")",
"{",
"throw",
"new",
"UaException",
"(",
"StatusCodes",
".",
"Bad_InternalError",
",",
"e",
")",
";",
"}",
"try",
"{",
"Collection",
"<",
"?",
"extends",
"Certificate",
">",
"certificates",
"=",
"factory",
".",
"generateCertificates",
"(",
"new",
"ByteArrayInputStream",
"(",
"certificateBytes",
")",
")",
";",
"return",
"certificates",
".",
"stream",
"(",
")",
".",
"map",
"(",
"X509Certificate",
".",
"class",
"::",
"cast",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"}",
"catch",
"(",
"CertificateException",
"e",
")",
"{",
"throw",
"new",
"UaException",
"(",
"StatusCodes",
".",
"Bad_CertificateInvalid",
",",
"e",
")",
";",
"}",
"}"
]
| Decode either a sequence of DER-encoded X.509 certificates or a PKCS#7 certificate chain.
@param certificateBytes the byte[] to decode from.
@return a {@link List} of certificates deocded from {@code certificateBytes}.
@throws UaException if decoding fails. | [
"Decode",
"either",
"a",
"sequence",
"of",
"DER",
"-",
"encoded",
"X",
".",
"509",
"certificates",
"or",
"a",
"PKCS#7",
"certificate",
"chain",
"."
]
| train | https://github.com/kevinherron/opc-ua-stack/blob/007f4e5c4ff102814bec17bb7c41f27e2e52f2fd/stack-core/src/main/java/com/digitalpetri/opcua/stack/core/util/CertificateUtil.java#L87-L108 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java | ApplicationExtensions.setHeaderResponseDecorator | public static void setHeaderResponseDecorator(final Application application,
final String footerFilterName) {
"""
Sets an {@link IHeaderResponseDecorator} for the given application to use to decorate header
responses.
@param application
the application
@param footerFilterName
the footer filter name
"""
application.setHeaderResponseDecorator(new IHeaderResponseDecorator()
{
@Override
public IHeaderResponse decorate(final IHeaderResponse response)
{
return new JavaScriptFilteredIntoFooterHeaderResponse(response, footerFilterName);
}
});
} | java | public static void setHeaderResponseDecorator(final Application application,
final String footerFilterName)
{
application.setHeaderResponseDecorator(new IHeaderResponseDecorator()
{
@Override
public IHeaderResponse decorate(final IHeaderResponse response)
{
return new JavaScriptFilteredIntoFooterHeaderResponse(response, footerFilterName);
}
});
} | [
"public",
"static",
"void",
"setHeaderResponseDecorator",
"(",
"final",
"Application",
"application",
",",
"final",
"String",
"footerFilterName",
")",
"{",
"application",
".",
"setHeaderResponseDecorator",
"(",
"new",
"IHeaderResponseDecorator",
"(",
")",
"{",
"@",
"Override",
"public",
"IHeaderResponse",
"decorate",
"(",
"final",
"IHeaderResponse",
"response",
")",
"{",
"return",
"new",
"JavaScriptFilteredIntoFooterHeaderResponse",
"(",
"response",
",",
"footerFilterName",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Sets an {@link IHeaderResponseDecorator} for the given application to use to decorate header
responses.
@param application
the application
@param footerFilterName
the footer filter name | [
"Sets",
"an",
"{",
"@link",
"IHeaderResponseDecorator",
"}",
"for",
"the",
"given",
"application",
"to",
"use",
"to",
"decorate",
"header",
"responses",
"."
]
| train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/application/ApplicationExtensions.java#L473-L484 |
ManfredTremmel/gwt-bean-validators | gwtp-spring-integration/src/main/java/de/knightsoftnet/gwtp/spring/server/security/CsrfCookieHandler.java | CsrfCookieHandler.setCookie | public void setCookie(final HttpServletRequest prequest, final HttpServletResponse presponse)
throws IOException {
"""
set csrf/xsrf cookie.
@param prequest http servlet request
@param presponse http servlet response
@throws IOException when io operation fails
"""
final CsrfToken csrf = (CsrfToken) prequest.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(prequest, ResourcePaths.XSRF_COOKIE);
final String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie(ResourcePaths.XSRF_COOKIE, token);
cookie.setPath(
StringUtils.defaultString(StringUtils.trimToNull(prequest.getContextPath()), "/"));
presponse.addCookie(cookie);
}
}
} | java | public void setCookie(final HttpServletRequest prequest, final HttpServletResponse presponse)
throws IOException {
final CsrfToken csrf = (CsrfToken) prequest.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(prequest, ResourcePaths.XSRF_COOKIE);
final String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie(ResourcePaths.XSRF_COOKIE, token);
cookie.setPath(
StringUtils.defaultString(StringUtils.trimToNull(prequest.getContextPath()), "/"));
presponse.addCookie(cookie);
}
}
} | [
"public",
"void",
"setCookie",
"(",
"final",
"HttpServletRequest",
"prequest",
",",
"final",
"HttpServletResponse",
"presponse",
")",
"throws",
"IOException",
"{",
"final",
"CsrfToken",
"csrf",
"=",
"(",
"CsrfToken",
")",
"prequest",
".",
"getAttribute",
"(",
"CsrfToken",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"csrf",
"!=",
"null",
")",
"{",
"Cookie",
"cookie",
"=",
"WebUtils",
".",
"getCookie",
"(",
"prequest",
",",
"ResourcePaths",
".",
"XSRF_COOKIE",
")",
";",
"final",
"String",
"token",
"=",
"csrf",
".",
"getToken",
"(",
")",
";",
"if",
"(",
"cookie",
"==",
"null",
"||",
"token",
"!=",
"null",
"&&",
"!",
"token",
".",
"equals",
"(",
"cookie",
".",
"getValue",
"(",
")",
")",
")",
"{",
"cookie",
"=",
"new",
"Cookie",
"(",
"ResourcePaths",
".",
"XSRF_COOKIE",
",",
"token",
")",
";",
"cookie",
".",
"setPath",
"(",
"StringUtils",
".",
"defaultString",
"(",
"StringUtils",
".",
"trimToNull",
"(",
"prequest",
".",
"getContextPath",
"(",
")",
")",
",",
"\"/\"",
")",
")",
";",
"presponse",
".",
"addCookie",
"(",
"cookie",
")",
";",
"}",
"}",
"}"
]
| set csrf/xsrf cookie.
@param prequest http servlet request
@param presponse http servlet response
@throws IOException when io operation fails | [
"set",
"csrf",
"/",
"xsrf",
"cookie",
"."
]
| train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwtp-spring-integration/src/main/java/de/knightsoftnet/gwtp/spring/server/security/CsrfCookieHandler.java#L46-L59 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/av/Muxer.java | Muxer.getSafePts | private long getSafePts(long pts, int trackIndex) {
"""
Sometimes packets with non-increasing pts are dequeued from the MediaCodec output buffer.
This method ensures that a crash won't occur due to non monotonically increasing packet timestamp.
"""
if (mLastPts[trackIndex] >= pts) {
// Enforce a non-zero minimum spacing
// between pts
mLastPts[trackIndex] += 9643;
return mLastPts[trackIndex];
}
mLastPts[trackIndex] = pts;
return pts;
} | java | private long getSafePts(long pts, int trackIndex) {
if (mLastPts[trackIndex] >= pts) {
// Enforce a non-zero minimum spacing
// between pts
mLastPts[trackIndex] += 9643;
return mLastPts[trackIndex];
}
mLastPts[trackIndex] = pts;
return pts;
} | [
"private",
"long",
"getSafePts",
"(",
"long",
"pts",
",",
"int",
"trackIndex",
")",
"{",
"if",
"(",
"mLastPts",
"[",
"trackIndex",
"]",
">=",
"pts",
")",
"{",
"// Enforce a non-zero minimum spacing",
"// between pts",
"mLastPts",
"[",
"trackIndex",
"]",
"+=",
"9643",
";",
"return",
"mLastPts",
"[",
"trackIndex",
"]",
";",
"}",
"mLastPts",
"[",
"trackIndex",
"]",
"=",
"pts",
";",
"return",
"pts",
";",
"}"
]
| Sometimes packets with non-increasing pts are dequeued from the MediaCodec output buffer.
This method ensures that a crash won't occur due to non monotonically increasing packet timestamp. | [
"Sometimes",
"packets",
"with",
"non",
"-",
"increasing",
"pts",
"are",
"dequeued",
"from",
"the",
"MediaCodec",
"output",
"buffer",
".",
"This",
"method",
"ensures",
"that",
"a",
"crash",
"won",
"t",
"occur",
"due",
"to",
"non",
"monotonically",
"increasing",
"packet",
"timestamp",
"."
]
| train | https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/Muxer.java#L176-L185 |
knowm/XChange | xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java | WexAdapters.adaptOrderInfo | public static LimitOrder adaptOrderInfo(String orderId, WexOrderInfoResult orderInfo) {
"""
Adapts a WexOrderInfoResult to a LimitOrder
@param orderId Order original id
@param orderInfo
@return
"""
OrderType orderType =
orderInfo.getType() == WexOrderInfoResult.Type.buy ? OrderType.BID : OrderType.ASK;
BigDecimal price = orderInfo.getRate();
Date timestamp = DateUtils.fromMillisUtc(orderInfo.getTimestampCreated() * 1000L);
CurrencyPair currencyPair = adaptCurrencyPair(orderInfo.getPair());
OrderStatus orderStatus = null;
switch (orderInfo.getStatus()) {
case 0:
if (orderInfo.getAmount().compareTo(orderInfo.getStartAmount()) == 0) {
orderStatus = OrderStatus.NEW;
} else {
orderStatus = OrderStatus.PARTIALLY_FILLED;
}
break;
case 1:
orderStatus = OrderStatus.FILLED;
break;
case 2:
case 3:
orderStatus = OrderStatus.CANCELED;
break;
}
return new LimitOrder(
orderType,
orderInfo.getStartAmount(),
currencyPair,
orderId,
timestamp,
price,
price,
orderInfo.getStartAmount().subtract(orderInfo.getAmount()),
null,
orderStatus);
} | java | public static LimitOrder adaptOrderInfo(String orderId, WexOrderInfoResult orderInfo) {
OrderType orderType =
orderInfo.getType() == WexOrderInfoResult.Type.buy ? OrderType.BID : OrderType.ASK;
BigDecimal price = orderInfo.getRate();
Date timestamp = DateUtils.fromMillisUtc(orderInfo.getTimestampCreated() * 1000L);
CurrencyPair currencyPair = adaptCurrencyPair(orderInfo.getPair());
OrderStatus orderStatus = null;
switch (orderInfo.getStatus()) {
case 0:
if (orderInfo.getAmount().compareTo(orderInfo.getStartAmount()) == 0) {
orderStatus = OrderStatus.NEW;
} else {
orderStatus = OrderStatus.PARTIALLY_FILLED;
}
break;
case 1:
orderStatus = OrderStatus.FILLED;
break;
case 2:
case 3:
orderStatus = OrderStatus.CANCELED;
break;
}
return new LimitOrder(
orderType,
orderInfo.getStartAmount(),
currencyPair,
orderId,
timestamp,
price,
price,
orderInfo.getStartAmount().subtract(orderInfo.getAmount()),
null,
orderStatus);
} | [
"public",
"static",
"LimitOrder",
"adaptOrderInfo",
"(",
"String",
"orderId",
",",
"WexOrderInfoResult",
"orderInfo",
")",
"{",
"OrderType",
"orderType",
"=",
"orderInfo",
".",
"getType",
"(",
")",
"==",
"WexOrderInfoResult",
".",
"Type",
".",
"buy",
"?",
"OrderType",
".",
"BID",
":",
"OrderType",
".",
"ASK",
";",
"BigDecimal",
"price",
"=",
"orderInfo",
".",
"getRate",
"(",
")",
";",
"Date",
"timestamp",
"=",
"DateUtils",
".",
"fromMillisUtc",
"(",
"orderInfo",
".",
"getTimestampCreated",
"(",
")",
"*",
"1000L",
")",
";",
"CurrencyPair",
"currencyPair",
"=",
"adaptCurrencyPair",
"(",
"orderInfo",
".",
"getPair",
"(",
")",
")",
";",
"OrderStatus",
"orderStatus",
"=",
"null",
";",
"switch",
"(",
"orderInfo",
".",
"getStatus",
"(",
")",
")",
"{",
"case",
"0",
":",
"if",
"(",
"orderInfo",
".",
"getAmount",
"(",
")",
".",
"compareTo",
"(",
"orderInfo",
".",
"getStartAmount",
"(",
")",
")",
"==",
"0",
")",
"{",
"orderStatus",
"=",
"OrderStatus",
".",
"NEW",
";",
"}",
"else",
"{",
"orderStatus",
"=",
"OrderStatus",
".",
"PARTIALLY_FILLED",
";",
"}",
"break",
";",
"case",
"1",
":",
"orderStatus",
"=",
"OrderStatus",
".",
"FILLED",
";",
"break",
";",
"case",
"2",
":",
"case",
"3",
":",
"orderStatus",
"=",
"OrderStatus",
".",
"CANCELED",
";",
"break",
";",
"}",
"return",
"new",
"LimitOrder",
"(",
"orderType",
",",
"orderInfo",
".",
"getStartAmount",
"(",
")",
",",
"currencyPair",
",",
"orderId",
",",
"timestamp",
",",
"price",
",",
"price",
",",
"orderInfo",
".",
"getStartAmount",
"(",
")",
".",
"subtract",
"(",
"orderInfo",
".",
"getAmount",
"(",
")",
")",
",",
"null",
",",
"orderStatus",
")",
";",
"}"
]
| Adapts a WexOrderInfoResult to a LimitOrder
@param orderId Order original id
@param orderInfo
@return | [
"Adapts",
"a",
"WexOrderInfoResult",
"to",
"a",
"LimitOrder"
]
| train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java#L235-L271 |
geomajas/geomajas-project-client-gwt | common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java | HtmlBuilder.tagClassHtmlContent | public static String tagClassHtmlContent(String tag, String clazz, String... content) {
"""
Build a String containing a HTML opening tag with given CSS class, HTML content and closing tag.
@param tag String name of HTML tag
@param clazz CSS class of the tag
@param content content string
@return HTML tag element as string
"""
return openTagClassHtmlContent(tag, clazz, content) + closeTag(tag);
} | java | public static String tagClassHtmlContent(String tag, String clazz, String... content) {
return openTagClassHtmlContent(tag, clazz, content) + closeTag(tag);
} | [
"public",
"static",
"String",
"tagClassHtmlContent",
"(",
"String",
"tag",
",",
"String",
"clazz",
",",
"String",
"...",
"content",
")",
"{",
"return",
"openTagClassHtmlContent",
"(",
"tag",
",",
"clazz",
",",
"content",
")",
"+",
"closeTag",
"(",
"tag",
")",
";",
"}"
]
| Build a String containing a HTML opening tag with given CSS class, HTML content and closing tag.
@param tag String name of HTML tag
@param clazz CSS class of the tag
@param content content string
@return HTML tag element as string | [
"Build",
"a",
"String",
"containing",
"a",
"HTML",
"opening",
"tag",
"with",
"given",
"CSS",
"class",
"HTML",
"content",
"and",
"closing",
"tag",
"."
]
| train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java#L325-L327 |
kubernetes-client/java | examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java | ExpandedExample.scaleDeployment | public static void scaleDeployment(String deploymentName, int numberOfReplicas)
throws ApiException {
"""
Scale up/down the number of pod in Deployment
@param deploymentName
@param numberOfReplicas
@throws ApiException
"""
ExtensionsV1beta1Api extensionV1Api = new ExtensionsV1beta1Api();
extensionV1Api.setApiClient(COREV1_API.getApiClient());
ExtensionsV1beta1DeploymentList listNamespacedDeployment =
extensionV1Api.listNamespacedDeployment(
DEFAULT_NAME_SPACE, null, null, null, null, null, null, null, null, Boolean.FALSE);
List<ExtensionsV1beta1Deployment> extensionsV1beta1DeploymentItems =
listNamespacedDeployment.getItems();
Optional<ExtensionsV1beta1Deployment> findedDeployment =
extensionsV1beta1DeploymentItems
.stream()
.filter(
(ExtensionsV1beta1Deployment deployment) ->
deployment.getMetadata().getName().equals(deploymentName))
.findFirst();
findedDeployment.ifPresent(
(ExtensionsV1beta1Deployment deploy) -> {
try {
ExtensionsV1beta1DeploymentSpec newSpec = deploy.getSpec().replicas(numberOfReplicas);
ExtensionsV1beta1Deployment newDeploy = deploy.spec(newSpec);
extensionV1Api.replaceNamespacedDeployment(
deploymentName, DEFAULT_NAME_SPACE, newDeploy, null, null);
} catch (ApiException ex) {
LOGGER.warn("Scale the pod failed for Deployment:" + deploymentName, ex);
}
});
} | java | public static void scaleDeployment(String deploymentName, int numberOfReplicas)
throws ApiException {
ExtensionsV1beta1Api extensionV1Api = new ExtensionsV1beta1Api();
extensionV1Api.setApiClient(COREV1_API.getApiClient());
ExtensionsV1beta1DeploymentList listNamespacedDeployment =
extensionV1Api.listNamespacedDeployment(
DEFAULT_NAME_SPACE, null, null, null, null, null, null, null, null, Boolean.FALSE);
List<ExtensionsV1beta1Deployment> extensionsV1beta1DeploymentItems =
listNamespacedDeployment.getItems();
Optional<ExtensionsV1beta1Deployment> findedDeployment =
extensionsV1beta1DeploymentItems
.stream()
.filter(
(ExtensionsV1beta1Deployment deployment) ->
deployment.getMetadata().getName().equals(deploymentName))
.findFirst();
findedDeployment.ifPresent(
(ExtensionsV1beta1Deployment deploy) -> {
try {
ExtensionsV1beta1DeploymentSpec newSpec = deploy.getSpec().replicas(numberOfReplicas);
ExtensionsV1beta1Deployment newDeploy = deploy.spec(newSpec);
extensionV1Api.replaceNamespacedDeployment(
deploymentName, DEFAULT_NAME_SPACE, newDeploy, null, null);
} catch (ApiException ex) {
LOGGER.warn("Scale the pod failed for Deployment:" + deploymentName, ex);
}
});
} | [
"public",
"static",
"void",
"scaleDeployment",
"(",
"String",
"deploymentName",
",",
"int",
"numberOfReplicas",
")",
"throws",
"ApiException",
"{",
"ExtensionsV1beta1Api",
"extensionV1Api",
"=",
"new",
"ExtensionsV1beta1Api",
"(",
")",
";",
"extensionV1Api",
".",
"setApiClient",
"(",
"COREV1_API",
".",
"getApiClient",
"(",
")",
")",
";",
"ExtensionsV1beta1DeploymentList",
"listNamespacedDeployment",
"=",
"extensionV1Api",
".",
"listNamespacedDeployment",
"(",
"DEFAULT_NAME_SPACE",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"Boolean",
".",
"FALSE",
")",
";",
"List",
"<",
"ExtensionsV1beta1Deployment",
">",
"extensionsV1beta1DeploymentItems",
"=",
"listNamespacedDeployment",
".",
"getItems",
"(",
")",
";",
"Optional",
"<",
"ExtensionsV1beta1Deployment",
">",
"findedDeployment",
"=",
"extensionsV1beta1DeploymentItems",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"(",
"ExtensionsV1beta1Deployment",
"deployment",
")",
"->",
"deployment",
".",
"getMetadata",
"(",
")",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"deploymentName",
")",
")",
".",
"findFirst",
"(",
")",
";",
"findedDeployment",
".",
"ifPresent",
"(",
"(",
"ExtensionsV1beta1Deployment",
"deploy",
")",
"->",
"{",
"try",
"{",
"ExtensionsV1beta1DeploymentSpec",
"newSpec",
"=",
"deploy",
".",
"getSpec",
"(",
")",
".",
"replicas",
"(",
"numberOfReplicas",
")",
";",
"ExtensionsV1beta1Deployment",
"newDeploy",
"=",
"deploy",
".",
"spec",
"(",
"newSpec",
")",
";",
"extensionV1Api",
".",
"replaceNamespacedDeployment",
"(",
"deploymentName",
",",
"DEFAULT_NAME_SPACE",
",",
"newDeploy",
",",
"null",
",",
"null",
")",
";",
"}",
"catch",
"(",
"ApiException",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Scale the pod failed for Deployment:\"",
"+",
"deploymentName",
",",
"ex",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Scale up/down the number of pod in Deployment
@param deploymentName
@param numberOfReplicas
@throws ApiException | [
"Scale",
"up",
"/",
"down",
"the",
"number",
"of",
"pod",
"in",
"Deployment"
]
| train | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java#L218-L246 |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/interestrate/products/CMSOption.java | CMSOption.getValue | public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {
"""
This method returns the value of the product using a Black-Scholes model for the swap rate with the Hunt-Kennedy convexity adjustment.
The model is determined by a discount factor curve and a swap rate volatility.
@param forwardCurve The forward curve from which the swap rate is calculated. The discount curve, associated with this forward curve is used for discounting this option.
@param swaprateVolatility The volatility of the log-swaprate.
@return Value of this product
"""
double[] swapTenor = new double[fixingDates.length+1];
System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);
swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];
TimeDiscretization fixTenor = new TimeDiscretizationFromArray(swapTenor);
TimeDiscretization floatTenor = new TimeDiscretizationFromArray(swapTenor);
double forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);
double payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);
return AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);
} | java | public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {
double[] swapTenor = new double[fixingDates.length+1];
System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);
swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];
TimeDiscretization fixTenor = new TimeDiscretizationFromArray(swapTenor);
TimeDiscretization floatTenor = new TimeDiscretizationFromArray(swapTenor);
double forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);
double payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);
return AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);
} | [
"public",
"double",
"getValue",
"(",
"ForwardCurve",
"forwardCurve",
",",
"double",
"swaprateVolatility",
")",
"{",
"double",
"[",
"]",
"swapTenor",
"=",
"new",
"double",
"[",
"fixingDates",
".",
"length",
"+",
"1",
"]",
";",
"System",
".",
"arraycopy",
"(",
"fixingDates",
",",
"0",
",",
"swapTenor",
",",
"0",
",",
"fixingDates",
".",
"length",
")",
";",
"swapTenor",
"[",
"swapTenor",
".",
"length",
"-",
"1",
"]",
"=",
"paymentDates",
"[",
"paymentDates",
".",
"length",
"-",
"1",
"]",
";",
"TimeDiscretization",
"fixTenor",
"=",
"new",
"TimeDiscretizationFromArray",
"(",
"swapTenor",
")",
";",
"TimeDiscretization",
"floatTenor",
"=",
"new",
"TimeDiscretizationFromArray",
"(",
"swapTenor",
")",
";",
"double",
"forwardSwapRate",
"=",
"Swap",
".",
"getForwardSwapRate",
"(",
"fixTenor",
",",
"floatTenor",
",",
"forwardCurve",
")",
";",
"double",
"swapAnnuity",
"=",
"SwapAnnuity",
".",
"getSwapAnnuity",
"(",
"fixTenor",
",",
"forwardCurve",
")",
";",
"double",
"payoffUnit",
"=",
"SwapAnnuity",
".",
"getSwapAnnuity",
"(",
"new",
"TimeDiscretizationFromArray",
"(",
"swapTenor",
"[",
"0",
"]",
",",
"swapTenor",
"[",
"1",
"]",
")",
",",
"forwardCurve",
")",
"/",
"(",
"swapTenor",
"[",
"1",
"]",
"-",
"swapTenor",
"[",
"0",
"]",
")",
";",
"return",
"AnalyticFormulas",
".",
"huntKennedyCMSOptionValue",
"(",
"forwardSwapRate",
",",
"swaprateVolatility",
",",
"swapAnnuity",
",",
"exerciseDate",
",",
"swapTenor",
"[",
"swapTenor",
".",
"length",
"-",
"1",
"]",
"-",
"swapTenor",
"[",
"0",
"]",
",",
"payoffUnit",
",",
"strike",
")",
"*",
"(",
"swapTenor",
"[",
"1",
"]",
"-",
"swapTenor",
"[",
"0",
"]",
")",
";",
"}"
]
| This method returns the value of the product using a Black-Scholes model for the swap rate with the Hunt-Kennedy convexity adjustment.
The model is determined by a discount factor curve and a swap rate volatility.
@param forwardCurve The forward curve from which the swap rate is calculated. The discount curve, associated with this forward curve is used for discounting this option.
@param swaprateVolatility The volatility of the log-swaprate.
@return Value of this product | [
"This",
"method",
"returns",
"the",
"value",
"of",
"the",
"product",
"using",
"a",
"Black",
"-",
"Scholes",
"model",
"for",
"the",
"swap",
"rate",
"with",
"the",
"Hunt",
"-",
"Kennedy",
"convexity",
"adjustment",
".",
"The",
"model",
"is",
"determined",
"by",
"a",
"discount",
"factor",
"curve",
"and",
"a",
"swap",
"rate",
"volatility",
"."
]
| train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/CMSOption.java#L132-L143 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ConBox.java | ConBox.hasDifferentCompartments | public static Constraint hasDifferentCompartments() {
"""
Checks if two physical entities have non-empty and different compartments.
@return the constraint
"""
String acStr = "PhysicalEntity/cellularLocation/term";
return new Field(acStr, acStr, Field.Operation.NOT_EMPTY_AND_NOT_INTERSECT);
} | java | public static Constraint hasDifferentCompartments()
{
String acStr = "PhysicalEntity/cellularLocation/term";
return new Field(acStr, acStr, Field.Operation.NOT_EMPTY_AND_NOT_INTERSECT);
} | [
"public",
"static",
"Constraint",
"hasDifferentCompartments",
"(",
")",
"{",
"String",
"acStr",
"=",
"\"PhysicalEntity/cellularLocation/term\"",
";",
"return",
"new",
"Field",
"(",
"acStr",
",",
"acStr",
",",
"Field",
".",
"Operation",
".",
"NOT_EMPTY_AND_NOT_INTERSECT",
")",
";",
"}"
]
| Checks if two physical entities have non-empty and different compartments.
@return the constraint | [
"Checks",
"if",
"two",
"physical",
"entities",
"have",
"non",
"-",
"empty",
"and",
"different",
"compartments",
"."
]
| train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ConBox.java#L645-L649 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java | Aggregations.bigDecimalMin | public static <Key, Value> Aggregation<Key, BigDecimal, BigDecimal> bigDecimalMin() {
"""
Returns an aggregation to find the {@link java.math.BigDecimal} minimum
of all supplied values.<br/>
This aggregation is similar to: <pre>SELECT MIN(value) FROM x</pre>
@param <Key> the input key type
@param <Value> the supplied value type
@return the minimum value over all supplied values
"""
return new AggregationAdapter(new BigDecimalMinAggregation<Key, Value>());
} | java | public static <Key, Value> Aggregation<Key, BigDecimal, BigDecimal> bigDecimalMin() {
return new AggregationAdapter(new BigDecimalMinAggregation<Key, Value>());
} | [
"public",
"static",
"<",
"Key",
",",
"Value",
">",
"Aggregation",
"<",
"Key",
",",
"BigDecimal",
",",
"BigDecimal",
">",
"bigDecimalMin",
"(",
")",
"{",
"return",
"new",
"AggregationAdapter",
"(",
"new",
"BigDecimalMinAggregation",
"<",
"Key",
",",
"Value",
">",
"(",
")",
")",
";",
"}"
]
| Returns an aggregation to find the {@link java.math.BigDecimal} minimum
of all supplied values.<br/>
This aggregation is similar to: <pre>SELECT MIN(value) FROM x</pre>
@param <Key> the input key type
@param <Value> the supplied value type
@return the minimum value over all supplied values | [
"Returns",
"an",
"aggregation",
"to",
"find",
"the",
"{",
"@link",
"java",
".",
"math",
".",
"BigDecimal",
"}",
"minimum",
"of",
"all",
"supplied",
"values",
".",
"<br",
"/",
">",
"This",
"aggregation",
"is",
"similar",
"to",
":",
"<pre",
">",
"SELECT",
"MIN",
"(",
"value",
")",
"FROM",
"x<",
"/",
"pre",
">"
]
| train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/mapreduce/aggregation/Aggregations.java#L273-L275 |
Azure/azure-sdk-for-java | redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/FirewallRulesInner.java | FirewallRulesInner.createOrUpdateAsync | public Observable<RedisFirewallRuleInner> createOrUpdateAsync(String resourceGroupName, String cacheName, String ruleName, RedisFirewallRuleCreateParameters parameters) {
"""
Create or update a redis cache firewall rule.
@param resourceGroupName The name of the resource group.
@param cacheName The name of the Redis cache.
@param ruleName The name of the firewall rule.
@param parameters Parameters supplied to the create or update redis firewall rule operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisFirewallRuleInner object
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, cacheName, ruleName, parameters).map(new Func1<ServiceResponse<RedisFirewallRuleInner>, RedisFirewallRuleInner>() {
@Override
public RedisFirewallRuleInner call(ServiceResponse<RedisFirewallRuleInner> response) {
return response.body();
}
});
} | java | public Observable<RedisFirewallRuleInner> createOrUpdateAsync(String resourceGroupName, String cacheName, String ruleName, RedisFirewallRuleCreateParameters parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, cacheName, ruleName, parameters).map(new Func1<ServiceResponse<RedisFirewallRuleInner>, RedisFirewallRuleInner>() {
@Override
public RedisFirewallRuleInner call(ServiceResponse<RedisFirewallRuleInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"RedisFirewallRuleInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"cacheName",
",",
"String",
"ruleName",
",",
"RedisFirewallRuleCreateParameters",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"cacheName",
",",
"ruleName",
",",
"parameters",
")",
".",
"map",
"(",
"new",
"Func1",
"<",
"ServiceResponse",
"<",
"RedisFirewallRuleInner",
">",
",",
"RedisFirewallRuleInner",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"RedisFirewallRuleInner",
"call",
"(",
"ServiceResponse",
"<",
"RedisFirewallRuleInner",
">",
"response",
")",
"{",
"return",
"response",
".",
"body",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Create or update a redis cache firewall rule.
@param resourceGroupName The name of the resource group.
@param cacheName The name of the Redis cache.
@param ruleName The name of the firewall rule.
@param parameters Parameters supplied to the create or update redis firewall rule operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the RedisFirewallRuleInner object | [
"Create",
"or",
"update",
"a",
"redis",
"cache",
"firewall",
"rule",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/FirewallRulesInner.java#L251-L258 |
versionone/VersionOne.SDK.Java.ObjectModel | src/main/java/com/versionone/om/V1InstanceGetter.java | V1InstanceGetter.environments | public Collection<Environment> environments(EnvironmentFilter filter) {
"""
Get Environment filtered by the criteria specified in the passed in filter.
@param filter Limit the items returned. If null, then all items are returned.
@return Collection of items as specified in the filter.
"""
return get(Environment.class, (filter != null) ? filter : new EnvironmentFilter());
} | java | public Collection<Environment> environments(EnvironmentFilter filter) {
return get(Environment.class, (filter != null) ? filter : new EnvironmentFilter());
} | [
"public",
"Collection",
"<",
"Environment",
">",
"environments",
"(",
"EnvironmentFilter",
"filter",
")",
"{",
"return",
"get",
"(",
"Environment",
".",
"class",
",",
"(",
"filter",
"!=",
"null",
")",
"?",
"filter",
":",
"new",
"EnvironmentFilter",
"(",
")",
")",
";",
"}"
]
| Get Environment filtered by the criteria specified in the passed in filter.
@param filter Limit the items returned. If null, then all items are returned.
@return Collection of items as specified in the filter. | [
"Get",
"Environment",
"filtered",
"by",
"the",
"criteria",
"specified",
"in",
"the",
"passed",
"in",
"filter",
"."
]
| train | https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/V1InstanceGetter.java#L400-L402 |
strator-dev/greenpepper | greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Reference.java | Reference.newInstance | public static Reference newInstance(Requirement requirement, Specification specification, SystemUnderTest sut, String sections) {
"""
<p>newInstance.</p>
@param requirement a {@link com.greenpepper.server.domain.Requirement} object.
@param specification a {@link com.greenpepper.server.domain.Specification} object.
@param sut a {@link com.greenpepper.server.domain.SystemUnderTest} object.
@param sections a {@link java.lang.String} object.
@return a {@link com.greenpepper.server.domain.Reference} object.
"""
Reference reference = new Reference();
reference.setSections(sections);
reference.setRequirement(requirement);
reference.setSpecification(specification);
reference.setSystemUnderTest(sut);
requirement.getReferences().add(reference);
specification.getReferences().add(reference);
return reference;
} | java | public static Reference newInstance(Requirement requirement, Specification specification, SystemUnderTest sut, String sections)
{
Reference reference = new Reference();
reference.setSections(sections);
reference.setRequirement(requirement);
reference.setSpecification(specification);
reference.setSystemUnderTest(sut);
requirement.getReferences().add(reference);
specification.getReferences().add(reference);
return reference;
} | [
"public",
"static",
"Reference",
"newInstance",
"(",
"Requirement",
"requirement",
",",
"Specification",
"specification",
",",
"SystemUnderTest",
"sut",
",",
"String",
"sections",
")",
"{",
"Reference",
"reference",
"=",
"new",
"Reference",
"(",
")",
";",
"reference",
".",
"setSections",
"(",
"sections",
")",
";",
"reference",
".",
"setRequirement",
"(",
"requirement",
")",
";",
"reference",
".",
"setSpecification",
"(",
"specification",
")",
";",
"reference",
".",
"setSystemUnderTest",
"(",
"sut",
")",
";",
"requirement",
".",
"getReferences",
"(",
")",
".",
"add",
"(",
"reference",
")",
";",
"specification",
".",
"getReferences",
"(",
")",
".",
"add",
"(",
"reference",
")",
";",
"return",
"reference",
";",
"}"
]
| <p>newInstance.</p>
@param requirement a {@link com.greenpepper.server.domain.Requirement} object.
@param specification a {@link com.greenpepper.server.domain.Specification} object.
@param sut a {@link com.greenpepper.server.domain.SystemUnderTest} object.
@param sections a {@link java.lang.String} object.
@return a {@link com.greenpepper.server.domain.Reference} object. | [
"<p",
">",
"newInstance",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/server/domain/Reference.java#L67-L79 |
opencb/biodata | biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java | ChunkFrequencyManager.updateChromosomeChunks | private void updateChromosomeChunks(String chromosome, int numChunks, Connection conn) throws SQLException {
"""
Insert all the chunks for the given chromosome and update the internal map of chunks, if necessary.
@param chromosome Chromosome target
@param numChunks Number of chunks for that chromosome
@param conn Database connection
Database connection
"""
// insert all the chunks for that chromosome
String minorChunkSuffix = (chunkSize / 1000) * 64 + "k";
String sql = "insert into chunk (chunk_id, chromosome, start, end) values (?, ?, ?, ?)";
PreparedStatement insertChunk = conn.prepareStatement(sql);
conn.setAutoCommit(false);
for (int i = 0, j = 1; i < numChunks; i++, j += chunkSize64k) {
String chunkId = chromosome + "_" + i + "_" + minorChunkSuffix;
//
// // check if this chunk is in the dabasete
// sql = "SELECT id FROM chunk where chunk_id = '" + chunkId + "'";
// ResultSet rs = stmt.executeQuery(sql);
// if (!rs.next()) {
// if this chunk is not in the database, then insert it
insertChunk.setString(1, chunkId);
insertChunk.setString(2, chromosome);
insertChunk.setInt(3, j);
insertChunk.setInt(4, j + chunkSize64k - 1);
insertChunk.addBatch();
// }
}
insertChunk.executeBatch();
conn.commit();
conn.setAutoCommit(true);
initChunkMap();
} | java | private void updateChromosomeChunks(String chromosome, int numChunks, Connection conn) throws SQLException {
// insert all the chunks for that chromosome
String minorChunkSuffix = (chunkSize / 1000) * 64 + "k";
String sql = "insert into chunk (chunk_id, chromosome, start, end) values (?, ?, ?, ?)";
PreparedStatement insertChunk = conn.prepareStatement(sql);
conn.setAutoCommit(false);
for (int i = 0, j = 1; i < numChunks; i++, j += chunkSize64k) {
String chunkId = chromosome + "_" + i + "_" + minorChunkSuffix;
//
// // check if this chunk is in the dabasete
// sql = "SELECT id FROM chunk where chunk_id = '" + chunkId + "'";
// ResultSet rs = stmt.executeQuery(sql);
// if (!rs.next()) {
// if this chunk is not in the database, then insert it
insertChunk.setString(1, chunkId);
insertChunk.setString(2, chromosome);
insertChunk.setInt(3, j);
insertChunk.setInt(4, j + chunkSize64k - 1);
insertChunk.addBatch();
// }
}
insertChunk.executeBatch();
conn.commit();
conn.setAutoCommit(true);
initChunkMap();
} | [
"private",
"void",
"updateChromosomeChunks",
"(",
"String",
"chromosome",
",",
"int",
"numChunks",
",",
"Connection",
"conn",
")",
"throws",
"SQLException",
"{",
"// insert all the chunks for that chromosome",
"String",
"minorChunkSuffix",
"=",
"(",
"chunkSize",
"/",
"1000",
")",
"*",
"64",
"+",
"\"k\"",
";",
"String",
"sql",
"=",
"\"insert into chunk (chunk_id, chromosome, start, end) values (?, ?, ?, ?)\"",
";",
"PreparedStatement",
"insertChunk",
"=",
"conn",
".",
"prepareStatement",
"(",
"sql",
")",
";",
"conn",
".",
"setAutoCommit",
"(",
"false",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"j",
"=",
"1",
";",
"i",
"<",
"numChunks",
";",
"i",
"++",
",",
"j",
"+=",
"chunkSize64k",
")",
"{",
"String",
"chunkId",
"=",
"chromosome",
"+",
"\"_\"",
"+",
"i",
"+",
"\"_\"",
"+",
"minorChunkSuffix",
";",
"//",
"// // check if this chunk is in the dabasete",
"// sql = \"SELECT id FROM chunk where chunk_id = '\" + chunkId + \"'\";",
"// ResultSet rs = stmt.executeQuery(sql);",
"// if (!rs.next()) {",
"// if this chunk is not in the database, then insert it",
"insertChunk",
".",
"setString",
"(",
"1",
",",
"chunkId",
")",
";",
"insertChunk",
".",
"setString",
"(",
"2",
",",
"chromosome",
")",
";",
"insertChunk",
".",
"setInt",
"(",
"3",
",",
"j",
")",
";",
"insertChunk",
".",
"setInt",
"(",
"4",
",",
"j",
"+",
"chunkSize64k",
"-",
"1",
")",
";",
"insertChunk",
".",
"addBatch",
"(",
")",
";",
"// }",
"}",
"insertChunk",
".",
"executeBatch",
"(",
")",
";",
"conn",
".",
"commit",
"(",
")",
";",
"conn",
".",
"setAutoCommit",
"(",
"true",
")",
";",
"initChunkMap",
"(",
")",
";",
"}"
]
| Insert all the chunks for the given chromosome and update the internal map of chunks, if necessary.
@param chromosome Chromosome target
@param numChunks Number of chunks for that chromosome
@param conn Database connection
Database connection | [
"Insert",
"all",
"the",
"chunks",
"for",
"the",
"given",
"chromosome",
"and",
"update",
"the",
"internal",
"map",
"of",
"chunks",
"if",
"necessary",
"."
]
| train | https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java#L467-L494 |
google/j2objc | jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java | MutableBigInteger.divideAndRemainderBurnikelZiegler | MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) {
"""
Computes {@code this/b} and {@code this%b} using the
<a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>.
This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper.
The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are
multiples of 32 bits.<br/>
{@code this} and {@code b} must be nonnegative.
@param b the divisor
@param quotient output parameter for {@code this/b}
@return the remainder
"""
int r = intLen;
int s = b.intLen;
// Clear the quotient
quotient.offset = quotient.intLen = 0;
if (r < s) {
return this;
} else {
// Unlike Knuth division, we don't check for common powers of two here because
// BZ already runs faster if both numbers contain powers of two and cancelling them has no
// additional benefit.
// step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}
int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD));
int j = (s+m-1) / m; // step 2a: j = ceil(s/m)
int n = j * m; // step 2b: block length in 32-bit units
long n32 = 32L * n; // block length in bits
int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n}
MutableBigInteger bShifted = new MutableBigInteger(b);
bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n
safeLeftShift(sigma); // step 4b: shift this by the same amount
// step 5: t is the number of blocks needed to accommodate this plus one additional bit
int t = (int) ((bitLength()+n32) / n32);
if (t < 2) {
t = 2;
}
// step 6: conceptually split this into blocks a[t-1], ..., a[0]
MutableBigInteger a1 = getBlock(t-1, t, n); // the most significant block of this
// step 7: z[t-2] = [a[t-1], a[t-2]]
MutableBigInteger z = getBlock(t-2, t, n); // the second to most significant block
z.addDisjoint(a1, n); // z[t-2]
// do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers
MutableBigInteger qi = new MutableBigInteger();
MutableBigInteger ri;
for (int i=t-2; i > 0; i--) {
// step 8a: compute (qi,ri) such that z=b*qi+ri
ri = z.divide2n1n(bShifted, qi);
// step 8b: z = [ri, a[i-1]]
z = getBlock(i-1, t, n); // a[i-1]
z.addDisjoint(ri, n);
quotient.addShifted(qi, i*n); // update q (part of step 9)
}
// final iteration of step 8: do the loop one more time for i=0 but leave z unchanged
ri = z.divide2n1n(bShifted, qi);
quotient.add(qi);
ri.rightShift(sigma); // step 9: this and b were shifted, so shift back
return ri;
}
} | java | MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) {
int r = intLen;
int s = b.intLen;
// Clear the quotient
quotient.offset = quotient.intLen = 0;
if (r < s) {
return this;
} else {
// Unlike Knuth division, we don't check for common powers of two here because
// BZ already runs faster if both numbers contain powers of two and cancelling them has no
// additional benefit.
// step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}
int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD));
int j = (s+m-1) / m; // step 2a: j = ceil(s/m)
int n = j * m; // step 2b: block length in 32-bit units
long n32 = 32L * n; // block length in bits
int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n}
MutableBigInteger bShifted = new MutableBigInteger(b);
bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n
safeLeftShift(sigma); // step 4b: shift this by the same amount
// step 5: t is the number of blocks needed to accommodate this plus one additional bit
int t = (int) ((bitLength()+n32) / n32);
if (t < 2) {
t = 2;
}
// step 6: conceptually split this into blocks a[t-1], ..., a[0]
MutableBigInteger a1 = getBlock(t-1, t, n); // the most significant block of this
// step 7: z[t-2] = [a[t-1], a[t-2]]
MutableBigInteger z = getBlock(t-2, t, n); // the second to most significant block
z.addDisjoint(a1, n); // z[t-2]
// do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers
MutableBigInteger qi = new MutableBigInteger();
MutableBigInteger ri;
for (int i=t-2; i > 0; i--) {
// step 8a: compute (qi,ri) such that z=b*qi+ri
ri = z.divide2n1n(bShifted, qi);
// step 8b: z = [ri, a[i-1]]
z = getBlock(i-1, t, n); // a[i-1]
z.addDisjoint(ri, n);
quotient.addShifted(qi, i*n); // update q (part of step 9)
}
// final iteration of step 8: do the loop one more time for i=0 but leave z unchanged
ri = z.divide2n1n(bShifted, qi);
quotient.add(qi);
ri.rightShift(sigma); // step 9: this and b were shifted, so shift back
return ri;
}
} | [
"MutableBigInteger",
"divideAndRemainderBurnikelZiegler",
"(",
"MutableBigInteger",
"b",
",",
"MutableBigInteger",
"quotient",
")",
"{",
"int",
"r",
"=",
"intLen",
";",
"int",
"s",
"=",
"b",
".",
"intLen",
";",
"// Clear the quotient",
"quotient",
".",
"offset",
"=",
"quotient",
".",
"intLen",
"=",
"0",
";",
"if",
"(",
"r",
"<",
"s",
")",
"{",
"return",
"this",
";",
"}",
"else",
"{",
"// Unlike Knuth division, we don't check for common powers of two here because",
"// BZ already runs faster if both numbers contain powers of two and cancelling them has no",
"// additional benefit.",
"// step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}",
"int",
"m",
"=",
"1",
"<<",
"(",
"32",
"-",
"Integer",
".",
"numberOfLeadingZeros",
"(",
"s",
"/",
"BigInteger",
".",
"BURNIKEL_ZIEGLER_THRESHOLD",
")",
")",
";",
"int",
"j",
"=",
"(",
"s",
"+",
"m",
"-",
"1",
")",
"/",
"m",
";",
"// step 2a: j = ceil(s/m)",
"int",
"n",
"=",
"j",
"*",
"m",
";",
"// step 2b: block length in 32-bit units",
"long",
"n32",
"=",
"32L",
"*",
"n",
";",
"// block length in bits",
"int",
"sigma",
"=",
"(",
"int",
")",
"Math",
".",
"max",
"(",
"0",
",",
"n32",
"-",
"b",
".",
"bitLength",
"(",
")",
")",
";",
"// step 3: sigma = max{T | (2^T)*B < beta^n}",
"MutableBigInteger",
"bShifted",
"=",
"new",
"MutableBigInteger",
"(",
"b",
")",
";",
"bShifted",
".",
"safeLeftShift",
"(",
"sigma",
")",
";",
"// step 4a: shift b so its length is a multiple of n",
"safeLeftShift",
"(",
"sigma",
")",
";",
"// step 4b: shift this by the same amount",
"// step 5: t is the number of blocks needed to accommodate this plus one additional bit",
"int",
"t",
"=",
"(",
"int",
")",
"(",
"(",
"bitLength",
"(",
")",
"+",
"n32",
")",
"/",
"n32",
")",
";",
"if",
"(",
"t",
"<",
"2",
")",
"{",
"t",
"=",
"2",
";",
"}",
"// step 6: conceptually split this into blocks a[t-1], ..., a[0]",
"MutableBigInteger",
"a1",
"=",
"getBlock",
"(",
"t",
"-",
"1",
",",
"t",
",",
"n",
")",
";",
"// the most significant block of this",
"// step 7: z[t-2] = [a[t-1], a[t-2]]",
"MutableBigInteger",
"z",
"=",
"getBlock",
"(",
"t",
"-",
"2",
",",
"t",
",",
"n",
")",
";",
"// the second to most significant block",
"z",
".",
"addDisjoint",
"(",
"a1",
",",
"n",
")",
";",
"// z[t-2]",
"// do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers",
"MutableBigInteger",
"qi",
"=",
"new",
"MutableBigInteger",
"(",
")",
";",
"MutableBigInteger",
"ri",
";",
"for",
"(",
"int",
"i",
"=",
"t",
"-",
"2",
";",
"i",
">",
"0",
";",
"i",
"--",
")",
"{",
"// step 8a: compute (qi,ri) such that z=b*qi+ri",
"ri",
"=",
"z",
".",
"divide2n1n",
"(",
"bShifted",
",",
"qi",
")",
";",
"// step 8b: z = [ri, a[i-1]]",
"z",
"=",
"getBlock",
"(",
"i",
"-",
"1",
",",
"t",
",",
"n",
")",
";",
"// a[i-1]",
"z",
".",
"addDisjoint",
"(",
"ri",
",",
"n",
")",
";",
"quotient",
".",
"addShifted",
"(",
"qi",
",",
"i",
"*",
"n",
")",
";",
"// update q (part of step 9)",
"}",
"// final iteration of step 8: do the loop one more time for i=0 but leave z unchanged",
"ri",
"=",
"z",
".",
"divide2n1n",
"(",
"bShifted",
",",
"qi",
")",
";",
"quotient",
".",
"add",
"(",
"qi",
")",
";",
"ri",
".",
"rightShift",
"(",
"sigma",
")",
";",
"// step 9: this and b were shifted, so shift back",
"return",
"ri",
";",
"}",
"}"
]
| Computes {@code this/b} and {@code this%b} using the
<a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>.
This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper.
The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are
multiples of 32 bits.<br/>
{@code this} and {@code b} must be nonnegative.
@param b the divisor
@param quotient output parameter for {@code this/b}
@return the remainder | [
"Computes",
"{"
]
| train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java#L1241-L1298 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxCollaborationWhitelist.java | BoxCollaborationWhitelist.getAll | public static Iterable<BoxCollaborationWhitelist.Info> getAll(final BoxAPIConnection api, String ... fields) {
"""
Returns all the collaboration whitelisting with specified filters.
@param api the API connection to be used by the resource.
@param fields the fields to retrieve.
@return an iterable with all the collaboration whitelists met search conditions.
"""
return getAll(api, DEFAULT_LIMIT, fields);
} | java | public static Iterable<BoxCollaborationWhitelist.Info> getAll(final BoxAPIConnection api, String ... fields) {
return getAll(api, DEFAULT_LIMIT, fields);
} | [
"public",
"static",
"Iterable",
"<",
"BoxCollaborationWhitelist",
".",
"Info",
">",
"getAll",
"(",
"final",
"BoxAPIConnection",
"api",
",",
"String",
"...",
"fields",
")",
"{",
"return",
"getAll",
"(",
"api",
",",
"DEFAULT_LIMIT",
",",
"fields",
")",
";",
"}"
]
| Returns all the collaboration whitelisting with specified filters.
@param api the API connection to be used by the resource.
@param fields the fields to retrieve.
@return an iterable with all the collaboration whitelists met search conditions. | [
"Returns",
"all",
"the",
"collaboration",
"whitelisting",
"with",
"specified",
"filters",
"."
]
| train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxCollaborationWhitelist.java#L93-L96 |
jMotif/GI | src/main/java/net/seninp/gi/sequitur/SequiturFactory.java | SequiturFactory.getRulePositionsByRuleNum | public static ArrayList<RuleInterval> getRulePositionsByRuleNum(int ruleIdx, SAXRule grammar,
SAXRecords saxFrequencyData, double[] originalTimeSeries, int saxWindowSize) {
"""
Recovers start and stop coordinates of a rule subsequences.
@param ruleIdx The rule index.
@param grammar The grammar to analyze.
@param saxFrequencyData the SAX frquency data used for the grammar construction.
@param originalTimeSeries the original time series.
@param saxWindowSize the SAX sliding window size.
@return The array of all intervals corresponding to this rule.
"""
// this will be the result
ArrayList<RuleInterval> resultIntervals = new ArrayList<RuleInterval>();
// the rule container
GrammarRuleRecord ruleContainer = grammar.getRuleRecords().get(ruleIdx);
// the original indexes of all SAX words
ArrayList<Integer> saxWordsIndexes = new ArrayList<Integer>(saxFrequencyData.getAllIndices());
// debug printout
LOGGER.trace("Expanded rule: \"" + ruleContainer.getExpandedRuleString() + '\"');
LOGGER.trace("Indexes: " + ruleContainer.getOccurrences());
// array of all words of this expanded rule
String[] expandedRuleSplit = ruleContainer.getExpandedRuleString().trim().split(" ");
for (Integer currentIndex : ruleContainer.getOccurrences()) {
String extractedStr = "";
StringBuffer sb = new StringBuffer(expandedRuleSplit.length);
for (int i = 0; i < expandedRuleSplit.length; i++) {
LOGGER.trace("currentIndex " + currentIndex + ", i: " + i);
extractedStr = extractedStr.concat(" ").concat(String.valueOf(
saxFrequencyData.getByIndex(saxWordsIndexes.get(currentIndex + i)).getPayload()));
sb.append(saxWordsIndexes.get(currentIndex + i)).append(" ");
}
LOGGER.trace("Recovered string: " + extractedStr);
LOGGER.trace("Recovered positions: " + sb.toString());
int start = saxWordsIndexes.get(currentIndex);
int end = -1;
// need to care about bouncing beyond the all SAX words index array
if ((currentIndex + expandedRuleSplit.length) >= saxWordsIndexes.size()) {
// if we at the last index - then it's easy - end is the timeseries end
end = originalTimeSeries.length - 1;
}
else {
// if we OK with indexes, the Rule subsequence end is the start of the very next SAX word
// after the kast in this expanded rule
end = saxWordsIndexes.get(currentIndex + expandedRuleSplit.length) - 1 + saxWindowSize;
}
// save it
resultIntervals.add(new RuleInterval(start, end));
}
return resultIntervals;
} | java | public static ArrayList<RuleInterval> getRulePositionsByRuleNum(int ruleIdx, SAXRule grammar,
SAXRecords saxFrequencyData, double[] originalTimeSeries, int saxWindowSize) {
// this will be the result
ArrayList<RuleInterval> resultIntervals = new ArrayList<RuleInterval>();
// the rule container
GrammarRuleRecord ruleContainer = grammar.getRuleRecords().get(ruleIdx);
// the original indexes of all SAX words
ArrayList<Integer> saxWordsIndexes = new ArrayList<Integer>(saxFrequencyData.getAllIndices());
// debug printout
LOGGER.trace("Expanded rule: \"" + ruleContainer.getExpandedRuleString() + '\"');
LOGGER.trace("Indexes: " + ruleContainer.getOccurrences());
// array of all words of this expanded rule
String[] expandedRuleSplit = ruleContainer.getExpandedRuleString().trim().split(" ");
for (Integer currentIndex : ruleContainer.getOccurrences()) {
String extractedStr = "";
StringBuffer sb = new StringBuffer(expandedRuleSplit.length);
for (int i = 0; i < expandedRuleSplit.length; i++) {
LOGGER.trace("currentIndex " + currentIndex + ", i: " + i);
extractedStr = extractedStr.concat(" ").concat(String.valueOf(
saxFrequencyData.getByIndex(saxWordsIndexes.get(currentIndex + i)).getPayload()));
sb.append(saxWordsIndexes.get(currentIndex + i)).append(" ");
}
LOGGER.trace("Recovered string: " + extractedStr);
LOGGER.trace("Recovered positions: " + sb.toString());
int start = saxWordsIndexes.get(currentIndex);
int end = -1;
// need to care about bouncing beyond the all SAX words index array
if ((currentIndex + expandedRuleSplit.length) >= saxWordsIndexes.size()) {
// if we at the last index - then it's easy - end is the timeseries end
end = originalTimeSeries.length - 1;
}
else {
// if we OK with indexes, the Rule subsequence end is the start of the very next SAX word
// after the kast in this expanded rule
end = saxWordsIndexes.get(currentIndex + expandedRuleSplit.length) - 1 + saxWindowSize;
}
// save it
resultIntervals.add(new RuleInterval(start, end));
}
return resultIntervals;
} | [
"public",
"static",
"ArrayList",
"<",
"RuleInterval",
">",
"getRulePositionsByRuleNum",
"(",
"int",
"ruleIdx",
",",
"SAXRule",
"grammar",
",",
"SAXRecords",
"saxFrequencyData",
",",
"double",
"[",
"]",
"originalTimeSeries",
",",
"int",
"saxWindowSize",
")",
"{",
"// this will be the result",
"ArrayList",
"<",
"RuleInterval",
">",
"resultIntervals",
"=",
"new",
"ArrayList",
"<",
"RuleInterval",
">",
"(",
")",
";",
"// the rule container",
"GrammarRuleRecord",
"ruleContainer",
"=",
"grammar",
".",
"getRuleRecords",
"(",
")",
".",
"get",
"(",
"ruleIdx",
")",
";",
"// the original indexes of all SAX words",
"ArrayList",
"<",
"Integer",
">",
"saxWordsIndexes",
"=",
"new",
"ArrayList",
"<",
"Integer",
">",
"(",
"saxFrequencyData",
".",
"getAllIndices",
"(",
")",
")",
";",
"// debug printout",
"LOGGER",
".",
"trace",
"(",
"\"Expanded rule: \\\"\"",
"+",
"ruleContainer",
".",
"getExpandedRuleString",
"(",
")",
"+",
"'",
"'",
")",
";",
"LOGGER",
".",
"trace",
"(",
"\"Indexes: \"",
"+",
"ruleContainer",
".",
"getOccurrences",
"(",
")",
")",
";",
"// array of all words of this expanded rule",
"String",
"[",
"]",
"expandedRuleSplit",
"=",
"ruleContainer",
".",
"getExpandedRuleString",
"(",
")",
".",
"trim",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
";",
"for",
"(",
"Integer",
"currentIndex",
":",
"ruleContainer",
".",
"getOccurrences",
"(",
")",
")",
"{",
"String",
"extractedStr",
"=",
"\"\"",
";",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
"expandedRuleSplit",
".",
"length",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"expandedRuleSplit",
".",
"length",
";",
"i",
"++",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"currentIndex \"",
"+",
"currentIndex",
"+",
"\", i: \"",
"+",
"i",
")",
";",
"extractedStr",
"=",
"extractedStr",
".",
"concat",
"(",
"\" \"",
")",
".",
"concat",
"(",
"String",
".",
"valueOf",
"(",
"saxFrequencyData",
".",
"getByIndex",
"(",
"saxWordsIndexes",
".",
"get",
"(",
"currentIndex",
"+",
"i",
")",
")",
".",
"getPayload",
"(",
")",
")",
")",
";",
"sb",
".",
"append",
"(",
"saxWordsIndexes",
".",
"get",
"(",
"currentIndex",
"+",
"i",
")",
")",
".",
"append",
"(",
"\" \"",
")",
";",
"}",
"LOGGER",
".",
"trace",
"(",
"\"Recovered string: \"",
"+",
"extractedStr",
")",
";",
"LOGGER",
".",
"trace",
"(",
"\"Recovered positions: \"",
"+",
"sb",
".",
"toString",
"(",
")",
")",
";",
"int",
"start",
"=",
"saxWordsIndexes",
".",
"get",
"(",
"currentIndex",
")",
";",
"int",
"end",
"=",
"-",
"1",
";",
"// need to care about bouncing beyond the all SAX words index array",
"if",
"(",
"(",
"currentIndex",
"+",
"expandedRuleSplit",
".",
"length",
")",
">=",
"saxWordsIndexes",
".",
"size",
"(",
")",
")",
"{",
"// if we at the last index - then it's easy - end is the timeseries end",
"end",
"=",
"originalTimeSeries",
".",
"length",
"-",
"1",
";",
"}",
"else",
"{",
"// if we OK with indexes, the Rule subsequence end is the start of the very next SAX word",
"// after the kast in this expanded rule",
"end",
"=",
"saxWordsIndexes",
".",
"get",
"(",
"currentIndex",
"+",
"expandedRuleSplit",
".",
"length",
")",
"-",
"1",
"+",
"saxWindowSize",
";",
"}",
"// save it",
"resultIntervals",
".",
"add",
"(",
"new",
"RuleInterval",
"(",
"start",
",",
"end",
")",
")",
";",
"}",
"return",
"resultIntervals",
";",
"}"
]
| Recovers start and stop coordinates of a rule subsequences.
@param ruleIdx The rule index.
@param grammar The grammar to analyze.
@param saxFrequencyData the SAX frquency data used for the grammar construction.
@param originalTimeSeries the original time series.
@param saxWindowSize the SAX sliding window size.
@return The array of all intervals corresponding to this rule. | [
"Recovers",
"start",
"and",
"stop",
"coordinates",
"of",
"a",
"rule",
"subsequences",
"."
]
| train | https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/sequitur/SequiturFactory.java#L236-L285 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/IntrospectionLevelMember.java | IntrospectionLevelMember.addNewChild | private void addNewChild(String name, Object value) {
"""
Add a new IntrospectionLevelMember to _children List (Checking to see if
the new child should be introspected further
@param name
The name of the new child
@param value
The value of the new child
"""
IntrospectionLevelMember prospectiveMember = new IntrospectionLevelMember(_level + 1, name, makeDescription(value), makeMember(value), _allKnownMembersInThisTree);
if (makeMember(value) != null) {
// OK, we'd like to introspect the object further - have we seen it?
if (_allKnownMembersInThisTree.contains(prospectiveMember)) {
// Already seen it, so ensure we don't reexamine it
prospectiveMember = new IntrospectionLevelMember(_level + 1, name, makeDescription(value), null, _allKnownMembersInThisTree);
} else {
// Ensure we don't reexamine it if we see it again!
_allKnownMembersInThisTree.add(prospectiveMember);
}
}
_children.add(prospectiveMember);
} | java | private void addNewChild(String name, Object value) {
IntrospectionLevelMember prospectiveMember = new IntrospectionLevelMember(_level + 1, name, makeDescription(value), makeMember(value), _allKnownMembersInThisTree);
if (makeMember(value) != null) {
// OK, we'd like to introspect the object further - have we seen it?
if (_allKnownMembersInThisTree.contains(prospectiveMember)) {
// Already seen it, so ensure we don't reexamine it
prospectiveMember = new IntrospectionLevelMember(_level + 1, name, makeDescription(value), null, _allKnownMembersInThisTree);
} else {
// Ensure we don't reexamine it if we see it again!
_allKnownMembersInThisTree.add(prospectiveMember);
}
}
_children.add(prospectiveMember);
} | [
"private",
"void",
"addNewChild",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"IntrospectionLevelMember",
"prospectiveMember",
"=",
"new",
"IntrospectionLevelMember",
"(",
"_level",
"+",
"1",
",",
"name",
",",
"makeDescription",
"(",
"value",
")",
",",
"makeMember",
"(",
"value",
")",
",",
"_allKnownMembersInThisTree",
")",
";",
"if",
"(",
"makeMember",
"(",
"value",
")",
"!=",
"null",
")",
"{",
"// OK, we'd like to introspect the object further - have we seen it?",
"if",
"(",
"_allKnownMembersInThisTree",
".",
"contains",
"(",
"prospectiveMember",
")",
")",
"{",
"// Already seen it, so ensure we don't reexamine it",
"prospectiveMember",
"=",
"new",
"IntrospectionLevelMember",
"(",
"_level",
"+",
"1",
",",
"name",
",",
"makeDescription",
"(",
"value",
")",
",",
"null",
",",
"_allKnownMembersInThisTree",
")",
";",
"}",
"else",
"{",
"// Ensure we don't reexamine it if we see it again!",
"_allKnownMembersInThisTree",
".",
"add",
"(",
"prospectiveMember",
")",
";",
"}",
"}",
"_children",
".",
"add",
"(",
"prospectiveMember",
")",
";",
"}"
]
| Add a new IntrospectionLevelMember to _children List (Checking to see if
the new child should be introspected further
@param name
The name of the new child
@param value
The value of the new child | [
"Add",
"a",
"new",
"IntrospectionLevelMember",
"to",
"_children",
"List",
"(",
"Checking",
"to",
"see",
"if",
"the",
"new",
"child",
"should",
"be",
"introspected",
"further"
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/IntrospectionLevelMember.java#L256-L269 |
EXIficient/exificient-core | src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java | MethodsBag.itosReverse | public final static void itosReverse(long i, int index, char[] buf) {
"""
Places characters representing the integer i into the character array buf
in reverse order.
Will fail if i < 0 (zero)
@param i
integer
@param index
index
@param buf
character buffer
"""
assert (i >= 0);
long q;
int r;
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int) i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16 + 3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
buf[index++] = digits[r];
i2 = q2;
if (i2 == 0)
break;
}
} | java | public final static void itosReverse(long i, int index, char[] buf) {
assert (i >= 0);
long q;
int r;
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int) i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
buf[index++] = DigitOnes[r];
buf[index++] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16 + 3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
buf[index++] = digits[r];
i2 = q2;
if (i2 == 0)
break;
}
} | [
"public",
"final",
"static",
"void",
"itosReverse",
"(",
"long",
"i",
",",
"int",
"index",
",",
"char",
"[",
"]",
"buf",
")",
"{",
"assert",
"(",
"i",
">=",
"0",
")",
";",
"long",
"q",
";",
"int",
"r",
";",
"// Get 2 digits/iteration using longs until quotient fits into an int",
"while",
"(",
"i",
">",
"Integer",
".",
"MAX_VALUE",
")",
"{",
"q",
"=",
"i",
"/",
"100",
";",
"// really: r = i - (q * 100);",
"r",
"=",
"(",
"int",
")",
"(",
"i",
"-",
"(",
"(",
"q",
"<<",
"6",
")",
"+",
"(",
"q",
"<<",
"5",
")",
"+",
"(",
"q",
"<<",
"2",
")",
")",
")",
";",
"i",
"=",
"q",
";",
"buf",
"[",
"index",
"++",
"]",
"=",
"DigitOnes",
"[",
"r",
"]",
";",
"buf",
"[",
"index",
"++",
"]",
"=",
"DigitTens",
"[",
"r",
"]",
";",
"}",
"// Get 2 digits/iteration using ints",
"int",
"q2",
";",
"int",
"i2",
"=",
"(",
"int",
")",
"i",
";",
"while",
"(",
"i2",
">=",
"65536",
")",
"{",
"q2",
"=",
"i2",
"/",
"100",
";",
"// really: r = i2 - (q * 100);",
"r",
"=",
"i2",
"-",
"(",
"(",
"q2",
"<<",
"6",
")",
"+",
"(",
"q2",
"<<",
"5",
")",
"+",
"(",
"q2",
"<<",
"2",
")",
")",
";",
"i2",
"=",
"q2",
";",
"buf",
"[",
"index",
"++",
"]",
"=",
"DigitOnes",
"[",
"r",
"]",
";",
"buf",
"[",
"index",
"++",
"]",
"=",
"DigitTens",
"[",
"r",
"]",
";",
"}",
"// Fall thru to fast mode for smaller numbers",
"// assert(i2 <= 65536, i2);",
"for",
"(",
";",
";",
")",
"{",
"q2",
"=",
"(",
"i2",
"*",
"52429",
")",
">>>",
"(",
"16",
"+",
"3",
")",
";",
"r",
"=",
"i2",
"-",
"(",
"(",
"q2",
"<<",
"3",
")",
"+",
"(",
"q2",
"<<",
"1",
")",
")",
";",
"// r = i2-(q2*10) ...",
"buf",
"[",
"index",
"++",
"]",
"=",
"digits",
"[",
"r",
"]",
";",
"i2",
"=",
"q2",
";",
"if",
"(",
"i2",
"==",
"0",
")",
"break",
";",
"}",
"}"
]
| Places characters representing the integer i into the character array buf
in reverse order.
Will fail if i < 0 (zero)
@param i
integer
@param index
index
@param buf
character buffer | [
"Places",
"characters",
"representing",
"the",
"integer",
"i",
"into",
"the",
"character",
"array",
"buf",
"in",
"reverse",
"order",
"."
]
| train | https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java#L496-L533 |
jbundle/jbundle | base/message/service/src/main/java/org/jbundle/base/message/service/BaseServiceMessageTransport.java | BaseServiceMessageTransport.processMessage | public Object processMessage(Object message) {
"""
This is the application code for handling the message.. Once the
message is received the application can retrieve the soap part, the
attachment part if there are any, or any other information from the
message.
@param message The incoming message to process.
"""
Utility.getLogger().info("processMessage called in service message");
BaseMessage msgReplyInternal = null;
try {
BaseMessage messageIn = new TreeMessage(null, null);
new ServiceTrxMessageIn(messageIn, message);
msgReplyInternal = this.processIncomingMessage(messageIn, null);
Utility.getLogger().info("msgReplyInternal: " + msgReplyInternal);
int iErrorCode = this.convertToExternal(msgReplyInternal, null);
Utility.getLogger().info("externalMessageReply: " + msgReplyInternal);
Object msg = null;//fac.createMessage();
if (iErrorCode == DBConstants.NORMAL_RETURN)
{
msg = msgReplyInternal.getExternalMessage().getRawData();
String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
this.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.SENTOK, null, null); // Sent (no reply required)
}
return msg;
} catch (Throwable ex) {
ex.printStackTrace();
String strError = "Error in processing or replying to a message";
Utility.getLogger().warning(strError);
if (msgReplyInternal != null)
{
String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
this.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.ERROR, strError, null);
}
return null;
}
} | java | public Object processMessage(Object message)
{
Utility.getLogger().info("processMessage called in service message");
BaseMessage msgReplyInternal = null;
try {
BaseMessage messageIn = new TreeMessage(null, null);
new ServiceTrxMessageIn(messageIn, message);
msgReplyInternal = this.processIncomingMessage(messageIn, null);
Utility.getLogger().info("msgReplyInternal: " + msgReplyInternal);
int iErrorCode = this.convertToExternal(msgReplyInternal, null);
Utility.getLogger().info("externalMessageReply: " + msgReplyInternal);
Object msg = null;//fac.createMessage();
if (iErrorCode == DBConstants.NORMAL_RETURN)
{
msg = msgReplyInternal.getExternalMessage().getRawData();
String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
this.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.SENTOK, null, null); // Sent (no reply required)
}
return msg;
} catch (Throwable ex) {
ex.printStackTrace();
String strError = "Error in processing or replying to a message";
Utility.getLogger().warning(strError);
if (msgReplyInternal != null)
{
String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
this.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.ERROR, strError, null);
}
return null;
}
} | [
"public",
"Object",
"processMessage",
"(",
"Object",
"message",
")",
"{",
"Utility",
".",
"getLogger",
"(",
")",
".",
"info",
"(",
"\"processMessage called in service message\"",
")",
";",
"BaseMessage",
"msgReplyInternal",
"=",
"null",
";",
"try",
"{",
"BaseMessage",
"messageIn",
"=",
"new",
"TreeMessage",
"(",
"null",
",",
"null",
")",
";",
"new",
"ServiceTrxMessageIn",
"(",
"messageIn",
",",
"message",
")",
";",
"msgReplyInternal",
"=",
"this",
".",
"processIncomingMessage",
"(",
"messageIn",
",",
"null",
")",
";",
"Utility",
".",
"getLogger",
"(",
")",
".",
"info",
"(",
"\"msgReplyInternal: \"",
"+",
"msgReplyInternal",
")",
";",
"int",
"iErrorCode",
"=",
"this",
".",
"convertToExternal",
"(",
"msgReplyInternal",
",",
"null",
")",
";",
"Utility",
".",
"getLogger",
"(",
")",
".",
"info",
"(",
"\"externalMessageReply: \"",
"+",
"msgReplyInternal",
")",
";",
"Object",
"msg",
"=",
"null",
";",
"//fac.createMessage();",
"if",
"(",
"iErrorCode",
"==",
"DBConstants",
".",
"NORMAL_RETURN",
")",
"{",
"msg",
"=",
"msgReplyInternal",
".",
"getExternalMessage",
"(",
")",
".",
"getRawData",
"(",
")",
";",
"String",
"strTrxID",
"=",
"(",
"String",
")",
"msgReplyInternal",
".",
"getMessageHeader",
"(",
")",
".",
"get",
"(",
"TrxMessageHeader",
".",
"LOG_TRX_ID",
")",
";",
"this",
".",
"logMessage",
"(",
"strTrxID",
",",
"msgReplyInternal",
",",
"MessageInfoTypeModel",
".",
"REPLY",
",",
"MessageTypeModel",
".",
"MESSAGE_OUT",
",",
"MessageStatusModel",
".",
"SENTOK",
",",
"null",
",",
"null",
")",
";",
"// Sent (no reply required)",
"}",
"return",
"msg",
";",
"}",
"catch",
"(",
"Throwable",
"ex",
")",
"{",
"ex",
".",
"printStackTrace",
"(",
")",
";",
"String",
"strError",
"=",
"\"Error in processing or replying to a message\"",
";",
"Utility",
".",
"getLogger",
"(",
")",
".",
"warning",
"(",
"strError",
")",
";",
"if",
"(",
"msgReplyInternal",
"!=",
"null",
")",
"{",
"String",
"strTrxID",
"=",
"(",
"String",
")",
"msgReplyInternal",
".",
"getMessageHeader",
"(",
")",
".",
"get",
"(",
"TrxMessageHeader",
".",
"LOG_TRX_ID",
")",
";",
"this",
".",
"logMessage",
"(",
"strTrxID",
",",
"msgReplyInternal",
",",
"MessageInfoTypeModel",
".",
"REPLY",
",",
"MessageTypeModel",
".",
"MESSAGE_OUT",
",",
"MessageStatusModel",
".",
"ERROR",
",",
"strError",
",",
"null",
")",
";",
"}",
"return",
"null",
";",
"}",
"}"
]
| This is the application code for handling the message.. Once the
message is received the application can retrieve the soap part, the
attachment part if there are any, or any other information from the
message.
@param message The incoming message to process. | [
"This",
"is",
"the",
"application",
"code",
"for",
"handling",
"the",
"message",
"..",
"Once",
"the",
"message",
"is",
"received",
"the",
"application",
"can",
"retrieve",
"the",
"soap",
"part",
"the",
"attachment",
"part",
"if",
"there",
"are",
"any",
"or",
"any",
"other",
"information",
"from",
"the",
"message",
"."
]
| train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/service/src/main/java/org/jbundle/base/message/service/BaseServiceMessageTransport.java#L63-L97 |
stratosphere/stratosphere | stratosphere-core/src/main/java/eu/stratosphere/core/memory/MemorySegment.java | MemorySegment.copyTo | public final void copyTo(int offset, MemorySegment target, int targetOffset, int numBytes) {
"""
Bulk copy method. Copies {@code numBytes} bytes from this memory segment, starting at position
{@code offset} to the target memory segment. The bytes will be put into the target segment
starting at position {@code targetOffset}.
@param offset The position where the bytes are started to be read from in this memory segment.
@param target The memory segment to copy the bytes to.
@param targetOffset The position in the target memory segment to copy the chunk to.
@param numBytes The number of bytes to copy.
@throws IndexOutOfBoundsException If either of the offsets is invalid, or the source segment does not
contain the given number of bytes (starting from offset), or the target segment does
not have enough space for the bytes (counting from targetOffset).
"""
// system arraycopy does the boundary checks anyways, no need to check extra
System.arraycopy(this.memory, offset, target.memory, targetOffset, numBytes);
} | java | public final void copyTo(int offset, MemorySegment target, int targetOffset, int numBytes) {
// system arraycopy does the boundary checks anyways, no need to check extra
System.arraycopy(this.memory, offset, target.memory, targetOffset, numBytes);
} | [
"public",
"final",
"void",
"copyTo",
"(",
"int",
"offset",
",",
"MemorySegment",
"target",
",",
"int",
"targetOffset",
",",
"int",
"numBytes",
")",
"{",
"// system arraycopy does the boundary checks anyways, no need to check extra",
"System",
".",
"arraycopy",
"(",
"this",
".",
"memory",
",",
"offset",
",",
"target",
".",
"memory",
",",
"targetOffset",
",",
"numBytes",
")",
";",
"}"
]
| Bulk copy method. Copies {@code numBytes} bytes from this memory segment, starting at position
{@code offset} to the target memory segment. The bytes will be put into the target segment
starting at position {@code targetOffset}.
@param offset The position where the bytes are started to be read from in this memory segment.
@param target The memory segment to copy the bytes to.
@param targetOffset The position in the target memory segment to copy the chunk to.
@param numBytes The number of bytes to copy.
@throws IndexOutOfBoundsException If either of the offsets is invalid, or the source segment does not
contain the given number of bytes (starting from offset), or the target segment does
not have enough space for the bytes (counting from targetOffset). | [
"Bulk",
"copy",
"method",
".",
"Copies",
"{",
"@code",
"numBytes",
"}",
"bytes",
"from",
"this",
"memory",
"segment",
"starting",
"at",
"position",
"{",
"@code",
"offset",
"}",
"to",
"the",
"target",
"memory",
"segment",
".",
"The",
"bytes",
"will",
"be",
"put",
"into",
"the",
"target",
"segment",
"starting",
"at",
"position",
"{",
"@code",
"targetOffset",
"}",
"."
]
| train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/core/memory/MemorySegment.java#L933-L936 |
ical4j/ical4j | src/main/java/net/fortuna/ical4j/data/CalendarParserImpl.java | CalendarParserImpl.assertToken | private int assertToken(final StreamTokenizer tokeniser, Reader in,
final String token, final boolean ignoreCase, final boolean isBeginToken) throws IOException,
ParserException {
"""
Asserts that the next token in the stream matches the specified token.
@param tokeniser stream tokeniser to perform assertion on
@param in
@param token expected token
@param ignoreCase
@param isBeginToken
@return int value of the ttype field of the tokeniser
@throws IOException when unable to read from stream
@throws ParserException when next token in the stream does not match the expected token
"""
// ensure next token is a word token..
String sval;
int ntok;
if(isBeginToken) {
ntok = skipNewLines(tokeniser, in, token);
sval = getSvalIgnoringBom(tokeniser, in, token);
} else {
ntok = assertToken(tokeniser, in, StreamTokenizer.TT_WORD);
sval = tokeniser.sval;
}
if (ignoreCase) {
if (!token.equalsIgnoreCase(sval)) {
throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in));
}
}
else if (!token.equals(sval)) {
throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in));
}
if (log.isDebugEnabled()) {
log.debug("[" + token + "]");
}
return ntok;
} | java | private int assertToken(final StreamTokenizer tokeniser, Reader in,
final String token, final boolean ignoreCase, final boolean isBeginToken) throws IOException,
ParserException {
// ensure next token is a word token..
String sval;
int ntok;
if(isBeginToken) {
ntok = skipNewLines(tokeniser, in, token);
sval = getSvalIgnoringBom(tokeniser, in, token);
} else {
ntok = assertToken(tokeniser, in, StreamTokenizer.TT_WORD);
sval = tokeniser.sval;
}
if (ignoreCase) {
if (!token.equalsIgnoreCase(sval)) {
throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in));
}
}
else if (!token.equals(sval)) {
throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, token, sval), getLineNumber(tokeniser, in));
}
if (log.isDebugEnabled()) {
log.debug("[" + token + "]");
}
return ntok;
} | [
"private",
"int",
"assertToken",
"(",
"final",
"StreamTokenizer",
"tokeniser",
",",
"Reader",
"in",
",",
"final",
"String",
"token",
",",
"final",
"boolean",
"ignoreCase",
",",
"final",
"boolean",
"isBeginToken",
")",
"throws",
"IOException",
",",
"ParserException",
"{",
"// ensure next token is a word token..",
"String",
"sval",
";",
"int",
"ntok",
";",
"if",
"(",
"isBeginToken",
")",
"{",
"ntok",
"=",
"skipNewLines",
"(",
"tokeniser",
",",
"in",
",",
"token",
")",
";",
"sval",
"=",
"getSvalIgnoringBom",
"(",
"tokeniser",
",",
"in",
",",
"token",
")",
";",
"}",
"else",
"{",
"ntok",
"=",
"assertToken",
"(",
"tokeniser",
",",
"in",
",",
"StreamTokenizer",
".",
"TT_WORD",
")",
";",
"sval",
"=",
"tokeniser",
".",
"sval",
";",
"}",
"if",
"(",
"ignoreCase",
")",
"{",
"if",
"(",
"!",
"token",
".",
"equalsIgnoreCase",
"(",
"sval",
")",
")",
"{",
"throw",
"new",
"ParserException",
"(",
"MessageFormat",
".",
"format",
"(",
"UNEXPECTED_TOKEN_MESSAGE",
",",
"token",
",",
"sval",
")",
",",
"getLineNumber",
"(",
"tokeniser",
",",
"in",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"token",
".",
"equals",
"(",
"sval",
")",
")",
"{",
"throw",
"new",
"ParserException",
"(",
"MessageFormat",
".",
"format",
"(",
"UNEXPECTED_TOKEN_MESSAGE",
",",
"token",
",",
"sval",
")",
",",
"getLineNumber",
"(",
"tokeniser",
",",
"in",
")",
")",
";",
"}",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"[\"",
"+",
"token",
"+",
"\"]\"",
")",
";",
"}",
"return",
"ntok",
";",
"}"
]
| Asserts that the next token in the stream matches the specified token.
@param tokeniser stream tokeniser to perform assertion on
@param in
@param token expected token
@param ignoreCase
@param isBeginToken
@return int value of the ttype field of the tokeniser
@throws IOException when unable to read from stream
@throws ParserException when next token in the stream does not match the expected token | [
"Asserts",
"that",
"the",
"next",
"token",
"in",
"the",
"stream",
"matches",
"the",
"specified",
"token",
"."
]
| train | https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/data/CalendarParserImpl.java#L502-L530 |
VoltDB/voltdb | src/frontend/org/voltdb/SnapshotSiteProcessor.java | SnapshotSiteProcessor.startSnapshotWithTargets | public void startSnapshotWithTargets(Collection<SnapshotDataTarget> targets, long now) {
"""
This is called from the snapshot IO thread when the deferred setup is finished. It sets
the data targets and queues a snapshot task onto the site thread.
"""
// TRAIL [SnapSave:9] 5 [all SP] Start snapshot by putting task into the site queue.
//Basically asserts that there are no tasks with null targets at this point
//getTarget checks and crashes
for (SnapshotTableTask t : m_snapshotTableTasks.values()) {
t.getTarget();
}
ArrayList<SnapshotDataTarget> targetsToClose = Lists.newArrayList();
for (final SnapshotDataTarget target : targets) {
if (target.needsFinalClose()) {
targetsToClose.add(target);
}
}
m_snapshotTargets = targetsToClose;
// Queue the first snapshot task
VoltDB.instance().schedulePriorityWork(
new Runnable() {
@Override
public void run()
{
m_siteTaskerQueue.offer(new SnapshotTask());
}
},
(m_quietUntil + (5 * m_snapshotPriority) - now),
0,
TimeUnit.MILLISECONDS);
m_quietUntil += 5 * m_snapshotPriority;
} | java | public void startSnapshotWithTargets(Collection<SnapshotDataTarget> targets, long now)
{
// TRAIL [SnapSave:9] 5 [all SP] Start snapshot by putting task into the site queue.
//Basically asserts that there are no tasks with null targets at this point
//getTarget checks and crashes
for (SnapshotTableTask t : m_snapshotTableTasks.values()) {
t.getTarget();
}
ArrayList<SnapshotDataTarget> targetsToClose = Lists.newArrayList();
for (final SnapshotDataTarget target : targets) {
if (target.needsFinalClose()) {
targetsToClose.add(target);
}
}
m_snapshotTargets = targetsToClose;
// Queue the first snapshot task
VoltDB.instance().schedulePriorityWork(
new Runnable() {
@Override
public void run()
{
m_siteTaskerQueue.offer(new SnapshotTask());
}
},
(m_quietUntil + (5 * m_snapshotPriority) - now),
0,
TimeUnit.MILLISECONDS);
m_quietUntil += 5 * m_snapshotPriority;
} | [
"public",
"void",
"startSnapshotWithTargets",
"(",
"Collection",
"<",
"SnapshotDataTarget",
">",
"targets",
",",
"long",
"now",
")",
"{",
"// TRAIL [SnapSave:9] 5 [all SP] Start snapshot by putting task into the site queue.",
"//Basically asserts that there are no tasks with null targets at this point",
"//getTarget checks and crashes",
"for",
"(",
"SnapshotTableTask",
"t",
":",
"m_snapshotTableTasks",
".",
"values",
"(",
")",
")",
"{",
"t",
".",
"getTarget",
"(",
")",
";",
"}",
"ArrayList",
"<",
"SnapshotDataTarget",
">",
"targetsToClose",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"final",
"SnapshotDataTarget",
"target",
":",
"targets",
")",
"{",
"if",
"(",
"target",
".",
"needsFinalClose",
"(",
")",
")",
"{",
"targetsToClose",
".",
"add",
"(",
"target",
")",
";",
"}",
"}",
"m_snapshotTargets",
"=",
"targetsToClose",
";",
"// Queue the first snapshot task",
"VoltDB",
".",
"instance",
"(",
")",
".",
"schedulePriorityWork",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"m_siteTaskerQueue",
".",
"offer",
"(",
"new",
"SnapshotTask",
"(",
")",
")",
";",
"}",
"}",
",",
"(",
"m_quietUntil",
"+",
"(",
"5",
"*",
"m_snapshotPriority",
")",
"-",
"now",
")",
",",
"0",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"m_quietUntil",
"+=",
"5",
"*",
"m_snapshotPriority",
";",
"}"
]
| This is called from the snapshot IO thread when the deferred setup is finished. It sets
the data targets and queues a snapshot task onto the site thread. | [
"This",
"is",
"called",
"from",
"the",
"snapshot",
"IO",
"thread",
"when",
"the",
"deferred",
"setup",
"is",
"finished",
".",
"It",
"sets",
"the",
"data",
"targets",
"and",
"queues",
"a",
"snapshot",
"task",
"onto",
"the",
"site",
"thread",
"."
]
| train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/SnapshotSiteProcessor.java#L452-L482 |
knightliao/apollo | src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java | DateUtils.formatDateString | public static String formatDateString(String dateString, String format1, String format2) {
"""
@param dateString
@param format1 ,如yyyyMMdd
@param format2 , 如yyyy/MM/dd
@return
@author zhangpingan
"""
if (dateString == null) {
return null;
}
java.text.SimpleDateFormat beforeFormat = new java.text.SimpleDateFormat(format1);
java.text.SimpleDateFormat endFormat = new java.text.SimpleDateFormat(format2);
try {
return endFormat.format(beforeFormat.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
return dateString;
}
} | java | public static String formatDateString(String dateString, String format1, String format2) {
if (dateString == null) {
return null;
}
java.text.SimpleDateFormat beforeFormat = new java.text.SimpleDateFormat(format1);
java.text.SimpleDateFormat endFormat = new java.text.SimpleDateFormat(format2);
try {
return endFormat.format(beforeFormat.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
return dateString;
}
} | [
"public",
"static",
"String",
"formatDateString",
"(",
"String",
"dateString",
",",
"String",
"format1",
",",
"String",
"format2",
")",
"{",
"if",
"(",
"dateString",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"java",
".",
"text",
".",
"SimpleDateFormat",
"beforeFormat",
"=",
"new",
"java",
".",
"text",
".",
"SimpleDateFormat",
"(",
"format1",
")",
";",
"java",
".",
"text",
".",
"SimpleDateFormat",
"endFormat",
"=",
"new",
"java",
".",
"text",
".",
"SimpleDateFormat",
"(",
"format2",
")",
";",
"try",
"{",
"return",
"endFormat",
".",
"format",
"(",
"beforeFormat",
".",
"parse",
"(",
"dateString",
")",
")",
";",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
"dateString",
";",
"}",
"}"
]
| @param dateString
@param format1 ,如yyyyMMdd
@param format2 , 如yyyy/MM/dd
@return
@author zhangpingan | [
"@param",
"dateString",
"@param",
"format1",
",如yyyyMMdd",
"@param",
"format2",
"如yyyy",
"/",
"MM",
"/",
"dd"
]
| train | https://github.com/knightliao/apollo/blob/d7a283659fa3e67af6375db8969b2d065a8ce6eb/src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java#L909-L921 |
apereo/cas | support/cas-server-support-cosmosdb-core/src/main/java/org/apereo/cas/cosmosdb/CosmosDbObjectFactory.java | CosmosDbObjectFactory.getDocumentLink | public static String getDocumentLink(final String databaseName, final String collectionName, final String documentId) {
"""
Gets document link.
@param databaseName the database name
@param collectionName the collection name
@param documentId the document id
@return the document link
"""
return getCollectionLink(databaseName, collectionName) + "/docs/" + documentId;
} | java | public static String getDocumentLink(final String databaseName, final String collectionName, final String documentId) {
return getCollectionLink(databaseName, collectionName) + "/docs/" + documentId;
} | [
"public",
"static",
"String",
"getDocumentLink",
"(",
"final",
"String",
"databaseName",
",",
"final",
"String",
"collectionName",
",",
"final",
"String",
"documentId",
")",
"{",
"return",
"getCollectionLink",
"(",
"databaseName",
",",
"collectionName",
")",
"+",
"\"/docs/\"",
"+",
"documentId",
";",
"}"
]
| Gets document link.
@param databaseName the database name
@param collectionName the collection name
@param documentId the document id
@return the document link | [
"Gets",
"document",
"link",
"."
]
| train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-cosmosdb-core/src/main/java/org/apereo/cas/cosmosdb/CosmosDbObjectFactory.java#L62-L64 |
mygreen/xlsmapper | src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java | SheetBindingErrors.createFieldError | public InternalFieldErrorBuilder createFieldError(final String field, final String errorCode) {
"""
フィールドエラーのビルダーを作成します。
@param field フィールドパス。
@param errorCode エラーコード
@return {@link FieldError}のインスタンスを組み立てるビルダクラス。
"""
return createFieldError(field, new String[]{errorCode});
} | java | public InternalFieldErrorBuilder createFieldError(final String field, final String errorCode) {
return createFieldError(field, new String[]{errorCode});
} | [
"public",
"InternalFieldErrorBuilder",
"createFieldError",
"(",
"final",
"String",
"field",
",",
"final",
"String",
"errorCode",
")",
"{",
"return",
"createFieldError",
"(",
"field",
",",
"new",
"String",
"[",
"]",
"{",
"errorCode",
"}",
")",
";",
"}"
]
| フィールドエラーのビルダーを作成します。
@param field フィールドパス。
@param errorCode エラーコード
@return {@link FieldError}のインスタンスを組み立てるビルダクラス。 | [
"フィールドエラーのビルダーを作成します。"
]
| train | https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/validation/SheetBindingErrors.java#L607-L611 |
OpenBEL/openbel-framework | org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/ExternalType.java | ExternalType.writeLong | public static void writeLong(final ObjectOutput out, final Long l)
throws IOException {
"""
Writes the {@link Long} to the output.
<p>
This method and its equivalent {@link #readLong(ObjectInput)
read-variant} store {@code l} in a more efficient way than serializing
the {@link Long} class.
</p>
@param out Non-null {@link ObjectOutput}
@param l {@link Long}; may be null
@throws IOException Thrown if an I/O error occurred
@see #readLong(ObjectInput)
"""
if (l == null) {
out.writeByte(0);
return;
}
out.writeByte(1);
out.writeLong(l);
} | java | public static void writeLong(final ObjectOutput out, final Long l)
throws IOException {
if (l == null) {
out.writeByte(0);
return;
}
out.writeByte(1);
out.writeLong(l);
} | [
"public",
"static",
"void",
"writeLong",
"(",
"final",
"ObjectOutput",
"out",
",",
"final",
"Long",
"l",
")",
"throws",
"IOException",
"{",
"if",
"(",
"l",
"==",
"null",
")",
"{",
"out",
".",
"writeByte",
"(",
"0",
")",
";",
"return",
";",
"}",
"out",
".",
"writeByte",
"(",
"1",
")",
";",
"out",
".",
"writeLong",
"(",
"l",
")",
";",
"}"
]
| Writes the {@link Long} to the output.
<p>
This method and its equivalent {@link #readLong(ObjectInput)
read-variant} store {@code l} in a more efficient way than serializing
the {@link Long} class.
</p>
@param out Non-null {@link ObjectOutput}
@param l {@link Long}; may be null
@throws IOException Thrown if an I/O error occurred
@see #readLong(ObjectInput) | [
"Writes",
"the",
"{",
"@link",
"Long",
"}",
"to",
"the",
"output",
".",
"<p",
">",
"This",
"method",
"and",
"its",
"equivalent",
"{",
"@link",
"#readLong",
"(",
"ObjectInput",
")",
"read",
"-",
"variant",
"}",
"store",
"{",
"@code",
"l",
"}",
"in",
"a",
"more",
"efficient",
"way",
"than",
"serializing",
"the",
"{",
"@link",
"Long",
"}",
"class",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/ExternalType.java#L175-L183 |
alkacon/opencms-core | src/org/opencms/xml/types/CmsXmlVfsFileValue.java | CmsXmlVfsFileValue.setIdValue | public void setIdValue(CmsObject cms, CmsUUID id) {
"""
Sets the value as a structure id.<p>
@param cms the current CMS context
@param id the structure id which should be stored in the file value
"""
CmsRelationType type = getRelationType(getPath());
CmsLink link = new CmsLink(TYPE_VFS_LINK, type, id, "@", true);
// link management check
link.checkConsistency(cms);
// update xml node
CmsLinkUpdateUtil.updateXmlForVfsFile(link, m_element.addElement(CmsXmlPage.NODE_LINK));
} | java | public void setIdValue(CmsObject cms, CmsUUID id) {
CmsRelationType type = getRelationType(getPath());
CmsLink link = new CmsLink(TYPE_VFS_LINK, type, id, "@", true);
// link management check
link.checkConsistency(cms);
// update xml node
CmsLinkUpdateUtil.updateXmlForVfsFile(link, m_element.addElement(CmsXmlPage.NODE_LINK));
} | [
"public",
"void",
"setIdValue",
"(",
"CmsObject",
"cms",
",",
"CmsUUID",
"id",
")",
"{",
"CmsRelationType",
"type",
"=",
"getRelationType",
"(",
"getPath",
"(",
")",
")",
";",
"CmsLink",
"link",
"=",
"new",
"CmsLink",
"(",
"TYPE_VFS_LINK",
",",
"type",
",",
"id",
",",
"\"@\"",
",",
"true",
")",
";",
"// link management check",
"link",
".",
"checkConsistency",
"(",
"cms",
")",
";",
"// update xml node",
"CmsLinkUpdateUtil",
".",
"updateXmlForVfsFile",
"(",
"link",
",",
"m_element",
".",
"addElement",
"(",
"CmsXmlPage",
".",
"NODE_LINK",
")",
")",
";",
"}"
]
| Sets the value as a structure id.<p>
@param cms the current CMS context
@param id the structure id which should be stored in the file value | [
"Sets",
"the",
"value",
"as",
"a",
"structure",
"id",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/types/CmsXmlVfsFileValue.java#L248-L257 |
akberc/ceylon-maven-plugin | src/main/java/com/dgwave/car/common/CeylonUtil.java | CeylonUtil.extractFile | public static void extractFile(final ZipInputStream in, final File outdir, final String name) throws IOException {
"""
Extracts a single file from a zip archive.
@param in Input zip stream
@param outdir Output directory
@param name File name
@throws IOException In case of IO error
"""
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
int count = -1;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.close();
} | java | public static void extractFile(final ZipInputStream in, final File outdir, final String name) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
int count = -1;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.close();
} | [
"public",
"static",
"void",
"extractFile",
"(",
"final",
"ZipInputStream",
"in",
",",
"final",
"File",
"outdir",
",",
"final",
"String",
"name",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"BUFFER_SIZE",
"]",
";",
"BufferedOutputStream",
"out",
"=",
"new",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"new",
"File",
"(",
"outdir",
",",
"name",
")",
")",
")",
";",
"int",
"count",
"=",
"-",
"1",
";",
"while",
"(",
"(",
"count",
"=",
"in",
".",
"read",
"(",
"buffer",
")",
")",
"!=",
"-",
"1",
")",
"{",
"out",
".",
"write",
"(",
"buffer",
",",
"0",
",",
"count",
")",
";",
"}",
"out",
".",
"close",
"(",
")",
";",
"}"
]
| Extracts a single file from a zip archive.
@param in Input zip stream
@param outdir Output directory
@param name File name
@throws IOException In case of IO error | [
"Extracts",
"a",
"single",
"file",
"from",
"a",
"zip",
"archive",
"."
]
| train | https://github.com/akberc/ceylon-maven-plugin/blob/b7f6c4a2b24f2fa237350c9e715f4193e83415ef/src/main/java/com/dgwave/car/common/CeylonUtil.java#L223-L231 |
biojava/biojava | biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/CalcPoint.java | CalcPoint.TMScore | public static double TMScore(Point3d[] x, Point3d[] y, int lengthNative) {
"""
Returns the TM-Score for two superimposed sets of coordinates Yang Zhang
and Jeffrey Skolnick, PROTEINS: Structure, Function, and Bioinformatics
57:702–710 (2004)
@param x
coordinate set 1
@param y
coordinate set 2
@param lengthNative
total length of native sequence
@return
"""
if (x.length != y.length) {
throw new IllegalArgumentException(
"Point arrays are not of the same length.");
}
double d0 = 1.24 * Math.cbrt(x.length - 15.0) - 1.8;
double d0Sq = d0 * d0;
double sum = 0;
for (int i = 0; i < x.length; i++) {
sum += 1.0 / (1.0 + x[i].distanceSquared(y[i]) / d0Sq);
}
return sum / lengthNative;
} | java | public static double TMScore(Point3d[] x, Point3d[] y, int lengthNative) {
if (x.length != y.length) {
throw new IllegalArgumentException(
"Point arrays are not of the same length.");
}
double d0 = 1.24 * Math.cbrt(x.length - 15.0) - 1.8;
double d0Sq = d0 * d0;
double sum = 0;
for (int i = 0; i < x.length; i++) {
sum += 1.0 / (1.0 + x[i].distanceSquared(y[i]) / d0Sq);
}
return sum / lengthNative;
} | [
"public",
"static",
"double",
"TMScore",
"(",
"Point3d",
"[",
"]",
"x",
",",
"Point3d",
"[",
"]",
"y",
",",
"int",
"lengthNative",
")",
"{",
"if",
"(",
"x",
".",
"length",
"!=",
"y",
".",
"length",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Point arrays are not of the same length.\"",
")",
";",
"}",
"double",
"d0",
"=",
"1.24",
"*",
"Math",
".",
"cbrt",
"(",
"x",
".",
"length",
"-",
"15.0",
")",
"-",
"1.8",
";",
"double",
"d0Sq",
"=",
"d0",
"*",
"d0",
";",
"double",
"sum",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"i",
"++",
")",
"{",
"sum",
"+=",
"1.0",
"/",
"(",
"1.0",
"+",
"x",
"[",
"i",
"]",
".",
"distanceSquared",
"(",
"y",
"[",
"i",
"]",
")",
"/",
"d0Sq",
")",
";",
"}",
"return",
"sum",
"/",
"lengthNative",
";",
"}"
]
| Returns the TM-Score for two superimposed sets of coordinates Yang Zhang
and Jeffrey Skolnick, PROTEINS: Structure, Function, and Bioinformatics
57:702–710 (2004)
@param x
coordinate set 1
@param y
coordinate set 2
@param lengthNative
total length of native sequence
@return | [
"Returns",
"the",
"TM",
"-",
"Score",
"for",
"two",
"superimposed",
"sets",
"of",
"coordinates",
"Yang",
"Zhang",
"and",
"Jeffrey",
"Skolnick",
"PROTEINS",
":",
"Structure",
"Function",
"and",
"Bioinformatics",
"57",
":",
"702–710",
"(",
"2004",
")"
]
| train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/CalcPoint.java#L172-L188 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/jboss/logging/Logger.java | Logger.errorf | public void errorf(Throwable t, String format, Object param1) {
"""
Issue a formatted log message with a level of ERROR.
@param t the throwable
@param format the format string, as per {@link String#format(String, Object...)}
@param param1 the sole parameter
"""
if (isEnabled(Level.ERROR)) {
doLogf(Level.ERROR, FQCN, format, new Object[] { param1 }, t);
}
} | java | public void errorf(Throwable t, String format, Object param1) {
if (isEnabled(Level.ERROR)) {
doLogf(Level.ERROR, FQCN, format, new Object[] { param1 }, t);
}
} | [
"public",
"void",
"errorf",
"(",
"Throwable",
"t",
",",
"String",
"format",
",",
"Object",
"param1",
")",
"{",
"if",
"(",
"isEnabled",
"(",
"Level",
".",
"ERROR",
")",
")",
"{",
"doLogf",
"(",
"Level",
".",
"ERROR",
",",
"FQCN",
",",
"format",
",",
"new",
"Object",
"[",
"]",
"{",
"param1",
"}",
",",
"t",
")",
";",
"}",
"}"
]
| Issue a formatted log message with a level of ERROR.
@param t the throwable
@param format the format string, as per {@link String#format(String, Object...)}
@param param1 the sole parameter | [
"Issue",
"a",
"formatted",
"log",
"message",
"with",
"a",
"level",
"of",
"ERROR",
"."
]
| train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/jboss/logging/Logger.java#L1727-L1731 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslvserver_sslciphersuite_binding.java | sslvserver_sslciphersuite_binding.count_filtered | public static long count_filtered(nitro_service service, String vservername, String filter) throws Exception {
"""
Use this API to count the filtered set of sslvserver_sslciphersuite_binding resources.
filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
sslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();
obj.set_vservername(vservername);
options option = new options();
option.set_count(true);
option.set_filter(filter);
sslvserver_sslciphersuite_binding[] response = (sslvserver_sslciphersuite_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} | java | public static long count_filtered(nitro_service service, String vservername, String filter) throws Exception{
sslvserver_sslciphersuite_binding obj = new sslvserver_sslciphersuite_binding();
obj.set_vservername(vservername);
options option = new options();
option.set_count(true);
option.set_filter(filter);
sslvserver_sslciphersuite_binding[] response = (sslvserver_sslciphersuite_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} | [
"public",
"static",
"long",
"count_filtered",
"(",
"nitro_service",
"service",
",",
"String",
"vservername",
",",
"String",
"filter",
")",
"throws",
"Exception",
"{",
"sslvserver_sslciphersuite_binding",
"obj",
"=",
"new",
"sslvserver_sslciphersuite_binding",
"(",
")",
";",
"obj",
".",
"set_vservername",
"(",
"vservername",
")",
";",
"options",
"option",
"=",
"new",
"options",
"(",
")",
";",
"option",
".",
"set_count",
"(",
"true",
")",
";",
"option",
".",
"set_filter",
"(",
"filter",
")",
";",
"sslvserver_sslciphersuite_binding",
"[",
"]",
"response",
"=",
"(",
"sslvserver_sslciphersuite_binding",
"[",
"]",
")",
"obj",
".",
"getfiltered",
"(",
"service",
",",
"option",
")",
";",
"if",
"(",
"response",
"!=",
"null",
")",
"{",
"return",
"response",
"[",
"0",
"]",
".",
"__count",
";",
"}",
"return",
"0",
";",
"}"
]
| Use this API to count the filtered set of sslvserver_sslciphersuite_binding resources.
filter string should be in JSON format.eg: "port:80,servicetype:HTTP". | [
"Use",
"this",
"API",
"to",
"count",
"the",
"filtered",
"set",
"of",
"sslvserver_sslciphersuite_binding",
"resources",
".",
"filter",
"string",
"should",
"be",
"in",
"JSON",
"format",
".",
"eg",
":",
"port",
":",
"80",
"servicetype",
":",
"HTTP",
"."
]
| train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslvserver_sslciphersuite_binding.java#L225-L236 |
alkacon/opencms-core | src/org/opencms/file/collectors/CmsDefaultResourceCollector.java | CmsDefaultResourceCollector.allInFolderDateReleasedDesc | protected List<CmsResource> allInFolderDateReleasedDesc(CmsObject cms, String param, boolean tree, int numResults)
throws CmsException {
"""
Returns a List of all resources in the folder pointed to by the parameter
sorted by the release date, descending.<p>
@param cms the current CmsObject
@param param the folder name to use
@param tree if true, look in folder and all child folders, if false, look only in given folder
@param numResults the number of results
@return a List of all resources in the folder pointed to by the parameter
sorted by the release date, descending
@throws CmsException if something goes wrong
"""
CmsCollectorData data = new CmsCollectorData(param);
String foldername = CmsResource.getFolderPath(data.getFileName());
CmsResourceFilter filter = CmsResourceFilter.DEFAULT_FILES.addRequireType(data.getType()).addExcludeFlags(
CmsResource.FLAG_TEMPFILE);
if (data.isExcludeTimerange() && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// include all not yet released and expired resources in an offline project
filter = filter.addExcludeTimerange();
}
List<CmsResource> result = cms.readResources(foldername, filter, tree);
Collections.sort(result, I_CmsResource.COMPARE_DATE_RELEASED);
return shrinkToFit(result, data.getCount(), numResults);
} | java | protected List<CmsResource> allInFolderDateReleasedDesc(CmsObject cms, String param, boolean tree, int numResults)
throws CmsException {
CmsCollectorData data = new CmsCollectorData(param);
String foldername = CmsResource.getFolderPath(data.getFileName());
CmsResourceFilter filter = CmsResourceFilter.DEFAULT_FILES.addRequireType(data.getType()).addExcludeFlags(
CmsResource.FLAG_TEMPFILE);
if (data.isExcludeTimerange() && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
// include all not yet released and expired resources in an offline project
filter = filter.addExcludeTimerange();
}
List<CmsResource> result = cms.readResources(foldername, filter, tree);
Collections.sort(result, I_CmsResource.COMPARE_DATE_RELEASED);
return shrinkToFit(result, data.getCount(), numResults);
} | [
"protected",
"List",
"<",
"CmsResource",
">",
"allInFolderDateReleasedDesc",
"(",
"CmsObject",
"cms",
",",
"String",
"param",
",",
"boolean",
"tree",
",",
"int",
"numResults",
")",
"throws",
"CmsException",
"{",
"CmsCollectorData",
"data",
"=",
"new",
"CmsCollectorData",
"(",
"param",
")",
";",
"String",
"foldername",
"=",
"CmsResource",
".",
"getFolderPath",
"(",
"data",
".",
"getFileName",
"(",
")",
")",
";",
"CmsResourceFilter",
"filter",
"=",
"CmsResourceFilter",
".",
"DEFAULT_FILES",
".",
"addRequireType",
"(",
"data",
".",
"getType",
"(",
")",
")",
".",
"addExcludeFlags",
"(",
"CmsResource",
".",
"FLAG_TEMPFILE",
")",
";",
"if",
"(",
"data",
".",
"isExcludeTimerange",
"(",
")",
"&&",
"!",
"cms",
".",
"getRequestContext",
"(",
")",
".",
"getCurrentProject",
"(",
")",
".",
"isOnlineProject",
"(",
")",
")",
"{",
"// include all not yet released and expired resources in an offline project",
"filter",
"=",
"filter",
".",
"addExcludeTimerange",
"(",
")",
";",
"}",
"List",
"<",
"CmsResource",
">",
"result",
"=",
"cms",
".",
"readResources",
"(",
"foldername",
",",
"filter",
",",
"tree",
")",
";",
"Collections",
".",
"sort",
"(",
"result",
",",
"I_CmsResource",
".",
"COMPARE_DATE_RELEASED",
")",
";",
"return",
"shrinkToFit",
"(",
"result",
",",
"data",
".",
"getCount",
"(",
")",
",",
"numResults",
")",
";",
"}"
]
| Returns a List of all resources in the folder pointed to by the parameter
sorted by the release date, descending.<p>
@param cms the current CmsObject
@param param the folder name to use
@param tree if true, look in folder and all child folders, if false, look only in given folder
@param numResults the number of results
@return a List of all resources in the folder pointed to by the parameter
sorted by the release date, descending
@throws CmsException if something goes wrong | [
"Returns",
"a",
"List",
"of",
"all",
"resources",
"in",
"the",
"folder",
"pointed",
"to",
"by",
"the",
"parameter",
"sorted",
"by",
"the",
"release",
"date",
"descending",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/collectors/CmsDefaultResourceCollector.java#L225-L242 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonRead.java | GeoJsonRead.readGeoJson | public static void readGeoJson(Connection connection, String fileName, String tableReference) throws IOException, SQLException {
"""
Read the GeoJSON file.
@param connection
@param fileName
@param tableReference
@throws IOException
@throws SQLException
"""
GeoJsonDriverFunction gjdf = new GeoJsonDriverFunction();
gjdf.importFile(connection, tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor());
} | java | public static void readGeoJson(Connection connection, String fileName, String tableReference) throws IOException, SQLException {
GeoJsonDriverFunction gjdf = new GeoJsonDriverFunction();
gjdf.importFile(connection, tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor());
} | [
"public",
"static",
"void",
"readGeoJson",
"(",
"Connection",
"connection",
",",
"String",
"fileName",
",",
"String",
"tableReference",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"GeoJsonDriverFunction",
"gjdf",
"=",
"new",
"GeoJsonDriverFunction",
"(",
")",
";",
"gjdf",
".",
"importFile",
"(",
"connection",
",",
"tableReference",
",",
"URIUtilities",
".",
"fileFromString",
"(",
"fileName",
")",
",",
"new",
"EmptyProgressVisitor",
"(",
")",
")",
";",
"}"
]
| Read the GeoJSON file.
@param connection
@param fileName
@param tableReference
@throws IOException
@throws SQLException | [
"Read",
"the",
"GeoJSON",
"file",
"."
]
| train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonRead.java#L75-L78 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/NetworkSecurityGroupsInner.java | NetworkSecurityGroupsInner.createOrUpdate | public NetworkSecurityGroupInner createOrUpdate(String resourceGroupName, String networkSecurityGroupName, NetworkSecurityGroupInner parameters) {
"""
Creates or updates a network security group in the specified resource group.
@param resourceGroupName The name of the resource group.
@param networkSecurityGroupName The name of the network security group.
@param parameters Parameters supplied to the create or update network security group 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 NetworkSecurityGroupInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, parameters).toBlocking().last().body();
} | java | public NetworkSecurityGroupInner createOrUpdate(String resourceGroupName, String networkSecurityGroupName, NetworkSecurityGroupInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, parameters).toBlocking().last().body();
} | [
"public",
"NetworkSecurityGroupInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkSecurityGroupName",
",",
"NetworkSecurityGroupInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"networkSecurityGroupName",
",",
"parameters",
")",
".",
"toBlocking",
"(",
")",
".",
"last",
"(",
")",
".",
"body",
"(",
")",
";",
"}"
]
| Creates or updates a network security group in the specified resource group.
@param resourceGroupName The name of the resource group.
@param networkSecurityGroupName The name of the network security group.
@param parameters Parameters supplied to the create or update network security group 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 NetworkSecurityGroupInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"network",
"security",
"group",
"in",
"the",
"specified",
"resource",
"group",
"."
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/NetworkSecurityGroupsInner.java#L444-L446 |
apache/spark | core/src/main/java/org/apache/spark/memory/TaskMemoryManager.java | TaskMemoryManager.allocatePage | public MemoryBlock allocatePage(long size, MemoryConsumer consumer) {
"""
Allocate a block of memory that will be tracked in the MemoryManager's page table; this is
intended for allocating large blocks of Tungsten memory that will be shared between operators.
Returns `null` if there was not enough memory to allocate the page. May return a page that
contains fewer bytes than requested, so callers should verify the size of returned pages.
@throws TooLargePageException
"""
assert(consumer != null);
assert(consumer.getMode() == tungstenMemoryMode);
if (size > MAXIMUM_PAGE_SIZE_BYTES) {
throw new TooLargePageException(size);
}
long acquired = acquireExecutionMemory(size, consumer);
if (acquired <= 0) {
return null;
}
final int pageNumber;
synchronized (this) {
pageNumber = allocatedPages.nextClearBit(0);
if (pageNumber >= PAGE_TABLE_SIZE) {
releaseExecutionMemory(acquired, consumer);
throw new IllegalStateException(
"Have already allocated a maximum of " + PAGE_TABLE_SIZE + " pages");
}
allocatedPages.set(pageNumber);
}
MemoryBlock page = null;
try {
page = memoryManager.tungstenMemoryAllocator().allocate(acquired);
} catch (OutOfMemoryError e) {
logger.warn("Failed to allocate a page ({} bytes), try again.", acquired);
// there is no enough memory actually, it means the actual free memory is smaller than
// MemoryManager thought, we should keep the acquired memory.
synchronized (this) {
acquiredButNotUsed += acquired;
allocatedPages.clear(pageNumber);
}
// this could trigger spilling to free some pages.
return allocatePage(size, consumer);
}
page.pageNumber = pageNumber;
pageTable[pageNumber] = page;
if (logger.isTraceEnabled()) {
logger.trace("Allocate page number {} ({} bytes)", pageNumber, acquired);
}
return page;
} | java | public MemoryBlock allocatePage(long size, MemoryConsumer consumer) {
assert(consumer != null);
assert(consumer.getMode() == tungstenMemoryMode);
if (size > MAXIMUM_PAGE_SIZE_BYTES) {
throw new TooLargePageException(size);
}
long acquired = acquireExecutionMemory(size, consumer);
if (acquired <= 0) {
return null;
}
final int pageNumber;
synchronized (this) {
pageNumber = allocatedPages.nextClearBit(0);
if (pageNumber >= PAGE_TABLE_SIZE) {
releaseExecutionMemory(acquired, consumer);
throw new IllegalStateException(
"Have already allocated a maximum of " + PAGE_TABLE_SIZE + " pages");
}
allocatedPages.set(pageNumber);
}
MemoryBlock page = null;
try {
page = memoryManager.tungstenMemoryAllocator().allocate(acquired);
} catch (OutOfMemoryError e) {
logger.warn("Failed to allocate a page ({} bytes), try again.", acquired);
// there is no enough memory actually, it means the actual free memory is smaller than
// MemoryManager thought, we should keep the acquired memory.
synchronized (this) {
acquiredButNotUsed += acquired;
allocatedPages.clear(pageNumber);
}
// this could trigger spilling to free some pages.
return allocatePage(size, consumer);
}
page.pageNumber = pageNumber;
pageTable[pageNumber] = page;
if (logger.isTraceEnabled()) {
logger.trace("Allocate page number {} ({} bytes)", pageNumber, acquired);
}
return page;
} | [
"public",
"MemoryBlock",
"allocatePage",
"(",
"long",
"size",
",",
"MemoryConsumer",
"consumer",
")",
"{",
"assert",
"(",
"consumer",
"!=",
"null",
")",
";",
"assert",
"(",
"consumer",
".",
"getMode",
"(",
")",
"==",
"tungstenMemoryMode",
")",
";",
"if",
"(",
"size",
">",
"MAXIMUM_PAGE_SIZE_BYTES",
")",
"{",
"throw",
"new",
"TooLargePageException",
"(",
"size",
")",
";",
"}",
"long",
"acquired",
"=",
"acquireExecutionMemory",
"(",
"size",
",",
"consumer",
")",
";",
"if",
"(",
"acquired",
"<=",
"0",
")",
"{",
"return",
"null",
";",
"}",
"final",
"int",
"pageNumber",
";",
"synchronized",
"(",
"this",
")",
"{",
"pageNumber",
"=",
"allocatedPages",
".",
"nextClearBit",
"(",
"0",
")",
";",
"if",
"(",
"pageNumber",
">=",
"PAGE_TABLE_SIZE",
")",
"{",
"releaseExecutionMemory",
"(",
"acquired",
",",
"consumer",
")",
";",
"throw",
"new",
"IllegalStateException",
"(",
"\"Have already allocated a maximum of \"",
"+",
"PAGE_TABLE_SIZE",
"+",
"\" pages\"",
")",
";",
"}",
"allocatedPages",
".",
"set",
"(",
"pageNumber",
")",
";",
"}",
"MemoryBlock",
"page",
"=",
"null",
";",
"try",
"{",
"page",
"=",
"memoryManager",
".",
"tungstenMemoryAllocator",
"(",
")",
".",
"allocate",
"(",
"acquired",
")",
";",
"}",
"catch",
"(",
"OutOfMemoryError",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Failed to allocate a page ({} bytes), try again.\"",
",",
"acquired",
")",
";",
"// there is no enough memory actually, it means the actual free memory is smaller than",
"// MemoryManager thought, we should keep the acquired memory.",
"synchronized",
"(",
"this",
")",
"{",
"acquiredButNotUsed",
"+=",
"acquired",
";",
"allocatedPages",
".",
"clear",
"(",
"pageNumber",
")",
";",
"}",
"// this could trigger spilling to free some pages.",
"return",
"allocatePage",
"(",
"size",
",",
"consumer",
")",
";",
"}",
"page",
".",
"pageNumber",
"=",
"pageNumber",
";",
"pageTable",
"[",
"pageNumber",
"]",
"=",
"page",
";",
"if",
"(",
"logger",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"logger",
".",
"trace",
"(",
"\"Allocate page number {} ({} bytes)\"",
",",
"pageNumber",
",",
"acquired",
")",
";",
"}",
"return",
"page",
";",
"}"
]
| Allocate a block of memory that will be tracked in the MemoryManager's page table; this is
intended for allocating large blocks of Tungsten memory that will be shared between operators.
Returns `null` if there was not enough memory to allocate the page. May return a page that
contains fewer bytes than requested, so callers should verify the size of returned pages.
@throws TooLargePageException | [
"Allocate",
"a",
"block",
"of",
"memory",
"that",
"will",
"be",
"tracked",
"in",
"the",
"MemoryManager",
"s",
"page",
"table",
";",
"this",
"is",
"intended",
"for",
"allocating",
"large",
"blocks",
"of",
"Tungsten",
"memory",
"that",
"will",
"be",
"shared",
"between",
"operators",
"."
]
| train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/core/src/main/java/org/apache/spark/memory/TaskMemoryManager.java#L282-L324 |
cdapio/tigon | tigon-api/src/main/java/co/cask/tigon/internal/io/SchemaTypeAdapter.java | SchemaTypeAdapter.readInnerSchema | private Schema readInnerSchema(JsonReader reader, String key, Set<String> knownRecords) throws IOException {
"""
Constructs a {@link Schema} from the "key":"schema" pair.
@param reader The {@link JsonReader} for streaming json input tokens.
@param key The json property name that need to match.
@param knownRecords Set of record name already encountered during the reading.
@return A {@link Schema} object representing the schema of the json input.
@throws java.io.IOException When fails to construct a valid schema from the input.
"""
if (!key.equals(reader.nextName())) {
throw new IOException("Property \"" + key + "\" missing.");
}
return read(reader, knownRecords);
} | java | private Schema readInnerSchema(JsonReader reader, String key, Set<String> knownRecords) throws IOException {
if (!key.equals(reader.nextName())) {
throw new IOException("Property \"" + key + "\" missing.");
}
return read(reader, knownRecords);
} | [
"private",
"Schema",
"readInnerSchema",
"(",
"JsonReader",
"reader",
",",
"String",
"key",
",",
"Set",
"<",
"String",
">",
"knownRecords",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"key",
".",
"equals",
"(",
"reader",
".",
"nextName",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Property \\\"\"",
"+",
"key",
"+",
"\"\\\" missing.\"",
")",
";",
"}",
"return",
"read",
"(",
"reader",
",",
"knownRecords",
")",
";",
"}"
]
| Constructs a {@link Schema} from the "key":"schema" pair.
@param reader The {@link JsonReader} for streaming json input tokens.
@param key The json property name that need to match.
@param knownRecords Set of record name already encountered during the reading.
@return A {@link Schema} object representing the schema of the json input.
@throws java.io.IOException When fails to construct a valid schema from the input. | [
"Constructs",
"a",
"{",
"@link",
"Schema",
"}",
"from",
"the",
"key",
":",
"schema",
"pair",
"."
]
| train | https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-api/src/main/java/co/cask/tigon/internal/io/SchemaTypeAdapter.java#L228-L233 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/MethodUtils.java | MethodUtils.getMatchingAccessibleMethod | public static Method getMatchingAccessibleMethod(Class<?> clazz, String methodName, Class<?>[] paramTypes) {
"""
<p>Find an accessible method that matches the given name and has compatible parameters.
Compatible parameters mean that every method parameter is assignable from
the given parameters.
In other words, it finds a method with the given name
that will take the parameters given.
<p>This method is slightly undeterminstic since it loops
through methods names and return the first matching method.</p>
<p>This method can match primitive parameter by passing in wrapper classes.
For example, a {@code Boolean} will match a primitive {@code boolean}
parameter.
@param clazz find method in this class
@param methodName find method with this name
@param paramTypes find method with compatible parameters
@return the accessible method
"""
return getMatchingAccessibleMethod(clazz, methodName, null, paramTypes);
} | java | public static Method getMatchingAccessibleMethod(Class<?> clazz, String methodName, Class<?>[] paramTypes) {
return getMatchingAccessibleMethod(clazz, methodName, null, paramTypes);
} | [
"public",
"static",
"Method",
"getMatchingAccessibleMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"paramTypes",
")",
"{",
"return",
"getMatchingAccessibleMethod",
"(",
"clazz",
",",
"methodName",
",",
"null",
",",
"paramTypes",
")",
";",
"}"
]
| <p>Find an accessible method that matches the given name and has compatible parameters.
Compatible parameters mean that every method parameter is assignable from
the given parameters.
In other words, it finds a method with the given name
that will take the parameters given.
<p>This method is slightly undeterminstic since it loops
through methods names and return the first matching method.</p>
<p>This method can match primitive parameter by passing in wrapper classes.
For example, a {@code Boolean} will match a primitive {@code boolean}
parameter.
@param clazz find method in this class
@param methodName find method with this name
@param paramTypes find method with compatible parameters
@return the accessible method | [
"<p",
">",
"Find",
"an",
"accessible",
"method",
"that",
"matches",
"the",
"given",
"name",
"and",
"has",
"compatible",
"parameters",
".",
"Compatible",
"parameters",
"mean",
"that",
"every",
"method",
"parameter",
"is",
"assignable",
"from",
"the",
"given",
"parameters",
".",
"In",
"other",
"words",
"it",
"finds",
"a",
"method",
"with",
"the",
"given",
"name",
"that",
"will",
"take",
"the",
"parameters",
"given",
"."
]
| train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/MethodUtils.java#L904-L906 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java | ClientFactory.acceptSessionFromEntityPath | public static IMessageSession acceptSessionFromEntityPath(MessagingFactory messagingFactory, String entityPath, String sessionId, ReceiveMode receiveMode) throws InterruptedException, ServiceBusException {
"""
Accept a {@link IMessageSession} from service bus using the client settings with specified session id. Session Id can be null, if null, service will return the first available session.
@param messagingFactory messaging factory (which represents a connection) on which the session receiver needs to be created.
@param entityPath path of entity
@param sessionId session id, if null, service will return the first available session, otherwise, service will return specified session
@param receiveMode PeekLock or ReceiveAndDelete
@return IMessageSession instance
@throws InterruptedException if the current thread was interrupted while waiting
@throws ServiceBusException if the session cannot be accepted
"""
return Utils.completeFuture(acceptSessionFromEntityPathAsync(messagingFactory, entityPath, sessionId, receiveMode));
} | java | public static IMessageSession acceptSessionFromEntityPath(MessagingFactory messagingFactory, String entityPath, String sessionId, ReceiveMode receiveMode) throws InterruptedException, ServiceBusException {
return Utils.completeFuture(acceptSessionFromEntityPathAsync(messagingFactory, entityPath, sessionId, receiveMode));
} | [
"public",
"static",
"IMessageSession",
"acceptSessionFromEntityPath",
"(",
"MessagingFactory",
"messagingFactory",
",",
"String",
"entityPath",
",",
"String",
"sessionId",
",",
"ReceiveMode",
"receiveMode",
")",
"throws",
"InterruptedException",
",",
"ServiceBusException",
"{",
"return",
"Utils",
".",
"completeFuture",
"(",
"acceptSessionFromEntityPathAsync",
"(",
"messagingFactory",
",",
"entityPath",
",",
"sessionId",
",",
"receiveMode",
")",
")",
";",
"}"
]
| Accept a {@link IMessageSession} from service bus using the client settings with specified session id. Session Id can be null, if null, service will return the first available session.
@param messagingFactory messaging factory (which represents a connection) on which the session receiver needs to be created.
@param entityPath path of entity
@param sessionId session id, if null, service will return the first available session, otherwise, service will return specified session
@param receiveMode PeekLock or ReceiveAndDelete
@return IMessageSession instance
@throws InterruptedException if the current thread was interrupted while waiting
@throws ServiceBusException if the session cannot be accepted | [
"Accept",
"a",
"{"
]
| train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L611-L613 |
gresrun/jesque | src/main/java/net/greghaines/jesque/utils/JesqueUtils.java | JesqueUtils.addCauseToBacktrace | private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {
"""
Add a cause to the backtrace.
@param cause
the cause
@param bTrace
the backtrace list
"""
if (cause.getMessage() == null) {
bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());
} else {
bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + ": " + cause.getMessage());
}
for (final StackTraceElement ste : cause.getStackTrace()) {
bTrace.add(BT_PREFIX + ste.toString());
}
if (cause.getCause() != null) {
addCauseToBacktrace(cause.getCause(), bTrace);
}
} | java | private static void addCauseToBacktrace(final Throwable cause, final List<String> bTrace) {
if (cause.getMessage() == null) {
bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName());
} else {
bTrace.add(BT_CAUSED_BY_PREFIX + cause.getClass().getName() + ": " + cause.getMessage());
}
for (final StackTraceElement ste : cause.getStackTrace()) {
bTrace.add(BT_PREFIX + ste.toString());
}
if (cause.getCause() != null) {
addCauseToBacktrace(cause.getCause(), bTrace);
}
} | [
"private",
"static",
"void",
"addCauseToBacktrace",
"(",
"final",
"Throwable",
"cause",
",",
"final",
"List",
"<",
"String",
">",
"bTrace",
")",
"{",
"if",
"(",
"cause",
".",
"getMessage",
"(",
")",
"==",
"null",
")",
"{",
"bTrace",
".",
"add",
"(",
"BT_CAUSED_BY_PREFIX",
"+",
"cause",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"else",
"{",
"bTrace",
".",
"add",
"(",
"BT_CAUSED_BY_PREFIX",
"+",
"cause",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\": \"",
"+",
"cause",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"for",
"(",
"final",
"StackTraceElement",
"ste",
":",
"cause",
".",
"getStackTrace",
"(",
")",
")",
"{",
"bTrace",
".",
"add",
"(",
"BT_PREFIX",
"+",
"ste",
".",
"toString",
"(",
")",
")",
";",
"}",
"if",
"(",
"cause",
".",
"getCause",
"(",
")",
"!=",
"null",
")",
"{",
"addCauseToBacktrace",
"(",
"cause",
".",
"getCause",
"(",
")",
",",
"bTrace",
")",
";",
"}",
"}"
]
| Add a cause to the backtrace.
@param cause
the cause
@param bTrace
the backtrace list | [
"Add",
"a",
"cause",
"to",
"the",
"backtrace",
"."
]
| train | https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/utils/JesqueUtils.java#L150-L162 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java | CPDefinitionLinkPersistenceImpl.findAll | @Override
public List<CPDefinitionLink> findAll() {
"""
Returns all the cp definition links.
@return the cp definition links
"""
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CPDefinitionLink> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDefinitionLink",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
]
| Returns all the cp definition links.
@return the cp definition links | [
"Returns",
"all",
"the",
"cp",
"definition",
"links",
"."
]
| train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java#L4721-L4724 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java | XmlUtil.toFile | public static void toFile(Document doc, String path, String charset) {
"""
将XML文档写入到文件<br>
@param doc XML文档
@param path 文件路径绝对路径或相对ClassPath路径,不存在会自动创建
@param charset 自定义XML文件的编码,如果为{@code null} 读取XML文档中的编码,否则默认UTF-8
"""
if (StrUtil.isBlank(charset)) {
charset = doc.getXmlEncoding();
}
if (StrUtil.isBlank(charset)) {
charset = CharsetUtil.UTF_8;
}
BufferedWriter writer = null;
try {
writer = FileUtil.getWriter(path, charset, false);
write(doc, writer, charset, INDENT_DEFAULT);
} finally {
IoUtil.close(writer);
}
} | java | public static void toFile(Document doc, String path, String charset) {
if (StrUtil.isBlank(charset)) {
charset = doc.getXmlEncoding();
}
if (StrUtil.isBlank(charset)) {
charset = CharsetUtil.UTF_8;
}
BufferedWriter writer = null;
try {
writer = FileUtil.getWriter(path, charset, false);
write(doc, writer, charset, INDENT_DEFAULT);
} finally {
IoUtil.close(writer);
}
} | [
"public",
"static",
"void",
"toFile",
"(",
"Document",
"doc",
",",
"String",
"path",
",",
"String",
"charset",
")",
"{",
"if",
"(",
"StrUtil",
".",
"isBlank",
"(",
"charset",
")",
")",
"{",
"charset",
"=",
"doc",
".",
"getXmlEncoding",
"(",
")",
";",
"}",
"if",
"(",
"StrUtil",
".",
"isBlank",
"(",
"charset",
")",
")",
"{",
"charset",
"=",
"CharsetUtil",
".",
"UTF_8",
";",
"}",
"BufferedWriter",
"writer",
"=",
"null",
";",
"try",
"{",
"writer",
"=",
"FileUtil",
".",
"getWriter",
"(",
"path",
",",
"charset",
",",
"false",
")",
";",
"write",
"(",
"doc",
",",
"writer",
",",
"charset",
",",
"INDENT_DEFAULT",
")",
";",
"}",
"finally",
"{",
"IoUtil",
".",
"close",
"(",
"writer",
")",
";",
"}",
"}"
]
| 将XML文档写入到文件<br>
@param doc XML文档
@param path 文件路径绝对路径或相对ClassPath路径,不存在会自动创建
@param charset 自定义XML文件的编码,如果为{@code null} 读取XML文档中的编码,否则默认UTF-8 | [
"将XML文档写入到文件<br",
">"
]
| train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java#L298-L313 |
alkacon/opencms-core | src-gwt/org/opencms/ade/galleries/client/CmsGalleryControllerHandler.java | CmsGalleryControllerHandler.setCategoriesTabContent | public void setCategoriesTabContent(List<CmsCategoryTreeEntry> categoryRoot, List<String> selected) {
"""
Sets the list content of the category tab.<p>
@param categoryRoot the root category tree entry
@param selected the selected categories
"""
m_galleryDialog.getCategoriesTab().fillContent(categoryRoot, selected);
} | java | public void setCategoriesTabContent(List<CmsCategoryTreeEntry> categoryRoot, List<String> selected) {
m_galleryDialog.getCategoriesTab().fillContent(categoryRoot, selected);
} | [
"public",
"void",
"setCategoriesTabContent",
"(",
"List",
"<",
"CmsCategoryTreeEntry",
">",
"categoryRoot",
",",
"List",
"<",
"String",
">",
"selected",
")",
"{",
"m_galleryDialog",
".",
"getCategoriesTab",
"(",
")",
".",
"fillContent",
"(",
"categoryRoot",
",",
"selected",
")",
";",
"}"
]
| Sets the list content of the category tab.<p>
@param categoryRoot the root category tree entry
@param selected the selected categories | [
"Sets",
"the",
"list",
"content",
"of",
"the",
"category",
"tab",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/CmsGalleryControllerHandler.java#L438-L441 |
couchbase/couchbase-lite-java-core | src/main/java/com/couchbase/lite/Query.java | Query.run | @InterfaceAudience.Public
public QueryEnumerator run() throws CouchbaseLiteException {
"""
Sends the query to the server and returns an enumerator over the result rows (Synchronous).
If the query fails, this method returns nil and sets the query's .error property.
"""
List<Long> outSequence = new ArrayList<Long>();
String viewName = (view != null) ? view.getName() : null;
List<QueryRow> rows = database.queryViewNamed(viewName, getQueryOptions(), outSequence);
lastSequence = outSequence.get(0);
return new QueryEnumerator(database, rows, lastSequence);
} | java | @InterfaceAudience.Public
public QueryEnumerator run() throws CouchbaseLiteException {
List<Long> outSequence = new ArrayList<Long>();
String viewName = (view != null) ? view.getName() : null;
List<QueryRow> rows = database.queryViewNamed(viewName, getQueryOptions(), outSequence);
lastSequence = outSequence.get(0);
return new QueryEnumerator(database, rows, lastSequence);
} | [
"@",
"InterfaceAudience",
".",
"Public",
"public",
"QueryEnumerator",
"run",
"(",
")",
"throws",
"CouchbaseLiteException",
"{",
"List",
"<",
"Long",
">",
"outSequence",
"=",
"new",
"ArrayList",
"<",
"Long",
">",
"(",
")",
";",
"String",
"viewName",
"=",
"(",
"view",
"!=",
"null",
")",
"?",
"view",
".",
"getName",
"(",
")",
":",
"null",
";",
"List",
"<",
"QueryRow",
">",
"rows",
"=",
"database",
".",
"queryViewNamed",
"(",
"viewName",
",",
"getQueryOptions",
"(",
")",
",",
"outSequence",
")",
";",
"lastSequence",
"=",
"outSequence",
".",
"get",
"(",
"0",
")",
";",
"return",
"new",
"QueryEnumerator",
"(",
"database",
",",
"rows",
",",
"lastSequence",
")",
";",
"}"
]
| Sends the query to the server and returns an enumerator over the result rows (Synchronous).
If the query fails, this method returns nil and sets the query's .error property. | [
"Sends",
"the",
"query",
"to",
"the",
"server",
"and",
"returns",
"an",
"enumerator",
"over",
"the",
"result",
"rows",
"(",
"Synchronous",
")",
".",
"If",
"the",
"query",
"fails",
"this",
"method",
"returns",
"nil",
"and",
"sets",
"the",
"query",
"s",
".",
"error",
"property",
"."
]
| train | https://github.com/couchbase/couchbase-lite-java-core/blob/3b275642e2d2f231fd155ad9def9c5e9eff3118e/src/main/java/com/couchbase/lite/Query.java#L442-L449 |
exoplatform/jcr | exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/Utils.java | Utils.getGroupIds | GroupIds getGroupIds(Node groupNode) throws RepositoryException {
"""
Evaluate the group identifier and parent group identifier based on group node path.
"""
String storagePath = getGroupStoragePath();
String nodePath = groupNode.getPath();
String groupId = nodePath.substring(storagePath.length());
String parentId = groupId.substring(0, groupId.lastIndexOf("/"));
return new GroupIds(groupId, parentId);
} | java | GroupIds getGroupIds(Node groupNode) throws RepositoryException
{
String storagePath = getGroupStoragePath();
String nodePath = groupNode.getPath();
String groupId = nodePath.substring(storagePath.length());
String parentId = groupId.substring(0, groupId.lastIndexOf("/"));
return new GroupIds(groupId, parentId);
} | [
"GroupIds",
"getGroupIds",
"(",
"Node",
"groupNode",
")",
"throws",
"RepositoryException",
"{",
"String",
"storagePath",
"=",
"getGroupStoragePath",
"(",
")",
";",
"String",
"nodePath",
"=",
"groupNode",
".",
"getPath",
"(",
")",
";",
"String",
"groupId",
"=",
"nodePath",
".",
"substring",
"(",
"storagePath",
".",
"length",
"(",
")",
")",
";",
"String",
"parentId",
"=",
"groupId",
".",
"substring",
"(",
"0",
",",
"groupId",
".",
"lastIndexOf",
"(",
"\"/\"",
")",
")",
";",
"return",
"new",
"GroupIds",
"(",
"groupId",
",",
"parentId",
")",
";",
"}"
]
| Evaluate the group identifier and parent group identifier based on group node path. | [
"Evaluate",
"the",
"group",
"identifier",
"and",
"parent",
"group",
"identifier",
"based",
"on",
"group",
"node",
"path",
"."
]
| train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/Utils.java#L219-L228 |
fuinorg/objects4j | src/main/java/org/fuin/objects4j/vo/CurrencyAmount.java | CurrencyAmount.strToAmount | public static BigDecimal strToAmount(@CurrencyAmountStr final String amount) {
"""
Converts an amount from it's canonical string representation back into a big decimal. A <code>null</code> argument will return
<code>null</code>.
@param amount
Amount string to convert.
@return String as big decimal.
"""
if (amount == null) {
return null;
}
final int dot = amount.indexOf('.');
final int scale;
final String unscaledStr;
if (dot == -1) {
scale = 0;
unscaledStr = amount;
} else {
scale = amount.length() - dot - 1;
unscaledStr = amount.substring(0, dot) + amount.substring(dot + 1);
}
final BigInteger unscaled = new BigInteger(unscaledStr);
return new BigDecimal(unscaled, scale);
} | java | public static BigDecimal strToAmount(@CurrencyAmountStr final String amount) {
if (amount == null) {
return null;
}
final int dot = amount.indexOf('.');
final int scale;
final String unscaledStr;
if (dot == -1) {
scale = 0;
unscaledStr = amount;
} else {
scale = amount.length() - dot - 1;
unscaledStr = amount.substring(0, dot) + amount.substring(dot + 1);
}
final BigInteger unscaled = new BigInteger(unscaledStr);
return new BigDecimal(unscaled, scale);
} | [
"public",
"static",
"BigDecimal",
"strToAmount",
"(",
"@",
"CurrencyAmountStr",
"final",
"String",
"amount",
")",
"{",
"if",
"(",
"amount",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"int",
"dot",
"=",
"amount",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"final",
"int",
"scale",
";",
"final",
"String",
"unscaledStr",
";",
"if",
"(",
"dot",
"==",
"-",
"1",
")",
"{",
"scale",
"=",
"0",
";",
"unscaledStr",
"=",
"amount",
";",
"}",
"else",
"{",
"scale",
"=",
"amount",
".",
"length",
"(",
")",
"-",
"dot",
"-",
"1",
";",
"unscaledStr",
"=",
"amount",
".",
"substring",
"(",
"0",
",",
"dot",
")",
"+",
"amount",
".",
"substring",
"(",
"dot",
"+",
"1",
")",
";",
"}",
"final",
"BigInteger",
"unscaled",
"=",
"new",
"BigInteger",
"(",
"unscaledStr",
")",
";",
"return",
"new",
"BigDecimal",
"(",
"unscaled",
",",
"scale",
")",
";",
"}"
]
| Converts an amount from it's canonical string representation back into a big decimal. A <code>null</code> argument will return
<code>null</code>.
@param amount
Amount string to convert.
@return String as big decimal. | [
"Converts",
"an",
"amount",
"from",
"it",
"s",
"canonical",
"string",
"representation",
"back",
"into",
"a",
"big",
"decimal",
".",
"A",
"<code",
">",
"null<",
"/",
"code",
">",
"argument",
"will",
"return",
"<code",
">",
"null<",
"/",
"code",
">",
"."
]
| train | https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/CurrencyAmount.java#L225-L241 |
alkacon/opencms-core | src/org/opencms/ugc/CmsUgcSession.java | CmsUgcSession.addContentValue | protected void addContentValue(CmsXmlContent content, Locale locale, String path, String value) {
"""
Adds the given value to the content document.<p>
@param content the content document
@param locale the content locale
@param path the value XPath
@param value the value
"""
boolean hasValue = content.hasValue(path, locale);
if (!hasValue) {
String[] pathElements = path.split("/");
String currentPath = pathElements[0];
for (int i = 0; i < pathElements.length; i++) {
if (i > 0) {
currentPath = CmsStringUtil.joinPaths(currentPath, pathElements[i]);
}
while (!content.hasValue(currentPath, locale)) {
content.addValue(m_cms, currentPath, locale, CmsXmlUtils.getXpathIndexInt(currentPath) - 1);
}
}
}
content.getValue(path, locale).setStringValue(m_cms, value);
} | java | protected void addContentValue(CmsXmlContent content, Locale locale, String path, String value) {
boolean hasValue = content.hasValue(path, locale);
if (!hasValue) {
String[] pathElements = path.split("/");
String currentPath = pathElements[0];
for (int i = 0; i < pathElements.length; i++) {
if (i > 0) {
currentPath = CmsStringUtil.joinPaths(currentPath, pathElements[i]);
}
while (!content.hasValue(currentPath, locale)) {
content.addValue(m_cms, currentPath, locale, CmsXmlUtils.getXpathIndexInt(currentPath) - 1);
}
}
}
content.getValue(path, locale).setStringValue(m_cms, value);
} | [
"protected",
"void",
"addContentValue",
"(",
"CmsXmlContent",
"content",
",",
"Locale",
"locale",
",",
"String",
"path",
",",
"String",
"value",
")",
"{",
"boolean",
"hasValue",
"=",
"content",
".",
"hasValue",
"(",
"path",
",",
"locale",
")",
";",
"if",
"(",
"!",
"hasValue",
")",
"{",
"String",
"[",
"]",
"pathElements",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
";",
"String",
"currentPath",
"=",
"pathElements",
"[",
"0",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"pathElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"currentPath",
"=",
"CmsStringUtil",
".",
"joinPaths",
"(",
"currentPath",
",",
"pathElements",
"[",
"i",
"]",
")",
";",
"}",
"while",
"(",
"!",
"content",
".",
"hasValue",
"(",
"currentPath",
",",
"locale",
")",
")",
"{",
"content",
".",
"addValue",
"(",
"m_cms",
",",
"currentPath",
",",
"locale",
",",
"CmsXmlUtils",
".",
"getXpathIndexInt",
"(",
"currentPath",
")",
"-",
"1",
")",
";",
"}",
"}",
"}",
"content",
".",
"getValue",
"(",
"path",
",",
"locale",
")",
".",
"setStringValue",
"(",
"m_cms",
",",
"value",
")",
";",
"}"
]
| Adds the given value to the content document.<p>
@param content the content document
@param locale the content locale
@param path the value XPath
@param value the value | [
"Adds",
"the",
"given",
"value",
"to",
"the",
"content",
"document",
".",
"<p",
">"
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcSession.java#L550-L567 |
finmath/finmath-lib | src/main/java6/net/finmath/time/ScheduleGenerator.java | ScheduleGenerator.createDateFromDateAndOffset | private static LocalDate createDateFromDateAndOffset(LocalDate baseDate, double offsetYearFrac) {
"""
Create a new date by "adding" a year fraction to the start date.
The year fraction is interpreted in a 30/360 way. More specifically,
every integer unit advances by a year, each remaining fraction of 12
advances by a month and each remaining fraction of 30 advances a day.
The function may be used to ease the creation of maturities in spreadsheets.
@param baseDate The start date.
@param offsetYearFrac The year fraction in 30/360 to be used for adding to the start date.
@return A date corresponding the maturity.
"""
// Years
LocalDate maturity = baseDate.plusYears((int)offsetYearFrac);
// Months
offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 12;
maturity = maturity.plusMonths((int)offsetYearFrac);
// Days
offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 30;
maturity = maturity.plusDays((int)Math.round(offsetYearFrac));
return maturity;
} | java | private static LocalDate createDateFromDateAndOffset(LocalDate baseDate, double offsetYearFrac) {
// Years
LocalDate maturity = baseDate.plusYears((int)offsetYearFrac);
// Months
offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 12;
maturity = maturity.plusMonths((int)offsetYearFrac);
// Days
offsetYearFrac = (offsetYearFrac - (int)offsetYearFrac) * 30;
maturity = maturity.plusDays((int)Math.round(offsetYearFrac));
return maturity;
} | [
"private",
"static",
"LocalDate",
"createDateFromDateAndOffset",
"(",
"LocalDate",
"baseDate",
",",
"double",
"offsetYearFrac",
")",
"{",
"// Years",
"LocalDate",
"maturity",
"=",
"baseDate",
".",
"plusYears",
"(",
"(",
"int",
")",
"offsetYearFrac",
")",
";",
"// Months",
"offsetYearFrac",
"=",
"(",
"offsetYearFrac",
"-",
"(",
"int",
")",
"offsetYearFrac",
")",
"*",
"12",
";",
"maturity",
"=",
"maturity",
".",
"plusMonths",
"(",
"(",
"int",
")",
"offsetYearFrac",
")",
";",
"// Days",
"offsetYearFrac",
"=",
"(",
"offsetYearFrac",
"-",
"(",
"int",
")",
"offsetYearFrac",
")",
"*",
"30",
";",
"maturity",
"=",
"maturity",
".",
"plusDays",
"(",
"(",
"int",
")",
"Math",
".",
"round",
"(",
"offsetYearFrac",
")",
")",
";",
"return",
"maturity",
";",
"}"
]
| Create a new date by "adding" a year fraction to the start date.
The year fraction is interpreted in a 30/360 way. More specifically,
every integer unit advances by a year, each remaining fraction of 12
advances by a month and each remaining fraction of 30 advances a day.
The function may be used to ease the creation of maturities in spreadsheets.
@param baseDate The start date.
@param offsetYearFrac The year fraction in 30/360 to be used for adding to the start date.
@return A date corresponding the maturity. | [
"Create",
"a",
"new",
"date",
"by",
"adding",
"a",
"year",
"fraction",
"to",
"the",
"start",
"date",
".",
"The",
"year",
"fraction",
"is",
"interpreted",
"in",
"a",
"30",
"/",
"360",
"way",
".",
"More",
"specifically",
"every",
"integer",
"unit",
"advances",
"by",
"a",
"year",
"each",
"remaining",
"fraction",
"of",
"12",
"advances",
"by",
"a",
"month",
"and",
"each",
"remaining",
"fraction",
"of",
"30",
"advances",
"a",
"day",
"."
]
| train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/time/ScheduleGenerator.java#L824-L838 |
upwork/java-upwork | src/com/Upwork/api/OAuthClient.java | OAuthClient.sendPostRequest | private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException {
"""
Send signed POST OAuth request
@param url Relative URL
@param type Type of HTTP request (HTTP method)
@param params Hash of parameters
@throws JSONException If JSON object is invalid or request was abnormal
@return {@link JSONObject} JSON Object that contains data from response
"""
String fullUrl = getFullUrl(url);
HttpPost request = new HttpPost(fullUrl);
switch(type) {
case METHOD_PUT:
case METHOD_DELETE:
// assign overload value
String oValue;
if (type == METHOD_PUT) {
oValue = "put";
} else {
oValue = "delete";
}
params.put(OVERLOAD_PARAM, oValue);
case METHOD_POST:
break;
default:
throw new RuntimeException("Wrong http method requested");
}
// doing post request using json to avoid issue with urlencoded symbols
JSONObject json = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
request.setHeader("Content-Type", "application/json");
try {
request.setEntity(new StringEntity(json.toString()));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// sign request
try {
mOAuthConsumer.sign(request);
}
catch (OAuthException e) {
e.printStackTrace();
}
return UpworkRestClient.getJSONObject(request, type, params);
} | java | private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException {
String fullUrl = getFullUrl(url);
HttpPost request = new HttpPost(fullUrl);
switch(type) {
case METHOD_PUT:
case METHOD_DELETE:
// assign overload value
String oValue;
if (type == METHOD_PUT) {
oValue = "put";
} else {
oValue = "delete";
}
params.put(OVERLOAD_PARAM, oValue);
case METHOD_POST:
break;
default:
throw new RuntimeException("Wrong http method requested");
}
// doing post request using json to avoid issue with urlencoded symbols
JSONObject json = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
request.setHeader("Content-Type", "application/json");
try {
request.setEntity(new StringEntity(json.toString()));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// sign request
try {
mOAuthConsumer.sign(request);
}
catch (OAuthException e) {
e.printStackTrace();
}
return UpworkRestClient.getJSONObject(request, type, params);
} | [
"private",
"JSONObject",
"sendPostRequest",
"(",
"String",
"url",
",",
"Integer",
"type",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"params",
")",
"throws",
"JSONException",
"{",
"String",
"fullUrl",
"=",
"getFullUrl",
"(",
"url",
")",
";",
"HttpPost",
"request",
"=",
"new",
"HttpPost",
"(",
"fullUrl",
")",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"METHOD_PUT",
":",
"case",
"METHOD_DELETE",
":",
"// assign overload value",
"String",
"oValue",
";",
"if",
"(",
"type",
"==",
"METHOD_PUT",
")",
"{",
"oValue",
"=",
"\"put\"",
";",
"}",
"else",
"{",
"oValue",
"=",
"\"delete\"",
";",
"}",
"params",
".",
"put",
"(",
"OVERLOAD_PARAM",
",",
"oValue",
")",
";",
"case",
"METHOD_POST",
":",
"break",
";",
"default",
":",
"throw",
"new",
"RuntimeException",
"(",
"\"Wrong http method requested\"",
")",
";",
"}",
"// doing post request using json to avoid issue with urlencoded symbols",
"JSONObject",
"json",
"=",
"new",
"JSONObject",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"params",
".",
"entrySet",
"(",
")",
")",
"{",
"json",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"request",
".",
"setHeader",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
";",
"try",
"{",
"request",
".",
"setEntity",
"(",
"new",
"StringEntity",
"(",
"json",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e1",
")",
"{",
"// TODO Auto-generated catch block",
"e1",
".",
"printStackTrace",
"(",
")",
";",
"}",
"// sign request",
"try",
"{",
"mOAuthConsumer",
".",
"sign",
"(",
"request",
")",
";",
"}",
"catch",
"(",
"OAuthException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"return",
"UpworkRestClient",
".",
"getJSONObject",
"(",
"request",
",",
"type",
",",
"params",
")",
";",
"}"
]
| Send signed POST OAuth request
@param url Relative URL
@param type Type of HTTP request (HTTP method)
@param params Hash of parameters
@throws JSONException If JSON object is invalid or request was abnormal
@return {@link JSONObject} JSON Object that contains data from response | [
"Send",
"signed",
"POST",
"OAuth",
"request"
]
| train | https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/OAuthClient.java#L323-L368 |
jhunters/jprotobuf | android/src/main/java/com/baidu/bjf/remoting/protobuf/utils/StringUtils.java | StringUtils.removeEndIgnoreCase | public static String removeEndIgnoreCase(String str, String remove) {
"""
<p>
Case insensitive removal of a substring if it is at the end of a source
string, otherwise returns the source string.
</p>
<p>
A <code>null</code> source string will return <code>null</code>. An empty
("") source string will return the empty string. A <code>null</code>
search string will return the source string.
</p>
<pre>
StringUtils.removeEnd(null, *) = null
StringUtils.removeEnd("", *) = ""
StringUtils.removeEnd(*, null) = *
StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com."
StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param remove
the String to search for (case insensitive) and remove, may be
null
@return the substring with the string removed if found, <code>null</code>
if null String input
@since 2.4
"""
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (endsWithIgnoreCase(str, remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
} | java | public static String removeEndIgnoreCase(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (endsWithIgnoreCase(str, remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
} | [
"public",
"static",
"String",
"removeEndIgnoreCase",
"(",
"String",
"str",
",",
"String",
"remove",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"str",
")",
"||",
"isEmpty",
"(",
"remove",
")",
")",
"{",
"return",
"str",
";",
"}",
"if",
"(",
"endsWithIgnoreCase",
"(",
"str",
",",
"remove",
")",
")",
"{",
"return",
"str",
".",
"substring",
"(",
"0",
",",
"str",
".",
"length",
"(",
")",
"-",
"remove",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"str",
";",
"}"
]
| <p>
Case insensitive removal of a substring if it is at the end of a source
string, otherwise returns the source string.
</p>
<p>
A <code>null</code> source string will return <code>null</code>. An empty
("") source string will return the empty string. A <code>null</code>
search string will return the source string.
</p>
<pre>
StringUtils.removeEnd(null, *) = null
StringUtils.removeEnd("", *) = ""
StringUtils.removeEnd(*, null) = *
StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com."
StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param remove
the String to search for (case insensitive) and remove, may be
null
@return the substring with the string removed if found, <code>null</code>
if null String input
@since 2.4 | [
"<p",
">",
"Case",
"insensitive",
"removal",
"of",
"a",
"substring",
"if",
"it",
"is",
"at",
"the",
"end",
"of",
"a",
"source",
"string",
"otherwise",
"returns",
"the",
"source",
"string",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/android/src/main/java/com/baidu/bjf/remoting/protobuf/utils/StringUtils.java#L199-L207 |
OpenLiberty/open-liberty | dev/wlp.lib.extract/src/wlp/lib/extract/SelfExtractRun.java | SelfExtractRun.disable2PC | private static void disable2PC(String extractDirectory, String serverName) throws IOException {
"""
Write property into jvm.options to disable 2PC transactions.
2PC transactions are disabled by default because default transaction
log is stored in extract directory and therefore foils transaction
recovery if the server terminates unexpectedly.
@param extractDirectory
@param serverName
@throws IOException
"""
String fileName = extractDirectory + File.separator + "wlp" + File.separator + "usr" + File.separator + "servers" + File.separator + serverName + File.separator
+ "jvm.options";
BufferedReader br = null;
BufferedWriter bw = null;
StringBuffer sb = new StringBuffer();
try {
String sCurrentLine;
File file = new File(fileName);
// if file doesnt exists, then create it
if (!file.exists()) {
boolean success = file.createNewFile();
if (!success) {
throw new IOException("Failed to create file " + fileName);
}
} else {
// read existing file content
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine + "\n");
}
}
// write property to disable 2PC commit
String content = "-Dcom.ibm.tx.jta.disable2PC=true";
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()), "UTF-8"));
bw.write(sb.toString());
bw.write(content);
} finally {
if (br != null)
br.close();
if (bw != null)
bw.close();
}
} | java | private static void disable2PC(String extractDirectory, String serverName) throws IOException {
String fileName = extractDirectory + File.separator + "wlp" + File.separator + "usr" + File.separator + "servers" + File.separator + serverName + File.separator
+ "jvm.options";
BufferedReader br = null;
BufferedWriter bw = null;
StringBuffer sb = new StringBuffer();
try {
String sCurrentLine;
File file = new File(fileName);
// if file doesnt exists, then create it
if (!file.exists()) {
boolean success = file.createNewFile();
if (!success) {
throw new IOException("Failed to create file " + fileName);
}
} else {
// read existing file content
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine + "\n");
}
}
// write property to disable 2PC commit
String content = "-Dcom.ibm.tx.jta.disable2PC=true";
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()), "UTF-8"));
bw.write(sb.toString());
bw.write(content);
} finally {
if (br != null)
br.close();
if (bw != null)
bw.close();
}
} | [
"private",
"static",
"void",
"disable2PC",
"(",
"String",
"extractDirectory",
",",
"String",
"serverName",
")",
"throws",
"IOException",
"{",
"String",
"fileName",
"=",
"extractDirectory",
"+",
"File",
".",
"separator",
"+",
"\"wlp\"",
"+",
"File",
".",
"separator",
"+",
"\"usr\"",
"+",
"File",
".",
"separator",
"+",
"\"servers\"",
"+",
"File",
".",
"separator",
"+",
"serverName",
"+",
"File",
".",
"separator",
"+",
"\"jvm.options\"",
";",
"BufferedReader",
"br",
"=",
"null",
";",
"BufferedWriter",
"bw",
"=",
"null",
";",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"try",
"{",
"String",
"sCurrentLine",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"fileName",
")",
";",
"// if file doesnt exists, then create it",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"boolean",
"success",
"=",
"file",
".",
"createNewFile",
"(",
")",
";",
"if",
"(",
"!",
"success",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to create file \"",
"+",
"fileName",
")",
";",
"}",
"}",
"else",
"{",
"// read existing file content",
"br",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"new",
"FileInputStream",
"(",
"fileName",
")",
",",
"\"UTF-8\"",
")",
")",
";",
"while",
"(",
"(",
"sCurrentLine",
"=",
"br",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"sCurrentLine",
"+",
"\"\\n\"",
")",
";",
"}",
"}",
"// write property to disable 2PC commit",
"String",
"content",
"=",
"\"-Dcom.ibm.tx.jta.disable2PC=true\"",
";",
"bw",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
"FileOutputStream",
"(",
"file",
".",
"getAbsoluteFile",
"(",
")",
")",
",",
"\"UTF-8\"",
")",
")",
";",
"bw",
".",
"write",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"bw",
".",
"write",
"(",
"content",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"br",
"!=",
"null",
")",
"br",
".",
"close",
"(",
")",
";",
"if",
"(",
"bw",
"!=",
"null",
")",
"bw",
".",
"close",
"(",
")",
";",
"}",
"}"
]
| Write property into jvm.options to disable 2PC transactions.
2PC transactions are disabled by default because default transaction
log is stored in extract directory and therefore foils transaction
recovery if the server terminates unexpectedly.
@param extractDirectory
@param serverName
@throws IOException | [
"Write",
"property",
"into",
"jvm",
".",
"options",
"to",
"disable",
"2PC",
"transactions",
".",
"2PC",
"transactions",
"are",
"disabled",
"by",
"default",
"because",
"default",
"transaction",
"log",
"is",
"stored",
"in",
"extract",
"directory",
"and",
"therefore",
"foils",
"transaction",
"recovery",
"if",
"the",
"server",
"terminates",
"unexpectedly",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/wlp.lib.extract/src/wlp/lib/extract/SelfExtractRun.java#L176-L218 |
apiman/apiman | gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/auth/LDAPIdentityValidator.java | LDAPIdentityValidator.formatDn | private String formatDn(String dnPattern, String username, ApiRequest request) {
"""
Formats the configured DN by replacing any properties it finds.
@param dnPattern
@param username
@param request
"""
Map<String, String> valuesMap = request.getHeaders().toMap();
valuesMap.put("username", username); //$NON-NLS-1$
StrSubstitutor sub = new StrSubstitutor(valuesMap);
return sub.replace(dnPattern);
} | java | private String formatDn(String dnPattern, String username, ApiRequest request) {
Map<String, String> valuesMap = request.getHeaders().toMap();
valuesMap.put("username", username); //$NON-NLS-1$
StrSubstitutor sub = new StrSubstitutor(valuesMap);
return sub.replace(dnPattern);
} | [
"private",
"String",
"formatDn",
"(",
"String",
"dnPattern",
",",
"String",
"username",
",",
"ApiRequest",
"request",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"valuesMap",
"=",
"request",
".",
"getHeaders",
"(",
")",
".",
"toMap",
"(",
")",
";",
"valuesMap",
".",
"put",
"(",
"\"username\"",
",",
"username",
")",
";",
"//$NON-NLS-1$",
"StrSubstitutor",
"sub",
"=",
"new",
"StrSubstitutor",
"(",
"valuesMap",
")",
";",
"return",
"sub",
".",
"replace",
"(",
"dnPattern",
")",
";",
"}"
]
| Formats the configured DN by replacing any properties it finds.
@param dnPattern
@param username
@param request | [
"Formats",
"the",
"configured",
"DN",
"by",
"replacing",
"any",
"properties",
"it",
"finds",
"."
]
| train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/auth/LDAPIdentityValidator.java#L269-L274 |
Harium/keel | src/main/java/com/harium/keel/catalano/math/ComplexNumber.java | ComplexNumber.Swap | public static void Swap(ComplexNumber[] z) {
"""
Swap values between real and imaginary.
@param z Complex number.
"""
for (int i = 0; i < z.length; i++) {
z[i] = new ComplexNumber(z[i].imaginary, z[i].real);
}
} | java | public static void Swap(ComplexNumber[] z) {
for (int i = 0; i < z.length; i++) {
z[i] = new ComplexNumber(z[i].imaginary, z[i].real);
}
} | [
"public",
"static",
"void",
"Swap",
"(",
"ComplexNumber",
"[",
"]",
"z",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"z",
".",
"length",
";",
"i",
"++",
")",
"{",
"z",
"[",
"i",
"]",
"=",
"new",
"ComplexNumber",
"(",
"z",
"[",
"i",
"]",
".",
"imaginary",
",",
"z",
"[",
"i",
"]",
".",
"real",
")",
";",
"}",
"}"
]
| Swap values between real and imaginary.
@param z Complex number. | [
"Swap",
"values",
"between",
"real",
"and",
"imaginary",
"."
]
| train | https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/ComplexNumber.java#L174-L178 |
mapbox/mapbox-navigation-android | libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCamera.java | NavigationCamera.buildRouteInformationFromLocation | @NonNull
private RouteInformation buildRouteInformationFromLocation(Location location, RouteProgress routeProgress) {
"""
Creates a camera position based on the given location.
<p>
From the {@link Location}, a target position is created.
Then using a preset tilt and zoom (based on screen orientation), a {@link CameraPosition} is built.
@param location used to build the camera position
@return camera position to be animated to
"""
return RouteInformation.create(null, location, routeProgress);
} | java | @NonNull
private RouteInformation buildRouteInformationFromLocation(Location location, RouteProgress routeProgress) {
return RouteInformation.create(null, location, routeProgress);
} | [
"@",
"NonNull",
"private",
"RouteInformation",
"buildRouteInformationFromLocation",
"(",
"Location",
"location",
",",
"RouteProgress",
"routeProgress",
")",
"{",
"return",
"RouteInformation",
".",
"create",
"(",
"null",
",",
"location",
",",
"routeProgress",
")",
";",
"}"
]
| Creates a camera position based on the given location.
<p>
From the {@link Location}, a target position is created.
Then using a preset tilt and zoom (based on screen orientation), a {@link CameraPosition} is built.
@param location used to build the camera position
@return camera position to be animated to | [
"Creates",
"a",
"camera",
"position",
"based",
"on",
"the",
"given",
"location",
".",
"<p",
">",
"From",
"the",
"{",
"@link",
"Location",
"}",
"a",
"target",
"position",
"is",
"created",
".",
"Then",
"using",
"a",
"preset",
"tilt",
"and",
"zoom",
"(",
"based",
"on",
"screen",
"orientation",
")",
"a",
"{",
"@link",
"CameraPosition",
"}",
"is",
"built",
"."
]
| train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/camera/NavigationCamera.java#L417-L420 |
casmi/casmi | src/main/java/casmi/graphics/color/CMYKColor.java | CMYKColor.lerpColor | public static Color lerpColor(CMYKColor color1, CMYKColor color2, double amt) {
"""
Calculates a color or colors between two color at a specific increment.
@param color1
interpolate from this color
@param color2
interpolate to this color
@param amt
between 0.0 and 1.0
@return
The calculated color values.
"""
double cyan, magenta, yellow, black, alpha;
cyan = color2.cyan * amt + color1.cyan * (1.0 - amt);
magenta = color2.magenta * amt + color1.magenta * (1.0 - amt);
yellow = color2.yellow * amt + color1.yellow * (1.0 - amt);
black = color2.black * amt + color1.black * (1.0 - amt);
alpha = color2.alpha * amt + color1.alpha * (1.0 - amt);
return new CMYKColor(cyan, magenta, yellow, black, alpha);
} | java | public static Color lerpColor(CMYKColor color1, CMYKColor color2, double amt) {
double cyan, magenta, yellow, black, alpha;
cyan = color2.cyan * amt + color1.cyan * (1.0 - amt);
magenta = color2.magenta * amt + color1.magenta * (1.0 - amt);
yellow = color2.yellow * amt + color1.yellow * (1.0 - amt);
black = color2.black * amt + color1.black * (1.0 - amt);
alpha = color2.alpha * amt + color1.alpha * (1.0 - amt);
return new CMYKColor(cyan, magenta, yellow, black, alpha);
} | [
"public",
"static",
"Color",
"lerpColor",
"(",
"CMYKColor",
"color1",
",",
"CMYKColor",
"color2",
",",
"double",
"amt",
")",
"{",
"double",
"cyan",
",",
"magenta",
",",
"yellow",
",",
"black",
",",
"alpha",
";",
"cyan",
"=",
"color2",
".",
"cyan",
"*",
"amt",
"+",
"color1",
".",
"cyan",
"*",
"(",
"1.0",
"-",
"amt",
")",
";",
"magenta",
"=",
"color2",
".",
"magenta",
"*",
"amt",
"+",
"color1",
".",
"magenta",
"*",
"(",
"1.0",
"-",
"amt",
")",
";",
"yellow",
"=",
"color2",
".",
"yellow",
"*",
"amt",
"+",
"color1",
".",
"yellow",
"*",
"(",
"1.0",
"-",
"amt",
")",
";",
"black",
"=",
"color2",
".",
"black",
"*",
"amt",
"+",
"color1",
".",
"black",
"*",
"(",
"1.0",
"-",
"amt",
")",
";",
"alpha",
"=",
"color2",
".",
"alpha",
"*",
"amt",
"+",
"color1",
".",
"alpha",
"*",
"(",
"1.0",
"-",
"amt",
")",
";",
"return",
"new",
"CMYKColor",
"(",
"cyan",
",",
"magenta",
",",
"yellow",
",",
"black",
",",
"alpha",
")",
";",
"}"
]
| Calculates a color or colors between two color at a specific increment.
@param color1
interpolate from this color
@param color2
interpolate to this color
@param amt
between 0.0 and 1.0
@return
The calculated color values. | [
"Calculates",
"a",
"color",
"or",
"colors",
"between",
"two",
"color",
"at",
"a",
"specific",
"increment",
"."
]
| train | https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/color/CMYKColor.java#L181-L189 |
sundrio/sundrio | annotations/builder/src/main/java/io/sundr/builder/internal/functions/ToPojo.java | ToPojo.readProperty | private static String readProperty(String ref, TypeDef source, Property property) {
"""
Returns the string representation of the code that given a reference of the specified type, reads the specified property.
@param ref The reference.
@param source The type of the reference.
@param property The property to read.
@return The code.
"""
TypeRef propertyTypeRef = property.getTypeRef();
Method getter = getterOf(source, property);
if (getter == null) {
return "null";
}
TypeRef getterTypeRef = getter.getReturnType();
if (propertyTypeRef.getDimensions() == getterTypeRef.getDimensions() && propertyTypeRef.isAssignableFrom(getterTypeRef)) {
return readObjectProperty(ref, source, property);
}
if (property.getTypeRef().getDimensions() > 0) {
return readArrayProperty(ref, source, property);
}
if (property.getTypeRef() instanceof ClassRef && ((ClassRef)getterTypeRef).getDefinition().isAnnotation()) {
return readAnnotationProperty(ref + "."+getter.getName()+"()", ((ClassRef) getterTypeRef).getDefinition(), property);
}
return readObjectProperty(ref, source, property);
} | java | private static String readProperty(String ref, TypeDef source, Property property) {
TypeRef propertyTypeRef = property.getTypeRef();
Method getter = getterOf(source, property);
if (getter == null) {
return "null";
}
TypeRef getterTypeRef = getter.getReturnType();
if (propertyTypeRef.getDimensions() == getterTypeRef.getDimensions() && propertyTypeRef.isAssignableFrom(getterTypeRef)) {
return readObjectProperty(ref, source, property);
}
if (property.getTypeRef().getDimensions() > 0) {
return readArrayProperty(ref, source, property);
}
if (property.getTypeRef() instanceof ClassRef && ((ClassRef)getterTypeRef).getDefinition().isAnnotation()) {
return readAnnotationProperty(ref + "."+getter.getName()+"()", ((ClassRef) getterTypeRef).getDefinition(), property);
}
return readObjectProperty(ref, source, property);
} | [
"private",
"static",
"String",
"readProperty",
"(",
"String",
"ref",
",",
"TypeDef",
"source",
",",
"Property",
"property",
")",
"{",
"TypeRef",
"propertyTypeRef",
"=",
"property",
".",
"getTypeRef",
"(",
")",
";",
"Method",
"getter",
"=",
"getterOf",
"(",
"source",
",",
"property",
")",
";",
"if",
"(",
"getter",
"==",
"null",
")",
"{",
"return",
"\"null\"",
";",
"}",
"TypeRef",
"getterTypeRef",
"=",
"getter",
".",
"getReturnType",
"(",
")",
";",
"if",
"(",
"propertyTypeRef",
".",
"getDimensions",
"(",
")",
"==",
"getterTypeRef",
".",
"getDimensions",
"(",
")",
"&&",
"propertyTypeRef",
".",
"isAssignableFrom",
"(",
"getterTypeRef",
")",
")",
"{",
"return",
"readObjectProperty",
"(",
"ref",
",",
"source",
",",
"property",
")",
";",
"}",
"if",
"(",
"property",
".",
"getTypeRef",
"(",
")",
".",
"getDimensions",
"(",
")",
">",
"0",
")",
"{",
"return",
"readArrayProperty",
"(",
"ref",
",",
"source",
",",
"property",
")",
";",
"}",
"if",
"(",
"property",
".",
"getTypeRef",
"(",
")",
"instanceof",
"ClassRef",
"&&",
"(",
"(",
"ClassRef",
")",
"getterTypeRef",
")",
".",
"getDefinition",
"(",
")",
".",
"isAnnotation",
"(",
")",
")",
"{",
"return",
"readAnnotationProperty",
"(",
"ref",
"+",
"\".\"",
"+",
"getter",
".",
"getName",
"(",
")",
"+",
"\"()\"",
",",
"(",
"(",
"ClassRef",
")",
"getterTypeRef",
")",
".",
"getDefinition",
"(",
")",
",",
"property",
")",
";",
"}",
"return",
"readObjectProperty",
"(",
"ref",
",",
"source",
",",
"property",
")",
";",
"}"
]
| Returns the string representation of the code that given a reference of the specified type, reads the specified property.
@param ref The reference.
@param source The type of the reference.
@param property The property to read.
@return The code. | [
"Returns",
"the",
"string",
"representation",
"of",
"the",
"code",
"that",
"given",
"a",
"reference",
"of",
"the",
"specified",
"type",
"reads",
"the",
"specified",
"property",
"."
]
| train | https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/annotations/builder/src/main/java/io/sundr/builder/internal/functions/ToPojo.java#L571-L590 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/LongStream.java | LongStream.iterate | @NotNull
public static LongStream iterate(final long seed,
@NotNull final LongUnaryOperator f) {
"""
Creates a {@code LongStream} by iterative application {@code LongUnaryOperator} function
to an initial element {@code seed}. Produces {@code LongStream} consisting of
{@code seed}, {@code f(seed)}, {@code f(f(seed))}, etc.
<p> The first element (position {@code 0}) in the {@code LongStream} will be
the provided {@code seed}. For {@code n > 0}, the element at position
{@code n}, will be the result of applying the function {@code f} to the
element at position {@code n - 1}.
<p>Example:
<pre>
seed: 1
f: (a) -> a + 5
result: [1, 6, 11, 16, ...]
</pre>
@param seed the initial element
@param f a function to be applied to the previous element to produce a new element
@return a new sequential {@code LongStream}
@throws NullPointerException if {@code f} is null
"""
Objects.requireNonNull(f);
return new LongStream(new LongIterate(seed, f));
} | java | @NotNull
public static LongStream iterate(final long seed,
@NotNull final LongUnaryOperator f) {
Objects.requireNonNull(f);
return new LongStream(new LongIterate(seed, f));
} | [
"@",
"NotNull",
"public",
"static",
"LongStream",
"iterate",
"(",
"final",
"long",
"seed",
",",
"@",
"NotNull",
"final",
"LongUnaryOperator",
"f",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"f",
")",
";",
"return",
"new",
"LongStream",
"(",
"new",
"LongIterate",
"(",
"seed",
",",
"f",
")",
")",
";",
"}"
]
| Creates a {@code LongStream} by iterative application {@code LongUnaryOperator} function
to an initial element {@code seed}. Produces {@code LongStream} consisting of
{@code seed}, {@code f(seed)}, {@code f(f(seed))}, etc.
<p> The first element (position {@code 0}) in the {@code LongStream} will be
the provided {@code seed}. For {@code n > 0}, the element at position
{@code n}, will be the result of applying the function {@code f} to the
element at position {@code n - 1}.
<p>Example:
<pre>
seed: 1
f: (a) -> a + 5
result: [1, 6, 11, 16, ...]
</pre>
@param seed the initial element
@param f a function to be applied to the previous element to produce a new element
@return a new sequential {@code LongStream}
@throws NullPointerException if {@code f} is null | [
"Creates",
"a",
"{",
"@code",
"LongStream",
"}",
"by",
"iterative",
"application",
"{",
"@code",
"LongUnaryOperator",
"}",
"function",
"to",
"an",
"initial",
"element",
"{",
"@code",
"seed",
"}",
".",
"Produces",
"{",
"@code",
"LongStream",
"}",
"consisting",
"of",
"{",
"@code",
"seed",
"}",
"{",
"@code",
"f",
"(",
"seed",
")",
"}",
"{",
"@code",
"f",
"(",
"f",
"(",
"seed",
"))",
"}",
"etc",
"."
]
| train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/LongStream.java#L162-L167 |
alkacon/opencms-core | src/org/opencms/main/CmsShellCommands.java | CmsShellCommands.setUserInfo | public void setUserInfo(String username, String infoName, String value) throws CmsException {
"""
Sets a string-valued additional info entry on the user.
@param username the name of the user
@param infoName the additional info key
@param value the additional info value
@throws CmsException if something goes wrong
"""
CmsUser user = m_cms.readUser(username);
user.setAdditionalInfo(infoName, value);
m_cms.writeUser(user);
} | java | public void setUserInfo(String username, String infoName, String value) throws CmsException {
CmsUser user = m_cms.readUser(username);
user.setAdditionalInfo(infoName, value);
m_cms.writeUser(user);
} | [
"public",
"void",
"setUserInfo",
"(",
"String",
"username",
",",
"String",
"infoName",
",",
"String",
"value",
")",
"throws",
"CmsException",
"{",
"CmsUser",
"user",
"=",
"m_cms",
".",
"readUser",
"(",
"username",
")",
";",
"user",
".",
"setAdditionalInfo",
"(",
"infoName",
",",
"value",
")",
";",
"m_cms",
".",
"writeUser",
"(",
"user",
")",
";",
"}"
]
| Sets a string-valued additional info entry on the user.
@param username the name of the user
@param infoName the additional info key
@param value the additional info value
@throws CmsException if something goes wrong | [
"Sets",
"a",
"string",
"-",
"valued",
"additional",
"info",
"entry",
"on",
"the",
"user",
"."
]
| train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L1589-L1594 |
powermock/powermock | powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java | BsdVirtualMachine.writeString | private void writeString(int fd, String s) throws IOException {
"""
/*
Write/sends the given to the target VM. String is transmitted in
UTF-8 encoding.
"""
if (s.length() > 0) {
byte b[];
try {
b = s.getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException x) {
throw new InternalError();
}
BsdVirtualMachine.write(fd, b, 0, b.length);
}
byte b[] = new byte[1];
b[0] = 0;
write(fd, b, 0, 1);
} | java | private void writeString(int fd, String s) throws IOException {
if (s.length() > 0) {
byte b[];
try {
b = s.getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException x) {
throw new InternalError();
}
BsdVirtualMachine.write(fd, b, 0, b.length);
}
byte b[] = new byte[1];
b[0] = 0;
write(fd, b, 0, 1);
} | [
"private",
"void",
"writeString",
"(",
"int",
"fd",
",",
"String",
"s",
")",
"throws",
"IOException",
"{",
"if",
"(",
"s",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"byte",
"b",
"[",
"]",
";",
"try",
"{",
"b",
"=",
"s",
".",
"getBytes",
"(",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"java",
".",
"io",
".",
"UnsupportedEncodingException",
"x",
")",
"{",
"throw",
"new",
"InternalError",
"(",
")",
";",
"}",
"BsdVirtualMachine",
".",
"write",
"(",
"fd",
",",
"b",
",",
"0",
",",
"b",
".",
"length",
")",
";",
"}",
"byte",
"b",
"[",
"]",
"=",
"new",
"byte",
"[",
"1",
"]",
";",
"b",
"[",
"0",
"]",
"=",
"0",
";",
"write",
"(",
"fd",
",",
"b",
",",
"0",
",",
"1",
")",
";",
"}"
]
| /*
Write/sends the given to the target VM. String is transmitted in
UTF-8 encoding. | [
"/",
"*",
"Write",
"/",
"sends",
"the",
"given",
"to",
"the",
"target",
"VM",
".",
"String",
"is",
"transmitted",
"in",
"UTF",
"-",
"8",
"encoding",
"."
]
| train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java#L267-L280 |
twitter/hraven | hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryService.java | JobHistoryService.getFlowSeries | public List<Flow> getFlowSeries(String cluster, String user, String appId,
String version, boolean populateTasks, int limit) throws IOException {
"""
Returns the most recent {@link Flow} runs, up to {@code limit} instances.
If the {@code version} parameter is non-null, the returned results will be
restricted to those matching this app version.
@param cluster the cluster where the jobs were run
@param user the user running the jobs
@param appId the application identifier for the jobs
@param version if non-null, only flows matching this application version
will be returned
@param populateTasks if {@code true}, then TaskDetails will be populated
for each job
@param limit the maximum number of flows to return
@return
"""
// TODO: use RunMatchFilter to limit scan on the server side
byte[] rowPrefix = Bytes.toBytes(
cluster + Constants.SEP + user + Constants.SEP + appId + Constants.SEP);
Scan scan = createFlowScan(rowPrefix, limit, version);
return createFromResults(scan, populateTasks, limit);
} | java | public List<Flow> getFlowSeries(String cluster, String user, String appId,
String version, boolean populateTasks, int limit) throws IOException {
// TODO: use RunMatchFilter to limit scan on the server side
byte[] rowPrefix = Bytes.toBytes(
cluster + Constants.SEP + user + Constants.SEP + appId + Constants.SEP);
Scan scan = createFlowScan(rowPrefix, limit, version);
return createFromResults(scan, populateTasks, limit);
} | [
"public",
"List",
"<",
"Flow",
">",
"getFlowSeries",
"(",
"String",
"cluster",
",",
"String",
"user",
",",
"String",
"appId",
",",
"String",
"version",
",",
"boolean",
"populateTasks",
",",
"int",
"limit",
")",
"throws",
"IOException",
"{",
"// TODO: use RunMatchFilter to limit scan on the server side",
"byte",
"[",
"]",
"rowPrefix",
"=",
"Bytes",
".",
"toBytes",
"(",
"cluster",
"+",
"Constants",
".",
"SEP",
"+",
"user",
"+",
"Constants",
".",
"SEP",
"+",
"appId",
"+",
"Constants",
".",
"SEP",
")",
";",
"Scan",
"scan",
"=",
"createFlowScan",
"(",
"rowPrefix",
",",
"limit",
",",
"version",
")",
";",
"return",
"createFromResults",
"(",
"scan",
",",
"populateTasks",
",",
"limit",
")",
";",
"}"
]
| Returns the most recent {@link Flow} runs, up to {@code limit} instances.
If the {@code version} parameter is non-null, the returned results will be
restricted to those matching this app version.
@param cluster the cluster where the jobs were run
@param user the user running the jobs
@param appId the application identifier for the jobs
@param version if non-null, only flows matching this application version
will be returned
@param populateTasks if {@code true}, then TaskDetails will be populated
for each job
@param limit the maximum number of flows to return
@return | [
"Returns",
"the",
"most",
"recent",
"{",
"@link",
"Flow",
"}",
"runs",
"up",
"to",
"{",
"@code",
"limit",
"}",
"instances",
".",
"If",
"the",
"{",
"@code",
"version",
"}",
"parameter",
"is",
"non",
"-",
"null",
"the",
"returned",
"results",
"will",
"be",
"restricted",
"to",
"those",
"matching",
"this",
"app",
"version",
"."
]
| train | https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-core/src/main/java/com/twitter/hraven/datasource/JobHistoryService.java#L263-L270 |
minio/minio-java | api/src/main/java/io/minio/messages/S3Key.java | S3Key.setRule | private void setRule(String name, String value) throws InvalidArgumentException, XmlPullParserException {
"""
Sets filter rule to list.
As per Amazon AWS S3 server behavior, its not possible to set more than one rule for "prefix" or "suffix".
However the spec http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html
is not clear about this behavior.
"""
if (value.length() > 1024) {
throw new InvalidArgumentException("value '" + value + "' is more than 1024 long");
}
for (FilterRule rule: filterRuleList) {
// Remove rule.name is same as given name.
if (rule.name().equals(name)) {
filterRuleList.remove(rule);
}
}
FilterRule newRule = new FilterRule();
newRule.setName(name);
newRule.setValue(value);
filterRuleList.add(newRule);
} | java | private void setRule(String name, String value) throws InvalidArgumentException, XmlPullParserException {
if (value.length() > 1024) {
throw new InvalidArgumentException("value '" + value + "' is more than 1024 long");
}
for (FilterRule rule: filterRuleList) {
// Remove rule.name is same as given name.
if (rule.name().equals(name)) {
filterRuleList.remove(rule);
}
}
FilterRule newRule = new FilterRule();
newRule.setName(name);
newRule.setValue(value);
filterRuleList.add(newRule);
} | [
"private",
"void",
"setRule",
"(",
"String",
"name",
",",
"String",
"value",
")",
"throws",
"InvalidArgumentException",
",",
"XmlPullParserException",
"{",
"if",
"(",
"value",
".",
"length",
"(",
")",
">",
"1024",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"value '\"",
"+",
"value",
"+",
"\"' is more than 1024 long\"",
")",
";",
"}",
"for",
"(",
"FilterRule",
"rule",
":",
"filterRuleList",
")",
"{",
"// Remove rule.name is same as given name.",
"if",
"(",
"rule",
".",
"name",
"(",
")",
".",
"equals",
"(",
"name",
")",
")",
"{",
"filterRuleList",
".",
"remove",
"(",
"rule",
")",
";",
"}",
"}",
"FilterRule",
"newRule",
"=",
"new",
"FilterRule",
"(",
")",
";",
"newRule",
".",
"setName",
"(",
"name",
")",
";",
"newRule",
".",
"setValue",
"(",
"value",
")",
";",
"filterRuleList",
".",
"add",
"(",
"newRule",
")",
";",
"}"
]
| Sets filter rule to list.
As per Amazon AWS S3 server behavior, its not possible to set more than one rule for "prefix" or "suffix".
However the spec http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html
is not clear about this behavior. | [
"Sets",
"filter",
"rule",
"to",
"list",
".",
"As",
"per",
"Amazon",
"AWS",
"S3",
"server",
"behavior",
"its",
"not",
"possible",
"to",
"set",
"more",
"than",
"one",
"rule",
"for",
"prefix",
"or",
"suffix",
".",
"However",
"the",
"spec",
"http",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"AmazonS3",
"/",
"latest",
"/",
"API",
"/",
"RESTBucketPUTnotification",
".",
"html",
"is",
"not",
"clear",
"about",
"this",
"behavior",
"."
]
| train | https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/messages/S3Key.java#L58-L74 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/UnicodeFont.java | UnicodeFont.initializeFont | private void initializeFont(Font baseFont, int size, boolean bold, boolean italic) {
"""
Initialise the font to be used based on configuration
@param baseFont The AWT font to render
@param size The point size of the font to generated
@param bold True if the font should be rendered in bold typeface
@param italic True if the font should be rendered in bold typeface
"""
Map attributes = baseFont.getAttributes();
attributes.put(TextAttribute.SIZE, new Float(size));
attributes.put(TextAttribute.WEIGHT, bold ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR);
attributes.put(TextAttribute.POSTURE, italic ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR);
try {
attributes.put(TextAttribute.class.getDeclaredField("KERNING").get(null), TextAttribute.class.getDeclaredField(
"KERNING_ON").get(null));
} catch (Exception ignored) {
}
font = baseFont.deriveFont(attributes);
FontMetrics metrics = GlyphPage.getScratchGraphics().getFontMetrics(font);
ascent = metrics.getAscent();
descent = metrics.getDescent();
leading = metrics.getLeading();
// Determine width of space glyph (getGlyphPixelBounds gives a width of zero).
char[] chars = " ".toCharArray();
GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
spaceWidth = vector.getGlyphLogicalBounds(0).getBounds().width;
} | java | private void initializeFont(Font baseFont, int size, boolean bold, boolean italic) {
Map attributes = baseFont.getAttributes();
attributes.put(TextAttribute.SIZE, new Float(size));
attributes.put(TextAttribute.WEIGHT, bold ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR);
attributes.put(TextAttribute.POSTURE, italic ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR);
try {
attributes.put(TextAttribute.class.getDeclaredField("KERNING").get(null), TextAttribute.class.getDeclaredField(
"KERNING_ON").get(null));
} catch (Exception ignored) {
}
font = baseFont.deriveFont(attributes);
FontMetrics metrics = GlyphPage.getScratchGraphics().getFontMetrics(font);
ascent = metrics.getAscent();
descent = metrics.getDescent();
leading = metrics.getLeading();
// Determine width of space glyph (getGlyphPixelBounds gives a width of zero).
char[] chars = " ".toCharArray();
GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
spaceWidth = vector.getGlyphLogicalBounds(0).getBounds().width;
} | [
"private",
"void",
"initializeFont",
"(",
"Font",
"baseFont",
",",
"int",
"size",
",",
"boolean",
"bold",
",",
"boolean",
"italic",
")",
"{",
"Map",
"attributes",
"=",
"baseFont",
".",
"getAttributes",
"(",
")",
";",
"attributes",
".",
"put",
"(",
"TextAttribute",
".",
"SIZE",
",",
"new",
"Float",
"(",
"size",
")",
")",
";",
"attributes",
".",
"put",
"(",
"TextAttribute",
".",
"WEIGHT",
",",
"bold",
"?",
"TextAttribute",
".",
"WEIGHT_BOLD",
":",
"TextAttribute",
".",
"WEIGHT_REGULAR",
")",
";",
"attributes",
".",
"put",
"(",
"TextAttribute",
".",
"POSTURE",
",",
"italic",
"?",
"TextAttribute",
".",
"POSTURE_OBLIQUE",
":",
"TextAttribute",
".",
"POSTURE_REGULAR",
")",
";",
"try",
"{",
"attributes",
".",
"put",
"(",
"TextAttribute",
".",
"class",
".",
"getDeclaredField",
"(",
"\"KERNING\"",
")",
".",
"get",
"(",
"null",
")",
",",
"TextAttribute",
".",
"class",
".",
"getDeclaredField",
"(",
"\"KERNING_ON\"",
")",
".",
"get",
"(",
"null",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ignored",
")",
"{",
"}",
"font",
"=",
"baseFont",
".",
"deriveFont",
"(",
"attributes",
")",
";",
"FontMetrics",
"metrics",
"=",
"GlyphPage",
".",
"getScratchGraphics",
"(",
")",
".",
"getFontMetrics",
"(",
"font",
")",
";",
"ascent",
"=",
"metrics",
".",
"getAscent",
"(",
")",
";",
"descent",
"=",
"metrics",
".",
"getDescent",
"(",
")",
";",
"leading",
"=",
"metrics",
".",
"getLeading",
"(",
")",
";",
"// Determine width of space glyph (getGlyphPixelBounds gives a width of zero).\r",
"char",
"[",
"]",
"chars",
"=",
"\" \"",
".",
"toCharArray",
"(",
")",
";",
"GlyphVector",
"vector",
"=",
"font",
".",
"layoutGlyphVector",
"(",
"GlyphPage",
".",
"renderContext",
",",
"chars",
",",
"0",
",",
"chars",
".",
"length",
",",
"Font",
".",
"LAYOUT_LEFT_TO_RIGHT",
")",
";",
"spaceWidth",
"=",
"vector",
".",
"getGlyphLogicalBounds",
"(",
"0",
")",
".",
"getBounds",
"(",
")",
".",
"width",
";",
"}"
]
| Initialise the font to be used based on configuration
@param baseFont The AWT font to render
@param size The point size of the font to generated
@param bold True if the font should be rendered in bold typeface
@param italic True if the font should be rendered in bold typeface | [
"Initialise",
"the",
"font",
"to",
"be",
"used",
"based",
"on",
"configuration"
]
| train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/UnicodeFont.java#L227-L248 |
classgraph/classgraph | src/main/java/io/github/classgraph/Classfile.java | Classfile.readAnnotationElementValue | private Object readAnnotationElementValue() throws IOException {
"""
Read annotation element value from classfile.
@return the annotation element value
@throws IOException
If an IO exception occurs.
"""
final int tag = (char) inputStreamOrByteBuffer.readUnsignedByte();
switch (tag) {
case 'B':
return (byte) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'C':
return (char) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'D':
return Double.longBitsToDouble(cpReadLong(inputStreamOrByteBuffer.readUnsignedShort()));
case 'F':
return Float.intBitsToFloat(cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()));
case 'I':
return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'J':
return cpReadLong(inputStreamOrByteBuffer.readUnsignedShort());
case 'S':
return (short) cpReadUnsignedShort(inputStreamOrByteBuffer.readUnsignedShort());
case 'Z':
return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()) != 0;
case 's':
return getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
case 'e': {
// Return type is AnnotationEnumVal.
final String annotationClassName = getConstantPoolClassDescriptor(
inputStreamOrByteBuffer.readUnsignedShort());
final String annotationConstName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
return new AnnotationEnumValue(annotationClassName, annotationConstName);
}
case 'c':
// Return type is AnnotationClassRef (for class references in annotations)
final String classRefTypeDescriptor = getConstantPoolString(
inputStreamOrByteBuffer.readUnsignedShort());
return new AnnotationClassRef(classRefTypeDescriptor);
case '@':
// Complex (nested) annotation. Return type is AnnotationInfo.
return readAnnotation();
case '[':
// Return type is Object[] (of nested annotation element values)
final int count = inputStreamOrByteBuffer.readUnsignedShort();
final Object[] arr = new Object[count];
for (int i = 0; i < count; ++i) {
// Nested annotation element value
arr[i] = readAnnotationElementValue();
}
return arr;
default:
throw new ClassfileFormatException("Class " + className + " has unknown annotation element type tag '"
+ ((char) tag) + "': element size unknown, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
} | java | private Object readAnnotationElementValue() throws IOException {
final int tag = (char) inputStreamOrByteBuffer.readUnsignedByte();
switch (tag) {
case 'B':
return (byte) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'C':
return (char) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'D':
return Double.longBitsToDouble(cpReadLong(inputStreamOrByteBuffer.readUnsignedShort()));
case 'F':
return Float.intBitsToFloat(cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()));
case 'I':
return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort());
case 'J':
return cpReadLong(inputStreamOrByteBuffer.readUnsignedShort());
case 'S':
return (short) cpReadUnsignedShort(inputStreamOrByteBuffer.readUnsignedShort());
case 'Z':
return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()) != 0;
case 's':
return getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
case 'e': {
// Return type is AnnotationEnumVal.
final String annotationClassName = getConstantPoolClassDescriptor(
inputStreamOrByteBuffer.readUnsignedShort());
final String annotationConstName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
return new AnnotationEnumValue(annotationClassName, annotationConstName);
}
case 'c':
// Return type is AnnotationClassRef (for class references in annotations)
final String classRefTypeDescriptor = getConstantPoolString(
inputStreamOrByteBuffer.readUnsignedShort());
return new AnnotationClassRef(classRefTypeDescriptor);
case '@':
// Complex (nested) annotation. Return type is AnnotationInfo.
return readAnnotation();
case '[':
// Return type is Object[] (of nested annotation element values)
final int count = inputStreamOrByteBuffer.readUnsignedShort();
final Object[] arr = new Object[count];
for (int i = 0; i < count; ++i) {
// Nested annotation element value
arr[i] = readAnnotationElementValue();
}
return arr;
default:
throw new ClassfileFormatException("Class " + className + " has unknown annotation element type tag '"
+ ((char) tag) + "': element size unknown, cannot continue reading class. "
+ "Please report this at https://github.com/classgraph/classgraph/issues");
}
} | [
"private",
"Object",
"readAnnotationElementValue",
"(",
")",
"throws",
"IOException",
"{",
"final",
"int",
"tag",
"=",
"(",
"char",
")",
"inputStreamOrByteBuffer",
".",
"readUnsignedByte",
"(",
")",
";",
"switch",
"(",
"tag",
")",
"{",
"case",
"'",
"'",
":",
"return",
"(",
"byte",
")",
"cpReadInt",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"case",
"'",
"'",
":",
"return",
"(",
"char",
")",
"cpReadInt",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"case",
"'",
"'",
":",
"return",
"Double",
".",
"longBitsToDouble",
"(",
"cpReadLong",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
")",
";",
"case",
"'",
"'",
":",
"return",
"Float",
".",
"intBitsToFloat",
"(",
"cpReadInt",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
")",
";",
"case",
"'",
"'",
":",
"return",
"cpReadInt",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"case",
"'",
"'",
":",
"return",
"cpReadLong",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"case",
"'",
"'",
":",
"return",
"(",
"short",
")",
"cpReadUnsignedShort",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"case",
"'",
"'",
":",
"return",
"cpReadInt",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
"!=",
"0",
";",
"case",
"'",
"'",
":",
"return",
"getConstantPoolString",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"case",
"'",
"'",
":",
"{",
"// Return type is AnnotationEnumVal.",
"final",
"String",
"annotationClassName",
"=",
"getConstantPoolClassDescriptor",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"final",
"String",
"annotationConstName",
"=",
"getConstantPoolString",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"return",
"new",
"AnnotationEnumValue",
"(",
"annotationClassName",
",",
"annotationConstName",
")",
";",
"}",
"case",
"'",
"'",
":",
"// Return type is AnnotationClassRef (for class references in annotations)",
"final",
"String",
"classRefTypeDescriptor",
"=",
"getConstantPoolString",
"(",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
")",
";",
"return",
"new",
"AnnotationClassRef",
"(",
"classRefTypeDescriptor",
")",
";",
"case",
"'",
"'",
":",
"// Complex (nested) annotation. Return type is AnnotationInfo.",
"return",
"readAnnotation",
"(",
")",
";",
"case",
"'",
"'",
":",
"// Return type is Object[] (of nested annotation element values)",
"final",
"int",
"count",
"=",
"inputStreamOrByteBuffer",
".",
"readUnsignedShort",
"(",
")",
";",
"final",
"Object",
"[",
"]",
"arr",
"=",
"new",
"Object",
"[",
"count",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"++",
"i",
")",
"{",
"// Nested annotation element value",
"arr",
"[",
"i",
"]",
"=",
"readAnnotationElementValue",
"(",
")",
";",
"}",
"return",
"arr",
";",
"default",
":",
"throw",
"new",
"ClassfileFormatException",
"(",
"\"Class \"",
"+",
"className",
"+",
"\" has unknown annotation element type tag '\"",
"+",
"(",
"(",
"char",
")",
"tag",
")",
"+",
"\"': element size unknown, cannot continue reading class. \"",
"+",
"\"Please report this at https://github.com/classgraph/classgraph/issues\"",
")",
";",
"}",
"}"
]
| Read annotation element value from classfile.
@return the annotation element value
@throws IOException
If an IO exception occurs. | [
"Read",
"annotation",
"element",
"value",
"from",
"classfile",
"."
]
| train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/Classfile.java#L831-L881 |
cdk/cdk | legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java | GeometryTools.get3DCentreOfMass | public static Point3d get3DCentreOfMass(IAtomContainer ac) {
"""
Calculates the center of mass for the <code>Atom</code>s in the
AtomContainer for the 2D coordinates.
See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
@param ac AtomContainer for which the center of mass is calculated
@return Description of the Return Value
@cdk.keyword center of mass
@cdk.dictref blue-obelisk:calculate3DCenterOfMass
"""
double xsum = 0.0;
double ysum = 0.0;
double zsum = 0.0;
double totalmass = 0.0;
Iterator<IAtom> atoms = ac.atoms().iterator();
while (atoms.hasNext()) {
IAtom a = (IAtom) atoms.next();
Double mass = a.getExactMass();
// some sanity checking
if (a.getPoint3d() == null) return null;
if (mass == null) return null;
totalmass += mass;
xsum += mass * a.getPoint3d().x;
ysum += mass * a.getPoint3d().y;
zsum += mass * a.getPoint3d().z;
}
return new Point3d(xsum / totalmass, ysum / totalmass, zsum / totalmass);
} | java | public static Point3d get3DCentreOfMass(IAtomContainer ac) {
double xsum = 0.0;
double ysum = 0.0;
double zsum = 0.0;
double totalmass = 0.0;
Iterator<IAtom> atoms = ac.atoms().iterator();
while (atoms.hasNext()) {
IAtom a = (IAtom) atoms.next();
Double mass = a.getExactMass();
// some sanity checking
if (a.getPoint3d() == null) return null;
if (mass == null) return null;
totalmass += mass;
xsum += mass * a.getPoint3d().x;
ysum += mass * a.getPoint3d().y;
zsum += mass * a.getPoint3d().z;
}
return new Point3d(xsum / totalmass, ysum / totalmass, zsum / totalmass);
} | [
"public",
"static",
"Point3d",
"get3DCentreOfMass",
"(",
"IAtomContainer",
"ac",
")",
"{",
"double",
"xsum",
"=",
"0.0",
";",
"double",
"ysum",
"=",
"0.0",
";",
"double",
"zsum",
"=",
"0.0",
";",
"double",
"totalmass",
"=",
"0.0",
";",
"Iterator",
"<",
"IAtom",
">",
"atoms",
"=",
"ac",
".",
"atoms",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"atoms",
".",
"hasNext",
"(",
")",
")",
"{",
"IAtom",
"a",
"=",
"(",
"IAtom",
")",
"atoms",
".",
"next",
"(",
")",
";",
"Double",
"mass",
"=",
"a",
".",
"getExactMass",
"(",
")",
";",
"// some sanity checking",
"if",
"(",
"a",
".",
"getPoint3d",
"(",
")",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"mass",
"==",
"null",
")",
"return",
"null",
";",
"totalmass",
"+=",
"mass",
";",
"xsum",
"+=",
"mass",
"*",
"a",
".",
"getPoint3d",
"(",
")",
".",
"x",
";",
"ysum",
"+=",
"mass",
"*",
"a",
".",
"getPoint3d",
"(",
")",
".",
"y",
";",
"zsum",
"+=",
"mass",
"*",
"a",
".",
"getPoint3d",
"(",
")",
".",
"z",
";",
"}",
"return",
"new",
"Point3d",
"(",
"xsum",
"/",
"totalmass",
",",
"ysum",
"/",
"totalmass",
",",
"zsum",
"/",
"totalmass",
")",
";",
"}"
]
| Calculates the center of mass for the <code>Atom</code>s in the
AtomContainer for the 2D coordinates.
See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
@param ac AtomContainer for which the center of mass is calculated
@return Description of the Return Value
@cdk.keyword center of mass
@cdk.dictref blue-obelisk:calculate3DCenterOfMass | [
"Calculates",
"the",
"center",
"of",
"mass",
"for",
"the",
"<code",
">",
"Atom<",
"/",
"code",
">",
"s",
"in",
"the",
"AtomContainer",
"for",
"the",
"2D",
"coordinates",
".",
"See",
"comment",
"for",
"center",
"(",
"IAtomContainer",
"atomCon",
"Dimension",
"areaDim",
"HashMap",
"renderingCoordinates",
")",
"for",
"details",
"on",
"coordinate",
"sets"
]
| train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L528-L550 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/user/UserCoreDao.java | UserCoreDao.buildWhere | public String buildWhere(String field, ColumnValue value) {
"""
Build where (or selection) statement for a single field
@param field
field name
@param value
column value
@return where clause
"""
String where;
if (value != null) {
if (value.getValue() != null && value.getTolerance() != null) {
if (!(value.getValue() instanceof Number)) {
throw new GeoPackageException(
"Field value is not a number and can not use a tolerance, Field: "
+ field + ", Value: " + value);
}
String quotedField = CoreSQLUtils.quoteWrap(field);
where = quotedField + " >= ? AND " + quotedField + " <= ?";
} else {
where = buildWhere(field, value.getValue());
}
} else {
where = buildWhere(field, null, null);
}
return where;
} | java | public String buildWhere(String field, ColumnValue value) {
String where;
if (value != null) {
if (value.getValue() != null && value.getTolerance() != null) {
if (!(value.getValue() instanceof Number)) {
throw new GeoPackageException(
"Field value is not a number and can not use a tolerance, Field: "
+ field + ", Value: " + value);
}
String quotedField = CoreSQLUtils.quoteWrap(field);
where = quotedField + " >= ? AND " + quotedField + " <= ?";
} else {
where = buildWhere(field, value.getValue());
}
} else {
where = buildWhere(field, null, null);
}
return where;
} | [
"public",
"String",
"buildWhere",
"(",
"String",
"field",
",",
"ColumnValue",
"value",
")",
"{",
"String",
"where",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"if",
"(",
"value",
".",
"getValue",
"(",
")",
"!=",
"null",
"&&",
"value",
".",
"getTolerance",
"(",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"(",
"value",
".",
"getValue",
"(",
")",
"instanceof",
"Number",
")",
")",
"{",
"throw",
"new",
"GeoPackageException",
"(",
"\"Field value is not a number and can not use a tolerance, Field: \"",
"+",
"field",
"+",
"\", Value: \"",
"+",
"value",
")",
";",
"}",
"String",
"quotedField",
"=",
"CoreSQLUtils",
".",
"quoteWrap",
"(",
"field",
")",
";",
"where",
"=",
"quotedField",
"+",
"\" >= ? AND \"",
"+",
"quotedField",
"+",
"\" <= ?\"",
";",
"}",
"else",
"{",
"where",
"=",
"buildWhere",
"(",
"field",
",",
"value",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"where",
"=",
"buildWhere",
"(",
"field",
",",
"null",
",",
"null",
")",
";",
"}",
"return",
"where",
";",
"}"
]
| Build where (or selection) statement for a single field
@param field
field name
@param value
column value
@return where clause | [
"Build",
"where",
"(",
"or",
"selection",
")",
"statement",
"for",
"a",
"single",
"field"
]
| train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/user/UserCoreDao.java#L729-L747 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java | SSLUtils.adjustBufferForJSSE | public static int adjustBufferForJSSE(WsByteBuffer buffer, int maxBufferSize) {
"""
The purpose of this method is to prepare the input buffer to be sent
into a call to wrap or unwrap in the JSSE considering the limitations
about how much data can be present in each buffer. This amount is determined
by the amount of data between position and limit.
@param buffer being examined which will be sent into the JSSE
@param maxBufferSize maximum size allowed
@return int - limit to restore later, -1 if no changes required
"""
int limit = -1;
if (null != buffer) {
int size = buffer.remaining();
if (maxBufferSize < size) {
limit = buffer.limit();
// Adjust the limit to the max allowed.
int overFlow = size - maxBufferSize;
buffer.limit(limit - overFlow);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "adjustBufferForJSSE: from " + limit + " to " + buffer.limit());
}
}
}
return limit;
} | java | public static int adjustBufferForJSSE(WsByteBuffer buffer, int maxBufferSize) {
int limit = -1;
if (null != buffer) {
int size = buffer.remaining();
if (maxBufferSize < size) {
limit = buffer.limit();
// Adjust the limit to the max allowed.
int overFlow = size - maxBufferSize;
buffer.limit(limit - overFlow);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "adjustBufferForJSSE: from " + limit + " to " + buffer.limit());
}
}
}
return limit;
} | [
"public",
"static",
"int",
"adjustBufferForJSSE",
"(",
"WsByteBuffer",
"buffer",
",",
"int",
"maxBufferSize",
")",
"{",
"int",
"limit",
"=",
"-",
"1",
";",
"if",
"(",
"null",
"!=",
"buffer",
")",
"{",
"int",
"size",
"=",
"buffer",
".",
"remaining",
"(",
")",
";",
"if",
"(",
"maxBufferSize",
"<",
"size",
")",
"{",
"limit",
"=",
"buffer",
".",
"limit",
"(",
")",
";",
"// Adjust the limit to the max allowed.",
"int",
"overFlow",
"=",
"size",
"-",
"maxBufferSize",
";",
"buffer",
".",
"limit",
"(",
"limit",
"-",
"overFlow",
")",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"(",
"tc",
",",
"\"adjustBufferForJSSE: from \"",
"+",
"limit",
"+",
"\" to \"",
"+",
"buffer",
".",
"limit",
"(",
")",
")",
";",
"}",
"}",
"}",
"return",
"limit",
";",
"}"
]
| The purpose of this method is to prepare the input buffer to be sent
into a call to wrap or unwrap in the JSSE considering the limitations
about how much data can be present in each buffer. This amount is determined
by the amount of data between position and limit.
@param buffer being examined which will be sent into the JSSE
@param maxBufferSize maximum size allowed
@return int - limit to restore later, -1 if no changes required | [
"The",
"purpose",
"of",
"this",
"method",
"is",
"to",
"prepare",
"the",
"input",
"buffer",
"to",
"be",
"sent",
"into",
"a",
"call",
"to",
"wrap",
"or",
"unwrap",
"in",
"the",
"JSSE",
"considering",
"the",
"limitations",
"about",
"how",
"much",
"data",
"can",
"be",
"present",
"in",
"each",
"buffer",
".",
"This",
"amount",
"is",
"determined",
"by",
"the",
"amount",
"of",
"data",
"between",
"position",
"and",
"limit",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java#L1314-L1329 |
onelogin/onelogin-java-sdk | src/main/java/com/onelogin/sdk/conn/Client.java | Client.getRolesBatch | public OneLoginResponse<Role> getRolesBatch(HashMap<String, String> queryParameters, int batchSize, String afterCursor)
throws OAuthSystemException, OAuthProblemException, URISyntaxException {
"""
Get a batch of Roles.
@param queryParameters Query parameters of the Resource
@param batchSize Size of the Batch
@param afterCursor Reference to continue collecting items of next page
@return OneLoginResponse of Role (Batch)
@throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection
@throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled
@throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor
@see com.onelogin.sdk.model.Role
@see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/roles/get-roles">Get Roles documentation</a>
"""
ExtractionContext context = extractResourceBatch(queryParameters, batchSize, afterCursor, Constants.GET_ROLES_URL);
List<Role> roles = new ArrayList<Role>(batchSize);
afterCursor = getRolesBatch(roles, context.url, context.bearerRequest, context.oAuthResponse);
return new OneLoginResponse<Role>(roles, afterCursor);
} | java | public OneLoginResponse<Role> getRolesBatch(HashMap<String, String> queryParameters, int batchSize, String afterCursor)
throws OAuthSystemException, OAuthProblemException, URISyntaxException {
ExtractionContext context = extractResourceBatch(queryParameters, batchSize, afterCursor, Constants.GET_ROLES_URL);
List<Role> roles = new ArrayList<Role>(batchSize);
afterCursor = getRolesBatch(roles, context.url, context.bearerRequest, context.oAuthResponse);
return new OneLoginResponse<Role>(roles, afterCursor);
} | [
"public",
"OneLoginResponse",
"<",
"Role",
">",
"getRolesBatch",
"(",
"HashMap",
"<",
"String",
",",
"String",
">",
"queryParameters",
",",
"int",
"batchSize",
",",
"String",
"afterCursor",
")",
"throws",
"OAuthSystemException",
",",
"OAuthProblemException",
",",
"URISyntaxException",
"{",
"ExtractionContext",
"context",
"=",
"extractResourceBatch",
"(",
"queryParameters",
",",
"batchSize",
",",
"afterCursor",
",",
"Constants",
".",
"GET_ROLES_URL",
")",
";",
"List",
"<",
"Role",
">",
"roles",
"=",
"new",
"ArrayList",
"<",
"Role",
">",
"(",
"batchSize",
")",
";",
"afterCursor",
"=",
"getRolesBatch",
"(",
"roles",
",",
"context",
".",
"url",
",",
"context",
".",
"bearerRequest",
",",
"context",
".",
"oAuthResponse",
")",
";",
"return",
"new",
"OneLoginResponse",
"<",
"Role",
">",
"(",
"roles",
",",
"afterCursor",
")",
";",
"}"
]
| Get a batch of Roles.
@param queryParameters Query parameters of the Resource
@param batchSize Size of the Batch
@param afterCursor Reference to continue collecting items of next page
@return OneLoginResponse of Role (Batch)
@throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection
@throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled
@throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor
@see com.onelogin.sdk.model.Role
@see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/roles/get-roles">Get Roles documentation</a> | [
"Get",
"a",
"batch",
"of",
"Roles",
"."
]
| train | https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L1779-L1785 |
glookast/commons-timecode | src/main/java/com/glookast/commons/timecode/MutableTimecode.java | MutableTimecode.valueOf | public static MutableTimecode valueOf(String timecode, int timecodeBase, StringType stringType) throws IllegalArgumentException {
"""
Returns a Timecode instance for given timecode string and timecode base.
What is considered acceptable input varies per selected StringType
@param timecode
@param timecodeBase
@param stringType
@return the timecode
@throws IllegalArgumentException
"""
MutableTimecode tc = new MutableTimecode();
return (MutableTimecode) tc.parse(timecode, timecodeBase, stringType);
} | java | public static MutableTimecode valueOf(String timecode, int timecodeBase, StringType stringType) throws IllegalArgumentException
{
MutableTimecode tc = new MutableTimecode();
return (MutableTimecode) tc.parse(timecode, timecodeBase, stringType);
} | [
"public",
"static",
"MutableTimecode",
"valueOf",
"(",
"String",
"timecode",
",",
"int",
"timecodeBase",
",",
"StringType",
"stringType",
")",
"throws",
"IllegalArgumentException",
"{",
"MutableTimecode",
"tc",
"=",
"new",
"MutableTimecode",
"(",
")",
";",
"return",
"(",
"MutableTimecode",
")",
"tc",
".",
"parse",
"(",
"timecode",
",",
"timecodeBase",
",",
"stringType",
")",
";",
"}"
]
| Returns a Timecode instance for given timecode string and timecode base.
What is considered acceptable input varies per selected StringType
@param timecode
@param timecodeBase
@param stringType
@return the timecode
@throws IllegalArgumentException | [
"Returns",
"a",
"Timecode",
"instance",
"for",
"given",
"timecode",
"string",
"and",
"timecode",
"base",
".",
"What",
"is",
"considered",
"acceptable",
"input",
"varies",
"per",
"selected",
"StringType"
]
| train | https://github.com/glookast/commons-timecode/blob/ec2f682a51d1cc435d0b42d80de48ff15adb4ee8/src/main/java/com/glookast/commons/timecode/MutableTimecode.java#L88-L92 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.delegatedAccount_email_filter_name_GET | public OvhFilter delegatedAccount_email_filter_name_GET(String email, String name) throws IOException {
"""
Get this object properties
REST: GET /email/domain/delegatedAccount/{email}/filter/{name}
@param email [required] Email
@param name [required] Filter name
"""
String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}";
StringBuilder sb = path(qPath, email, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhFilter.class);
} | java | public OvhFilter delegatedAccount_email_filter_name_GET(String email, String name) throws IOException {
String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}";
StringBuilder sb = path(qPath, email, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhFilter.class);
} | [
"public",
"OvhFilter",
"delegatedAccount_email_filter_name_GET",
"(",
"String",
"email",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/delegatedAccount/{email}/filter/{name}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"email",
",",
"name",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhFilter",
".",
"class",
")",
";",
"}"
]
| Get this object properties
REST: GET /email/domain/delegatedAccount/{email}/filter/{name}
@param email [required] Email
@param name [required] Filter name | [
"Get",
"this",
"object",
"properties"
]
| train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L244-L249 |
unbescape/unbescape | src/main/java/org/unbescape/html/HtmlEscape.java | HtmlEscape.escapeHtml | public static String escapeHtml(final String text, final HtmlEscapeType type, final HtmlEscapeLevel level) {
"""
<p>
Perform a (configurable) HTML <strong>escape</strong> operation on a <tt>String</tt> input.
</p>
<p>
This method will perform an escape operation according to the specified
{@link org.unbescape.html.HtmlEscapeType} and {@link org.unbescape.html.HtmlEscapeLevel}
argument values.
</p>
<p>
All other <tt>String</tt>-based <tt>escapeHtml*(...)</tt> methods call this one with preconfigured
<tt>type</tt> and <tt>level</tt> values.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param type the type of escape operation to be performed, see {@link org.unbescape.html.HtmlEscapeType}.
@param level the escape level to be applied, see {@link org.unbescape.html.HtmlEscapeLevel}.
@return The escaped result <tt>String</tt>. As a memory-performance improvement, will return the exact
same object as the <tt>text</tt> input argument if no escaping modifications were required (and
no additional <tt>String</tt> objects will be created during processing). Will
return <tt>null</tt> if input is <tt>null</tt>.
"""
if (type == null) {
throw new IllegalArgumentException("The 'type' argument cannot be null");
}
if (level == null) {
throw new IllegalArgumentException("The 'level' argument cannot be null");
}
return HtmlEscapeUtil.escape(text, type, level);
} | java | public static String escapeHtml(final String text, final HtmlEscapeType type, final HtmlEscapeLevel level) {
if (type == null) {
throw new IllegalArgumentException("The 'type' argument cannot be null");
}
if (level == null) {
throw new IllegalArgumentException("The 'level' argument cannot be null");
}
return HtmlEscapeUtil.escape(text, type, level);
} | [
"public",
"static",
"String",
"escapeHtml",
"(",
"final",
"String",
"text",
",",
"final",
"HtmlEscapeType",
"type",
",",
"final",
"HtmlEscapeLevel",
"level",
")",
"{",
"if",
"(",
"type",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The 'type' argument cannot be null\"",
")",
";",
"}",
"if",
"(",
"level",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The 'level' argument cannot be null\"",
")",
";",
"}",
"return",
"HtmlEscapeUtil",
".",
"escape",
"(",
"text",
",",
"type",
",",
"level",
")",
";",
"}"
]
| <p>
Perform a (configurable) HTML <strong>escape</strong> operation on a <tt>String</tt> input.
</p>
<p>
This method will perform an escape operation according to the specified
{@link org.unbescape.html.HtmlEscapeType} and {@link org.unbescape.html.HtmlEscapeLevel}
argument values.
</p>
<p>
All other <tt>String</tt>-based <tt>escapeHtml*(...)</tt> methods call this one with preconfigured
<tt>type</tt> and <tt>level</tt> values.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param type the type of escape operation to be performed, see {@link org.unbescape.html.HtmlEscapeType}.
@param level the escape level to be applied, see {@link org.unbescape.html.HtmlEscapeLevel}.
@return The escaped result <tt>String</tt>. As a memory-performance improvement, will return the exact
same object as the <tt>text</tt> input argument if no escaping modifications were required (and
no additional <tt>String</tt> objects will be created during processing). Will
return <tt>null</tt> if input is <tt>null</tt>. | [
"<p",
">",
"Perform",
"a",
"(",
"configurable",
")",
"HTML",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"will",
"perform",
"an",
"escape",
"operation",
"according",
"to",
"the",
"specified",
"{",
"@link",
"org",
".",
"unbescape",
".",
"html",
".",
"HtmlEscapeType",
"}",
"and",
"{",
"@link",
"org",
".",
"unbescape",
".",
"html",
".",
"HtmlEscapeLevel",
"}",
"argument",
"values",
".",
"<",
"/",
"p",
">",
"<p",
">",
"All",
"other",
"<tt",
">",
"String<",
"/",
"tt",
">",
"-",
"based",
"<tt",
">",
"escapeHtml",
"*",
"(",
"...",
")",
"<",
"/",
"tt",
">",
"methods",
"call",
"this",
"one",
"with",
"preconfigured",
"<tt",
">",
"type<",
"/",
"tt",
">",
"and",
"<tt",
">",
"level<",
"/",
"tt",
">",
"values",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"is",
"<strong",
">",
"thread",
"-",
"safe<",
"/",
"strong",
">",
".",
"<",
"/",
"p",
">"
]
| train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/html/HtmlEscape.java#L346-L358 |
Activiti/Activiti | activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/CachingAndArtifactsManager.java | CachingAndArtifactsManager.updateCachingAndArtifacts | public void updateCachingAndArtifacts(ParsedDeployment parsedDeployment) {
"""
Ensures that the process definition is cached in the appropriate places, including the
deployment's collection of deployed artifacts and the deployment manager's cache, as well
as caching any ProcessDefinitionInfos.
"""
CommandContext commandContext = Context.getCommandContext();
final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache
= processEngineConfiguration.getDeploymentManager().getProcessDefinitionCache();
DeploymentEntity deployment = parsedDeployment.getDeployment();
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
BpmnModel bpmnModel = parsedDeployment.getBpmnModelForProcessDefinition(processDefinition);
Process process = parsedDeployment.getProcessModelForProcessDefinition(processDefinition);
ProcessDefinitionCacheEntry cacheEntry = new ProcessDefinitionCacheEntry(processDefinition, bpmnModel, process);
processDefinitionCache.add(processDefinition.getId(), cacheEntry);
addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);
// Add to deployment for further usage
deployment.addDeployedArtifact(processDefinition);
}
} | java | public void updateCachingAndArtifacts(ParsedDeployment parsedDeployment) {
CommandContext commandContext = Context.getCommandContext();
final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache
= processEngineConfiguration.getDeploymentManager().getProcessDefinitionCache();
DeploymentEntity deployment = parsedDeployment.getDeployment();
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
BpmnModel bpmnModel = parsedDeployment.getBpmnModelForProcessDefinition(processDefinition);
Process process = parsedDeployment.getProcessModelForProcessDefinition(processDefinition);
ProcessDefinitionCacheEntry cacheEntry = new ProcessDefinitionCacheEntry(processDefinition, bpmnModel, process);
processDefinitionCache.add(processDefinition.getId(), cacheEntry);
addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);
// Add to deployment for further usage
deployment.addDeployedArtifact(processDefinition);
}
} | [
"public",
"void",
"updateCachingAndArtifacts",
"(",
"ParsedDeployment",
"parsedDeployment",
")",
"{",
"CommandContext",
"commandContext",
"=",
"Context",
".",
"getCommandContext",
"(",
")",
";",
"final",
"ProcessEngineConfigurationImpl",
"processEngineConfiguration",
"=",
"Context",
".",
"getProcessEngineConfiguration",
"(",
")",
";",
"DeploymentCache",
"<",
"ProcessDefinitionCacheEntry",
">",
"processDefinitionCache",
"=",
"processEngineConfiguration",
".",
"getDeploymentManager",
"(",
")",
".",
"getProcessDefinitionCache",
"(",
")",
";",
"DeploymentEntity",
"deployment",
"=",
"parsedDeployment",
".",
"getDeployment",
"(",
")",
";",
"for",
"(",
"ProcessDefinitionEntity",
"processDefinition",
":",
"parsedDeployment",
".",
"getAllProcessDefinitions",
"(",
")",
")",
"{",
"BpmnModel",
"bpmnModel",
"=",
"parsedDeployment",
".",
"getBpmnModelForProcessDefinition",
"(",
"processDefinition",
")",
";",
"Process",
"process",
"=",
"parsedDeployment",
".",
"getProcessModelForProcessDefinition",
"(",
"processDefinition",
")",
";",
"ProcessDefinitionCacheEntry",
"cacheEntry",
"=",
"new",
"ProcessDefinitionCacheEntry",
"(",
"processDefinition",
",",
"bpmnModel",
",",
"process",
")",
";",
"processDefinitionCache",
".",
"add",
"(",
"processDefinition",
".",
"getId",
"(",
")",
",",
"cacheEntry",
")",
";",
"addDefinitionInfoToCache",
"(",
"processDefinition",
",",
"processEngineConfiguration",
",",
"commandContext",
")",
";",
"// Add to deployment for further usage",
"deployment",
".",
"addDeployedArtifact",
"(",
"processDefinition",
")",
";",
"}",
"}"
]
| Ensures that the process definition is cached in the appropriate places, including the
deployment's collection of deployed artifacts and the deployment manager's cache, as well
as caching any ProcessDefinitionInfos. | [
"Ensures",
"that",
"the",
"process",
"definition",
"is",
"cached",
"in",
"the",
"appropriate",
"places",
"including",
"the",
"deployment",
"s",
"collection",
"of",
"deployed",
"artifacts",
"and",
"the",
"deployment",
"manager",
"s",
"cache",
"as",
"well",
"as",
"caching",
"any",
"ProcessDefinitionInfos",
"."
]
| train | https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/CachingAndArtifactsManager.java#L44-L61 |
mgm-tp/jfunk | jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java | ResourceLoader.getInputStream | public static InputStream getInputStream(final File baseDir, final String resource) throws IOException {
"""
Loads a resource as {@link InputStream}.
@param baseDir
If not {@code null}, the directory relative to which resources are loaded.
@param resource
The resource to be loaded. If {@code baseDir} is not {@code null}, it is loaded
relative to {@code baseDir}.
@return The stream
"""
File resourceFile = baseDir == null ? new File(resource) : new File(baseDir, resource);
return getInputStream(resourceFile);
} | java | public static InputStream getInputStream(final File baseDir, final String resource) throws IOException {
File resourceFile = baseDir == null ? new File(resource) : new File(baseDir, resource);
return getInputStream(resourceFile);
} | [
"public",
"static",
"InputStream",
"getInputStream",
"(",
"final",
"File",
"baseDir",
",",
"final",
"String",
"resource",
")",
"throws",
"IOException",
"{",
"File",
"resourceFile",
"=",
"baseDir",
"==",
"null",
"?",
"new",
"File",
"(",
"resource",
")",
":",
"new",
"File",
"(",
"baseDir",
",",
"resource",
")",
";",
"return",
"getInputStream",
"(",
"resourceFile",
")",
";",
"}"
]
| Loads a resource as {@link InputStream}.
@param baseDir
If not {@code null}, the directory relative to which resources are loaded.
@param resource
The resource to be loaded. If {@code baseDir} is not {@code null}, it is loaded
relative to {@code baseDir}.
@return The stream | [
"Loads",
"a",
"resource",
"as",
"{",
"@link",
"InputStream",
"}",
"."
]
| train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java#L233-L236 |
intive-FDV/DynamicJasper | src/main/java/ar/com/fdvs/dj/core/layout/AbstractLayoutManager.java | AbstractLayoutManager.setBandFinalHeight | private void setBandFinalHeight(JRDesignBand band, int currHeigth, boolean fitToContent) {
"""
Removes empty space when "fitToContent" is true and real height of object is
taller than current bands height, otherwise, it is not modified
@param band
@param currHeigth
@param fitToContent
"""
if (band != null) {
int finalHeight = LayoutUtils.findVerticalOffset(band);
//noinspection StatementWithEmptyBody
if (finalHeight < currHeigth && !fitToContent) {
//nothing
} else {
band.setHeight(finalHeight);
}
}
} | java | private void setBandFinalHeight(JRDesignBand band, int currHeigth, boolean fitToContent) {
if (band != null) {
int finalHeight = LayoutUtils.findVerticalOffset(band);
//noinspection StatementWithEmptyBody
if (finalHeight < currHeigth && !fitToContent) {
//nothing
} else {
band.setHeight(finalHeight);
}
}
} | [
"private",
"void",
"setBandFinalHeight",
"(",
"JRDesignBand",
"band",
",",
"int",
"currHeigth",
",",
"boolean",
"fitToContent",
")",
"{",
"if",
"(",
"band",
"!=",
"null",
")",
"{",
"int",
"finalHeight",
"=",
"LayoutUtils",
".",
"findVerticalOffset",
"(",
"band",
")",
";",
"//noinspection StatementWithEmptyBody",
"if",
"(",
"finalHeight",
"<",
"currHeigth",
"&&",
"!",
"fitToContent",
")",
"{",
"//nothing",
"}",
"else",
"{",
"band",
".",
"setHeight",
"(",
"finalHeight",
")",
";",
"}",
"}",
"}"
]
| Removes empty space when "fitToContent" is true and real height of object is
taller than current bands height, otherwise, it is not modified
@param band
@param currHeigth
@param fitToContent | [
"Removes",
"empty",
"space",
"when",
"fitToContent",
"is",
"true",
"and",
"real",
"height",
"of",
"object",
"is",
"taller",
"than",
"current",
"bands",
"height",
"otherwise",
"it",
"is",
"not",
"modified"
]
| train | https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/core/layout/AbstractLayoutManager.java#L742-L753 |
logic-ng/LogicNG | src/main/java/org/logicng/formulas/ExtendedFormulaFactory.java | ExtendedFormulaFactory.shrinkMap | private static <T, U> void shrinkMap(final Map<T, U> map, int newSize) {
"""
Shrinks a given map to a given size
@param map the map to be shrunk
@param newSize the new size, the map shall be shrunk to
"""
if (!(map instanceof LinkedHashMap))
throw new IllegalStateException("Cannot shrink a map which is not of type LinkedHashMap");
if (newSize > map.size())
throw new IllegalStateException("Cannot shrink a map of size " + map.size() + " to new size " + newSize);
Iterator<Map.Entry<T, U>> entryIterator = map.entrySet().iterator();
int count = 0;
while (count < newSize) {
entryIterator.next();
count++;
}
while (entryIterator.hasNext()) {
entryIterator.next();
entryIterator.remove();
}
} | java | private static <T, U> void shrinkMap(final Map<T, U> map, int newSize) {
if (!(map instanceof LinkedHashMap))
throw new IllegalStateException("Cannot shrink a map which is not of type LinkedHashMap");
if (newSize > map.size())
throw new IllegalStateException("Cannot shrink a map of size " + map.size() + " to new size " + newSize);
Iterator<Map.Entry<T, U>> entryIterator = map.entrySet().iterator();
int count = 0;
while (count < newSize) {
entryIterator.next();
count++;
}
while (entryIterator.hasNext()) {
entryIterator.next();
entryIterator.remove();
}
} | [
"private",
"static",
"<",
"T",
",",
"U",
">",
"void",
"shrinkMap",
"(",
"final",
"Map",
"<",
"T",
",",
"U",
">",
"map",
",",
"int",
"newSize",
")",
"{",
"if",
"(",
"!",
"(",
"map",
"instanceof",
"LinkedHashMap",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot shrink a map which is not of type LinkedHashMap\"",
")",
";",
"if",
"(",
"newSize",
">",
"map",
".",
"size",
"(",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot shrink a map of size \"",
"+",
"map",
".",
"size",
"(",
")",
"+",
"\" to new size \"",
"+",
"newSize",
")",
";",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"T",
",",
"U",
">",
">",
"entryIterator",
"=",
"map",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"int",
"count",
"=",
"0",
";",
"while",
"(",
"count",
"<",
"newSize",
")",
"{",
"entryIterator",
".",
"next",
"(",
")",
";",
"count",
"++",
";",
"}",
"while",
"(",
"entryIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"entryIterator",
".",
"next",
"(",
")",
";",
"entryIterator",
".",
"remove",
"(",
")",
";",
"}",
"}"
]
| Shrinks a given map to a given size
@param map the map to be shrunk
@param newSize the new size, the map shall be shrunk to | [
"Shrinks",
"a",
"given",
"map",
"to",
"a",
"given",
"size"
]
| train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/formulas/ExtendedFormulaFactory.java#L60-L75 |
OwlPlatform/java-owl-solver | src/main/java/com/owlplatform/solver/SolverAggregatorInterface.java | SolverAggregatorInterface.exceptionCaught | protected void exceptionCaught(IoSession session, Throwable cause) {
"""
Called when an exception occurs on the session
@param session
the session on which the exception occurred
@param cause
the exception
"""
log.error("Unhandled exception for: " + String.valueOf(session), cause);
if (this.disconnectOnException) {
this._disconnect();
}
} | java | protected void exceptionCaught(IoSession session, Throwable cause) {
log.error("Unhandled exception for: " + String.valueOf(session), cause);
if (this.disconnectOnException) {
this._disconnect();
}
} | [
"protected",
"void",
"exceptionCaught",
"(",
"IoSession",
"session",
",",
"Throwable",
"cause",
")",
"{",
"log",
".",
"error",
"(",
"\"Unhandled exception for: \"",
"+",
"String",
".",
"valueOf",
"(",
"session",
")",
",",
"cause",
")",
";",
"if",
"(",
"this",
".",
"disconnectOnException",
")",
"{",
"this",
".",
"_disconnect",
"(",
")",
";",
"}",
"}"
]
| Called when an exception occurs on the session
@param session
the session on which the exception occurred
@param cause
the exception | [
"Called",
"when",
"an",
"exception",
"occurs",
"on",
"the",
"session"
]
| train | https://github.com/OwlPlatform/java-owl-solver/blob/53a1faabd63613c716203922cd52f871e5fedb9b/src/main/java/com/owlplatform/solver/SolverAggregatorInterface.java#L827-L832 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataUnionOfImpl_CustomFieldSerializer.java | OWLDataUnionOfImpl_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataUnionOfImpl instance) throws SerializationException {
"""
Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful
"""
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataUnionOfImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLDataUnionOfImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
]
| Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamWriter",
"}",
"."
]
| train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataUnionOfImpl_CustomFieldSerializer.java#L69-L72 |
geomajas/geomajas-project-client-gwt2 | server-extension/src/main/java/org/geomajas/gwt2/client/controller/FeatureSelectionController.java | FeatureSelectionController.searchAtLocation | private void searchAtLocation(Coordinate location, boolean isShift) {
"""
Search for features at a certain location.
@param location
The location to check.
@param isShift
Is the shift button pressed down?
"""
Geometry point = new Geometry(Geometry.POINT, 0, -1);
point.setCoordinates(new Coordinate[] { location });
GeomajasServerExtension
.getInstance()
.getServerFeatureService()
.search(mapPresenter, point, pixelsToUnits(pixelTolerance), QueryType.INTERSECTS, searchLayerType, -1,
new SelectionCallback(isShift, false));
} | java | private void searchAtLocation(Coordinate location, boolean isShift) {
Geometry point = new Geometry(Geometry.POINT, 0, -1);
point.setCoordinates(new Coordinate[] { location });
GeomajasServerExtension
.getInstance()
.getServerFeatureService()
.search(mapPresenter, point, pixelsToUnits(pixelTolerance), QueryType.INTERSECTS, searchLayerType, -1,
new SelectionCallback(isShift, false));
} | [
"private",
"void",
"searchAtLocation",
"(",
"Coordinate",
"location",
",",
"boolean",
"isShift",
")",
"{",
"Geometry",
"point",
"=",
"new",
"Geometry",
"(",
"Geometry",
".",
"POINT",
",",
"0",
",",
"-",
"1",
")",
";",
"point",
".",
"setCoordinates",
"(",
"new",
"Coordinate",
"[",
"]",
"{",
"location",
"}",
")",
";",
"GeomajasServerExtension",
".",
"getInstance",
"(",
")",
".",
"getServerFeatureService",
"(",
")",
".",
"search",
"(",
"mapPresenter",
",",
"point",
",",
"pixelsToUnits",
"(",
"pixelTolerance",
")",
",",
"QueryType",
".",
"INTERSECTS",
",",
"searchLayerType",
",",
"-",
"1",
",",
"new",
"SelectionCallback",
"(",
"isShift",
",",
"false",
")",
")",
";",
"}"
]
| Search for features at a certain location.
@param location
The location to check.
@param isShift
Is the shift button pressed down? | [
"Search",
"for",
"features",
"at",
"a",
"certain",
"location",
"."
]
| train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/server-extension/src/main/java/org/geomajas/gwt2/client/controller/FeatureSelectionController.java#L275-L284 |
coveo/fmt-maven-plugin | src/main/java/com/coveo/Check.java | Check.postExecute | @Override
protected void postExecute(List<String> filesProcessed, int nonComplyingFiles)
throws MojoFailureException {
"""
Post Execute action. It is called at the end of the execute method. Subclasses can add extra
checks.
@param filesProcessed the list of processed files by the formatter
@param nonComplyingFiles the number of files that are not compliant
@throws MojoFailureException if there is an exception
"""
if (nonComplyingFiles > 0) {
String message = "Found " + nonComplyingFiles + " non-complying files, failing build";
getLog().error(message);
getLog().error("To fix formatting errors, run \"mvn com.coveo:fmt-maven-plugin:format\"");
// do not support limit < 1
displayLimit = max(1, displayLimit);
// Display first displayLimit files not formatted
if (displayFiles) {
for (String path :
filesNotFormatted.subList(0, min(displayLimit, filesNotFormatted.size()))) {
getLog().error("Non complying file: " + path);
}
if (nonComplyingFiles > displayLimit) {
getLog().error(format("... and %d more files.", nonComplyingFiles - displayLimit));
}
}
throw new MojoFailureException(message);
}
} | java | @Override
protected void postExecute(List<String> filesProcessed, int nonComplyingFiles)
throws MojoFailureException {
if (nonComplyingFiles > 0) {
String message = "Found " + nonComplyingFiles + " non-complying files, failing build";
getLog().error(message);
getLog().error("To fix formatting errors, run \"mvn com.coveo:fmt-maven-plugin:format\"");
// do not support limit < 1
displayLimit = max(1, displayLimit);
// Display first displayLimit files not formatted
if (displayFiles) {
for (String path :
filesNotFormatted.subList(0, min(displayLimit, filesNotFormatted.size()))) {
getLog().error("Non complying file: " + path);
}
if (nonComplyingFiles > displayLimit) {
getLog().error(format("... and %d more files.", nonComplyingFiles - displayLimit));
}
}
throw new MojoFailureException(message);
}
} | [
"@",
"Override",
"protected",
"void",
"postExecute",
"(",
"List",
"<",
"String",
">",
"filesProcessed",
",",
"int",
"nonComplyingFiles",
")",
"throws",
"MojoFailureException",
"{",
"if",
"(",
"nonComplyingFiles",
">",
"0",
")",
"{",
"String",
"message",
"=",
"\"Found \"",
"+",
"nonComplyingFiles",
"+",
"\" non-complying files, failing build\"",
";",
"getLog",
"(",
")",
".",
"error",
"(",
"message",
")",
";",
"getLog",
"(",
")",
".",
"error",
"(",
"\"To fix formatting errors, run \\\"mvn com.coveo:fmt-maven-plugin:format\\\"\"",
")",
";",
"// do not support limit < 1",
"displayLimit",
"=",
"max",
"(",
"1",
",",
"displayLimit",
")",
";",
"// Display first displayLimit files not formatted",
"if",
"(",
"displayFiles",
")",
"{",
"for",
"(",
"String",
"path",
":",
"filesNotFormatted",
".",
"subList",
"(",
"0",
",",
"min",
"(",
"displayLimit",
",",
"filesNotFormatted",
".",
"size",
"(",
")",
")",
")",
")",
"{",
"getLog",
"(",
")",
".",
"error",
"(",
"\"Non complying file: \"",
"+",
"path",
")",
";",
"}",
"if",
"(",
"nonComplyingFiles",
">",
"displayLimit",
")",
"{",
"getLog",
"(",
")",
".",
"error",
"(",
"format",
"(",
"\"... and %d more files.\"",
",",
"nonComplyingFiles",
"-",
"displayLimit",
")",
")",
";",
"}",
"}",
"throw",
"new",
"MojoFailureException",
"(",
"message",
")",
";",
"}",
"}"
]
| Post Execute action. It is called at the end of the execute method. Subclasses can add extra
checks.
@param filesProcessed the list of processed files by the formatter
@param nonComplyingFiles the number of files that are not compliant
@throws MojoFailureException if there is an exception | [
"Post",
"Execute",
"action",
".",
"It",
"is",
"called",
"at",
"the",
"end",
"of",
"the",
"execute",
"method",
".",
"Subclasses",
"can",
"add",
"extra",
"checks",
"."
]
| train | https://github.com/coveo/fmt-maven-plugin/blob/9368be6985ecc2126c875ff4aabe647c7e57ecca/src/main/java/com/coveo/Check.java#L42-L65 |
apache/incubator-druid | processing/src/main/java/org/apache/druid/query/TimewarpOperator.java | TimewarpOperator.computeOffset | protected long computeOffset(final long t, final DateTimeZone tz) {
"""
Map time t into the last `period` ending within `dataInterval`
@param t the current time to be mapped into `dataInterval`
@return the offset between the mapped time and time t
"""
// start is the beginning of the last period ending within dataInterval
long start = dataInterval.getEndMillis() - periodMillis;
long startOffset = start % periodMillis - originMillis % periodMillis;
if (startOffset < 0) {
startOffset += periodMillis;
}
start -= startOffset;
// tOffset is the offset time t within the last period
long tOffset = t % periodMillis - originMillis % periodMillis;
if (tOffset < 0) {
tOffset += periodMillis;
}
tOffset += start;
return tOffset - t - (tz.getOffset(tOffset) - tz.getOffset(t));
} | java | protected long computeOffset(final long t, final DateTimeZone tz)
{
// start is the beginning of the last period ending within dataInterval
long start = dataInterval.getEndMillis() - periodMillis;
long startOffset = start % periodMillis - originMillis % periodMillis;
if (startOffset < 0) {
startOffset += periodMillis;
}
start -= startOffset;
// tOffset is the offset time t within the last period
long tOffset = t % periodMillis - originMillis % periodMillis;
if (tOffset < 0) {
tOffset += periodMillis;
}
tOffset += start;
return tOffset - t - (tz.getOffset(tOffset) - tz.getOffset(t));
} | [
"protected",
"long",
"computeOffset",
"(",
"final",
"long",
"t",
",",
"final",
"DateTimeZone",
"tz",
")",
"{",
"// start is the beginning of the last period ending within dataInterval",
"long",
"start",
"=",
"dataInterval",
".",
"getEndMillis",
"(",
")",
"-",
"periodMillis",
";",
"long",
"startOffset",
"=",
"start",
"%",
"periodMillis",
"-",
"originMillis",
"%",
"periodMillis",
";",
"if",
"(",
"startOffset",
"<",
"0",
")",
"{",
"startOffset",
"+=",
"periodMillis",
";",
"}",
"start",
"-=",
"startOffset",
";",
"// tOffset is the offset time t within the last period",
"long",
"tOffset",
"=",
"t",
"%",
"periodMillis",
"-",
"originMillis",
"%",
"periodMillis",
";",
"if",
"(",
"tOffset",
"<",
"0",
")",
"{",
"tOffset",
"+=",
"periodMillis",
";",
"}",
"tOffset",
"+=",
"start",
";",
"return",
"tOffset",
"-",
"t",
"-",
"(",
"tz",
".",
"getOffset",
"(",
"tOffset",
")",
"-",
"tz",
".",
"getOffset",
"(",
"t",
")",
")",
";",
"}"
]
| Map time t into the last `period` ending within `dataInterval`
@param t the current time to be mapped into `dataInterval`
@return the offset between the mapped time and time t | [
"Map",
"time",
"t",
"into",
"the",
"last",
"period",
"ending",
"within",
"dataInterval"
]
| train | https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/query/TimewarpOperator.java#L148-L166 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/Async.java | Async.toAsyncThrowing | public static <T1, T2, T3, T4, T5, R> Func5<T1, T2, T3, T4, T5, Observable<R>> toAsyncThrowing(final ThrowingFunc5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> func, final Scheduler scheduler) {
"""
Convert a synchronous function call into an asynchronous function call through an Observable.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.png" alt="">
@param <T1> the first parameter type
@param <T2> the second parameter type
@param <T3> the third parameter type
@param <T4> the fourth parameter type
@param <T5> the fifth parameter type
@param <R> the result type
@param func the function to convert
@return a function that returns an Observable that executes the {@code func} and emits its returned value
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a>
@see <a href="http://msdn.microsoft.com/en-us/library/hh229571.aspx">MSDN: Observable.ToAsync</a>
"""
return new Func5<T1, T2, T3, T4, T5, Observable<R>>() {
@Override
public Observable<R> call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) {
return startCallable(ThrowingFunctions.toCallable(func, t1, t2, t3, t4, t5), scheduler);
}
};
} | java | public static <T1, T2, T3, T4, T5, R> Func5<T1, T2, T3, T4, T5, Observable<R>> toAsyncThrowing(final ThrowingFunc5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> func, final Scheduler scheduler) {
return new Func5<T1, T2, T3, T4, T5, Observable<R>>() {
@Override
public Observable<R> call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) {
return startCallable(ThrowingFunctions.toCallable(func, t1, t2, t3, t4, t5), scheduler);
}
};
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"R",
">",
"Func5",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"Observable",
"<",
"R",
">",
">",
"toAsyncThrowing",
"(",
"final",
"ThrowingFunc5",
"<",
"?",
"super",
"T1",
",",
"?",
"super",
"T2",
",",
"?",
"super",
"T3",
",",
"?",
"super",
"T4",
",",
"?",
"super",
"T5",
",",
"?",
"extends",
"R",
">",
"func",
",",
"final",
"Scheduler",
"scheduler",
")",
"{",
"return",
"new",
"Func5",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"Observable",
"<",
"R",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Observable",
"<",
"R",
">",
"call",
"(",
"T1",
"t1",
",",
"T2",
"t2",
",",
"T3",
"t3",
",",
"T4",
"t4",
",",
"T5",
"t5",
")",
"{",
"return",
"startCallable",
"(",
"ThrowingFunctions",
".",
"toCallable",
"(",
"func",
",",
"t1",
",",
"t2",
",",
"t3",
",",
"t4",
",",
"t5",
")",
",",
"scheduler",
")",
";",
"}",
"}",
";",
"}"
]
| Convert a synchronous function call into an asynchronous function call through an Observable.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.png" alt="">
@param <T1> the first parameter type
@param <T2> the second parameter type
@param <T3> the third parameter type
@param <T4> the fourth parameter type
@param <T5> the fifth parameter type
@param <R> the result type
@param func the function to convert
@return a function that returns an Observable that executes the {@code func} and emits its returned value
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a>
@see <a href="http://msdn.microsoft.com/en-us/library/hh229571.aspx">MSDN: Observable.ToAsync</a> | [
"Convert",
"a",
"synchronous",
"function",
"call",
"into",
"an",
"asynchronous",
"function",
"call",
"through",
"an",
"Observable",
".",
"<p",
">",
"<img",
"width",
"=",
"640",
"src",
"=",
"https",
":",
"//",
"raw",
".",
"github",
".",
"com",
"/",
"wiki",
"/",
"ReactiveX",
"/",
"RxJava",
"/",
"images",
"/",
"rx",
"-",
"operators",
"/",
"toAsync",
".",
"png",
"alt",
"=",
">"
]
| train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L1219-L1226 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.domain_mailingList_name_GET | public OvhMailingList domain_mailingList_name_GET(String domain, String name) throws IOException {
"""
Get this object properties
REST: GET /email/domain/{domain}/mailingList/{name}
@param domain [required] Name of your domain name
@param name [required] Name of mailing list
"""
String qPath = "/email/domain/{domain}/mailingList/{name}";
StringBuilder sb = path(qPath, domain, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhMailingList.class);
} | java | public OvhMailingList domain_mailingList_name_GET(String domain, String name) throws IOException {
String qPath = "/email/domain/{domain}/mailingList/{name}";
StringBuilder sb = path(qPath, domain, name);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhMailingList.class);
} | [
"public",
"OvhMailingList",
"domain_mailingList_name_GET",
"(",
"String",
"domain",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/{domain}/mailingList/{name}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"domain",
",",
"name",
")",
";",
"String",
"resp",
"=",
"exec",
"(",
"qPath",
",",
"\"GET\"",
",",
"sb",
".",
"toString",
"(",
")",
",",
"null",
")",
";",
"return",
"convertTo",
"(",
"resp",
",",
"OvhMailingList",
".",
"class",
")",
";",
"}"
]
| Get this object properties
REST: GET /email/domain/{domain}/mailingList/{name}
@param domain [required] Name of your domain name
@param name [required] Name of mailing list | [
"Get",
"this",
"object",
"properties"
]
| train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L1526-L1531 |
finmath/finmath-lib | src/main/java6/net/finmath/montecarlo/assetderivativevaluation/products/LocalRiskMinimizingHedgePortfolio.java | LocalRiskMinimizingHedgePortfolio.getBasisFunctions | private RandomVariableInterface[] getBasisFunctions(RandomVariableInterface underlying) {
"""
Create basis functions for a binning.
@param underlying
@return
"""
double min = underlying.getMin();
double max = underlying.getMax();
ArrayList<RandomVariableInterface> basisFunctionList = new ArrayList<RandomVariableInterface>();
double[] discretization = (new TimeDiscretization(min, numberOfBins, (max-min)/numberOfBins)).getAsDoubleArray();
for(double discretizationStep : discretization) {
RandomVariableInterface indicator = underlying.barrier(underlying.sub(discretizationStep), new RandomVariable(1.0), 0.0);
basisFunctionList.add(indicator);
}
return basisFunctionList.toArray(new RandomVariableInterface[0]);
} | java | private RandomVariableInterface[] getBasisFunctions(RandomVariableInterface underlying) {
double min = underlying.getMin();
double max = underlying.getMax();
ArrayList<RandomVariableInterface> basisFunctionList = new ArrayList<RandomVariableInterface>();
double[] discretization = (new TimeDiscretization(min, numberOfBins, (max-min)/numberOfBins)).getAsDoubleArray();
for(double discretizationStep : discretization) {
RandomVariableInterface indicator = underlying.barrier(underlying.sub(discretizationStep), new RandomVariable(1.0), 0.0);
basisFunctionList.add(indicator);
}
return basisFunctionList.toArray(new RandomVariableInterface[0]);
} | [
"private",
"RandomVariableInterface",
"[",
"]",
"getBasisFunctions",
"(",
"RandomVariableInterface",
"underlying",
")",
"{",
"double",
"min",
"=",
"underlying",
".",
"getMin",
"(",
")",
";",
"double",
"max",
"=",
"underlying",
".",
"getMax",
"(",
")",
";",
"ArrayList",
"<",
"RandomVariableInterface",
">",
"basisFunctionList",
"=",
"new",
"ArrayList",
"<",
"RandomVariableInterface",
">",
"(",
")",
";",
"double",
"[",
"]",
"discretization",
"=",
"(",
"new",
"TimeDiscretization",
"(",
"min",
",",
"numberOfBins",
",",
"(",
"max",
"-",
"min",
")",
"/",
"numberOfBins",
")",
")",
".",
"getAsDoubleArray",
"(",
")",
";",
"for",
"(",
"double",
"discretizationStep",
":",
"discretization",
")",
"{",
"RandomVariableInterface",
"indicator",
"=",
"underlying",
".",
"barrier",
"(",
"underlying",
".",
"sub",
"(",
"discretizationStep",
")",
",",
"new",
"RandomVariable",
"(",
"1.0",
")",
",",
"0.0",
")",
";",
"basisFunctionList",
".",
"add",
"(",
"indicator",
")",
";",
"}",
"return",
"basisFunctionList",
".",
"toArray",
"(",
"new",
"RandomVariableInterface",
"[",
"0",
"]",
")",
";",
"}"
]
| Create basis functions for a binning.
@param underlying
@return | [
"Create",
"basis",
"functions",
"for",
"a",
"binning",
"."
]
| train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/montecarlo/assetderivativevaluation/products/LocalRiskMinimizingHedgePortfolio.java#L155-L167 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/util/OverlayHelper.java | OverlayHelper.attachOverlay | public static void attachOverlay(JComponent overlay, JComponent overlayTarget, int center, int xOffset, int yOffset) {
"""
Attaches an overlay to the specified component.
@param overlay the overlay component
@param overlayTarget the component over which <code>overlay</code> will be
attached
@param center position relative to <code>overlayTarget</code> that overlay
should be centered. May be one of the
<code>SwingConstants</code> compass positions or
<code>SwingConstants.CENTER</code>.
@param xOffset x offset from center
@param yOffset y offset from center
@see SwingConstants
"""
new OverlayHelper(overlay, overlayTarget, center, xOffset, yOffset);
} | java | public static void attachOverlay(JComponent overlay, JComponent overlayTarget, int center, int xOffset, int yOffset)
{
new OverlayHelper(overlay, overlayTarget, center, xOffset, yOffset);
} | [
"public",
"static",
"void",
"attachOverlay",
"(",
"JComponent",
"overlay",
",",
"JComponent",
"overlayTarget",
",",
"int",
"center",
",",
"int",
"xOffset",
",",
"int",
"yOffset",
")",
"{",
"new",
"OverlayHelper",
"(",
"overlay",
",",
"overlayTarget",
",",
"center",
",",
"xOffset",
",",
"yOffset",
")",
";",
"}"
]
| Attaches an overlay to the specified component.
@param overlay the overlay component
@param overlayTarget the component over which <code>overlay</code> will be
attached
@param center position relative to <code>overlayTarget</code> that overlay
should be centered. May be one of the
<code>SwingConstants</code> compass positions or
<code>SwingConstants.CENTER</code>.
@param xOffset x offset from center
@param yOffset y offset from center
@see SwingConstants | [
"Attaches",
"an",
"overlay",
"to",
"the",
"specified",
"component",
"."
]
| train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/util/OverlayHelper.java#L67-L70 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java | BoxApiFile.getUploadNewVersionRequest | public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(File file, String destinationFileId) {
"""
Gets a request that uploads a new file version from an existing file
@param file file to upload as a new version
@param destinationFileId id of the file to upload a new version of
@return request to upload a new file version from an existing file
"""
try {
BoxRequestsFile.UploadNewVersion request = getUploadNewVersionRequest(new FileInputStream(file), destinationFileId);
request.setUploadSize(file.length());
request.setModifiedDate(new Date(file.lastModified()));
return request;
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e);
}
} | java | public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(File file, String destinationFileId) {
try {
BoxRequestsFile.UploadNewVersion request = getUploadNewVersionRequest(new FileInputStream(file), destinationFileId);
request.setUploadSize(file.length());
request.setModifiedDate(new Date(file.lastModified()));
return request;
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e);
}
} | [
"public",
"BoxRequestsFile",
".",
"UploadNewVersion",
"getUploadNewVersionRequest",
"(",
"File",
"file",
",",
"String",
"destinationFileId",
")",
"{",
"try",
"{",
"BoxRequestsFile",
".",
"UploadNewVersion",
"request",
"=",
"getUploadNewVersionRequest",
"(",
"new",
"FileInputStream",
"(",
"file",
")",
",",
"destinationFileId",
")",
";",
"request",
".",
"setUploadSize",
"(",
"file",
".",
"length",
"(",
")",
")",
";",
"request",
".",
"setModifiedDate",
"(",
"new",
"Date",
"(",
"file",
".",
"lastModified",
"(",
")",
")",
")",
";",
"return",
"request",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"e",
")",
";",
"}",
"}"
]
| Gets a request that uploads a new file version from an existing file
@param file file to upload as a new version
@param destinationFileId id of the file to upload a new version of
@return request to upload a new file version from an existing file | [
"Gets",
"a",
"request",
"that",
"uploads",
"a",
"new",
"file",
"version",
"from",
"an",
"existing",
"file"
]
| train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiFile.java#L348-L357 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.audit.reader/src/com/ibm/ws/security/audit/reader/tasks/BaseCommandTask.java | BaseCommandTask.promptForText | private String promptForText(ConsoleWrapper stdin, PrintStream stdout,
String enterText, String reenterText,
String readError, String entriesDidNotMatch) {
"""
Prompt the user to enter text.
Prompts twice and compares to ensure it was entered correctly.
@return Entered String
"""
String read1 = stdin.readMaskedText(getMessage(enterText) + " ");
String read2 = stdin.readMaskedText(getMessage(reenterText) + " ");
if (read1 == null && read2 == null) {
throw new IllegalArgumentException("Unable to read either entry. Aborting prompt.");
} else if (read1 == null || read2 == null) {
stdout.println(getMessage(readError));
return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch);
} else if (read1.equals(read2)) {
return read1;
} else {
stdout.println(getMessage(entriesDidNotMatch));
return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch);
}
} | java | private String promptForText(ConsoleWrapper stdin, PrintStream stdout,
String enterText, String reenterText,
String readError, String entriesDidNotMatch) {
String read1 = stdin.readMaskedText(getMessage(enterText) + " ");
String read2 = stdin.readMaskedText(getMessage(reenterText) + " ");
if (read1 == null && read2 == null) {
throw new IllegalArgumentException("Unable to read either entry. Aborting prompt.");
} else if (read1 == null || read2 == null) {
stdout.println(getMessage(readError));
return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch);
} else if (read1.equals(read2)) {
return read1;
} else {
stdout.println(getMessage(entriesDidNotMatch));
return promptForText(stdin, stdout, enterText, reenterText, readError, entriesDidNotMatch);
}
} | [
"private",
"String",
"promptForText",
"(",
"ConsoleWrapper",
"stdin",
",",
"PrintStream",
"stdout",
",",
"String",
"enterText",
",",
"String",
"reenterText",
",",
"String",
"readError",
",",
"String",
"entriesDidNotMatch",
")",
"{",
"String",
"read1",
"=",
"stdin",
".",
"readMaskedText",
"(",
"getMessage",
"(",
"enterText",
")",
"+",
"\" \"",
")",
";",
"String",
"read2",
"=",
"stdin",
".",
"readMaskedText",
"(",
"getMessage",
"(",
"reenterText",
")",
"+",
"\" \"",
")",
";",
"if",
"(",
"read1",
"==",
"null",
"&&",
"read2",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unable to read either entry. Aborting prompt.\"",
")",
";",
"}",
"else",
"if",
"(",
"read1",
"==",
"null",
"||",
"read2",
"==",
"null",
")",
"{",
"stdout",
".",
"println",
"(",
"getMessage",
"(",
"readError",
")",
")",
";",
"return",
"promptForText",
"(",
"stdin",
",",
"stdout",
",",
"enterText",
",",
"reenterText",
",",
"readError",
",",
"entriesDidNotMatch",
")",
";",
"}",
"else",
"if",
"(",
"read1",
".",
"equals",
"(",
"read2",
")",
")",
"{",
"return",
"read1",
";",
"}",
"else",
"{",
"stdout",
".",
"println",
"(",
"getMessage",
"(",
"entriesDidNotMatch",
")",
")",
";",
"return",
"promptForText",
"(",
"stdin",
",",
"stdout",
",",
"enterText",
",",
"reenterText",
",",
"readError",
",",
"entriesDidNotMatch",
")",
";",
"}",
"}"
]
| Prompt the user to enter text.
Prompts twice and compares to ensure it was entered correctly.
@return Entered String | [
"Prompt",
"the",
"user",
"to",
"enter",
"text",
".",
"Prompts",
"twice",
"and",
"compares",
"to",
"ensure",
"it",
"was",
"entered",
"correctly",
"."
]
| train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.audit.reader/src/com/ibm/ws/security/audit/reader/tasks/BaseCommandTask.java#L203-L219 |
lukas-krecan/lambda-param-name-extractor | src/main/java/net/javacrumbs/lambdaextractor/ParameterNameExtractor.java | ParameterNameExtractor.extractParameterNames | public static List<String> extractParameterNames(Serializable lambda, int lambdaParametersCount) {
"""
Extracts names of a serializable lambda parameters
@param lambda Serializable lambda
@param lambdaParametersCount number of lambda parameters
"""
SerializedLambda serializedLambda = serialized(lambda);
Method lambdaMethod = lambdaMethod(serializedLambda);
String[] paramNames = paramNameReader.getParamNames(lambdaMethod);
return asList(Arrays.copyOfRange(paramNames, paramNames.length - lambdaParametersCount, paramNames.length));
} | java | public static List<String> extractParameterNames(Serializable lambda, int lambdaParametersCount) {
SerializedLambda serializedLambda = serialized(lambda);
Method lambdaMethod = lambdaMethod(serializedLambda);
String[] paramNames = paramNameReader.getParamNames(lambdaMethod);
return asList(Arrays.copyOfRange(paramNames, paramNames.length - lambdaParametersCount, paramNames.length));
} | [
"public",
"static",
"List",
"<",
"String",
">",
"extractParameterNames",
"(",
"Serializable",
"lambda",
",",
"int",
"lambdaParametersCount",
")",
"{",
"SerializedLambda",
"serializedLambda",
"=",
"serialized",
"(",
"lambda",
")",
";",
"Method",
"lambdaMethod",
"=",
"lambdaMethod",
"(",
"serializedLambda",
")",
";",
"String",
"[",
"]",
"paramNames",
"=",
"paramNameReader",
".",
"getParamNames",
"(",
"lambdaMethod",
")",
";",
"return",
"asList",
"(",
"Arrays",
".",
"copyOfRange",
"(",
"paramNames",
",",
"paramNames",
".",
"length",
"-",
"lambdaParametersCount",
",",
"paramNames",
".",
"length",
")",
")",
";",
"}"
]
| Extracts names of a serializable lambda parameters
@param lambda Serializable lambda
@param lambdaParametersCount number of lambda parameters | [
"Extracts",
"names",
"of",
"a",
"serializable",
"lambda",
"parameters"
]
| train | https://github.com/lukas-krecan/lambda-param-name-extractor/blob/dec73479df14797771c8ec92819577f32a679362/src/main/java/net/javacrumbs/lambdaextractor/ParameterNameExtractor.java#L47-L53 |
Samsung/GearVRf | GVRf/Extensions/3DCursor/3DCursorLibrary/src/main/java/org/gearvrf/io/cursor3d/IoDevice.java | IoDevice.setRotation | protected void setRotation(float w, float x, float y, float z) {
"""
Use this method from the {@link IoDevice} subclass to set the rotation of the
{@link Cursor} in quaternion terms.
@param w 'W' component of the quaternion.
@param x 'X' component of the quaternion.
@param y 'Y' component of the quaternion.
@param z 'Z' component of the quaternion.
"""
if(disableRotation){
//we don't want to rotate a cursor with no rotation.
return;
}
GVRSceneObject sceneObject = gvrCursorController.getCursor();
if (sceneObject != null) {
sceneObject.getTransform().setRotation(w, x, y, z);
}
} | java | protected void setRotation(float w, float x, float y, float z) {
if(disableRotation){
//we don't want to rotate a cursor with no rotation.
return;
}
GVRSceneObject sceneObject = gvrCursorController.getCursor();
if (sceneObject != null) {
sceneObject.getTransform().setRotation(w, x, y, z);
}
} | [
"protected",
"void",
"setRotation",
"(",
"float",
"w",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"if",
"(",
"disableRotation",
")",
"{",
"//we don't want to rotate a cursor with no rotation.",
"return",
";",
"}",
"GVRSceneObject",
"sceneObject",
"=",
"gvrCursorController",
".",
"getCursor",
"(",
")",
";",
"if",
"(",
"sceneObject",
"!=",
"null",
")",
"{",
"sceneObject",
".",
"getTransform",
"(",
")",
".",
"setRotation",
"(",
"w",
",",
"x",
",",
"y",
",",
"z",
")",
";",
"}",
"}"
]
| Use this method from the {@link IoDevice} subclass to set the rotation of the
{@link Cursor} in quaternion terms.
@param w 'W' component of the quaternion.
@param x 'X' component of the quaternion.
@param y 'Y' component of the quaternion.
@param z 'Z' component of the quaternion. | [
"Use",
"this",
"method",
"from",
"the",
"{",
"@link",
"IoDevice",
"}",
"subclass",
"to",
"set",
"the",
"rotation",
"of",
"the",
"{",
"@link",
"Cursor",
"}",
"in",
"quaternion",
"terms",
"."
]
| train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/3DCursor/3DCursorLibrary/src/main/java/org/gearvrf/io/cursor3d/IoDevice.java#L268-L278 |
JavaKoan/koan-annotations | src/main/java/com/javakoan/fixture/io/KoanWriter.java | KoanWriter.writeSourceToFile | public static void writeSourceToFile(Class<?> koanClass, String newSource) {
"""
Write source to file.
@param koanClass the koan class
@param newSource the source code to be written
"""
Path currentRelativePath = Paths.get("");
String workingDirectory = currentRelativePath.toAbsolutePath().toString();
String packagePath = koanClass.getPackage().getName();
packagePath = packagePath.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR);
String className = koanClass.getSimpleName();
File file = new File(workingDirectory + KOAN_JAVA_PATH + packagePath + PATH_SEPARATOR + className + JAVA_EXTENSION);
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newSource);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} | java | public static void writeSourceToFile(Class<?> koanClass, String newSource) {
Path currentRelativePath = Paths.get("");
String workingDirectory = currentRelativePath.toAbsolutePath().toString();
String packagePath = koanClass.getPackage().getName();
packagePath = packagePath.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR);
String className = koanClass.getSimpleName();
File file = new File(workingDirectory + KOAN_JAVA_PATH + packagePath + PATH_SEPARATOR + className + JAVA_EXTENSION);
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newSource);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} | [
"public",
"static",
"void",
"writeSourceToFile",
"(",
"Class",
"<",
"?",
">",
"koanClass",
",",
"String",
"newSource",
")",
"{",
"Path",
"currentRelativePath",
"=",
"Paths",
".",
"get",
"(",
"\"\"",
")",
";",
"String",
"workingDirectory",
"=",
"currentRelativePath",
".",
"toAbsolutePath",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"packagePath",
"=",
"koanClass",
".",
"getPackage",
"(",
")",
".",
"getName",
"(",
")",
";",
"packagePath",
"=",
"packagePath",
".",
"replace",
"(",
"PACKAGE_SEPARATOR",
",",
"PATH_SEPARATOR",
")",
";",
"String",
"className",
"=",
"koanClass",
".",
"getSimpleName",
"(",
")",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"workingDirectory",
"+",
"KOAN_JAVA_PATH",
"+",
"packagePath",
"+",
"PATH_SEPARATOR",
"+",
"className",
"+",
"JAVA_EXTENSION",
")",
";",
"try",
"{",
"FileWriter",
"fw",
"=",
"new",
"FileWriter",
"(",
"file",
".",
"getAbsoluteFile",
"(",
")",
")",
";",
"BufferedWriter",
"bw",
"=",
"new",
"BufferedWriter",
"(",
"fw",
")",
";",
"bw",
".",
"write",
"(",
"newSource",
")",
";",
"bw",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}"
]
| Write source to file.
@param koanClass the koan class
@param newSource the source code to be written | [
"Write",
"source",
"to",
"file",
"."
]
| train | https://github.com/JavaKoan/koan-annotations/blob/e3c4872ae57051a0b74b2efa6f15f4ee9e37d263/src/main/java/com/javakoan/fixture/io/KoanWriter.java#L47-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.