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 |
|---|---|---|---|---|---|---|---|---|---|---|
imsweb/naaccr-xml | src/main/java/com/imsweb/naaccrxml/NaaccrXmlUtils.java | NaaccrXmlUtils.patientToLine | public static String patientToLine(Patient patient, NaaccrContext context) throws NaaccrIOException {
"""
Translates a single patient into a line representing a flat file line. This method expects a patient with 0 or 1 tumor. An exception will be raised if it has more.
<br/><br/>
Unlike the methods dealing with files, this method takes a context as a parameter. The reason for that difference is that this method uses a stream to convert
the patient, and so the stream needs to be re-created every time the method is invoked on a given patient. This is very inefficient and would be too slow if this
method was used in a loop (which is the common use-case). Having a shared context that is created once outside the loop avoids that inefficiency.
<br/><br/>
It is very important to not re-create the context when this method is called in a loop:
<br><br/>
This is NOT correct:
<code>
for (Patient patient : patients)
NaaccrXmlUtils.patientToLine(patient, new NaaccrContext(NaaccrFormat.NAACCR_FORMAT_16_ABSTRACT));
</code>
This is correct:
<code>
NaaccrContext context = new NaaccrContext(NaaccrFormat.NAACCR_FORMAT_16_ABSTRACT);
for (Patient patient : patients)
NaaccrXmlUtils.patientToLine(patient, context);
</code>
@param patient the patient to translate, required
@param context the context to use for the translation, required
@return the corresponding line, never null
@throws NaaccrIOException if there is problem translating the patient
"""
if (patient == null)
throw new NaaccrIOException("Patient is required");
if (context == null)
throw new NaaccrIOException("Context is required");
// it wouldn't be very hard to support more than one tumor, but will do it only if needed
if (patient.getTumors().size() > 1)
throw new NaaccrIOException("This method requires a patient with 0 or 1 tumor.");
StringWriter buf = new StringWriter();
try (PatientFlatWriter writer = new PatientFlatWriter(buf, new NaaccrData(context.getFormat()), context.getOptions(), context.getUserDictionaries(), context.getStreamConfiguration())) {
writer.writePatient(patient);
return buf.toString();
}
} | java | public static String patientToLine(Patient patient, NaaccrContext context) throws NaaccrIOException {
if (patient == null)
throw new NaaccrIOException("Patient is required");
if (context == null)
throw new NaaccrIOException("Context is required");
// it wouldn't be very hard to support more than one tumor, but will do it only if needed
if (patient.getTumors().size() > 1)
throw new NaaccrIOException("This method requires a patient with 0 or 1 tumor.");
StringWriter buf = new StringWriter();
try (PatientFlatWriter writer = new PatientFlatWriter(buf, new NaaccrData(context.getFormat()), context.getOptions(), context.getUserDictionaries(), context.getStreamConfiguration())) {
writer.writePatient(patient);
return buf.toString();
}
} | [
"public",
"static",
"String",
"patientToLine",
"(",
"Patient",
"patient",
",",
"NaaccrContext",
"context",
")",
"throws",
"NaaccrIOException",
"{",
"if",
"(",
"patient",
"==",
"null",
")",
"throw",
"new",
"NaaccrIOException",
"(",
"\"Patient is required\"",
")",
"... | Translates a single patient into a line representing a flat file line. This method expects a patient with 0 or 1 tumor. An exception will be raised if it has more.
<br/><br/>
Unlike the methods dealing with files, this method takes a context as a parameter. The reason for that difference is that this method uses a stream to convert
the patient, and so the stream needs to be re-created every time the method is invoked on a given patient. This is very inefficient and would be too slow if this
method was used in a loop (which is the common use-case). Having a shared context that is created once outside the loop avoids that inefficiency.
<br/><br/>
It is very important to not re-create the context when this method is called in a loop:
<br><br/>
This is NOT correct:
<code>
for (Patient patient : patients)
NaaccrXmlUtils.patientToLine(patient, new NaaccrContext(NaaccrFormat.NAACCR_FORMAT_16_ABSTRACT));
</code>
This is correct:
<code>
NaaccrContext context = new NaaccrContext(NaaccrFormat.NAACCR_FORMAT_16_ABSTRACT);
for (Patient patient : patients)
NaaccrXmlUtils.patientToLine(patient, context);
</code>
@param patient the patient to translate, required
@param context the context to use for the translation, required
@return the corresponding line, never null
@throws NaaccrIOException if there is problem translating the patient | [
"Translates",
"a",
"single",
"patient",
"into",
"a",
"line",
"representing",
"a",
"flat",
"file",
"line",
".",
"This",
"method",
"expects",
"a",
"patient",
"with",
"0",
"or",
"1",
"tumor",
".",
"An",
"exception",
"will",
"be",
"raised",
"if",
"it",
"has"... | train | https://github.com/imsweb/naaccr-xml/blob/a3a501faa2a0c3411dd5248b2c1379f279131696/src/main/java/com/imsweb/naaccrxml/NaaccrXmlUtils.java#L323-L338 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/mps/current_hostname.java | current_hostname.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception {
"""
<pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre>
"""
current_hostname_responses result = (current_hostname_responses) service.get_payload_formatter().string_to_resource(current_hostname_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.current_hostname_response_array);
}
current_hostname[] result_current_hostname = new current_hostname[result.current_hostname_response_array.length];
for(int i = 0; i < result.current_hostname_response_array.length; i++)
{
result_current_hostname[i] = result.current_hostname_response_array[i].current_hostname[0];
}
return result_current_hostname;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
current_hostname_responses result = (current_hostname_responses) service.get_payload_formatter().string_to_resource(current_hostname_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.current_hostname_response_array);
}
current_hostname[] result_current_hostname = new current_hostname[result.current_hostname_response_array.length];
for(int i = 0; i < result.current_hostname_response_array.length; i++)
{
result_current_hostname[i] = result.current_hostname_response_array[i].current_hostname[0];
}
return result_current_hostname;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"current_hostname_responses",
"result",
"=",
"(",
"current_hostname_responses",
")",
"service",
".",
"get_payl... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/current_hostname.java#L226-L243 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie.java | Trie.getCodePointOffset | protected final int getCodePointOffset(int ch) {
"""
Internal trie getter from a code point.
Could be faster(?) but longer with
if((c32)<=0xd7ff) { (result)=_TRIE_GET_RAW(trie, data, 0, c32); }
Gets the offset to data which the codepoint points to
@param ch codepoint
@return offset to data
"""
// if ((ch >> 16) == 0) slower
if (ch < 0) {
return -1;
} else if (ch < UTF16.LEAD_SURROGATE_MIN_VALUE) {
// fastpath for the part of the BMP below surrogates (D800) where getRawOffset() works
return getRawOffset(0, (char)ch);
} else if (ch < UTF16.SUPPLEMENTARY_MIN_VALUE) {
// BMP codepoint
return getBMPOffset((char)ch);
} else if (ch <= UCharacter.MAX_VALUE) {
// look at the construction of supplementary characters
// trail forms the ends of it.
return getSurrogateOffset(UTF16.getLeadSurrogate(ch),
(char)(ch & SURROGATE_MASK_));
} else {
// return -1 if there is an error, in this case we return
return -1;
}
} | java | protected final int getCodePointOffset(int ch)
{
// if ((ch >> 16) == 0) slower
if (ch < 0) {
return -1;
} else if (ch < UTF16.LEAD_SURROGATE_MIN_VALUE) {
// fastpath for the part of the BMP below surrogates (D800) where getRawOffset() works
return getRawOffset(0, (char)ch);
} else if (ch < UTF16.SUPPLEMENTARY_MIN_VALUE) {
// BMP codepoint
return getBMPOffset((char)ch);
} else if (ch <= UCharacter.MAX_VALUE) {
// look at the construction of supplementary characters
// trail forms the ends of it.
return getSurrogateOffset(UTF16.getLeadSurrogate(ch),
(char)(ch & SURROGATE_MASK_));
} else {
// return -1 if there is an error, in this case we return
return -1;
}
} | [
"protected",
"final",
"int",
"getCodePointOffset",
"(",
"int",
"ch",
")",
"{",
"// if ((ch >> 16) == 0) slower",
"if",
"(",
"ch",
"<",
"0",
")",
"{",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"ch",
"<",
"UTF16",
".",
"LEAD_SURROGATE_MIN_VALUE",
")",... | Internal trie getter from a code point.
Could be faster(?) but longer with
if((c32)<=0xd7ff) { (result)=_TRIE_GET_RAW(trie, data, 0, c32); }
Gets the offset to data which the codepoint points to
@param ch codepoint
@return offset to data | [
"Internal",
"trie",
"getter",
"from",
"a",
"code",
"point",
".",
"Could",
"be",
"faster",
"(",
"?",
")",
"but",
"longer",
"with",
"if",
"((",
"c32",
")",
"<",
"=",
"0xd7ff",
")",
"{",
"(",
"result",
")",
"=",
"_TRIE_GET_RAW",
"(",
"trie",
"data",
"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/Trie.java#L340-L360 |
OpenLiberty/open-liberty | dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java | Director.fireProgressEvent | private void fireProgressEvent(int state, int progress, String messageKey, RepositoryResource installResource) throws InstallException {
"""
Fires a progress event message to be displayed
@param state the state integer
@param progress the progress integer
@param messageKey the message key
@param installResource the resource necessitating the progress event
@throws InstallException
"""
String resourceName = null;
if (installResource instanceof EsaResource) {
EsaResource esar = ((EsaResource) installResource);
if (esar.getVisibility().equals(Visibility.PUBLIC) || esar.getVisibility().equals(Visibility.INSTALL)) {
resourceName = (esar.getShortName() == null) ? installResource.getName() : esar.getShortName();
} else if (!firePublicAssetOnly && messageKey.equals("STATE_DOWNLOADING")) {
messageKey = "STATE_DOWNLOADING_DEPENDENCY";
resourceName = "";
} else {
return;
}
}
if (installResource instanceof SampleResource) {
SampleResource sr = ((SampleResource) installResource);
resourceName = sr.getShortName() == null ? installResource.getName() : sr.getShortName();
} else {
resourceName = installResource.getName();
}
fireProgressEvent(state, progress,
Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(messageKey, resourceName));
} | java | private void fireProgressEvent(int state, int progress, String messageKey, RepositoryResource installResource) throws InstallException {
String resourceName = null;
if (installResource instanceof EsaResource) {
EsaResource esar = ((EsaResource) installResource);
if (esar.getVisibility().equals(Visibility.PUBLIC) || esar.getVisibility().equals(Visibility.INSTALL)) {
resourceName = (esar.getShortName() == null) ? installResource.getName() : esar.getShortName();
} else if (!firePublicAssetOnly && messageKey.equals("STATE_DOWNLOADING")) {
messageKey = "STATE_DOWNLOADING_DEPENDENCY";
resourceName = "";
} else {
return;
}
}
if (installResource instanceof SampleResource) {
SampleResource sr = ((SampleResource) installResource);
resourceName = sr.getShortName() == null ? installResource.getName() : sr.getShortName();
} else {
resourceName = installResource.getName();
}
fireProgressEvent(state, progress,
Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(messageKey, resourceName));
} | [
"private",
"void",
"fireProgressEvent",
"(",
"int",
"state",
",",
"int",
"progress",
",",
"String",
"messageKey",
",",
"RepositoryResource",
"installResource",
")",
"throws",
"InstallException",
"{",
"String",
"resourceName",
"=",
"null",
";",
"if",
"(",
"installR... | Fires a progress event message to be displayed
@param state the state integer
@param progress the progress integer
@param messageKey the message key
@param installResource the resource necessitating the progress event
@throws InstallException | [
"Fires",
"a",
"progress",
"event",
"message",
"to",
"be",
"displayed"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java#L168-L189 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java | Text.getRelativeParent | public static String getRelativeParent(String path, int level) {
"""
Returns the n<sup>th</sup> relative parent of the path, where n=level.
<p>
Example:<br>
<code>
Text.getRelativeParent("/foo/bar/test", 1) == "/foo/bar"
</code>
@param path
the path of the page
@param level
the level of the parent
@return String relative parent
"""
int idx = path.length();
while (level > 0)
{
idx = path.lastIndexOf('/', idx - 1);
if (idx < 0)
{
return "";
}
level--;
}
return (idx == 0) ? "/" : path.substring(0, idx);
} | java | public static String getRelativeParent(String path, int level)
{
int idx = path.length();
while (level > 0)
{
idx = path.lastIndexOf('/', idx - 1);
if (idx < 0)
{
return "";
}
level--;
}
return (idx == 0) ? "/" : path.substring(0, idx);
} | [
"public",
"static",
"String",
"getRelativeParent",
"(",
"String",
"path",
",",
"int",
"level",
")",
"{",
"int",
"idx",
"=",
"path",
".",
"length",
"(",
")",
";",
"while",
"(",
"level",
">",
"0",
")",
"{",
"idx",
"=",
"path",
".",
"lastIndexOf",
"(",
... | Returns the n<sup>th</sup> relative parent of the path, where n=level.
<p>
Example:<br>
<code>
Text.getRelativeParent("/foo/bar/test", 1) == "/foo/bar"
</code>
@param path
the path of the page
@param level
the level of the parent
@return String relative parent | [
"Returns",
"the",
"n<sup",
">",
"th<",
"/",
"sup",
">",
"relative",
"parent",
"of",
"the",
"path",
"where",
"n",
"=",
"level",
".",
"<p",
">",
"Example",
":",
"<br",
">",
"<code",
">",
"Text",
".",
"getRelativeParent",
"(",
"/",
"foo",
"/",
"bar",
... | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/util/Text.java#L760-L773 |
leancloud/java-sdk-all | android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/push/GetTokenApi.java | GetTokenApi.onConnect | @Override
public void onConnect(int rst, HuaweiApiClient client) {
"""
HuaweiApiClient 连接结果回调
@param rst 结果码
@param client HuaweiApiClient 实例
"""
if (client == null || !ApiClientMgr.INST.isConnect(client)) {
HMSAgentLog.e("client not connted");
onPushTokenResult(rst, null);
return;
}
PendingResult<TokenResult> tokenResult = HuaweiPush.HuaweiPushApi.getToken(client);
tokenResult.setResultCallback(new ResultCallback<TokenResult>() {
@Override
public void onResult(TokenResult result) {
if (result == null) {
HMSAgentLog.e("result is null");
onPushTokenResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
return;
}
Status status = result.getStatus();
if (status == null) {
HMSAgentLog.e("status is null");
onPushTokenResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null);
return;
}
int rstCode = status.getStatusCode();
HMSAgentLog.d("status=" + status);
// 需要重试的错误码,并且可以重试
if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID
|| rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) {
retryTimes--;
connect();
} else {
onPushTokenResult(rstCode, result);
}
}
});
} | java | @Override
public void onConnect(int rst, HuaweiApiClient client) {
if (client == null || !ApiClientMgr.INST.isConnect(client)) {
HMSAgentLog.e("client not connted");
onPushTokenResult(rst, null);
return;
}
PendingResult<TokenResult> tokenResult = HuaweiPush.HuaweiPushApi.getToken(client);
tokenResult.setResultCallback(new ResultCallback<TokenResult>() {
@Override
public void onResult(TokenResult result) {
if (result == null) {
HMSAgentLog.e("result is null");
onPushTokenResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
return;
}
Status status = result.getStatus();
if (status == null) {
HMSAgentLog.e("status is null");
onPushTokenResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null);
return;
}
int rstCode = status.getStatusCode();
HMSAgentLog.d("status=" + status);
// 需要重试的错误码,并且可以重试
if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID
|| rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) {
retryTimes--;
connect();
} else {
onPushTokenResult(rstCode, result);
}
}
});
} | [
"@",
"Override",
"public",
"void",
"onConnect",
"(",
"int",
"rst",
",",
"HuaweiApiClient",
"client",
")",
"{",
"if",
"(",
"client",
"==",
"null",
"||",
"!",
"ApiClientMgr",
".",
"INST",
".",
"isConnect",
"(",
"client",
")",
")",
"{",
"HMSAgentLog",
".",
... | HuaweiApiClient 连接结果回调
@param rst 结果码
@param client HuaweiApiClient 实例 | [
"HuaweiApiClient",
"连接结果回调"
] | train | https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/push/GetTokenApi.java#L47-L84 |
finmath/finmath-lib | src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java | HullWhiteModel.getB | private RandomVariable getB(double time, double maturity) {
"""
Calculates \( B(t,T) = \int_{t}^{T} \exp(-\int_{s}^{T} a(\tau) \mathrm{d}\tau) \mathrm{d}s \), where a is the mean reversion parameter.
For a constant \( a \) this results in \( \frac{1-\exp(-a (T-t)}{a} \), but the method also supports piecewise constant \( a \)'s.
@param time The parameter t.
@param maturity The parameter T.
@return The value of B(t,T).
"""
int timeIndexStart = volatilityModel.getTimeDiscretization().getTimeIndex(time);
if(timeIndexStart < 0) {
timeIndexStart = -timeIndexStart-2; // Get timeIndex corresponding to previous point
}
int timeIndexEnd =volatilityModel.getTimeDiscretization().getTimeIndex(maturity);
if(timeIndexEnd < 0) {
timeIndexEnd = -timeIndexEnd-2; // Get timeIndex corresponding to previous point
}
RandomVariable integral = new Scalar(0.0);
double timePrev = time;
double timeNext;
for(int timeIndex=timeIndexStart+1; timeIndex<=timeIndexEnd; timeIndex++) {
timeNext = volatilityModel.getTimeDiscretization().getTime(timeIndex);
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndex-1);
integral = integral.add(
getMRTime(timeNext,maturity).mult(-1.0).exp().sub(
getMRTime(timePrev,maturity).mult(-1.0).exp()).div(meanReversion));
timePrev = timeNext;
}
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndexEnd);
timeNext = maturity;
integral = integral.add(
getMRTime(timeNext,maturity).mult(-1.0).exp().sub(
getMRTime(timePrev,maturity).mult(-1.0).exp()).div(meanReversion));
return integral;
} | java | private RandomVariable getB(double time, double maturity) {
int timeIndexStart = volatilityModel.getTimeDiscretization().getTimeIndex(time);
if(timeIndexStart < 0) {
timeIndexStart = -timeIndexStart-2; // Get timeIndex corresponding to previous point
}
int timeIndexEnd =volatilityModel.getTimeDiscretization().getTimeIndex(maturity);
if(timeIndexEnd < 0) {
timeIndexEnd = -timeIndexEnd-2; // Get timeIndex corresponding to previous point
}
RandomVariable integral = new Scalar(0.0);
double timePrev = time;
double timeNext;
for(int timeIndex=timeIndexStart+1; timeIndex<=timeIndexEnd; timeIndex++) {
timeNext = volatilityModel.getTimeDiscretization().getTime(timeIndex);
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndex-1);
integral = integral.add(
getMRTime(timeNext,maturity).mult(-1.0).exp().sub(
getMRTime(timePrev,maturity).mult(-1.0).exp()).div(meanReversion));
timePrev = timeNext;
}
RandomVariable meanReversion = volatilityModel.getMeanReversion(timeIndexEnd);
timeNext = maturity;
integral = integral.add(
getMRTime(timeNext,maturity).mult(-1.0).exp().sub(
getMRTime(timePrev,maturity).mult(-1.0).exp()).div(meanReversion));
return integral;
} | [
"private",
"RandomVariable",
"getB",
"(",
"double",
"time",
",",
"double",
"maturity",
")",
"{",
"int",
"timeIndexStart",
"=",
"volatilityModel",
".",
"getTimeDiscretization",
"(",
")",
".",
"getTimeIndex",
"(",
"time",
")",
";",
"if",
"(",
"timeIndexStart",
"... | Calculates \( B(t,T) = \int_{t}^{T} \exp(-\int_{s}^{T} a(\tau) \mathrm{d}\tau) \mathrm{d}s \), where a is the mean reversion parameter.
For a constant \( a \) this results in \( \frac{1-\exp(-a (T-t)}{a} \), but the method also supports piecewise constant \( a \)'s.
@param time The parameter t.
@param maturity The parameter T.
@return The value of B(t,T). | [
"Calculates",
"\\",
"(",
"B",
"(",
"t",
"T",
")",
"=",
"\\",
"int_",
"{",
"t",
"}",
"^",
"{",
"T",
"}",
"\\",
"exp",
"(",
"-",
"\\",
"int_",
"{",
"s",
"}",
"^",
"{",
"T",
"}",
"a",
"(",
"\\",
"tau",
")",
"\\",
"mathrm",
"{",
"d",
"}",
... | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/models/HullWhiteModel.java#L615-L644 |
apache/reef | lang/java/reef-runtime-azbatch/src/main/java/org/apache/reef/runtime/azbatch/util/storage/SharedAccessSignatureCloudBlobClientProvider.java | SharedAccessSignatureCloudBlobClientProvider.getCloudBlobClient | @Override
public CloudBlobClient getCloudBlobClient() throws IOException {
"""
Returns an instance of {@link CloudBlobClient} based on available authentication mechanism.
@return an instance of {@link CloudBlobClient}.
@throws IOException
"""
StorageCredentialsSharedAccessSignature signature =
new StorageCredentialsSharedAccessSignature(this.azureStorageContainerSASToken);
URI storageAccountUri;
try {
storageAccountUri = new URI(String.format(AZURE_STORAGE_ACCOUNT_URI_FORMAT, this.azureStorageAccountName));
} catch (URISyntaxException e) {
throw new IOException("Failed to generate Storage Account URI", e);
}
return new CloudBlobClient(storageAccountUri, signature);
} | java | @Override
public CloudBlobClient getCloudBlobClient() throws IOException {
StorageCredentialsSharedAccessSignature signature =
new StorageCredentialsSharedAccessSignature(this.azureStorageContainerSASToken);
URI storageAccountUri;
try {
storageAccountUri = new URI(String.format(AZURE_STORAGE_ACCOUNT_URI_FORMAT, this.azureStorageAccountName));
} catch (URISyntaxException e) {
throw new IOException("Failed to generate Storage Account URI", e);
}
return new CloudBlobClient(storageAccountUri, signature);
} | [
"@",
"Override",
"public",
"CloudBlobClient",
"getCloudBlobClient",
"(",
")",
"throws",
"IOException",
"{",
"StorageCredentialsSharedAccessSignature",
"signature",
"=",
"new",
"StorageCredentialsSharedAccessSignature",
"(",
"this",
".",
"azureStorageContainerSASToken",
")",
"... | Returns an instance of {@link CloudBlobClient} based on available authentication mechanism.
@return an instance of {@link CloudBlobClient}.
@throws IOException | [
"Returns",
"an",
"instance",
"of",
"{"
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-runtime-azbatch/src/main/java/org/apache/reef/runtime/azbatch/util/storage/SharedAccessSignatureCloudBlobClientProvider.java#L65-L77 |
syphr42/prom | src/main/java/org/syphr/prom/PropertiesManager.java | PropertiesManager.saveProperty | public <E extends Enum<E>> void saveProperty(T property, E value) throws IOException {
"""
Save the given property using an Enum constant. See
{@link #saveProperty(Object, String)} for additional details.<br>
<br>
Please note that the Enum value saved here is case insensitive. See
{@link #getEnumProperty(Object, Class)} for additional details.
@param <E>
the type of Enum value to save
@param property
the property whose value is being saved
@param value
the value to save
@throws IOException
if there is an error while attempting to write the property
to the file
"""
saveProperty(property, value.name());
} | java | public <E extends Enum<E>> void saveProperty(T property, E value) throws IOException
{
saveProperty(property, value.name());
} | [
"public",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"void",
"saveProperty",
"(",
"T",
"property",
",",
"E",
"value",
")",
"throws",
"IOException",
"{",
"saveProperty",
"(",
"property",
",",
"value",
".",
"name",
"(",
")",
")",
";",
"}"
] | Save the given property using an Enum constant. See
{@link #saveProperty(Object, String)} for additional details.<br>
<br>
Please note that the Enum value saved here is case insensitive. See
{@link #getEnumProperty(Object, Class)} for additional details.
@param <E>
the type of Enum value to save
@param property
the property whose value is being saved
@param value
the value to save
@throws IOException
if there is an error while attempting to write the property
to the file | [
"Save",
"the",
"given",
"property",
"using",
"an",
"Enum",
"constant",
".",
"See",
"{",
"@link",
"#saveProperty",
"(",
"Object",
"String",
")",
"}",
"for",
"additional",
"details",
".",
"<br",
">",
"<br",
">",
"Please",
"note",
"that",
"the",
"Enum",
"va... | train | https://github.com/syphr42/prom/blob/074d67c4ebb3afb0b163fcb0bc4826ee577ac803/src/main/java/org/syphr/prom/PropertiesManager.java#L970-L973 |
apiman/apiman | manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java | EsMarshalling.unmarshallRole | public static RoleBean unmarshallRole(Map<String, Object> source) {
"""
Unmarshals the given map source into a bean.
@param source the source
@return the role
"""
if (source == null) {
return null;
}
RoleBean bean = new RoleBean();
bean.setId(asString(source.get("id")));
bean.setName(asString(source.get("name")));
bean.setDescription(asString(source.get("description")));
bean.setCreatedBy(asString(source.get("createdBy")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setAutoGrant(asBoolean(source.get("autoGrant")));
@SuppressWarnings("unchecked")
List<Object> permissions = (List<Object>) source.get("permissions");
if (permissions != null && !permissions.isEmpty()) {
bean.setPermissions(new HashSet<>());
for (Object permission : permissions) {
bean.getPermissions().add(asEnum(permission, PermissionType.class));
}
}
postMarshall(bean);
return bean;
} | java | public static RoleBean unmarshallRole(Map<String, Object> source) {
if (source == null) {
return null;
}
RoleBean bean = new RoleBean();
bean.setId(asString(source.get("id")));
bean.setName(asString(source.get("name")));
bean.setDescription(asString(source.get("description")));
bean.setCreatedBy(asString(source.get("createdBy")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setAutoGrant(asBoolean(source.get("autoGrant")));
@SuppressWarnings("unchecked")
List<Object> permissions = (List<Object>) source.get("permissions");
if (permissions != null && !permissions.isEmpty()) {
bean.setPermissions(new HashSet<>());
for (Object permission : permissions) {
bean.getPermissions().add(asEnum(permission, PermissionType.class));
}
}
postMarshall(bean);
return bean;
} | [
"public",
"static",
"RoleBean",
"unmarshallRole",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"source",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"RoleBean",
"bean",
"=",
"new",
"RoleBean",
"(",
")",
";",
"... | Unmarshals the given map source into a bean.
@param source the source
@return the role | [
"Unmarshals",
"the",
"given",
"map",
"source",
"into",
"a",
"bean",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L1106-L1127 |
google/error-prone | check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java | ASTHelpers.getGeneratedBy | public static ImmutableSet<String> getGeneratedBy(ClassSymbol symbol, VisitorState state) {
"""
Returns the values of the given symbol's {@code javax.annotation.Generated} or {@code
javax.annotation.processing.Generated} annotation, if present.
"""
checkNotNull(symbol);
Optional<Compound> c =
Stream.of("javax.annotation.Generated", "javax.annotation.processing.Generated")
.map(state::getSymbolFromString)
.filter(a -> a != null)
.map(symbol::attribute)
.filter(a -> a != null)
.findFirst();
if (!c.isPresent()) {
return ImmutableSet.of();
}
Optional<Attribute> values =
c.get().getElementValues().entrySet().stream()
.filter(e -> e.getKey().getSimpleName().contentEquals("value"))
.map(e -> e.getValue())
.findAny();
if (!values.isPresent()) {
return ImmutableSet.of();
}
ImmutableSet.Builder<String> suppressions = ImmutableSet.builder();
values
.get()
.accept(
new SimpleAnnotationValueVisitor8<Void, Void>() {
@Override
public Void visitString(String s, Void aVoid) {
suppressions.add(s);
return super.visitString(s, aVoid);
}
@Override
public Void visitArray(List<? extends AnnotationValue> vals, Void aVoid) {
vals.stream().forEachOrdered(v -> v.accept(this, null));
return super.visitArray(vals, aVoid);
}
},
null);
return suppressions.build();
} | java | public static ImmutableSet<String> getGeneratedBy(ClassSymbol symbol, VisitorState state) {
checkNotNull(symbol);
Optional<Compound> c =
Stream.of("javax.annotation.Generated", "javax.annotation.processing.Generated")
.map(state::getSymbolFromString)
.filter(a -> a != null)
.map(symbol::attribute)
.filter(a -> a != null)
.findFirst();
if (!c.isPresent()) {
return ImmutableSet.of();
}
Optional<Attribute> values =
c.get().getElementValues().entrySet().stream()
.filter(e -> e.getKey().getSimpleName().contentEquals("value"))
.map(e -> e.getValue())
.findAny();
if (!values.isPresent()) {
return ImmutableSet.of();
}
ImmutableSet.Builder<String> suppressions = ImmutableSet.builder();
values
.get()
.accept(
new SimpleAnnotationValueVisitor8<Void, Void>() {
@Override
public Void visitString(String s, Void aVoid) {
suppressions.add(s);
return super.visitString(s, aVoid);
}
@Override
public Void visitArray(List<? extends AnnotationValue> vals, Void aVoid) {
vals.stream().forEachOrdered(v -> v.accept(this, null));
return super.visitArray(vals, aVoid);
}
},
null);
return suppressions.build();
} | [
"public",
"static",
"ImmutableSet",
"<",
"String",
">",
"getGeneratedBy",
"(",
"ClassSymbol",
"symbol",
",",
"VisitorState",
"state",
")",
"{",
"checkNotNull",
"(",
"symbol",
")",
";",
"Optional",
"<",
"Compound",
">",
"c",
"=",
"Stream",
".",
"of",
"(",
"... | Returns the values of the given symbol's {@code javax.annotation.Generated} or {@code
javax.annotation.processing.Generated} annotation, if present. | [
"Returns",
"the",
"values",
"of",
"the",
"given",
"symbol",
"s",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L1189-L1228 |
dasein-cloud/dasein-cloud-aws | src/main/java/org/dasein/cloud/aws/AWSCloud.java | AWSCloud.addIndexedParameters | public static void addIndexedParameters( @Nonnull Map<String, String> parameters, @Nonnull String prefix, Map<String, String> extraParameters ) {
"""
Helper method for adding indexed member parameters, e.g. <i>AlarmNames.member.N</i>. Will overwrite existing
parameters if present. Assumes indexing starts at 1.
@param parameters the existing parameters map to add to
@param prefix the prefix value for each parameter key
@param extraParameters the values to add
"""
if( extraParameters == null || extraParameters.size() == 0 ) {
return;
}
int i = 1;
for( Map.Entry<String, String> entry : extraParameters.entrySet() ) {
parameters.put(prefix + i + ".Name", entry.getKey());
if( entry.getValue() != null ) {
parameters.put(prefix + i + ".Value", entry.getValue());
}
i++;
}
} | java | public static void addIndexedParameters( @Nonnull Map<String, String> parameters, @Nonnull String prefix, Map<String, String> extraParameters ) {
if( extraParameters == null || extraParameters.size() == 0 ) {
return;
}
int i = 1;
for( Map.Entry<String, String> entry : extraParameters.entrySet() ) {
parameters.put(prefix + i + ".Name", entry.getKey());
if( entry.getValue() != null ) {
parameters.put(prefix + i + ".Value", entry.getValue());
}
i++;
}
} | [
"public",
"static",
"void",
"addIndexedParameters",
"(",
"@",
"Nonnull",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
",",
"@",
"Nonnull",
"String",
"prefix",
",",
"Map",
"<",
"String",
",",
"String",
">",
"extraParameters",
")",
"{",
"if",
"(",... | Helper method for adding indexed member parameters, e.g. <i>AlarmNames.member.N</i>. Will overwrite existing
parameters if present. Assumes indexing starts at 1.
@param parameters the existing parameters map to add to
@param prefix the prefix value for each parameter key
@param extraParameters the values to add | [
"Helper",
"method",
"for",
"adding",
"indexed",
"member",
"parameters",
"e",
".",
"g",
".",
"<i",
">",
"AlarmNames",
".",
"member",
".",
"N<",
"/",
"i",
">",
".",
"Will",
"overwrite",
"existing",
"parameters",
"if",
"present",
".",
"Assumes",
"indexing",
... | train | https://github.com/dasein-cloud/dasein-cloud-aws/blob/05098574197a1f573f77447cadc39a76bf00b99d/src/main/java/org/dasein/cloud/aws/AWSCloud.java#L1415-L1427 |
actorapp/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java | Messenger.bindUpload | @NotNull
@ObjectiveCName("bindUploadWithRid:withCallback:")
public UploadFileVM bindUpload(long rid, UploadFileVMCallback callback) {
"""
Bind Uploading File View Model
@param rid randomId of uploading file
@param callback View Model file state callback
@return Upload File View Model
"""
return new UploadFileVM(rid, callback, modules);
} | java | @NotNull
@ObjectiveCName("bindUploadWithRid:withCallback:")
public UploadFileVM bindUpload(long rid, UploadFileVMCallback callback) {
return new UploadFileVM(rid, callback, modules);
} | [
"@",
"NotNull",
"@",
"ObjectiveCName",
"(",
"\"bindUploadWithRid:withCallback:\"",
")",
"public",
"UploadFileVM",
"bindUpload",
"(",
"long",
"rid",
",",
"UploadFileVMCallback",
"callback",
")",
"{",
"return",
"new",
"UploadFileVM",
"(",
"rid",
",",
"callback",
",",
... | Bind Uploading File View Model
@param rid randomId of uploading file
@param callback View Model file state callback
@return Upload File View Model | [
"Bind",
"Uploading",
"File",
"View",
"Model"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java#L1917-L1921 |
mapbox/mapbox-java | services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java | MultiLineString.fromLineString | public static MultiLineString fromLineString(@NonNull LineString lineString) {
"""
Create a new instance of this class by passing in a single {@link LineString} object. The
LineStrings should comply with the GeoJson specifications described in the documentation.
@param lineString a single LineString which make up this MultiLineString
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0
"""
List<List<Point>> coordinates = Arrays.asList(lineString.coordinates());
return new MultiLineString(TYPE, null, coordinates);
} | java | public static MultiLineString fromLineString(@NonNull LineString lineString) {
List<List<Point>> coordinates = Arrays.asList(lineString.coordinates());
return new MultiLineString(TYPE, null, coordinates);
} | [
"public",
"static",
"MultiLineString",
"fromLineString",
"(",
"@",
"NonNull",
"LineString",
"lineString",
")",
"{",
"List",
"<",
"List",
"<",
"Point",
">>",
"coordinates",
"=",
"Arrays",
".",
"asList",
"(",
"lineString",
".",
"coordinates",
"(",
")",
")",
";... | Create a new instance of this class by passing in a single {@link LineString} object. The
LineStrings should comply with the GeoJson specifications described in the documentation.
@param lineString a single LineString which make up this MultiLineString
@return a new instance of this class defined by the values passed inside this static factory
method
@since 3.0.0 | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"class",
"by",
"passing",
"in",
"a",
"single",
"{",
"@link",
"LineString",
"}",
"object",
".",
"The",
"LineStrings",
"should",
"comply",
"with",
"the",
"GeoJson",
"specifications",
"described",
"in",
"the",
"do... | train | https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java#L129-L132 |
iovation/launchkey-java | sdk/src/main/java/com/iovation/launchkey/sdk/crypto/JCECrypto.java | JCECrypto.getRSAPrivateKeyFromPEM | public static RSAPrivateKey getRSAPrivateKeyFromPEM(Provider provider, String pem) {
"""
Get an RSA private key utilizing the provided provider and PEM formatted string
@param provider Provider to generate the key
@param pem PEM formatted key string
@return RSA private key
"""
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA", provider);
return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(getKeyBytesFromPEM(pem)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
} catch (InvalidKeySpecException e) {
throw new IllegalArgumentException("Invalid PEM provided", e);
}
} | java | public static RSAPrivateKey getRSAPrivateKeyFromPEM(Provider provider, String pem) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA", provider);
return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(getKeyBytesFromPEM(pem)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
} catch (InvalidKeySpecException e) {
throw new IllegalArgumentException("Invalid PEM provided", e);
}
} | [
"public",
"static",
"RSAPrivateKey",
"getRSAPrivateKeyFromPEM",
"(",
"Provider",
"provider",
",",
"String",
"pem",
")",
"{",
"try",
"{",
"KeyFactory",
"keyFactory",
"=",
"KeyFactory",
".",
"getInstance",
"(",
"\"RSA\"",
",",
"provider",
")",
";",
"return",
"(",
... | Get an RSA private key utilizing the provided provider and PEM formatted string
@param provider Provider to generate the key
@param pem PEM formatted key string
@return RSA private key | [
"Get",
"an",
"RSA",
"private",
"key",
"utilizing",
"the",
"provided",
"provider",
"and",
"PEM",
"formatted",
"string"
] | train | https://github.com/iovation/launchkey-java/blob/ceecc70b9b04af07ddc14c57d4bcc933a4e0379c/sdk/src/main/java/com/iovation/launchkey/sdk/crypto/JCECrypto.java#L96-L105 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/spider/BatchObjectUpdater.java | BatchObjectUpdater.buildErrorStatus | private void buildErrorStatus(BatchResult result, Throwable ex) {
"""
Add error fields to the given BatchResult due to the given exception.
"""
result.setStatus(BatchResult.Status.ERROR);
result.setErrorMessage(ex.getLocalizedMessage());
if (ex instanceof IllegalArgumentException) {
m_logger.debug("Batch update error: {}", ex.toString());
} else {
result.setStackTrace(Utils.getStackTrace(ex));
m_logger.debug("Batch update error: {} stacktrace: {}",
ex.toString(), Utils.getStackTrace(ex));
}
} | java | private void buildErrorStatus(BatchResult result, Throwable ex) {
result.setStatus(BatchResult.Status.ERROR);
result.setErrorMessage(ex.getLocalizedMessage());
if (ex instanceof IllegalArgumentException) {
m_logger.debug("Batch update error: {}", ex.toString());
} else {
result.setStackTrace(Utils.getStackTrace(ex));
m_logger.debug("Batch update error: {} stacktrace: {}",
ex.toString(), Utils.getStackTrace(ex));
}
} | [
"private",
"void",
"buildErrorStatus",
"(",
"BatchResult",
"result",
",",
"Throwable",
"ex",
")",
"{",
"result",
".",
"setStatus",
"(",
"BatchResult",
".",
"Status",
".",
"ERROR",
")",
";",
"result",
".",
"setErrorMessage",
"(",
"ex",
".",
"getLocalizedMessage... | Add error fields to the given BatchResult due to the given exception. | [
"Add",
"error",
"fields",
"to",
"the",
"given",
"BatchResult",
"due",
"to",
"the",
"given",
"exception",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/BatchObjectUpdater.java#L223-L233 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/datastructures/collections/CouchbaseArraySet.java | CouchbaseArraySet.enforcePrimitive | protected void enforcePrimitive(Object t) throws ClassCastException {
"""
Verify that the type of object t is compatible with CouchbaseArraySet storage.
@param t the object to check.
@throws ClassCastException if the object is incompatible.
"""
if (!JsonValue.checkType(t)
|| t instanceof JsonValue) {
throw new ClassCastException("Only primitive types are supported in CouchbaseArraySet, got a " + t.getClass().getName());
}
} | java | protected void enforcePrimitive(Object t) throws ClassCastException {
if (!JsonValue.checkType(t)
|| t instanceof JsonValue) {
throw new ClassCastException("Only primitive types are supported in CouchbaseArraySet, got a " + t.getClass().getName());
}
} | [
"protected",
"void",
"enforcePrimitive",
"(",
"Object",
"t",
")",
"throws",
"ClassCastException",
"{",
"if",
"(",
"!",
"JsonValue",
".",
"checkType",
"(",
"t",
")",
"||",
"t",
"instanceof",
"JsonValue",
")",
"{",
"throw",
"new",
"ClassCastException",
"(",
"\... | Verify that the type of object t is compatible with CouchbaseArraySet storage.
@param t the object to check.
@throws ClassCastException if the object is incompatible. | [
"Verify",
"that",
"the",
"type",
"of",
"object",
"t",
"is",
"compatible",
"with",
"CouchbaseArraySet",
"storage",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/datastructures/collections/CouchbaseArraySet.java#L213-L218 |
twilio/twilio-java | src/main/java/com/twilio/rest/accounts/v1/credential/AwsReader.java | AwsReader.previousPage | @Override
public Page<Aws> previousPage(final Page<Aws> page,
final TwilioRestClient client) {
"""
Retrieve the previous page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Previous Page
"""
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.ACCOUNTS.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<Aws> previousPage(final Page<Aws> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.ACCOUNTS.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"Aws",
">",
"previousPage",
"(",
"final",
"Page",
"<",
"Aws",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
",",
"pag... | Retrieve the previous page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Previous Page | [
"Retrieve",
"the",
"previous",
"page",
"from",
"the",
"Twilio",
"API",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/accounts/v1/credential/AwsReader.java#L99-L110 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java | FSDatasetAsyncDiskService.deleteAsyncFile | void deleteAsyncFile(FSDataset.FSVolume volume, File file) {
"""
Delete a file or directory from the disk asynchronously.
Used for deleting obsolete block files.
Does not change dfs usage stats.
"""
DataNode.LOG.info("Scheduling file " + file.toString() + " for deletion");
FileDeleteTask deletionTask =
new FileDeleteTask(volume, file);
execute(volume.getCurrentDir(), deletionTask);
} | java | void deleteAsyncFile(FSDataset.FSVolume volume, File file){
DataNode.LOG.info("Scheduling file " + file.toString() + " for deletion");
FileDeleteTask deletionTask =
new FileDeleteTask(volume, file);
execute(volume.getCurrentDir(), deletionTask);
} | [
"void",
"deleteAsyncFile",
"(",
"FSDataset",
".",
"FSVolume",
"volume",
",",
"File",
"file",
")",
"{",
"DataNode",
".",
"LOG",
".",
"info",
"(",
"\"Scheduling file \"",
"+",
"file",
".",
"toString",
"(",
")",
"+",
"\" for deletion\"",
")",
";",
"FileDeleteTa... | Delete a file or directory from the disk asynchronously.
Used for deleting obsolete block files.
Does not change dfs usage stats. | [
"Delete",
"a",
"file",
"or",
"directory",
"from",
"the",
"disk",
"asynchronously",
".",
"Used",
"for",
"deleting",
"obsolete",
"block",
"files",
".",
"Does",
"not",
"change",
"dfs",
"usage",
"stats",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java#L174-L179 |
jenkinsci/ssh-slaves-plugin | src/main/java/hudson/plugins/sshslaves/JavaVersionChecker.java | JavaVersionChecker.checkJavaVersion | @CheckForNull
@Restricted(NoExternalUse.class)
public String checkJavaVersion(final PrintStream logger, String javaCommand,
final BufferedReader r, final StringWriter output) throws IOException {
"""
Given the output of "java -version" in <code>r</code>, determine if this
version of Java is supported.
@param logger
where to log the output
@param javaCommand
the command executed, used for logging
@param r
the output of "java -version"
@param output
copy the data from <code>r</code> into this output buffer
"""
String line;
while (null != (line = r.readLine())) {
output.write(line);
output.write("\n");
line = line.toLowerCase(Locale.ENGLISH);
if (line.startsWith("java version \"") || line.startsWith("openjdk version \"")) {
final String versionStr = line.substring(line.indexOf('\"') + 1, line.lastIndexOf('\"'));
logger.println(Messages.SSHLauncher_JavaVersionResult(SSHLauncher.getTimestamp(), javaCommand, versionStr));
// parse as a number and we should be OK as all we care about is up through the first dot.
final VersionNumber minJavaLevel = JavaProvider.getMinJavaLevel();
try {
final Number version = NumberFormat.getNumberInstance(Locale.US).parse(versionStr);
//TODO: burn it with fire
if(version.doubleValue() < Double.parseDouble("1."+minJavaLevel)) {
throw new IOException(Messages.SSHLauncher_NoJavaFound2(line, minJavaLevel.toString()));
}
} catch(final ParseException e) {
throw new IOException(Messages.SSHLauncher_NoJavaFound2(line, minJavaLevel));
}
return javaCommand;
}
}
return null;
} | java | @CheckForNull
@Restricted(NoExternalUse.class)
public String checkJavaVersion(final PrintStream logger, String javaCommand,
final BufferedReader r, final StringWriter output) throws IOException {
String line;
while (null != (line = r.readLine())) {
output.write(line);
output.write("\n");
line = line.toLowerCase(Locale.ENGLISH);
if (line.startsWith("java version \"") || line.startsWith("openjdk version \"")) {
final String versionStr = line.substring(line.indexOf('\"') + 1, line.lastIndexOf('\"'));
logger.println(Messages.SSHLauncher_JavaVersionResult(SSHLauncher.getTimestamp(), javaCommand, versionStr));
// parse as a number and we should be OK as all we care about is up through the first dot.
final VersionNumber minJavaLevel = JavaProvider.getMinJavaLevel();
try {
final Number version = NumberFormat.getNumberInstance(Locale.US).parse(versionStr);
//TODO: burn it with fire
if(version.doubleValue() < Double.parseDouble("1."+minJavaLevel)) {
throw new IOException(Messages.SSHLauncher_NoJavaFound2(line, minJavaLevel.toString()));
}
} catch(final ParseException e) {
throw new IOException(Messages.SSHLauncher_NoJavaFound2(line, minJavaLevel));
}
return javaCommand;
}
}
return null;
} | [
"@",
"CheckForNull",
"@",
"Restricted",
"(",
"NoExternalUse",
".",
"class",
")",
"public",
"String",
"checkJavaVersion",
"(",
"final",
"PrintStream",
"logger",
",",
"String",
"javaCommand",
",",
"final",
"BufferedReader",
"r",
",",
"final",
"StringWriter",
"output... | Given the output of "java -version" in <code>r</code>, determine if this
version of Java is supported.
@param logger
where to log the output
@param javaCommand
the command executed, used for logging
@param r
the output of "java -version"
@param output
copy the data from <code>r</code> into this output buffer | [
"Given",
"the",
"output",
"of",
"java",
"-",
"version",
"in",
"<code",
">",
"r<",
"/",
"code",
">",
"determine",
"if",
"this",
"version",
"of",
"Java",
"is",
"supported",
"."
] | train | https://github.com/jenkinsci/ssh-slaves-plugin/blob/95f528730fc1e01b25983459927b7516ead3ee00/src/main/java/hudson/plugins/sshslaves/JavaVersionChecker.java#L119-L147 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/config/Config.java | Config.setUserContext | public Config setUserContext(ConcurrentMap<String, Object> userContext) {
"""
Sets the user supplied context. This context can then be obtained
from an instance of {@link com.hazelcast.core.HazelcastInstance}.
@param userContext the user supplied context
@return this config instance
@see HazelcastInstance#getUserContext()
"""
if (userContext == null) {
throw new IllegalArgumentException("userContext can't be null");
}
this.userContext = userContext;
return this;
} | java | public Config setUserContext(ConcurrentMap<String, Object> userContext) {
if (userContext == null) {
throw new IllegalArgumentException("userContext can't be null");
}
this.userContext = userContext;
return this;
} | [
"public",
"Config",
"setUserContext",
"(",
"ConcurrentMap",
"<",
"String",
",",
"Object",
">",
"userContext",
")",
"{",
"if",
"(",
"userContext",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"userContext can't be null\"",
")",
";",
... | Sets the user supplied context. This context can then be obtained
from an instance of {@link com.hazelcast.core.HazelcastInstance}.
@param userContext the user supplied context
@return this config instance
@see HazelcastInstance#getUserContext() | [
"Sets",
"the",
"user",
"supplied",
"context",
".",
"This",
"context",
"can",
"then",
"be",
"obtained",
"from",
"an",
"instance",
"of",
"{",
"@link",
"com",
".",
"hazelcast",
".",
"core",
".",
"HazelcastInstance",
"}",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L3305-L3311 |
openbase/jul | exception/src/main/java/org/openbase/jul/exception/MultiException.java | MultiException.checkAndThrow | @Deprecated
public static void checkAndThrow(final String message, final ExceptionStack exceptionStack) throws MultiException {
"""
@param message the message used as {@code MultiException} headline message..
@param exceptionStack the stack to check.
@throws MultiException
@deprecated since v2.0 and will be removed in v3.0. Please use {@code checkAndThrow(final Callable<String> messageProvider, final ExceptionStack exceptionStack)} out of performance reasons.
"""
if (exceptionStack == null || exceptionStack.isEmpty()) {
return;
}
throw new MultiException(message, exceptionStack);
} | java | @Deprecated
public static void checkAndThrow(final String message, final ExceptionStack exceptionStack) throws MultiException {
if (exceptionStack == null || exceptionStack.isEmpty()) {
return;
}
throw new MultiException(message, exceptionStack);
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"checkAndThrow",
"(",
"final",
"String",
"message",
",",
"final",
"ExceptionStack",
"exceptionStack",
")",
"throws",
"MultiException",
"{",
"if",
"(",
"exceptionStack",
"==",
"null",
"||",
"exceptionStack",
".",
"isEm... | @param message the message used as {@code MultiException} headline message..
@param exceptionStack the stack to check.
@throws MultiException
@deprecated since v2.0 and will be removed in v3.0. Please use {@code checkAndThrow(final Callable<String> messageProvider, final ExceptionStack exceptionStack)} out of performance reasons. | [
"@param",
"message",
"the",
"message",
"used",
"as",
"{",
"@code",
"MultiException",
"}",
"headline",
"message",
"..",
"@param",
"exceptionStack",
"the",
"stack",
"to",
"check",
"."
] | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/exception/src/main/java/org/openbase/jul/exception/MultiException.java#L92-L98 |
iipc/webarchive-commons | src/main/java/org/archive/util/FileUtils.java | FileUtils.readFullyToFile | public static long readFullyToFile(InputStream is, File toFile)
throws IOException {
"""
Read the entire stream to EOF into the passed file.
Closes <code>is</code> when done or if an exception.
@param is Stream to read.
@param toFile File to write to.
@throws IOException
"""
OutputStream os = org.apache.commons.io.FileUtils.openOutputStream(toFile);
try {
return IOUtils.copyLarge(is, os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
} | java | public static long readFullyToFile(InputStream is, File toFile)
throws IOException {
OutputStream os = org.apache.commons.io.FileUtils.openOutputStream(toFile);
try {
return IOUtils.copyLarge(is, os);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
} | [
"public",
"static",
"long",
"readFullyToFile",
"(",
"InputStream",
"is",
",",
"File",
"toFile",
")",
"throws",
"IOException",
"{",
"OutputStream",
"os",
"=",
"org",
".",
"apache",
".",
"commons",
".",
"io",
".",
"FileUtils",
".",
"openOutputStream",
"(",
"to... | Read the entire stream to EOF into the passed file.
Closes <code>is</code> when done or if an exception.
@param is Stream to read.
@param toFile File to write to.
@throws IOException | [
"Read",
"the",
"entire",
"stream",
"to",
"EOF",
"into",
"the",
"passed",
"file",
".",
"Closes",
"<code",
">",
"is<",
"/",
"code",
">",
"when",
"done",
"or",
"if",
"an",
"exception",
"."
] | train | https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/FileUtils.java#L612-L621 |
actframework/actframework | src/main/java/act/ws/WebSocketContext.java | WebSocketContext.sendToTagged | public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {
"""
Send message to all connections labeled with tag specified.
@param message the message to be sent
@param tag the string that tag the connections to be sent
@param excludeSelf specify whether the connection of this context should be send
@return this context
"""
return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);
} | java | public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {
return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);
} | [
"public",
"WebSocketContext",
"sendToTagged",
"(",
"String",
"message",
",",
"String",
"tag",
",",
"boolean",
"excludeSelf",
")",
"{",
"return",
"sendToConnections",
"(",
"message",
",",
"tag",
",",
"manager",
".",
"tagRegistry",
"(",
")",
",",
"excludeSelf",
... | Send message to all connections labeled with tag specified.
@param message the message to be sent
@param tag the string that tag the connections to be sent
@param excludeSelf specify whether the connection of this context should be send
@return this context | [
"Send",
"message",
"to",
"all",
"connections",
"labeled",
"with",
"tag",
"specified",
"."
] | train | https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketContext.java#L232-L234 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/util/FileUtils.java | FileUtils.copyFileToDirectory | public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException {
"""
Copies a file to a directory optionally preserving the file date.
<p>
This method copies the contents of the specified source file to a file of
the same name in the specified destination directory. The destination
directory is created if it does not exist. If the destination file
exists, then this method will overwrite it.
@param srcFile
an existing file to copy, must not be <code>null</code>
@param destDir
the directory to place the copy in, must not be
<code>null</code>
@param preserveFileDate
true if the file date of the copy should be the same as the
original
@throws NullPointerException
if source or destination is <code>null</code>
@throws IOException
if source or destination is invalid
@throws IOException
if an IO error occurs during copying
@see #copyFile(File, File, boolean)
@since Commons IO 1.3
"""
if (destDir == null) {
throw new IllegalArgumentException("Destination must not be null");
}
if (destDir.exists() && destDir.isDirectory() == false) {
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
}
copyFile(srcFile, new File(destDir, srcFile.getName()), preserveFileDate);
} | java | public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException {
if (destDir == null) {
throw new IllegalArgumentException("Destination must not be null");
}
if (destDir.exists() && destDir.isDirectory() == false) {
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
}
copyFile(srcFile, new File(destDir, srcFile.getName()), preserveFileDate);
} | [
"public",
"static",
"void",
"copyFileToDirectory",
"(",
"File",
"srcFile",
",",
"File",
"destDir",
",",
"boolean",
"preserveFileDate",
")",
"throws",
"IOException",
"{",
"if",
"(",
"destDir",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(... | Copies a file to a directory optionally preserving the file date.
<p>
This method copies the contents of the specified source file to a file of
the same name in the specified destination directory. The destination
directory is created if it does not exist. If the destination file
exists, then this method will overwrite it.
@param srcFile
an existing file to copy, must not be <code>null</code>
@param destDir
the directory to place the copy in, must not be
<code>null</code>
@param preserveFileDate
true if the file date of the copy should be the same as the
original
@throws NullPointerException
if source or destination is <code>null</code>
@throws IOException
if source or destination is invalid
@throws IOException
if an IO error occurs during copying
@see #copyFile(File, File, boolean)
@since Commons IO 1.3 | [
"Copies",
"a",
"file",
"to",
"a",
"directory",
"optionally",
"preserving",
"the",
"file",
"date",
".",
"<p",
">",
"This",
"method",
"copies",
"the",
"contents",
"of",
"the",
"specified",
"source",
"file",
"to",
"a",
"file",
"of",
"the",
"same",
"name",
"... | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/util/FileUtils.java#L130-L138 |
auth0/auth0-java | src/main/java/com/auth0/client/auth/AuthAPI.java | AuthAPI.logoutUrl | public LogoutUrlBuilder logoutUrl(String returnToUrl, boolean setClientId) {
"""
Creates an instance of the {@link LogoutUrlBuilder} with the given return-to url.
i.e.:
<pre>
{@code
AuthAPI auth = new AuthAPI("me.auth0.com", "B3c6RYhk1v9SbIJcRIOwu62gIUGsnze", "2679NfkaBn62e6w5E8zNEzjr-yWfkaBne");
String url = auth.logoutUrl("https://me.auth0.com/home", true)
.useFederated(true)
.withAccessToken("A9CvPwFojaBIA9CvI");
}
</pre>
@param returnToUrl the redirect_uri value to set, white-listed in the Application settings. Must be already URL Encoded.
@param setClientId whether the client_id value must be set or not. This affects the white-list that the Auth0's Dashboard uses to validate the returnTo url.
@return a new instance of the {@link LogoutUrlBuilder} to configure.
"""
Asserts.assertValidUrl(returnToUrl, "return to url");
return LogoutUrlBuilder.newInstance(baseUrl, clientId, returnToUrl, setClientId);
} | java | public LogoutUrlBuilder logoutUrl(String returnToUrl, boolean setClientId) {
Asserts.assertValidUrl(returnToUrl, "return to url");
return LogoutUrlBuilder.newInstance(baseUrl, clientId, returnToUrl, setClientId);
} | [
"public",
"LogoutUrlBuilder",
"logoutUrl",
"(",
"String",
"returnToUrl",
",",
"boolean",
"setClientId",
")",
"{",
"Asserts",
".",
"assertValidUrl",
"(",
"returnToUrl",
",",
"\"return to url\"",
")",
";",
"return",
"LogoutUrlBuilder",
".",
"newInstance",
"(",
"baseUr... | Creates an instance of the {@link LogoutUrlBuilder} with the given return-to url.
i.e.:
<pre>
{@code
AuthAPI auth = new AuthAPI("me.auth0.com", "B3c6RYhk1v9SbIJcRIOwu62gIUGsnze", "2679NfkaBn62e6w5E8zNEzjr-yWfkaBne");
String url = auth.logoutUrl("https://me.auth0.com/home", true)
.useFederated(true)
.withAccessToken("A9CvPwFojaBIA9CvI");
}
</pre>
@param returnToUrl the redirect_uri value to set, white-listed in the Application settings. Must be already URL Encoded.
@param setClientId whether the client_id value must be set or not. This affects the white-list that the Auth0's Dashboard uses to validate the returnTo url.
@return a new instance of the {@link LogoutUrlBuilder} to configure. | [
"Creates",
"an",
"instance",
"of",
"the",
"{",
"@link",
"LogoutUrlBuilder",
"}",
"with",
"the",
"given",
"return",
"-",
"to",
"url",
".",
"i",
".",
"e",
".",
":",
"<pre",
">",
"{",
"@code",
"AuthAPI",
"auth",
"=",
"new",
"AuthAPI",
"(",
"me",
".",
... | train | https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/auth/AuthAPI.java#L153-L157 |
couchbase/couchbase-lite-java | src/main/java/com/couchbase/lite/Expression.java | Expression.isNullOrMissing | @NonNull
public Expression isNullOrMissing() {
"""
Creates an IS NULL OR MISSING expression that evaluates whether or not the current
expression is null or missing.
@return An IS NULL expression.
"""
return new UnaryExpression(this, UnaryExpression.OpType.Null)
.or(new UnaryExpression(this, UnaryExpression.OpType.Missing));
} | java | @NonNull
public Expression isNullOrMissing() {
return new UnaryExpression(this, UnaryExpression.OpType.Null)
.or(new UnaryExpression(this, UnaryExpression.OpType.Missing));
} | [
"@",
"NonNull",
"public",
"Expression",
"isNullOrMissing",
"(",
")",
"{",
"return",
"new",
"UnaryExpression",
"(",
"this",
",",
"UnaryExpression",
".",
"OpType",
".",
"Null",
")",
".",
"or",
"(",
"new",
"UnaryExpression",
"(",
"this",
",",
"UnaryExpression",
... | Creates an IS NULL OR MISSING expression that evaluates whether or not the current
expression is null or missing.
@return An IS NULL expression. | [
"Creates",
"an",
"IS",
"NULL",
"OR",
"MISSING",
"expression",
"that",
"evaluates",
"whether",
"or",
"not",
"the",
"current",
"expression",
"is",
"null",
"or",
"missing",
"."
] | train | https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/com/couchbase/lite/Expression.java#L815-L819 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/httpsessions/HttpSessionsSite.java | HttpSessionsSite.getMatchingHttpSession | private HttpSession getMatchingHttpSession(List<HttpCookie> cookies, final HttpSessionTokensSet siteTokens) {
"""
Gets the matching http session for a particular message containing a list of cookies.
@param siteTokens the tokens
@param cookies the cookies present in the request header of the message
@return the matching http session, if any, or null if no existing session was found to match
all the tokens
"""
Collection<HttpSession> sessionsCopy;
synchronized (sessions) {
sessionsCopy = new ArrayList<>(sessions);
}
return CookieBasedSessionManagementHelper.getMatchingHttpSession(sessionsCopy, cookies, siteTokens);
} | java | private HttpSession getMatchingHttpSession(List<HttpCookie> cookies, final HttpSessionTokensSet siteTokens) {
Collection<HttpSession> sessionsCopy;
synchronized (sessions) {
sessionsCopy = new ArrayList<>(sessions);
}
return CookieBasedSessionManagementHelper.getMatchingHttpSession(sessionsCopy, cookies, siteTokens);
} | [
"private",
"HttpSession",
"getMatchingHttpSession",
"(",
"List",
"<",
"HttpCookie",
">",
"cookies",
",",
"final",
"HttpSessionTokensSet",
"siteTokens",
")",
"{",
"Collection",
"<",
"HttpSession",
">",
"sessionsCopy",
";",
"synchronized",
"(",
"sessions",
")",
"{",
... | Gets the matching http session for a particular message containing a list of cookies.
@param siteTokens the tokens
@param cookies the cookies present in the request header of the message
@return the matching http session, if any, or null if no existing session was found to match
all the tokens | [
"Gets",
"the",
"matching",
"http",
"session",
"for",
"a",
"particular",
"message",
"containing",
"a",
"list",
"of",
"cookies",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/httpsessions/HttpSessionsSite.java#L485-L491 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ComparableTimSort.java | ComparableTimSort.binarySort | @SuppressWarnings( {
"""
Sorts the specified portion of the specified array using a binary
insertion sort. This is the best method for sorting small numbers
of elements. It requires O(n log n) compares, but O(n^2) data
movement (worst case).
If the initial part of the specified range is already sorted,
this method can take advantage of it: the method assumes that the
elements from index {@code lo}, inclusive, to {@code start},
exclusive are already sorted.
@param a the array in which a range is to be sorted
@param lo the index of the first element in the range to be sorted
@param hi the index after the last element in the range to be sorted
@param start the index of the first element in the range that is
not already known to be sorted ({@code lo <= start <= hi})
""""fallthrough", "rawtypes", "unchecked"})
private static void binarySort(Object[] a, int lo, int hi, int start) {
assert lo <= start && start <= hi;
if (start == lo)
start++;
for ( ; start < hi; start++) {
Comparable pivot = (Comparable) a[start];
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot.compareTo(a[mid]) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2: a[left + 2] = a[left + 1];
case 1: a[left + 1] = a[left];
break;
default: System.arraycopy(a, left, a, left + 1, n);
}
a[left] = pivot;
}
} | java | @SuppressWarnings({"fallthrough", "rawtypes", "unchecked"})
private static void binarySort(Object[] a, int lo, int hi, int start) {
assert lo <= start && start <= hi;
if (start == lo)
start++;
for ( ; start < hi; start++) {
Comparable pivot = (Comparable) a[start];
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot.compareTo(a[mid]) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2: a[left + 2] = a[left + 1];
case 1: a[left + 1] = a[left];
break;
default: System.arraycopy(a, left, a, left + 1, n);
}
a[left] = pivot;
}
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"fallthrough\"",
",",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"private",
"static",
"void",
"binarySort",
"(",
"Object",
"[",
"]",
"a",
",",
"int",
"lo",
",",
"int",
"hi",
",",
"int",
"start",
")",
"{",
"assert... | Sorts the specified portion of the specified array using a binary
insertion sort. This is the best method for sorting small numbers
of elements. It requires O(n log n) compares, but O(n^2) data
movement (worst case).
If the initial part of the specified range is already sorted,
this method can take advantage of it: the method assumes that the
elements from index {@code lo}, inclusive, to {@code start},
exclusive are already sorted.
@param a the array in which a range is to be sorted
@param lo the index of the first element in the range to be sorted
@param hi the index after the last element in the range to be sorted
@param start the index of the first element in the range that is
not already known to be sorted ({@code lo <= start <= hi}) | [
"Sorts",
"the",
"specified",
"portion",
"of",
"the",
"specified",
"array",
"using",
"a",
"binary",
"insertion",
"sort",
".",
"This",
"is",
"the",
"best",
"method",
"for",
"sorting",
"small",
"numbers",
"of",
"elements",
".",
"It",
"requires",
"O",
"(",
"n"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ComparableTimSort.java#L243-L286 |
wonderpush/wonderpush-android-sdk | sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java | WonderPushRestClient.fetchAnonymousAccessTokenIfNeeded | protected static boolean fetchAnonymousAccessTokenIfNeeded(final String userId, final ResponseHandler onFetchedHandler) {
"""
If no access token is found in the user's preferences, fetch an anonymous access token.
@param onFetchedHandler
A handler called if a request to fetch an access token has been
executed successfully, never called if retrieved from cache
@return Whether or not a request has been executed to fetch an anonymous
access token (true fetching, false retrieved from local cache)
"""
if (!WonderPush.isInitialized()) {
// Note: Could use WonderPush.safeDefer() here but as we require consent to proceed,
// let's use WonderPush.safeDeferWithConsent() to additionally passively wait for SDK initialization.
WonderPush.safeDeferWithConsent(new Runnable() {
@Override
public void run() {
if (!fetchAnonymousAccessTokenIfNeeded(userId, onFetchedHandler)) {
// Call the handler anyway
onFetchedHandler.onSuccess(null);
}
}
}, null);
return true; // true: the handler will be called
}
if (null == WonderPushConfiguration.getAccessToken()) {
fetchAnonymousAccessToken(userId, onFetchedHandler);
return true;
}
return false;
} | java | protected static boolean fetchAnonymousAccessTokenIfNeeded(final String userId, final ResponseHandler onFetchedHandler) {
if (!WonderPush.isInitialized()) {
// Note: Could use WonderPush.safeDefer() here but as we require consent to proceed,
// let's use WonderPush.safeDeferWithConsent() to additionally passively wait for SDK initialization.
WonderPush.safeDeferWithConsent(new Runnable() {
@Override
public void run() {
if (!fetchAnonymousAccessTokenIfNeeded(userId, onFetchedHandler)) {
// Call the handler anyway
onFetchedHandler.onSuccess(null);
}
}
}, null);
return true; // true: the handler will be called
}
if (null == WonderPushConfiguration.getAccessToken()) {
fetchAnonymousAccessToken(userId, onFetchedHandler);
return true;
}
return false;
} | [
"protected",
"static",
"boolean",
"fetchAnonymousAccessTokenIfNeeded",
"(",
"final",
"String",
"userId",
",",
"final",
"ResponseHandler",
"onFetchedHandler",
")",
"{",
"if",
"(",
"!",
"WonderPush",
".",
"isInitialized",
"(",
")",
")",
"{",
"// Note: Could use WonderPu... | If no access token is found in the user's preferences, fetch an anonymous access token.
@param onFetchedHandler
A handler called if a request to fetch an access token has been
executed successfully, never called if retrieved from cache
@return Whether or not a request has been executed to fetch an anonymous
access token (true fetching, false retrieved from local cache) | [
"If",
"no",
"access",
"token",
"is",
"found",
"in",
"the",
"user",
"s",
"preferences",
"fetch",
"an",
"anonymous",
"access",
"token",
"."
] | train | https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L155-L176 |
di2e/Argo | ProbeSender/src/main/java/ws/argo/transport/probe/standard/MulticastTransport.java | MulticastTransport.sendProbe | @Override
public void sendProbe(Probe probe) throws TransportException {
"""
Actually send the probe out on the wire.
@param probe the Probe instance that has been pre-configured
@throws TransportException if something bad happened when sending the
probe
"""
LOGGER.info("Sending probe [" + probe.getProbeID() + "] on network inteface [" + networkInterface.getName() + "] at port [" + multicastAddress + ":" + multicastPort + "]");
LOGGER.debug("Probe requesting TTL of [" + probe.getHopLimit() + "]");
try {
String msg = probe.asXML();
LOGGER.debug("Probe payload (always XML): \n" + msg);
byte[] msgBytes;
msgBytes = msg.getBytes(StandardCharsets.UTF_8);
// send discovery string
InetAddress group = InetAddress.getByName(multicastAddress);
DatagramPacket packet = new DatagramPacket(msgBytes, msgBytes.length, group, multicastPort);
outboundSocket.setTimeToLive(probe.getHopLimit());
outboundSocket.send(packet);
LOGGER.debug("Probe sent on port [" + multicastAddress + ":" + multicastPort + "]");
} catch (IOException e) {
throw new TransportException("Unable to send probe. Issue sending UDP packets.", e);
} catch (JAXBException e) {
throw new TransportException("Unable to send probe because it could not be serialized to XML", e);
}
} | java | @Override
public void sendProbe(Probe probe) throws TransportException {
LOGGER.info("Sending probe [" + probe.getProbeID() + "] on network inteface [" + networkInterface.getName() + "] at port [" + multicastAddress + ":" + multicastPort + "]");
LOGGER.debug("Probe requesting TTL of [" + probe.getHopLimit() + "]");
try {
String msg = probe.asXML();
LOGGER.debug("Probe payload (always XML): \n" + msg);
byte[] msgBytes;
msgBytes = msg.getBytes(StandardCharsets.UTF_8);
// send discovery string
InetAddress group = InetAddress.getByName(multicastAddress);
DatagramPacket packet = new DatagramPacket(msgBytes, msgBytes.length, group, multicastPort);
outboundSocket.setTimeToLive(probe.getHopLimit());
outboundSocket.send(packet);
LOGGER.debug("Probe sent on port [" + multicastAddress + ":" + multicastPort + "]");
} catch (IOException e) {
throw new TransportException("Unable to send probe. Issue sending UDP packets.", e);
} catch (JAXBException e) {
throw new TransportException("Unable to send probe because it could not be serialized to XML", e);
}
} | [
"@",
"Override",
"public",
"void",
"sendProbe",
"(",
"Probe",
"probe",
")",
"throws",
"TransportException",
"{",
"LOGGER",
".",
"info",
"(",
"\"Sending probe [\"",
"+",
"probe",
".",
"getProbeID",
"(",
")",
"+",
"\"] on network inteface [\"",
"+",
"networkInterfac... | Actually send the probe out on the wire.
@param probe the Probe instance that has been pre-configured
@throws TransportException if something bad happened when sending the
probe | [
"Actually",
"send",
"the",
"probe",
"out",
"on",
"the",
"wire",
"."
] | train | https://github.com/di2e/Argo/blob/f537a03d2d25fdfecda7999ec10e1da67dc3b8f3/ProbeSender/src/main/java/ws/argo/transport/probe/standard/MulticastTransport.java#L226-L254 |
ggrandes/packer | src/main/java/org/javastack/packer/Packer.java | Packer.getHexStringLower | public String getHexStringLower() {
"""
Get Hex String in lower case ("0123456789abcdef")
@return
@see #putHexString(String)
@see #getHexStringUpper()
"""
int len = getVInt();
byte[] hex = new byte[len];
System.arraycopy(buf, bufPosition, hex, 0, hex.length);
bufPosition += hex.length;
return toHex(hex, false);
} | java | public String getHexStringLower() {
int len = getVInt();
byte[] hex = new byte[len];
System.arraycopy(buf, bufPosition, hex, 0, hex.length);
bufPosition += hex.length;
return toHex(hex, false);
} | [
"public",
"String",
"getHexStringLower",
"(",
")",
"{",
"int",
"len",
"=",
"getVInt",
"(",
")",
";",
"byte",
"[",
"]",
"hex",
"=",
"new",
"byte",
"[",
"len",
"]",
";",
"System",
".",
"arraycopy",
"(",
"buf",
",",
"bufPosition",
",",
"hex",
",",
"0"... | Get Hex String in lower case ("0123456789abcdef")
@return
@see #putHexString(String)
@see #getHexStringUpper() | [
"Get",
"Hex",
"String",
"in",
"lower",
"case",
"(",
"0123456789abcdef",
")"
] | train | https://github.com/ggrandes/packer/blob/0b37b286a3d0555050eb2e65419dd74f8d8d3e78/src/main/java/org/javastack/packer/Packer.java#L1221-L1227 |
infinispan/infinispan | core/src/main/java/org/infinispan/interceptors/impl/InvocationContextInterceptor.java | InvocationContextInterceptor.stoppingAndNotAllowed | private boolean stoppingAndNotAllowed(ComponentStatus status, InvocationContext ctx) throws Exception {
"""
If the cache is STOPPING, non-transaction invocations, or transactional invocations for transaction others than
the ongoing ones, are no allowed. This method returns true if under this circumstances meet. Otherwise, it returns
false.
"""
return status.isStopping() && (!ctx.isInTxScope() || !isOngoingTransaction(ctx));
} | java | private boolean stoppingAndNotAllowed(ComponentStatus status, InvocationContext ctx) throws Exception {
return status.isStopping() && (!ctx.isInTxScope() || !isOngoingTransaction(ctx));
} | [
"private",
"boolean",
"stoppingAndNotAllowed",
"(",
"ComponentStatus",
"status",
",",
"InvocationContext",
"ctx",
")",
"throws",
"Exception",
"{",
"return",
"status",
".",
"isStopping",
"(",
")",
"&&",
"(",
"!",
"ctx",
".",
"isInTxScope",
"(",
")",
"||",
"!",
... | If the cache is STOPPING, non-transaction invocations, or transactional invocations for transaction others than
the ongoing ones, are no allowed. This method returns true if under this circumstances meet. Otherwise, it returns
false. | [
"If",
"the",
"cache",
"is",
"STOPPING",
"non",
"-",
"transaction",
"invocations",
"or",
"transactional",
"invocations",
"for",
"transaction",
"others",
"than",
"the",
"ongoing",
"ones",
"are",
"no",
"allowed",
".",
"This",
"method",
"returns",
"true",
"if",
"u... | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/interceptors/impl/InvocationContextInterceptor.java#L164-L166 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java | ComboBoxArrowButtonPainter.paintButton | private void paintButton(Graphics2D g, JComponent c, int width, int height) {
"""
Paint the button shape.
@param g the Graphics2D context to paint with.
@param c the component to paint.
@param width the width.
@param height the height.
"""
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Shape s = createButtonPath(CornerSize.BORDER, 0, 2, width - 2, height - 4);
g.setPaint(getComboBoxButtonBorderPaint(s, type));
g.fill(s);
s = createButtonPath(CornerSize.INTERIOR, 1, 3, width - 4, height - 6);
g.setPaint(getComboBoxButtonInteriorPaint(s, type));
g.fill(s);
} | java | private void paintButton(Graphics2D g, JComponent c, int width, int height) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Shape s = createButtonPath(CornerSize.BORDER, 0, 2, width - 2, height - 4);
g.setPaint(getComboBoxButtonBorderPaint(s, type));
g.fill(s);
s = createButtonPath(CornerSize.INTERIOR, 1, 3, width - 4, height - 6);
g.setPaint(getComboBoxButtonInteriorPaint(s, type));
g.fill(s);
} | [
"private",
"void",
"paintButton",
"(",
"Graphics2D",
"g",
",",
"JComponent",
"c",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"g",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_ANTIALIASING",
",",
"RenderingHints",
".",
"VALUE_ANTIALIAS_ON",... | Paint the button shape.
@param g the Graphics2D context to paint with.
@param c the component to paint.
@param width the width.
@param height the height. | [
"Paint",
"the",
"button",
"shape",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java#L145-L156 |
PeterisP/LVTagger | src/main/java/edu/stanford/nlp/stats/Counters.java | Counters.addInPlace | public static <E> void addInPlace(Counter<E> target, Collection<E> arg) {
"""
Sets each value of target to be target[k]+
num-of-times-it-occurs-in-collection if the key is present in the arg
collection.
"""
for (E key : arg) {
target.incrementCount(key, 1);
}
} | java | public static <E> void addInPlace(Counter<E> target, Collection<E> arg) {
for (E key : arg) {
target.incrementCount(key, 1);
}
} | [
"public",
"static",
"<",
"E",
">",
"void",
"addInPlace",
"(",
"Counter",
"<",
"E",
">",
"target",
",",
"Collection",
"<",
"E",
">",
"arg",
")",
"{",
"for",
"(",
"E",
"key",
":",
"arg",
")",
"{",
"target",
".",
"incrementCount",
"(",
"key",
",",
"... | Sets each value of target to be target[k]+
num-of-times-it-occurs-in-collection if the key is present in the arg
collection. | [
"Sets",
"each",
"value",
"of",
"target",
"to",
"be",
"target",
"[",
"k",
"]",
"+",
"num",
"-",
"of",
"-",
"times",
"-",
"it",
"-",
"occurs",
"-",
"in",
"-",
"collection",
"if",
"the",
"key",
"is",
"present",
"in",
"the",
"arg",
"collection",
"."
] | train | https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Counters.java#L373-L377 |
craigwblake/redline | src/main/java/org/redline_rpm/Builder.java | Builder.addHeaderEntry | public void addHeaderEntry( final Tag tag, final String value) {
"""
Adds a header entry value to the header. For example use this to set the source RPM package
name on your RPM
@param tag the header tag to set
@param value the value to set the header entry with
"""
format.getHeader().createEntry(tag, value);
} | java | public void addHeaderEntry( final Tag tag, final String value) {
format.getHeader().createEntry(tag, value);
} | [
"public",
"void",
"addHeaderEntry",
"(",
"final",
"Tag",
"tag",
",",
"final",
"String",
"value",
")",
"{",
"format",
".",
"getHeader",
"(",
")",
".",
"createEntry",
"(",
"tag",
",",
"value",
")",
";",
"}"
] | Adds a header entry value to the header. For example use this to set the source RPM package
name on your RPM
@param tag the header tag to set
@param value the value to set the header entry with | [
"Adds",
"a",
"header",
"entry",
"value",
"to",
"the",
"header",
".",
"For",
"example",
"use",
"this",
"to",
"set",
"the",
"source",
"RPM",
"package",
"name",
"on",
"your",
"RPM"
] | train | https://github.com/craigwblake/redline/blob/b2fee5eb6c8150e801a132a4478a643f9ec0df04/src/main/java/org/redline_rpm/Builder.java#L220-L222 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/converter/json/MapExtractor.java | MapExtractor.extractObject | public Object extractObject(ObjectToJsonConverter pConverter, Object pValue,
Stack<String> pPathParts,boolean jsonify) throws AttributeNotFoundException {
"""
Convert a Map to JSON (if <code>jsonify</code> is <code>true</code>). If a path is used, the
path is interpreted as a key into the map. The key in the path is a string and is compared agains
all keys in the map against their string representation.
@param pConverter the global converter in order to be able do dispatch for
serializing inner data types
@param pValue the value to convert which must be a {@link Map}
@param pPathParts extra argument stack which on top must be a key into the map
@param jsonify whether to convert to a JSON object/list or whether the plain object
should be returned. The later is required for writing an inner value
@return the extracted object
@throws AttributeNotFoundException
"""
Map<Object,Object> map = (Map<Object,Object>) pValue;
int length = pConverter.getCollectionLength(map.size());
String pathParth = pPathParts.isEmpty() ? null : pPathParts.pop();
if (pathParth != null) {
return extractMapValueWithPath(pConverter, pValue, pPathParts, jsonify, map, pathParth);
} else {
return jsonify ? extractMapValues(pConverter, pPathParts, jsonify, map, length) : map;
}
} | java | public Object extractObject(ObjectToJsonConverter pConverter, Object pValue,
Stack<String> pPathParts,boolean jsonify) throws AttributeNotFoundException {
Map<Object,Object> map = (Map<Object,Object>) pValue;
int length = pConverter.getCollectionLength(map.size());
String pathParth = pPathParts.isEmpty() ? null : pPathParts.pop();
if (pathParth != null) {
return extractMapValueWithPath(pConverter, pValue, pPathParts, jsonify, map, pathParth);
} else {
return jsonify ? extractMapValues(pConverter, pPathParts, jsonify, map, length) : map;
}
} | [
"public",
"Object",
"extractObject",
"(",
"ObjectToJsonConverter",
"pConverter",
",",
"Object",
"pValue",
",",
"Stack",
"<",
"String",
">",
"pPathParts",
",",
"boolean",
"jsonify",
")",
"throws",
"AttributeNotFoundException",
"{",
"Map",
"<",
"Object",
",",
"Objec... | Convert a Map to JSON (if <code>jsonify</code> is <code>true</code>). If a path is used, the
path is interpreted as a key into the map. The key in the path is a string and is compared agains
all keys in the map against their string representation.
@param pConverter the global converter in order to be able do dispatch for
serializing inner data types
@param pValue the value to convert which must be a {@link Map}
@param pPathParts extra argument stack which on top must be a key into the map
@param jsonify whether to convert to a JSON object/list or whether the plain object
should be returned. The later is required for writing an inner value
@return the extracted object
@throws AttributeNotFoundException | [
"Convert",
"a",
"Map",
"to",
"JSON",
"(",
"if",
"<code",
">",
"jsonify<",
"/",
"code",
">",
"is",
"<code",
">",
"true<",
"/",
"code",
">",
")",
".",
"If",
"a",
"path",
"is",
"used",
"the",
"path",
"is",
"interpreted",
"as",
"a",
"key",
"into",
"t... | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/converter/json/MapExtractor.java#L57-L67 |
apache/fluo-recipes | modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/RecordingTransaction.java | RecordingTransaction.wrap | public static RecordingTransaction wrap(Transaction tx, Predicate<LogEntry> filter) {
"""
Creates a RecordingTransaction using the provided LogEntry filter and existing Transaction
"""
return new RecordingTransaction(tx, filter);
} | java | public static RecordingTransaction wrap(Transaction tx, Predicate<LogEntry> filter) {
return new RecordingTransaction(tx, filter);
} | [
"public",
"static",
"RecordingTransaction",
"wrap",
"(",
"Transaction",
"tx",
",",
"Predicate",
"<",
"LogEntry",
">",
"filter",
")",
"{",
"return",
"new",
"RecordingTransaction",
"(",
"tx",
",",
"filter",
")",
";",
"}"
] | Creates a RecordingTransaction using the provided LogEntry filter and existing Transaction | [
"Creates",
"a",
"RecordingTransaction",
"using",
"the",
"provided",
"LogEntry",
"filter",
"and",
"existing",
"Transaction"
] | train | https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/transaction/RecordingTransaction.java#L63-L65 |
tvesalainen/util | util/src/main/java/org/vesalainen/bean/BeanHelper.java | BeanHelper.applyList | public static final <T> T applyList(Object base, String fieldname) {
"""
Applies bean action by using default factory.
<p>Bean actions are:
<p>List item property remove by adding '#' to the end of pattern.
<p>E.g. list.3- same as list.remove(3)
<p>List item property assign by adding '=' to the end of pattern
<p>E.g. list.3=hint same as list.set(3, factory.get(cls, hint))
<p>List item creation to the end of the list.
<p>E.g. list+ same as add(factory.get(cls, null))
<p>E.g. list+hint same as add(factory.get(cls, hint))
@param <T>
@param base
@param fieldname
@return true if pattern was applied
"""
return applyList(base, fieldname, BeanHelper::defaultFactory);
} | java | public static final <T> T applyList(Object base, String fieldname)
{
return applyList(base, fieldname, BeanHelper::defaultFactory);
} | [
"public",
"static",
"final",
"<",
"T",
">",
"T",
"applyList",
"(",
"Object",
"base",
",",
"String",
"fieldname",
")",
"{",
"return",
"applyList",
"(",
"base",
",",
"fieldname",
",",
"BeanHelper",
"::",
"defaultFactory",
")",
";",
"}"
] | Applies bean action by using default factory.
<p>Bean actions are:
<p>List item property remove by adding '#' to the end of pattern.
<p>E.g. list.3- same as list.remove(3)
<p>List item property assign by adding '=' to the end of pattern
<p>E.g. list.3=hint same as list.set(3, factory.get(cls, hint))
<p>List item creation to the end of the list.
<p>E.g. list+ same as add(factory.get(cls, null))
<p>E.g. list+hint same as add(factory.get(cls, hint))
@param <T>
@param base
@param fieldname
@return true if pattern was applied | [
"Applies",
"bean",
"action",
"by",
"using",
"default",
"factory",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/bean/BeanHelper.java#L443-L446 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/AbstractAggarwalYuOutlier.java | AbstractAggarwalYuOutlier.computeSubspaceForGene | protected DBIDs computeSubspaceForGene(short[] gene, ArrayList<ArrayList<DBIDs>> ranges) {
"""
Get the DBIDs in the current subspace.
@param gene gene data
@param ranges Database ranges
@return resulting DBIDs
"""
HashSetModifiableDBIDs m = null;
// intersect all present restrictions
for(int i = 0; i < gene.length; i++) {
if(gene[i] != DONT_CARE) {
DBIDs current = ranges.get(i).get(gene[i] - GENE_OFFSET);
if(m == null) {
m = DBIDUtil.newHashSet(current);
}
else {
m.retainAll(current);
}
}
}
assert (m != null) : "All genes set to '*', should not happen!";
return m;
} | java | protected DBIDs computeSubspaceForGene(short[] gene, ArrayList<ArrayList<DBIDs>> ranges) {
HashSetModifiableDBIDs m = null;
// intersect all present restrictions
for(int i = 0; i < gene.length; i++) {
if(gene[i] != DONT_CARE) {
DBIDs current = ranges.get(i).get(gene[i] - GENE_OFFSET);
if(m == null) {
m = DBIDUtil.newHashSet(current);
}
else {
m.retainAll(current);
}
}
}
assert (m != null) : "All genes set to '*', should not happen!";
return m;
} | [
"protected",
"DBIDs",
"computeSubspaceForGene",
"(",
"short",
"[",
"]",
"gene",
",",
"ArrayList",
"<",
"ArrayList",
"<",
"DBIDs",
">",
">",
"ranges",
")",
"{",
"HashSetModifiableDBIDs",
"m",
"=",
"null",
";",
"// intersect all present restrictions",
"for",
"(",
... | Get the DBIDs in the current subspace.
@param gene gene data
@param ranges Database ranges
@return resulting DBIDs | [
"Get",
"the",
"DBIDs",
"in",
"the",
"current",
"subspace",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/AbstractAggarwalYuOutlier.java#L178-L194 |
lucee/Lucee | core/src/main/java/lucee/runtime/text/xml/XMLCaster.java | XMLCaster._isAllOfSameType | private static boolean _isAllOfSameType(Node[] nodes, short type) {
"""
Check if all Node are of the type defnined by para,meter
@param nodes nodes to check
@param type to compare
@return are all of the same type
"""
for (int i = 0; i < nodes.length; i++) {
if (nodes[i].getNodeType() != type) return false;
}
return true;
} | java | private static boolean _isAllOfSameType(Node[] nodes, short type) {
for (int i = 0; i < nodes.length; i++) {
if (nodes[i].getNodeType() != type) return false;
}
return true;
} | [
"private",
"static",
"boolean",
"_isAllOfSameType",
"(",
"Node",
"[",
"]",
"nodes",
",",
"short",
"type",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"nodes",
"[",
"i",
... | Check if all Node are of the type defnined by para,meter
@param nodes nodes to check
@param type to compare
@return are all of the same type | [
"Check",
"if",
"all",
"Node",
"are",
"of",
"the",
"type",
"defnined",
"by",
"para",
"meter"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/text/xml/XMLCaster.java#L730-L735 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/management/ManagementClient.java | ManagementClient.ruleExists | public Boolean ruleExists(String topicPath, String subscriptionName, String ruleName) throws ServiceBusException, InterruptedException {
"""
Checks whether a given rule exists or not for a given subscription.
@param topicPath - Path of the topic
@param subscriptionName - Name of the subscription.
@param ruleName - Name of the rule
@return - True if the entity exists. False otherwise.
@throws IllegalArgumentException - path is not null / empty / too long / invalid.
@throws TimeoutException - The operation times out. The timeout period is initiated through ClientSettings.operationTimeout
@throws AuthorizationFailedException - No sufficient permission to perform this operation. Please check ClientSettings.tokenProvider has correct details.
@throws ServerBusyException - The server is busy. You should wait before you retry the operation.
@throws ServiceBusException - An internal error or an unexpected exception occurred.
@throws InterruptedException if the current thread was interrupted
"""
return Utils.completeFuture(this.asyncClient.ruleExistsAsync(topicPath, subscriptionName, ruleName));
} | java | public Boolean ruleExists(String topicPath, String subscriptionName, String ruleName) throws ServiceBusException, InterruptedException {
return Utils.completeFuture(this.asyncClient.ruleExistsAsync(topicPath, subscriptionName, ruleName));
} | [
"public",
"Boolean",
"ruleExists",
"(",
"String",
"topicPath",
",",
"String",
"subscriptionName",
",",
"String",
"ruleName",
")",
"throws",
"ServiceBusException",
",",
"InterruptedException",
"{",
"return",
"Utils",
".",
"completeFuture",
"(",
"this",
".",
"asyncCli... | Checks whether a given rule exists or not for a given subscription.
@param topicPath - Path of the topic
@param subscriptionName - Name of the subscription.
@param ruleName - Name of the rule
@return - True if the entity exists. False otherwise.
@throws IllegalArgumentException - path is not null / empty / too long / invalid.
@throws TimeoutException - The operation times out. The timeout period is initiated through ClientSettings.operationTimeout
@throws AuthorizationFailedException - No sufficient permission to perform this operation. Please check ClientSettings.tokenProvider has correct details.
@throws ServerBusyException - The server is busy. You should wait before you retry the operation.
@throws ServiceBusException - An internal error or an unexpected exception occurred.
@throws InterruptedException if the current thread was interrupted | [
"Checks",
"whether",
"a",
"given",
"rule",
"exists",
"or",
"not",
"for",
"a",
"given",
"subscription",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/management/ManagementClient.java#L552-L554 |
huangp/entityunit | src/main/java/com/github/huangp/entityunit/entity/EntityCleaner.java | EntityCleaner.getAssociationTables | private static Iterable<String> getAssociationTables(EntityClass entityClass) {
"""
This will find all ManyToMany and ElementCollection annotated tables.
"""
Iterable<Settable> association = filter(entityClass.getElements(),
and(or(has(ManyToMany.class), has(ElementCollection.class)), has(JoinTable.class)));
return transform(association, new Function<Settable, String>() {
@Override
public String apply(Settable input) {
JoinTable annotation = input.getAnnotation(JoinTable.class);
return annotation.name();
}
});
} | java | private static Iterable<String> getAssociationTables(EntityClass entityClass) {
Iterable<Settable> association = filter(entityClass.getElements(),
and(or(has(ManyToMany.class), has(ElementCollection.class)), has(JoinTable.class)));
return transform(association, new Function<Settable, String>() {
@Override
public String apply(Settable input) {
JoinTable annotation = input.getAnnotation(JoinTable.class);
return annotation.name();
}
});
} | [
"private",
"static",
"Iterable",
"<",
"String",
">",
"getAssociationTables",
"(",
"EntityClass",
"entityClass",
")",
"{",
"Iterable",
"<",
"Settable",
">",
"association",
"=",
"filter",
"(",
"entityClass",
".",
"getElements",
"(",
")",
",",
"and",
"(",
"or",
... | This will find all ManyToMany and ElementCollection annotated tables. | [
"This",
"will",
"find",
"all",
"ManyToMany",
"and",
"ElementCollection",
"annotated",
"tables",
"."
] | train | https://github.com/huangp/entityunit/blob/1a09b530149d707dbff7ff46f5428d9db709a4b4/src/main/java/com/github/huangp/entityunit/entity/EntityCleaner.java#L140-L150 |
overturetool/overture | core/interpreter/src/main/java/org/overture/interpreter/scheduler/SystemClock.java | SystemClock.timeToInternal | public static long timeToInternal(TimeUnit unit, Double time) {
"""
Utility method to convert a value in the given unit to the internal time
@param unit
The unit of the time parameter
@param time
The time to convert
@return The internal time representation of the parameter
"""
return Math.round(time * unit.getValue()
/ TimeUnit.nanosecond.getValue());
} | java | public static long timeToInternal(TimeUnit unit, Double time)
{
return Math.round(time * unit.getValue()
/ TimeUnit.nanosecond.getValue());
} | [
"public",
"static",
"long",
"timeToInternal",
"(",
"TimeUnit",
"unit",
",",
"Double",
"time",
")",
"{",
"return",
"Math",
".",
"round",
"(",
"time",
"*",
"unit",
".",
"getValue",
"(",
")",
"/",
"TimeUnit",
".",
"nanosecond",
".",
"getValue",
"(",
")",
... | Utility method to convert a value in the given unit to the internal time
@param unit
The unit of the time parameter
@param time
The time to convert
@return The internal time representation of the parameter | [
"Utility",
"method",
"to",
"convert",
"a",
"value",
"in",
"the",
"given",
"unit",
"to",
"the",
"internal",
"time"
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/scheduler/SystemClock.java#L100-L104 |
tvesalainen/util | util/src/main/java/org/vesalainen/lang/Primitives.java | Primitives.parseUnsignedInt | public static final int parseUnsignedInt(CharSequence cs, int radix, int beginIndex, int endIndex) {
"""
Parses unsigned int from input.
<p>Input can start with '+'.
<p>Numeric value is according to radix
@param cs
@param radix A value between Character.MIN_RADIX and Character.MAX_RADIX or -2
@param beginIndex the index to the first char of the text range.
@param endIndex the index after the last char of the text range.
@return
@throws java.lang.NumberFormatException if input cannot be parsed to proper
int.
@see java.lang.Integer#parseUnsignedInt(java.lang.String, int)
@see java.lang.Character#digit(int, int)
"""
check(cs, radix, NumberRanges.UnsignedIntRange, beginIndex, endIndex);
int end = endIndex;
int result = 0;
int index = beginIndex;
int cp = Character.codePointAt(cs, index);
if (cp == '+')
{
index++;
}
if (index >= end)
{
throw new NumberFormatException("unparsable number "+cs.subSequence(beginIndex, endIndex));
}
while (index < end)
{
result *= radix;
cp = Character.codePointAt(cs, index);
int digit = Character.digit(cp, radix);
if (digit == -1)
{
throw new NumberFormatException("unparsable number "+cs.subSequence(beginIndex, endIndex));
}
result += digit;
if (Character.isBmpCodePoint(cp))
{
index++;
}
else
{
index += 2;
}
}
return result;
} | java | public static final int parseUnsignedInt(CharSequence cs, int radix, int beginIndex, int endIndex)
{
check(cs, radix, NumberRanges.UnsignedIntRange, beginIndex, endIndex);
int end = endIndex;
int result = 0;
int index = beginIndex;
int cp = Character.codePointAt(cs, index);
if (cp == '+')
{
index++;
}
if (index >= end)
{
throw new NumberFormatException("unparsable number "+cs.subSequence(beginIndex, endIndex));
}
while (index < end)
{
result *= radix;
cp = Character.codePointAt(cs, index);
int digit = Character.digit(cp, radix);
if (digit == -1)
{
throw new NumberFormatException("unparsable number "+cs.subSequence(beginIndex, endIndex));
}
result += digit;
if (Character.isBmpCodePoint(cp))
{
index++;
}
else
{
index += 2;
}
}
return result;
} | [
"public",
"static",
"final",
"int",
"parseUnsignedInt",
"(",
"CharSequence",
"cs",
",",
"int",
"radix",
",",
"int",
"beginIndex",
",",
"int",
"endIndex",
")",
"{",
"check",
"(",
"cs",
",",
"radix",
",",
"NumberRanges",
".",
"UnsignedIntRange",
",",
"beginInd... | Parses unsigned int from input.
<p>Input can start with '+'.
<p>Numeric value is according to radix
@param cs
@param radix A value between Character.MIN_RADIX and Character.MAX_RADIX or -2
@param beginIndex the index to the first char of the text range.
@param endIndex the index after the last char of the text range.
@return
@throws java.lang.NumberFormatException if input cannot be parsed to proper
int.
@see java.lang.Integer#parseUnsignedInt(java.lang.String, int)
@see java.lang.Character#digit(int, int) | [
"Parses",
"unsigned",
"int",
"from",
"input",
".",
"<p",
">",
"Input",
"can",
"start",
"with",
"+",
".",
"<p",
">",
"Numeric",
"value",
"is",
"according",
"to",
"radix"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/lang/Primitives.java#L1489-L1524 |
alkacon/opencms-core | src-gwt/org/opencms/ui/client/CmsPrincipalSelectConnector.java | CmsPrincipalSelectConnector.setPrincipal | void setPrincipal(int type, String principalName) {
"""
Sets the principal.<p>
@param type the principal type
@param principalName the principal name
"""
m_rpc.setPrincipal(type, principalName);
// forcing the RPC to be executed immediately
getConnection().getHeartbeat().send();
} | java | void setPrincipal(int type, String principalName) {
m_rpc.setPrincipal(type, principalName);
// forcing the RPC to be executed immediately
getConnection().getHeartbeat().send();
} | [
"void",
"setPrincipal",
"(",
"int",
"type",
",",
"String",
"principalName",
")",
"{",
"m_rpc",
".",
"setPrincipal",
"(",
"type",
",",
"principalName",
")",
";",
"// forcing the RPC to be executed immediately",
"getConnection",
"(",
")",
".",
"getHeartbeat",
"(",
"... | Sets the principal.<p>
@param type the principal type
@param principalName the principal name | [
"Sets",
"the",
"principal",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ui/client/CmsPrincipalSelectConnector.java#L81-L86 |
mapsforge/mapsforge | mapsforge-map/src/main/java/org/mapsforge/map/model/MapViewPosition.java | MapViewPosition.setZoomLevel | @Override
public void setZoomLevel(byte zoomLevel, boolean animated) {
"""
Sets the new zoom level of the map
@param zoomLevel desired zoom level
@param animated true if the transition should be animated, false otherwise
@throws IllegalArgumentException if the zoom level is negative.
"""
if (zoomLevel < 0) {
throw new IllegalArgumentException("zoomLevel must not be negative: " + zoomLevel);
}
synchronized (this) {
setZoomLevelInternal(zoomLevel, animated);
}
notifyObservers();
} | java | @Override
public void setZoomLevel(byte zoomLevel, boolean animated) {
if (zoomLevel < 0) {
throw new IllegalArgumentException("zoomLevel must not be negative: " + zoomLevel);
}
synchronized (this) {
setZoomLevelInternal(zoomLevel, animated);
}
notifyObservers();
} | [
"@",
"Override",
"public",
"void",
"setZoomLevel",
"(",
"byte",
"zoomLevel",
",",
"boolean",
"animated",
")",
"{",
"if",
"(",
"zoomLevel",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"zoomLevel must not be negative: \"",
"+",
"zoomLevel"... | Sets the new zoom level of the map
@param zoomLevel desired zoom level
@param animated true if the transition should be animated, false otherwise
@throws IllegalArgumentException if the zoom level is negative. | [
"Sets",
"the",
"new",
"zoom",
"level",
"of",
"the",
"map"
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map/src/main/java/org/mapsforge/map/model/MapViewPosition.java#L453-L462 |
FedericoPecora/meta-csp-framework | src/main/java/org/metacsp/utility/UI/CurvedArrow.java | CurvedArrow.drawArrow | private void drawArrow(Graphics g, Point head, Point away) {
"""
Draws an arrow head on the graphics object. The arrow geometry is based
on the point of its head as well as another point, which the arrow is
defined as facing away from. This arrow head has no body.
@param g
the graphics object to draw upon
@param head
the point that is the point of the head of the arrow
@param away
the point opposite from where the arrow is pointing, a point
along the line segment extending from the head backwards from
the head if this were an arrow with a line trailing the head
"""
int endX, endY;
double angle = Math.atan2((double) (away.x - head.x),
(double) (away.y - head.y));
angle += ARROW_ANGLE;
endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x;
endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y;
g.drawLine(head.x, head.y, endX, endY);
angle -= 2 * ARROW_ANGLE;
endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x;
endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y;
g.drawLine(head.x, head.y, endX, endY);
} | java | private void drawArrow(Graphics g, Point head, Point away) {
int endX, endY;
double angle = Math.atan2((double) (away.x - head.x),
(double) (away.y - head.y));
angle += ARROW_ANGLE;
endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x;
endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y;
g.drawLine(head.x, head.y, endX, endY);
angle -= 2 * ARROW_ANGLE;
endX = ((int) (Math.sin(angle) * ARROW_LENGTH)) + head.x;
endY = ((int) (Math.cos(angle) * ARROW_LENGTH)) + head.y;
g.drawLine(head.x, head.y, endX, endY);
} | [
"private",
"void",
"drawArrow",
"(",
"Graphics",
"g",
",",
"Point",
"head",
",",
"Point",
"away",
")",
"{",
"int",
"endX",
",",
"endY",
";",
"double",
"angle",
"=",
"Math",
".",
"atan2",
"(",
"(",
"double",
")",
"(",
"away",
".",
"x",
"-",
"head",
... | Draws an arrow head on the graphics object. The arrow geometry is based
on the point of its head as well as another point, which the arrow is
defined as facing away from. This arrow head has no body.
@param g
the graphics object to draw upon
@param head
the point that is the point of the head of the arrow
@param away
the point opposite from where the arrow is pointing, a point
along the line segment extending from the head backwards from
the head if this were an arrow with a line trailing the head | [
"Draws",
"an",
"arrow",
"head",
"on",
"the",
"graphics",
"object",
".",
"The",
"arrow",
"geometry",
"is",
"based",
"on",
"the",
"point",
"of",
"its",
"head",
"as",
"well",
"as",
"another",
"point",
"which",
"the",
"arrow",
"is",
"defined",
"as",
"facing"... | train | https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/utility/UI/CurvedArrow.java#L261-L273 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/AbstractBoottimeAddStepHandler.java | AbstractBoottimeAddStepHandler.rollbackRuntime | @Override
protected void rollbackRuntime(OperationContext context, ModelNode operation, Resource resource) {
"""
Overrides the superclass to call {@link OperationContext#revertReloadRequired()}
if {@link OperationContext#isBooting()} returns {@code false}.
{@inheritDoc}
"""
revertReload(context);
} | java | @Override
protected void rollbackRuntime(OperationContext context, ModelNode operation, Resource resource) {
revertReload(context);
} | [
"@",
"Override",
"protected",
"void",
"rollbackRuntime",
"(",
"OperationContext",
"context",
",",
"ModelNode",
"operation",
",",
"Resource",
"resource",
")",
"{",
"revertReload",
"(",
"context",
")",
";",
"}"
] | Overrides the superclass to call {@link OperationContext#revertReloadRequired()}
if {@link OperationContext#isBooting()} returns {@code false}.
{@inheritDoc} | [
"Overrides",
"the",
"superclass",
"to",
"call",
"{",
"@link",
"OperationContext#revertReloadRequired",
"()",
"}",
"if",
"{",
"@link",
"OperationContext#isBooting",
"()",
"}",
"returns",
"{",
"@code",
"false",
"}",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractBoottimeAddStepHandler.java#L171-L174 |
apache/fluo-recipes | modules/core/src/main/java/org/apache/fluo/recipes/core/data/RowHasher.java | RowHasher.configure | public static void configure(FluoConfiguration fluoConfig, String prefix, int numTablets) {
"""
This method can be called to register table optimizations before initializing Fluo. This will
register {@link Optimizer} with
{@link TableOptimizations#registerOptimization(SimpleConfiguration, String, Class)}. See the
project level documentation for an example.
@param fluoConfig The config that will be used to initialize Fluo
@param prefix The prefix used for your Row Hasher. If you have a single instance, could call
{@link RowHasher#getPrefix()}.
@param numTablets Initial number of tablet to create.
"""
fluoConfig.getAppConfiguration().setProperty(PREFIX + prefix + ".numTablets", numTablets);
TableOptimizations.registerOptimization(fluoConfig.getAppConfiguration(), prefix,
Optimizer.class);
} | java | public static void configure(FluoConfiguration fluoConfig, String prefix, int numTablets) {
fluoConfig.getAppConfiguration().setProperty(PREFIX + prefix + ".numTablets", numTablets);
TableOptimizations.registerOptimization(fluoConfig.getAppConfiguration(), prefix,
Optimizer.class);
} | [
"public",
"static",
"void",
"configure",
"(",
"FluoConfiguration",
"fluoConfig",
",",
"String",
"prefix",
",",
"int",
"numTablets",
")",
"{",
"fluoConfig",
".",
"getAppConfiguration",
"(",
")",
".",
"setProperty",
"(",
"PREFIX",
"+",
"prefix",
"+",
"\".numTablet... | This method can be called to register table optimizations before initializing Fluo. This will
register {@link Optimizer} with
{@link TableOptimizations#registerOptimization(SimpleConfiguration, String, Class)}. See the
project level documentation for an example.
@param fluoConfig The config that will be used to initialize Fluo
@param prefix The prefix used for your Row Hasher. If you have a single instance, could call
{@link RowHasher#getPrefix()}.
@param numTablets Initial number of tablet to create. | [
"This",
"method",
"can",
"be",
"called",
"to",
"register",
"table",
"optimizations",
"before",
"initializing",
"Fluo",
".",
"This",
"will",
"register",
"{",
"@link",
"Optimizer",
"}",
"with",
"{",
"@link",
"TableOptimizations#registerOptimization",
"(",
"SimpleConfi... | train | https://github.com/apache/fluo-recipes/blob/24c11234c9654b16d999437ff49ddc3db86665f8/modules/core/src/main/java/org/apache/fluo/recipes/core/data/RowHasher.java#L99-L103 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/ThresholdBlock.java | ThresholdBlock.process | public void process(T input , GrayU8 output ) {
"""
Converts the gray scale input image into a binary image
@param input Input image
@param output Output binary image
"""
output.reshape(input.width,input.height);
int requestedBlockWidth = this.requestedBlockWidth.computeI(Math.min(input.width,input.height));
selectBlockSize(input.width,input.height,requestedBlockWidth);
stats.reshape(input.width/blockWidth,input.height/blockHeight);
int innerWidth = input.width%blockWidth == 0 ?
input.width : input.width-blockWidth-input.width%blockWidth;
int innerHeight = input.height%blockHeight == 0 ?
input.height : input.height-blockHeight-input.height%blockHeight;
computeStatistics(input, innerWidth, innerHeight);
applyThreshold(input,output);
} | java | public void process(T input , GrayU8 output ) {
output.reshape(input.width,input.height);
int requestedBlockWidth = this.requestedBlockWidth.computeI(Math.min(input.width,input.height));
selectBlockSize(input.width,input.height,requestedBlockWidth);
stats.reshape(input.width/blockWidth,input.height/blockHeight);
int innerWidth = input.width%blockWidth == 0 ?
input.width : input.width-blockWidth-input.width%blockWidth;
int innerHeight = input.height%blockHeight == 0 ?
input.height : input.height-blockHeight-input.height%blockHeight;
computeStatistics(input, innerWidth, innerHeight);
applyThreshold(input,output);
} | [
"public",
"void",
"process",
"(",
"T",
"input",
",",
"GrayU8",
"output",
")",
"{",
"output",
".",
"reshape",
"(",
"input",
".",
"width",
",",
"input",
".",
"height",
")",
";",
"int",
"requestedBlockWidth",
"=",
"this",
".",
"requestedBlockWidth",
".",
"c... | Converts the gray scale input image into a binary image
@param input Input image
@param output Output binary image | [
"Converts",
"the",
"gray",
"scale",
"input",
"image",
"into",
"a",
"binary",
"image"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/ThresholdBlock.java#L90-L107 |
jfoenixadmin/JFoenix | jfoenix/src/main/java/com/jfoenix/skins/PromptLinesWrapper.java | PromptLinesWrapper.animateFloatingLabel | private void animateFloatingLabel(boolean up, boolean animation) {
"""
this method is called when the text property is changed when the
field is not focused (changed in code)
@param up
"""
if (promptTextSupplier.get() == null) {
return;
}
if (up) {
if (promptTextSupplier.get().getTranslateY() != -contentHeight) {
unfocusTimer.stop();
runTimer(focusTimer, animation);
}
} else {
if (promptTextSupplier.get().getTranslateY() != 0) {
focusTimer.stop();
runTimer(unfocusTimer, animation);
}
}
} | java | private void animateFloatingLabel(boolean up, boolean animation) {
if (promptTextSupplier.get() == null) {
return;
}
if (up) {
if (promptTextSupplier.get().getTranslateY() != -contentHeight) {
unfocusTimer.stop();
runTimer(focusTimer, animation);
}
} else {
if (promptTextSupplier.get().getTranslateY() != 0) {
focusTimer.stop();
runTimer(unfocusTimer, animation);
}
}
} | [
"private",
"void",
"animateFloatingLabel",
"(",
"boolean",
"up",
",",
"boolean",
"animation",
")",
"{",
"if",
"(",
"promptTextSupplier",
".",
"get",
"(",
")",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"up",
")",
"{",
"if",
"(",
"promptText... | this method is called when the text property is changed when the
field is not focused (changed in code)
@param up | [
"this",
"method",
"is",
"called",
"when",
"the",
"text",
"property",
"is",
"changed",
"when",
"the",
"field",
"is",
"not",
"focused",
"(",
"changed",
"in",
"code",
")"
] | train | https://github.com/jfoenixadmin/JFoenix/blob/53235b5f561da4a515ef716059b8a8df5239ffa1/jfoenix/src/main/java/com/jfoenix/skins/PromptLinesWrapper.java#L271-L286 |
diffplug/JMatIO | src/main/java/ca/mjdsystems/jmatio/io/MatFileIncrementalWriter.java | MatFileIncrementalWriter.writeFlags | private void writeFlags(DataOutputStream os, MLArray array) throws IOException {
"""
Writes MATRIX flags into <code>OutputStream</code>.
@param os - <code>OutputStream</code>
@param array - a <code>MLArray</code>
@throws IOException
"""
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream bufferDOS = new DataOutputStream(buffer);
bufferDOS.writeInt( array.getFlags() );
if ( array.isSparse() )
{
bufferDOS.writeInt( ((MLSparse)array).getMaxNZ() );
}
else
{
bufferDOS.writeInt( 0 );
}
OSArrayTag tag = new OSArrayTag(MatDataTypes.miUINT32, buffer.toByteArray() );
tag.writeTo( os );
} | java | private void writeFlags(DataOutputStream os, MLArray array) throws IOException
{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream bufferDOS = new DataOutputStream(buffer);
bufferDOS.writeInt( array.getFlags() );
if ( array.isSparse() )
{
bufferDOS.writeInt( ((MLSparse)array).getMaxNZ() );
}
else
{
bufferDOS.writeInt( 0 );
}
OSArrayTag tag = new OSArrayTag(MatDataTypes.miUINT32, buffer.toByteArray() );
tag.writeTo( os );
} | [
"private",
"void",
"writeFlags",
"(",
"DataOutputStream",
"os",
",",
"MLArray",
"array",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"buffer",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"DataOutputStream",
"bufferDOS",
"=",
"new",
"DataOutpu... | Writes MATRIX flags into <code>OutputStream</code>.
@param os - <code>OutputStream</code>
@param array - a <code>MLArray</code>
@throws IOException | [
"Writes",
"MATRIX",
"flags",
"into",
"<code",
">",
"OutputStream<",
"/",
"code",
">",
"."
] | train | https://github.com/diffplug/JMatIO/blob/dab8a54fa21a8faeaa81537cdc45323c5c4e6ca6/src/main/java/ca/mjdsystems/jmatio/io/MatFileIncrementalWriter.java#L450-L468 |
goldmansachs/reladomo | reladomo/src/main/java/com/gs/fw/common/mithra/MithraManager.java | MithraManager.startOrContinueTransaction | public MithraTransaction startOrContinueTransaction(TransactionStyle style) throws MithraTransactionException {
"""
Behaves like startOrContinueTransaction(), but with a custom transaction style
@param style defines the parameters for this transaction.
@return
@throws MithraTransactionException
"""
MithraTransaction result;
MithraTransaction parent = this.getCurrentTransaction();
if (parent != null)
{
result = new MithraNestedTransaction(parent);
}
else
{
Transaction jtaTx;
try
{
if (this.getJtaTransactionManager().getStatus() != Status.STATUS_ACTIVE)
{
this.getJtaTransactionManager().setTransactionTimeout(style.getTimeout());
this.getJtaTransactionManager().begin();
}
jtaTx = this.getJtaTransactionManager().getTransaction();
result = this.createMithraRootTransaction(jtaTx, style.getTimeout()*1000);
}
catch (NotSupportedException e)
{
throw new MithraTransactionException("JTA exception", e);
}
catch (SystemException e)
{
throw new MithraTransactionException("JTA exception", e);
}
catch (RollbackException e)
{
throw new MithraTransactionException("JTA exception", e);
}
}
this.setThreadTransaction(result);
return result;
} | java | public MithraTransaction startOrContinueTransaction(TransactionStyle style) throws MithraTransactionException
{
MithraTransaction result;
MithraTransaction parent = this.getCurrentTransaction();
if (parent != null)
{
result = new MithraNestedTransaction(parent);
}
else
{
Transaction jtaTx;
try
{
if (this.getJtaTransactionManager().getStatus() != Status.STATUS_ACTIVE)
{
this.getJtaTransactionManager().setTransactionTimeout(style.getTimeout());
this.getJtaTransactionManager().begin();
}
jtaTx = this.getJtaTransactionManager().getTransaction();
result = this.createMithraRootTransaction(jtaTx, style.getTimeout()*1000);
}
catch (NotSupportedException e)
{
throw new MithraTransactionException("JTA exception", e);
}
catch (SystemException e)
{
throw new MithraTransactionException("JTA exception", e);
}
catch (RollbackException e)
{
throw new MithraTransactionException("JTA exception", e);
}
}
this.setThreadTransaction(result);
return result;
} | [
"public",
"MithraTransaction",
"startOrContinueTransaction",
"(",
"TransactionStyle",
"style",
")",
"throws",
"MithraTransactionException",
"{",
"MithraTransaction",
"result",
";",
"MithraTransaction",
"parent",
"=",
"this",
".",
"getCurrentTransaction",
"(",
")",
";",
"i... | Behaves like startOrContinueTransaction(), but with a custom transaction style
@param style defines the parameters for this transaction.
@return
@throws MithraTransactionException | [
"Behaves",
"like",
"startOrContinueTransaction",
"()",
"but",
"with",
"a",
"custom",
"transaction",
"style"
] | train | https://github.com/goldmansachs/reladomo/blob/e9a069452eece7a6ef9551caf81a69d3d9a3d990/reladomo/src/main/java/com/gs/fw/common/mithra/MithraManager.java#L246-L282 |
intive-FDV/DynamicJasper | src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJBar3DChartBuilder.java | DJBar3DChartBuilder.addSerie | public DJBar3DChartBuilder addSerie(AbstractColumn column, String label) {
"""
Adds the specified serie column to the dataset with custom label.
@param column the serie column
@param label column the custom label
"""
getDataset().addSerie(column, label);
return this;
} | java | public DJBar3DChartBuilder addSerie(AbstractColumn column, String label) {
getDataset().addSerie(column, label);
return this;
} | [
"public",
"DJBar3DChartBuilder",
"addSerie",
"(",
"AbstractColumn",
"column",
",",
"String",
"label",
")",
"{",
"getDataset",
"(",
")",
".",
"addSerie",
"(",
"column",
",",
"label",
")",
";",
"return",
"this",
";",
"}"
] | Adds the specified serie column to the dataset with custom label.
@param column the serie column
@param label column the custom label | [
"Adds",
"the",
"specified",
"serie",
"column",
"to",
"the",
"dataset",
"with",
"custom",
"label",
"."
] | train | https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/domain/chart/builder/DJBar3DChartBuilder.java#L366-L369 |
groupe-sii/ogham | ogham-core/src/main/java/fr/sii/ogham/html/inliner/impl/jsoup/JsoupCssInliner.java | JsoupCssInliner.internStyles | private void internStyles(Document doc, List<ExternalCss> cssContents) {
"""
Replace link tags with style tags in order to keep the same inclusion
order
@param doc
the html document
@param cssContents
the list of external css files with their content
"""
Elements els = doc.select(CSS_LINKS_SELECTOR);
for (Element e : els) {
if (!TRUE_VALUE.equals(e.attr(SKIP_INLINE))) {
String path = e.attr(HREF_ATTR);
Element style = new Element(Tag.valueOf(STYLE_TAG), "");
style.appendChild(new DataNode(getCss(cssContents, path), ""));
e.replaceWith(style);
}
}
} | java | private void internStyles(Document doc, List<ExternalCss> cssContents) {
Elements els = doc.select(CSS_LINKS_SELECTOR);
for (Element e : els) {
if (!TRUE_VALUE.equals(e.attr(SKIP_INLINE))) {
String path = e.attr(HREF_ATTR);
Element style = new Element(Tag.valueOf(STYLE_TAG), "");
style.appendChild(new DataNode(getCss(cssContents, path), ""));
e.replaceWith(style);
}
}
} | [
"private",
"void",
"internStyles",
"(",
"Document",
"doc",
",",
"List",
"<",
"ExternalCss",
">",
"cssContents",
")",
"{",
"Elements",
"els",
"=",
"doc",
".",
"select",
"(",
"CSS_LINKS_SELECTOR",
")",
";",
"for",
"(",
"Element",
"e",
":",
"els",
")",
"{",... | Replace link tags with style tags in order to keep the same inclusion
order
@param doc
the html document
@param cssContents
the list of external css files with their content | [
"Replace",
"link",
"tags",
"with",
"style",
"tags",
"in",
"order",
"to",
"keep",
"the",
"same",
"inclusion",
"order"
] | train | https://github.com/groupe-sii/ogham/blob/e273b845604add74b5a25dfd931cb3c166b1008f/ogham-core/src/main/java/fr/sii/ogham/html/inliner/impl/jsoup/JsoupCssInliner.java#L68-L78 |
Manabu-GT/EtsyBlur | sample/src/main/java/com/ms/square/android/etsyblurdemo/ui/fragment/PlaceholderFragment.java | PlaceholderFragment.newInstance | public static PlaceholderFragment newInstance(int sectionNumber, @LayoutRes int layoutRes) {
"""
Returns a new instance of this fragment for the given section
number.
"""
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putInt(ARG_LAYOUT_RESOURCE, layoutRes);
fragment.setArguments(args);
return fragment;
} | java | public static PlaceholderFragment newInstance(int sectionNumber, @LayoutRes int layoutRes) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putInt(ARG_LAYOUT_RESOURCE, layoutRes);
fragment.setArguments(args);
return fragment;
} | [
"public",
"static",
"PlaceholderFragment",
"newInstance",
"(",
"int",
"sectionNumber",
",",
"@",
"LayoutRes",
"int",
"layoutRes",
")",
"{",
"PlaceholderFragment",
"fragment",
"=",
"new",
"PlaceholderFragment",
"(",
")",
";",
"Bundle",
"args",
"=",
"new",
"Bundle",... | Returns a new instance of this fragment for the given section
number. | [
"Returns",
"a",
"new",
"instance",
"of",
"this",
"fragment",
"for",
"the",
"given",
"section",
"number",
"."
] | train | https://github.com/Manabu-GT/EtsyBlur/blob/b51c9e80e823fce3590cc061e79e267388b4d8e0/sample/src/main/java/com/ms/square/android/etsyblurdemo/ui/fragment/PlaceholderFragment.java#L31-L38 |
Alluxio/alluxio | shell/src/main/java/alluxio/cli/fs/command/FileSystemCommandUtils.java | FileSystemCommandUtils.setPinned | public static void setPinned(FileSystem fs, AlluxioURI path, boolean pinned)
throws AlluxioException, IOException {
"""
Sets pin state for the input path.
@param fs The {@link FileSystem} client
@param path The {@link AlluxioURI} path as the input of the command
@param pinned the state to be set
"""
SetAttributePOptions options = SetAttributePOptions.newBuilder().setPinned(pinned).build();
fs.setAttribute(path, options);
} | java | public static void setPinned(FileSystem fs, AlluxioURI path, boolean pinned)
throws AlluxioException, IOException {
SetAttributePOptions options = SetAttributePOptions.newBuilder().setPinned(pinned).build();
fs.setAttribute(path, options);
} | [
"public",
"static",
"void",
"setPinned",
"(",
"FileSystem",
"fs",
",",
"AlluxioURI",
"path",
",",
"boolean",
"pinned",
")",
"throws",
"AlluxioException",
",",
"IOException",
"{",
"SetAttributePOptions",
"options",
"=",
"SetAttributePOptions",
".",
"newBuilder",
"(",... | Sets pin state for the input path.
@param fs The {@link FileSystem} client
@param path The {@link AlluxioURI} path as the input of the command
@param pinned the state to be set | [
"Sets",
"pin",
"state",
"for",
"the",
"input",
"path",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fs/command/FileSystemCommandUtils.java#L60-L64 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jEntityQueries.java | BaseNeo4jEntityQueries.initUpdateEmbeddedColumnQuery | private String initUpdateEmbeddedColumnQuery(Object[] keyValues, String embeddedColumn) {
"""
/*
Example:
MERGE (owner:ENTITY:Account {login: {0}})
MERGE (owner) - [:homeAddress] -> (e:EMBEDDED)
ON CREATE SET e.country = {1}
ON MATCH SET e.country = {2}
"""
StringBuilder queryBuilder = new StringBuilder( getUpdateEmbeddedNodeQuery() );
String[] columns = appendEmbeddedNodes( embeddedColumn, queryBuilder );
queryBuilder.append( " ON CREATE SET e." );
escapeIdentifier( queryBuilder, columns[columns.length - 1] );
queryBuilder.append( " = {" );
queryBuilder.append( keyValues.length );
queryBuilder.append( "}" );
queryBuilder.append( " ON MATCH SET e." );
escapeIdentifier( queryBuilder, columns[columns.length - 1] );
queryBuilder.append( " = {" );
queryBuilder.append( keyValues.length + 1 );
queryBuilder.append( "}" );
return queryBuilder.toString();
} | java | private String initUpdateEmbeddedColumnQuery(Object[] keyValues, String embeddedColumn) {
StringBuilder queryBuilder = new StringBuilder( getUpdateEmbeddedNodeQuery() );
String[] columns = appendEmbeddedNodes( embeddedColumn, queryBuilder );
queryBuilder.append( " ON CREATE SET e." );
escapeIdentifier( queryBuilder, columns[columns.length - 1] );
queryBuilder.append( " = {" );
queryBuilder.append( keyValues.length );
queryBuilder.append( "}" );
queryBuilder.append( " ON MATCH SET e." );
escapeIdentifier( queryBuilder, columns[columns.length - 1] );
queryBuilder.append( " = {" );
queryBuilder.append( keyValues.length + 1 );
queryBuilder.append( "}" );
return queryBuilder.toString();
} | [
"private",
"String",
"initUpdateEmbeddedColumnQuery",
"(",
"Object",
"[",
"]",
"keyValues",
",",
"String",
"embeddedColumn",
")",
"{",
"StringBuilder",
"queryBuilder",
"=",
"new",
"StringBuilder",
"(",
"getUpdateEmbeddedNodeQuery",
"(",
")",
")",
";",
"String",
"[",... | /*
Example:
MERGE (owner:ENTITY:Account {login: {0}})
MERGE (owner) - [:homeAddress] -> (e:EMBEDDED)
ON CREATE SET e.country = {1}
ON MATCH SET e.country = {2} | [
"/",
"*",
"Example",
":"
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jEntityQueries.java#L572-L586 |
esigate/esigate | esigate-core/src/main/java/org/esigate/Driver.java | Driver.proxy | public CloseableHttpResponse proxy(String relUrl, IncomingRequest incomingRequest, Renderer... renderers)
throws IOException, HttpErrorPage {
"""
Retrieves a resource from the provider application and transforms it using the Renderer passed as a parameter.
@param relUrl
the relative URL to the resource
@param incomingRequest
the request
@param renderers
the renderers to use to transform the output
@return The resulting response.
@throws IOException
If an IOException occurs while writing to the response
@throws HttpErrorPage
If the page contains incorrect tags
"""
DriverRequest driverRequest = new DriverRequest(incomingRequest, this, relUrl);
driverRequest.setCharacterEncoding(this.config.getUriEncoding());
// This is used to ensure EVENT_PROXY_POST is called once and only once.
// there are 3 different cases
// - Success -> the main code
// - Error page -> the HttpErrorPage exception
// - Unexpected error -> Other Exceptions
boolean postProxyPerformed = false;
// Create Proxy event
ProxyEvent e = new ProxyEvent(incomingRequest);
// Event pre-proxy
this.eventManager.fire(EventManager.EVENT_PROXY_PRE, e);
// Return immediately if exit is requested by extension
if (e.isExit()) {
return e.getResponse();
}
logAction("proxy", relUrl, renderers);
String url = ResourceUtils.getHttpUrlWithQueryString(relUrl, driverRequest, true);
OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, url, true);
headerManager.copyHeaders(driverRequest, outgoingRequest);
try {
CloseableHttpResponse response = requestExecutor.execute(outgoingRequest);
response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response);
e.setResponse(response);
// Perform rendering
e.setResponse(performRendering(relUrl, driverRequest, e.getResponse(), renderers));
// Event post-proxy
// This must be done before calling sendResponse to ensure response
// can still be changed.
postProxyPerformed = true;
this.eventManager.fire(EventManager.EVENT_PROXY_POST, e);
// Send request to the client.
return e.getResponse();
} catch (HttpErrorPage errorPage) {
e.setErrorPage(errorPage);
// On error returned by the proxy request, perform rendering on the
// error page.
CloseableHttpResponse response = e.getErrorPage().getHttpResponse();
response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response);
e.setErrorPage(new HttpErrorPage(performRendering(relUrl, driverRequest, response, renderers)));
// Event post-proxy
// This must be done before throwing exception to ensure response
// can still be changed.
postProxyPerformed = true;
this.eventManager.fire(EventManager.EVENT_PROXY_POST, e);
throw e.getErrorPage();
} finally {
if (!postProxyPerformed) {
this.eventManager.fire(EventManager.EVENT_PROXY_POST, e);
}
}
} | java | public CloseableHttpResponse proxy(String relUrl, IncomingRequest incomingRequest, Renderer... renderers)
throws IOException, HttpErrorPage {
DriverRequest driverRequest = new DriverRequest(incomingRequest, this, relUrl);
driverRequest.setCharacterEncoding(this.config.getUriEncoding());
// This is used to ensure EVENT_PROXY_POST is called once and only once.
// there are 3 different cases
// - Success -> the main code
// - Error page -> the HttpErrorPage exception
// - Unexpected error -> Other Exceptions
boolean postProxyPerformed = false;
// Create Proxy event
ProxyEvent e = new ProxyEvent(incomingRequest);
// Event pre-proxy
this.eventManager.fire(EventManager.EVENT_PROXY_PRE, e);
// Return immediately if exit is requested by extension
if (e.isExit()) {
return e.getResponse();
}
logAction("proxy", relUrl, renderers);
String url = ResourceUtils.getHttpUrlWithQueryString(relUrl, driverRequest, true);
OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, url, true);
headerManager.copyHeaders(driverRequest, outgoingRequest);
try {
CloseableHttpResponse response = requestExecutor.execute(outgoingRequest);
response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response);
e.setResponse(response);
// Perform rendering
e.setResponse(performRendering(relUrl, driverRequest, e.getResponse(), renderers));
// Event post-proxy
// This must be done before calling sendResponse to ensure response
// can still be changed.
postProxyPerformed = true;
this.eventManager.fire(EventManager.EVENT_PROXY_POST, e);
// Send request to the client.
return e.getResponse();
} catch (HttpErrorPage errorPage) {
e.setErrorPage(errorPage);
// On error returned by the proxy request, perform rendering on the
// error page.
CloseableHttpResponse response = e.getErrorPage().getHttpResponse();
response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response);
e.setErrorPage(new HttpErrorPage(performRendering(relUrl, driverRequest, response, renderers)));
// Event post-proxy
// This must be done before throwing exception to ensure response
// can still be changed.
postProxyPerformed = true;
this.eventManager.fire(EventManager.EVENT_PROXY_POST, e);
throw e.getErrorPage();
} finally {
if (!postProxyPerformed) {
this.eventManager.fire(EventManager.EVENT_PROXY_POST, e);
}
}
} | [
"public",
"CloseableHttpResponse",
"proxy",
"(",
"String",
"relUrl",
",",
"IncomingRequest",
"incomingRequest",
",",
"Renderer",
"...",
"renderers",
")",
"throws",
"IOException",
",",
"HttpErrorPage",
"{",
"DriverRequest",
"driverRequest",
"=",
"new",
"DriverRequest",
... | Retrieves a resource from the provider application and transforms it using the Renderer passed as a parameter.
@param relUrl
the relative URL to the resource
@param incomingRequest
the request
@param renderers
the renderers to use to transform the output
@return The resulting response.
@throws IOException
If an IOException occurs while writing to the response
@throws HttpErrorPage
If the page contains incorrect tags | [
"Retrieves",
"a",
"resource",
"from",
"the",
"provider",
"application",
"and",
"transforms",
"it",
"using",
"the",
"Renderer",
"passed",
"as",
"a",
"parameter",
"."
] | train | https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/Driver.java#L269-L337 |
spring-projects/spring-ldap | core/src/main/java/org/springframework/ldap/support/LdapUtils.java | LdapUtils.getRdn | public static Rdn getRdn(Name name, String key) {
"""
Find the Rdn with the requested key in the supplied Name.
@param name the Name in which to search for the key.
@param key the attribute key to search for.
@return the rdn corresponding to the <b>first</b> occurrence of the requested key.
@throws NoSuchElementException if no corresponding entry is found.
@since 2.0
"""
Assert.notNull(name, "name must not be null");
Assert.hasText(key, "key must not be blank");
LdapName ldapName = returnOrConstructLdapNameFromName(name);
List<Rdn> rdns = ldapName.getRdns();
for (Rdn rdn : rdns) {
NamingEnumeration<String> ids = rdn.toAttributes().getIDs();
while (ids.hasMoreElements()) {
String id = ids.nextElement();
if(key.equalsIgnoreCase(id)) {
return rdn;
}
}
}
throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'");
} | java | public static Rdn getRdn(Name name, String key) {
Assert.notNull(name, "name must not be null");
Assert.hasText(key, "key must not be blank");
LdapName ldapName = returnOrConstructLdapNameFromName(name);
List<Rdn> rdns = ldapName.getRdns();
for (Rdn rdn : rdns) {
NamingEnumeration<String> ids = rdn.toAttributes().getIDs();
while (ids.hasMoreElements()) {
String id = ids.nextElement();
if(key.equalsIgnoreCase(id)) {
return rdn;
}
}
}
throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'");
} | [
"public",
"static",
"Rdn",
"getRdn",
"(",
"Name",
"name",
",",
"String",
"key",
")",
"{",
"Assert",
".",
"notNull",
"(",
"name",
",",
"\"name must not be null\"",
")",
";",
"Assert",
".",
"hasText",
"(",
"key",
",",
"\"key must not be blank\"",
")",
";",
"... | Find the Rdn with the requested key in the supplied Name.
@param name the Name in which to search for the key.
@param key the attribute key to search for.
@return the rdn corresponding to the <b>first</b> occurrence of the requested key.
@throws NoSuchElementException if no corresponding entry is found.
@since 2.0 | [
"Find",
"the",
"Rdn",
"with",
"the",
"requested",
"key",
"in",
"the",
"supplied",
"Name",
"."
] | train | https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapUtils.java#L506-L524 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java | CommonMpJwtFat.setUpAndStartBuilderServer | protected static void setUpAndStartBuilderServer(LibertyServer server, String configFile, boolean jwtEnabled) throws Exception {
"""
Startup a Liberty Server with the JWT Builder enabled
@param server - the server to startup
@param configFile - the config file to use when starting the serever
@param jwtEnabled - flag indicating if jwt should be enabled (used to set a bootstrap property that the config will use)
@throws Exception
"""
bootstrapUtils.writeBootstrapProperty(server, "oidcJWKEnabled", String.valueOf(jwtEnabled));
serverTracker.addServer(server);
server.startServerUsingExpandedConfiguration(configFile);
SecurityFatHttpUtils.saveServerPorts(server, MpJwtFatConstants.BVT_SERVER_2_PORT_NAME_ROOT);
} | java | protected static void setUpAndStartBuilderServer(LibertyServer server, String configFile, boolean jwtEnabled) throws Exception {
bootstrapUtils.writeBootstrapProperty(server, "oidcJWKEnabled", String.valueOf(jwtEnabled));
serverTracker.addServer(server);
server.startServerUsingExpandedConfiguration(configFile);
SecurityFatHttpUtils.saveServerPorts(server, MpJwtFatConstants.BVT_SERVER_2_PORT_NAME_ROOT);
} | [
"protected",
"static",
"void",
"setUpAndStartBuilderServer",
"(",
"LibertyServer",
"server",
",",
"String",
"configFile",
",",
"boolean",
"jwtEnabled",
")",
"throws",
"Exception",
"{",
"bootstrapUtils",
".",
"writeBootstrapProperty",
"(",
"server",
",",
"\"oidcJWKEnable... | Startup a Liberty Server with the JWT Builder enabled
@param server - the server to startup
@param configFile - the config file to use when starting the serever
@param jwtEnabled - flag indicating if jwt should be enabled (used to set a bootstrap property that the config will use)
@throws Exception | [
"Startup",
"a",
"Liberty",
"Server",
"with",
"the",
"JWT",
"Builder",
"enabled"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java#L67-L72 |
threerings/nenya | core/src/main/java/com/threerings/miso/client/MisoScenePanel.java | MisoScenePanel.setShowFlags | public void setShowFlags (int flags, boolean on) {
"""
Set whether or not to highlight object tooltips (and potentially other scene entities).
"""
int oldshow = _showFlags;
if (on) {
_showFlags |= flags;
} else {
_showFlags &= ~flags;
}
if (oldshow != _showFlags) {
showFlagsDidChange(oldshow);
}
} | java | public void setShowFlags (int flags, boolean on)
{
int oldshow = _showFlags;
if (on) {
_showFlags |= flags;
} else {
_showFlags &= ~flags;
}
if (oldshow != _showFlags) {
showFlagsDidChange(oldshow);
}
} | [
"public",
"void",
"setShowFlags",
"(",
"int",
"flags",
",",
"boolean",
"on",
")",
"{",
"int",
"oldshow",
"=",
"_showFlags",
";",
"if",
"(",
"on",
")",
"{",
"_showFlags",
"|=",
"flags",
";",
"}",
"else",
"{",
"_showFlags",
"&=",
"~",
"flags",
";",
"}"... | Set whether or not to highlight object tooltips (and potentially other scene entities). | [
"Set",
"whether",
"or",
"not",
"to",
"highlight",
"object",
"tooltips",
"(",
"and",
"potentially",
"other",
"scene",
"entities",
")",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/client/MisoScenePanel.java#L201-L214 |
hal/core | gui/src/main/java/org/useware/kernel/model/structure/InteractionUnit.java | InteractionUnit.findMapping | public <T extends Mapping> T findMapping(MappingType type, Predicate<T> predicate) {
"""
Finds the first mapping of a type within the hierarchy.
Uses parent delegation if the mapping cannot be found locally.
<p/>
The predicate needs to apply.
@param type
@param predicate Use {@code null} to ignore
@return
"""
T mapping = getMapping(type);
if (mapping != null)
{
// check predicate: can invalidate the local mapping
if (predicate != null)
{
mapping = (predicate.appliesTo(mapping)) ? mapping : null;
}
// complement the mapping (i.e. resource address at a higher level)
if(mapping!=null && parent!=null)
{
Mapping parentMapping = parent.findMapping(type, predicate);
if(parentMapping!=null)
{
mapping.complementFrom(parentMapping);
}
}
}
if (mapping == null && parent != null)
{
mapping = (T) parent.findMapping(type, predicate);
}
return mapping;
} | java | public <T extends Mapping> T findMapping(MappingType type, Predicate<T> predicate)
{
T mapping = getMapping(type);
if (mapping != null)
{
// check predicate: can invalidate the local mapping
if (predicate != null)
{
mapping = (predicate.appliesTo(mapping)) ? mapping : null;
}
// complement the mapping (i.e. resource address at a higher level)
if(mapping!=null && parent!=null)
{
Mapping parentMapping = parent.findMapping(type, predicate);
if(parentMapping!=null)
{
mapping.complementFrom(parentMapping);
}
}
}
if (mapping == null && parent != null)
{
mapping = (T) parent.findMapping(type, predicate);
}
return mapping;
} | [
"public",
"<",
"T",
"extends",
"Mapping",
">",
"T",
"findMapping",
"(",
"MappingType",
"type",
",",
"Predicate",
"<",
"T",
">",
"predicate",
")",
"{",
"T",
"mapping",
"=",
"getMapping",
"(",
"type",
")",
";",
"if",
"(",
"mapping",
"!=",
"null",
")",
... | Finds the first mapping of a type within the hierarchy.
Uses parent delegation if the mapping cannot be found locally.
<p/>
The predicate needs to apply.
@param type
@param predicate Use {@code null} to ignore
@return | [
"Finds",
"the",
"first",
"mapping",
"of",
"a",
"type",
"within",
"the",
"hierarchy",
".",
"Uses",
"parent",
"delegation",
"if",
"the",
"mapping",
"cannot",
"be",
"found",
"locally",
".",
"<p",
"/",
">",
"The",
"predicate",
"needs",
"to",
"apply",
"."
] | train | https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/useware/kernel/model/structure/InteractionUnit.java#L157-L187 |
unbescape/unbescape | src/main/java/org/unbescape/uri/UriEscape.java | UriEscape.escapeUriFragmentId | public static String escapeUriFragmentId(final String text, final String encoding) {
"""
<p>
Perform am URI fragment identifier <strong>escape</strong> operation
on a <tt>String</tt> input.
</p>
<p>
The following are the only allowed chars in an URI fragment identifier (will not be escaped):
</p>
<ul>
<li><tt>A-Z a-z 0-9</tt></li>
<li><tt>- . _ ~</tt></li>
<li><tt>! $ & ' ( ) * + , ; =</tt></li>
<li><tt>: @</tt></li>
<li><tt>/ ?</tt></li>
</ul>
<p>
All other chars will be escaped by converting them to the sequence of bytes that
represents them in the specified <em>encoding</em> and then representing each byte
in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param encoding the encoding to be used for escaping.
@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 (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
return UriEscapeUtil.escape(text, UriEscapeUtil.UriEscapeType.FRAGMENT_ID, encoding);
} | java | public static String escapeUriFragmentId(final String text, final String encoding) {
if (encoding == null) {
throw new IllegalArgumentException("Argument 'encoding' cannot be null");
}
return UriEscapeUtil.escape(text, UriEscapeUtil.UriEscapeType.FRAGMENT_ID, encoding);
} | [
"public",
"static",
"String",
"escapeUriFragmentId",
"(",
"final",
"String",
"text",
",",
"final",
"String",
"encoding",
")",
"{",
"if",
"(",
"encoding",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'encoding' cannot be null\"... | <p>
Perform am URI fragment identifier <strong>escape</strong> operation
on a <tt>String</tt> input.
</p>
<p>
The following are the only allowed chars in an URI fragment identifier (will not be escaped):
</p>
<ul>
<li><tt>A-Z a-z 0-9</tt></li>
<li><tt>- . _ ~</tt></li>
<li><tt>! $ & ' ( ) * + , ; =</tt></li>
<li><tt>: @</tt></li>
<li><tt>/ ?</tt></li>
</ul>
<p>
All other chars will be escaped by converting them to the sequence of bytes that
represents them in the specified <em>encoding</em> and then representing each byte
in <tt>%HH</tt> syntax, being <tt>HH</tt> the hexadecimal representation of the byte.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param encoding the encoding to be used for escaping.
@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",
"am",
"URI",
"fragment",
"identifier",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
".",
"<",
"/",
"p",
">",
"<p",
">",
"The",
"following",
"are",
"the",
... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L402-L407 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java | CPOptionValuePersistenceImpl.fetchByC_ERC | @Override
public CPOptionValue fetchByC_ERC(long companyId,
String externalReferenceCode) {
"""
Returns the cp option value where companyId = ? and externalReferenceCode = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param companyId the company ID
@param externalReferenceCode the external reference code
@return the matching cp option value, or <code>null</code> if a matching cp option value could not be found
"""
return fetchByC_ERC(companyId, externalReferenceCode, true);
} | java | @Override
public CPOptionValue fetchByC_ERC(long companyId,
String externalReferenceCode) {
return fetchByC_ERC(companyId, externalReferenceCode, true);
} | [
"@",
"Override",
"public",
"CPOptionValue",
"fetchByC_ERC",
"(",
"long",
"companyId",
",",
"String",
"externalReferenceCode",
")",
"{",
"return",
"fetchByC_ERC",
"(",
"companyId",
",",
"externalReferenceCode",
",",
"true",
")",
";",
"}"
] | Returns the cp option value where companyId = ? and externalReferenceCode = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param companyId the company ID
@param externalReferenceCode the external reference code
@return the matching cp option value, or <code>null</code> if a matching cp option value could not be found | [
"Returns",
"the",
"cp",
"option",
"value",
"where",
"companyId",
"=",
"?",
";",
"and",
"externalReferenceCode",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"Uses",
"the",
... | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java#L3308-L3312 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java | DateTimeUtils.addMonths | public static Calendar addMonths(Calendar origin, int value) {
"""
Add/Subtract the specified amount of months to the given {@link Calendar}.
<p>
The returned {@link Calendar} has its fields synced.
</p>
@param origin
@param value
@return
@since 0.9.2
"""
Calendar cal = sync((Calendar) origin.clone());
cal.add(Calendar.MONTH, value);
return sync(cal);
} | java | public static Calendar addMonths(Calendar origin, int value) {
Calendar cal = sync((Calendar) origin.clone());
cal.add(Calendar.MONTH, value);
return sync(cal);
} | [
"public",
"static",
"Calendar",
"addMonths",
"(",
"Calendar",
"origin",
",",
"int",
"value",
")",
"{",
"Calendar",
"cal",
"=",
"sync",
"(",
"(",
"Calendar",
")",
"origin",
".",
"clone",
"(",
")",
")",
";",
"cal",
".",
"add",
"(",
"Calendar",
".",
"MO... | Add/Subtract the specified amount of months to the given {@link Calendar}.
<p>
The returned {@link Calendar} has its fields synced.
</p>
@param origin
@param value
@return
@since 0.9.2 | [
"Add",
"/",
"Subtract",
"the",
"specified",
"amount",
"of",
"months",
"to",
"the",
"given",
"{",
"@link",
"Calendar",
"}",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java#L835-L839 |
Azure/azure-sdk-for-java | hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ApplicationsInner.java | ApplicationsInner.getAsync | public Observable<ApplicationInner> getAsync(String resourceGroupName, String clusterName, String applicationName) {
"""
Gets properties of the specified application.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param applicationName The constant value for the application name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ApplicationInner object
"""
return getWithServiceResponseAsync(resourceGroupName, clusterName, applicationName).map(new Func1<ServiceResponse<ApplicationInner>, ApplicationInner>() {
@Override
public ApplicationInner call(ServiceResponse<ApplicationInner> response) {
return response.body();
}
});
} | java | public Observable<ApplicationInner> getAsync(String resourceGroupName, String clusterName, String applicationName) {
return getWithServiceResponseAsync(resourceGroupName, clusterName, applicationName).map(new Func1<ServiceResponse<ApplicationInner>, ApplicationInner>() {
@Override
public ApplicationInner call(ServiceResponse<ApplicationInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ApplicationInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"String",
"applicationName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
",",
... | Gets properties of the specified application.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param applicationName The constant value for the application name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ApplicationInner object | [
"Gets",
"properties",
"of",
"the",
"specified",
"application",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ApplicationsInner.java#L255-L262 |
morimekta/utils | io-util/src/main/java/net/morimekta/util/io/BinaryReader.java | BinaryReader.expectUInt24 | public int expectUInt24() throws IOException {
"""
Read an unsigned short from the input stream.
@return The number read.
@throws IOException If no number to read.
"""
int b1 = in.read();
if (b1 < 0) {
throw new IOException("Missing byte 1 to expected uint24");
}
int b2 = in.read();
if (b2 < 0) {
throw new IOException("Missing byte 2 to expected uint24");
}
int b3 = in.read();
if (b3 < 0) {
throw new IOException("Missing byte 3 to expected uint24");
}
return unshift3bytes(b1, b2, b3);
} | java | public int expectUInt24() throws IOException {
int b1 = in.read();
if (b1 < 0) {
throw new IOException("Missing byte 1 to expected uint24");
}
int b2 = in.read();
if (b2 < 0) {
throw new IOException("Missing byte 2 to expected uint24");
}
int b3 = in.read();
if (b3 < 0) {
throw new IOException("Missing byte 3 to expected uint24");
}
return unshift3bytes(b1, b2, b3);
} | [
"public",
"int",
"expectUInt24",
"(",
")",
"throws",
"IOException",
"{",
"int",
"b1",
"=",
"in",
".",
"read",
"(",
")",
";",
"if",
"(",
"b1",
"<",
"0",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Missing byte 1 to expected uint24\"",
")",
";",
"}",
... | Read an unsigned short from the input stream.
@return The number read.
@throws IOException If no number to read. | [
"Read",
"an",
"unsigned",
"short",
"from",
"the",
"input",
"stream",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/io/BinaryReader.java#L315-L329 |
looly/hutool | hutool-setting/src/main/java/cn/hutool/setting/Setting.java | Setting.put | public String put(String group, String key, String value) {
"""
将键值对加入到对应分组中
@param group 分组
@param key 键
@param value 值
@return 此key之前存在的值,如果没有返回null
"""
return this.groupedMap.put(group, key, value);
} | java | public String put(String group, String key, String value) {
return this.groupedMap.put(group, key, value);
} | [
"public",
"String",
"put",
"(",
"String",
"group",
",",
"String",
"key",
",",
"String",
"value",
")",
"{",
"return",
"this",
".",
"groupedMap",
".",
"put",
"(",
"group",
",",
"key",
",",
"value",
")",
";",
"}"
] | 将键值对加入到对应分组中
@param group 分组
@param key 键
@param value 值
@return 此key之前存在的值,如果没有返回null | [
"将键值对加入到对应分组中"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-setting/src/main/java/cn/hutool/setting/Setting.java#L421-L423 |
VoltDB/voltdb | src/frontend/org/voltdb/ProcedureStatsCollector.java | ProcedureStatsCollector.updateStatsRow | @Override
protected void updateStatsRow(Object rowKey, Object rowValues[]) {
"""
Update the rowValues array with the latest statistical information.
This method overrides the super class version
which must also be called so that it can update its columns.
@param rowKey The corresponding StatementStats structure for this row.
@param rowValues Values of each column of the row of stats. Used as output.
"""
super.updateStatsRow(rowKey, rowValues);
rowValues[columnNameToIndex.get("PARTITION_ID")] = m_partitionId;
rowValues[columnNameToIndex.get("PROCEDURE")] = m_procName;
StatementStats currRow = (StatementStats)rowKey;
assert(currRow != null);
rowValues[columnNameToIndex.get("STATEMENT")] = currRow.m_stmtName;
long invocations = currRow.getInvocations();
long timedInvocations = currRow.getTimedInvocations();
long totalTimedExecutionTime = currRow.getTotalTimedExecutionTime();
long minExecutionTime = currRow.getMinExecutionTime();
long maxExecutionTime = currRow.getMaxExecutionTime();
long abortCount = currRow.getAbortCount();
long failureCount = currRow.getFailureCount();
int minResultSize = currRow.getMinResultSize();
int maxResultSize = currRow.getMaxResultSize();
long totalResultSize = currRow.getTotalResultSize();
int minParameterSetSize = currRow.getMinParameterSetSize();
int maxParameterSetSize = currRow.getMaxParameterSetSize();
long totalParameterSetSize = currRow.getTotalParameterSetSize();
if (m_incremental) {
abortCount -= currRow.getLastAbortCountAndReset();
failureCount -= currRow.getLastFailureCountAndReset();
totalTimedExecutionTime -= currRow.getLastTotalTimedExecutionTimeAndReset();
totalResultSize -= currRow.getLastTotalResultSizeAndReset();
totalParameterSetSize -= currRow.getLastTotalParameterSetSizeAndReset();
minExecutionTime = currRow.getIncrementalMinExecutionTimeAndReset();
maxExecutionTime = currRow.getIncrementalMaxExecutionTimeAndReset();
minResultSize = currRow.getIncrementalMinResultSizeAndReset();
maxResultSize = currRow.getIncrementalMaxResultSizeAndReset();
minParameterSetSize = currRow.getIncrementalMinParameterSetSizeAndReset();
maxParameterSetSize = currRow.getIncrementalMaxParameterSetSizeAndReset();
// Notice that invocation numbers must be updated in the end.
// Other numbers depend on them for correct behavior.
invocations -= currRow.getLastInvocationsAndReset();
timedInvocations -= currRow.getLastTimedInvocationsAndReset();
}
rowValues[columnNameToIndex.get("INVOCATIONS")] = invocations;
rowValues[columnNameToIndex.get("TIMED_INVOCATIONS")] = timedInvocations;
rowValues[columnNameToIndex.get("MIN_EXECUTION_TIME")] = minExecutionTime;
rowValues[columnNameToIndex.get("MAX_EXECUTION_TIME")] = maxExecutionTime;
if (timedInvocations != 0) {
rowValues[columnNameToIndex.get("AVG_EXECUTION_TIME")] =
(totalTimedExecutionTime / timedInvocations);
rowValues[columnNameToIndex.get("AVG_RESULT_SIZE")] =
(totalResultSize / timedInvocations);
rowValues[columnNameToIndex.get("AVG_PARAMETER_SET_SIZE")] =
(totalParameterSetSize / timedInvocations);
} else {
rowValues[columnNameToIndex.get("AVG_EXECUTION_TIME")] = 0L;
rowValues[columnNameToIndex.get("AVG_RESULT_SIZE")] = 0;
rowValues[columnNameToIndex.get("AVG_PARAMETER_SET_SIZE")] = 0;
}
rowValues[columnNameToIndex.get("ABORTS")] = abortCount;
rowValues[columnNameToIndex.get("FAILURES")] = failureCount;
rowValues[columnNameToIndex.get("MIN_RESULT_SIZE")] = minResultSize;
rowValues[columnNameToIndex.get("MAX_RESULT_SIZE")] = maxResultSize;
rowValues[columnNameToIndex.get("MIN_PARAMETER_SET_SIZE")] = minParameterSetSize;
rowValues[columnNameToIndex.get("MAX_PARAMETER_SET_SIZE")] = maxParameterSetSize;
rowValues[columnNameToIndex.get("TRANSACTIONAL")] = (byte) (m_isTransactional ? 1 : 0);
} | java | @Override
protected void updateStatsRow(Object rowKey, Object rowValues[]) {
super.updateStatsRow(rowKey, rowValues);
rowValues[columnNameToIndex.get("PARTITION_ID")] = m_partitionId;
rowValues[columnNameToIndex.get("PROCEDURE")] = m_procName;
StatementStats currRow = (StatementStats)rowKey;
assert(currRow != null);
rowValues[columnNameToIndex.get("STATEMENT")] = currRow.m_stmtName;
long invocations = currRow.getInvocations();
long timedInvocations = currRow.getTimedInvocations();
long totalTimedExecutionTime = currRow.getTotalTimedExecutionTime();
long minExecutionTime = currRow.getMinExecutionTime();
long maxExecutionTime = currRow.getMaxExecutionTime();
long abortCount = currRow.getAbortCount();
long failureCount = currRow.getFailureCount();
int minResultSize = currRow.getMinResultSize();
int maxResultSize = currRow.getMaxResultSize();
long totalResultSize = currRow.getTotalResultSize();
int minParameterSetSize = currRow.getMinParameterSetSize();
int maxParameterSetSize = currRow.getMaxParameterSetSize();
long totalParameterSetSize = currRow.getTotalParameterSetSize();
if (m_incremental) {
abortCount -= currRow.getLastAbortCountAndReset();
failureCount -= currRow.getLastFailureCountAndReset();
totalTimedExecutionTime -= currRow.getLastTotalTimedExecutionTimeAndReset();
totalResultSize -= currRow.getLastTotalResultSizeAndReset();
totalParameterSetSize -= currRow.getLastTotalParameterSetSizeAndReset();
minExecutionTime = currRow.getIncrementalMinExecutionTimeAndReset();
maxExecutionTime = currRow.getIncrementalMaxExecutionTimeAndReset();
minResultSize = currRow.getIncrementalMinResultSizeAndReset();
maxResultSize = currRow.getIncrementalMaxResultSizeAndReset();
minParameterSetSize = currRow.getIncrementalMinParameterSetSizeAndReset();
maxParameterSetSize = currRow.getIncrementalMaxParameterSetSizeAndReset();
// Notice that invocation numbers must be updated in the end.
// Other numbers depend on them for correct behavior.
invocations -= currRow.getLastInvocationsAndReset();
timedInvocations -= currRow.getLastTimedInvocationsAndReset();
}
rowValues[columnNameToIndex.get("INVOCATIONS")] = invocations;
rowValues[columnNameToIndex.get("TIMED_INVOCATIONS")] = timedInvocations;
rowValues[columnNameToIndex.get("MIN_EXECUTION_TIME")] = minExecutionTime;
rowValues[columnNameToIndex.get("MAX_EXECUTION_TIME")] = maxExecutionTime;
if (timedInvocations != 0) {
rowValues[columnNameToIndex.get("AVG_EXECUTION_TIME")] =
(totalTimedExecutionTime / timedInvocations);
rowValues[columnNameToIndex.get("AVG_RESULT_SIZE")] =
(totalResultSize / timedInvocations);
rowValues[columnNameToIndex.get("AVG_PARAMETER_SET_SIZE")] =
(totalParameterSetSize / timedInvocations);
} else {
rowValues[columnNameToIndex.get("AVG_EXECUTION_TIME")] = 0L;
rowValues[columnNameToIndex.get("AVG_RESULT_SIZE")] = 0;
rowValues[columnNameToIndex.get("AVG_PARAMETER_SET_SIZE")] = 0;
}
rowValues[columnNameToIndex.get("ABORTS")] = abortCount;
rowValues[columnNameToIndex.get("FAILURES")] = failureCount;
rowValues[columnNameToIndex.get("MIN_RESULT_SIZE")] = minResultSize;
rowValues[columnNameToIndex.get("MAX_RESULT_SIZE")] = maxResultSize;
rowValues[columnNameToIndex.get("MIN_PARAMETER_SET_SIZE")] = minParameterSetSize;
rowValues[columnNameToIndex.get("MAX_PARAMETER_SET_SIZE")] = maxParameterSetSize;
rowValues[columnNameToIndex.get("TRANSACTIONAL")] = (byte) (m_isTransactional ? 1 : 0);
} | [
"@",
"Override",
"protected",
"void",
"updateStatsRow",
"(",
"Object",
"rowKey",
",",
"Object",
"rowValues",
"[",
"]",
")",
"{",
"super",
".",
"updateStatsRow",
"(",
"rowKey",
",",
"rowValues",
")",
";",
"rowValues",
"[",
"columnNameToIndex",
".",
"get",
"("... | Update the rowValues array with the latest statistical information.
This method overrides the super class version
which must also be called so that it can update its columns.
@param rowKey The corresponding StatementStats structure for this row.
@param rowValues Values of each column of the row of stats. Used as output. | [
"Update",
"the",
"rowValues",
"array",
"with",
"the",
"latest",
"statistical",
"information",
".",
"This",
"method",
"overrides",
"the",
"super",
"class",
"version",
"which",
"must",
"also",
"be",
"called",
"so",
"that",
"it",
"can",
"update",
"its",
"columns"... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ProcedureStatsCollector.java#L281-L345 |
svenkubiak/mangooio | mangooio-core/src/main/java/io/mangoo/utils/CodecUtils.java | CodecUtils.hexSHA512 | public static String hexSHA512(String data, String salt) {
"""
Hashes a given cleartext data with SHA512 and an appended salt
@param data The cleartext data
@param salt The salt to use
@return SHA512 hashed value
"""
Objects.requireNonNull(data, Required.DATA.toString());
Objects.requireNonNull(salt, Required.SALT.toString());
return DigestUtils.sha512Hex(data + salt);
} | java | public static String hexSHA512(String data, String salt) {
Objects.requireNonNull(data, Required.DATA.toString());
Objects.requireNonNull(salt, Required.SALT.toString());
return DigestUtils.sha512Hex(data + salt);
} | [
"public",
"static",
"String",
"hexSHA512",
"(",
"String",
"data",
",",
"String",
"salt",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"data",
",",
"Required",
".",
"DATA",
".",
"toString",
"(",
")",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"s... | Hashes a given cleartext data with SHA512 and an appended salt
@param data The cleartext data
@param salt The salt to use
@return SHA512 hashed value | [
"Hashes",
"a",
"given",
"cleartext",
"data",
"with",
"SHA512",
"and",
"an",
"appended",
"salt"
] | train | https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/utils/CodecUtils.java#L57-L62 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NumberFormat.java | NumberFormat.getInstance | public static NumberFormat getInstance(Locale inLocale, int style) {
"""
<strong>[icu]</strong> Returns a specific style number format for a specific locale.
@param inLocale the specific locale.
@param style number format style
"""
return getInstance(ULocale.forLocale(inLocale), style);
} | java | public static NumberFormat getInstance(Locale inLocale, int style) {
return getInstance(ULocale.forLocale(inLocale), style);
} | [
"public",
"static",
"NumberFormat",
"getInstance",
"(",
"Locale",
"inLocale",
",",
"int",
"style",
")",
"{",
"return",
"getInstance",
"(",
"ULocale",
".",
"forLocale",
"(",
"inLocale",
")",
",",
"style",
")",
";",
"}"
] | <strong>[icu]</strong> Returns a specific style number format for a specific locale.
@param inLocale the specific locale.
@param style number format style | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Returns",
"a",
"specific",
"style",
"number",
"format",
"for",
"a",
"specific",
"locale",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/NumberFormat.java#L570-L572 |
powermock/powermock | powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SuppressCode.java | SuppressCode.suppressField | public static synchronized void suppressField(Class<?> clazz, String... fieldNames) {
"""
Suppress multiple methods for a class.
@param clazz
The class whose methods will be suppressed.
@param fieldNames
The names of the methods that'll be suppressed. If field names
are empty, <i>all</i> fields in the supplied class will be
suppressed.
"""
if (fieldNames == null || fieldNames.length == 0) {
suppressField(new Class<?>[] { clazz });
} else {
for (Field field : Whitebox.getFields(clazz, fieldNames)) {
MockRepository.addFieldToSuppress(field);
}
}
} | java | public static synchronized void suppressField(Class<?> clazz, String... fieldNames) {
if (fieldNames == null || fieldNames.length == 0) {
suppressField(new Class<?>[] { clazz });
} else {
for (Field field : Whitebox.getFields(clazz, fieldNames)) {
MockRepository.addFieldToSuppress(field);
}
}
} | [
"public",
"static",
"synchronized",
"void",
"suppressField",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"...",
"fieldNames",
")",
"{",
"if",
"(",
"fieldNames",
"==",
"null",
"||",
"fieldNames",
".",
"length",
"==",
"0",
")",
"{",
"suppressField",... | Suppress multiple methods for a class.
@param clazz
The class whose methods will be suppressed.
@param fieldNames
The names of the methods that'll be suppressed. If field names
are empty, <i>all</i> fields in the supplied class will be
suppressed. | [
"Suppress",
"multiple",
"methods",
"for",
"a",
"class",
"."
] | train | https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SuppressCode.java#L127-L135 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/query/impl/Indexes.java | Indexes.addOrGetIndex | public synchronized InternalIndex addOrGetIndex(String name, boolean ordered) {
"""
Obtains the existing index or creates a new one (if an index doesn't exist
yet) for the given name in this indexes instance.
@param name the name of the index; the passed value might not
represent a canonical index name (as specified by
{@link Index#getName()), in this case the method
canonicalizes it.
@param ordered {@code true} if the new index should be ordered, {@code
false} otherwise.
@return the existing or created index.
"""
InternalIndex index = indexesByName.get(name);
if (index != null) {
return index;
}
String[] components = PredicateUtils.parseOutCompositeIndexComponents(name);
if (components == null) {
name = PredicateUtils.canonicalizeAttribute(name);
} else {
name = PredicateUtils.constructCanonicalCompositeIndexName(components);
}
index = indexesByName.get(name);
if (index != null) {
return index;
}
index = indexProvider.createIndex(name, components, ordered, extractors, serializationService, indexCopyBehavior,
stats.createPerIndexStats(ordered, usesCachedQueryableEntries));
indexesByName.put(name, index);
attributeIndexRegistry.register(index);
converterCache.invalidate(index);
indexes = indexesByName.values().toArray(EMPTY_INDEXES);
if (components != null) {
InternalIndex[] oldCompositeIndexes = compositeIndexes;
InternalIndex[] newCompositeIndexes = Arrays.copyOf(oldCompositeIndexes, oldCompositeIndexes.length + 1);
newCompositeIndexes[oldCompositeIndexes.length] = index;
compositeIndexes = newCompositeIndexes;
}
return index;
} | java | public synchronized InternalIndex addOrGetIndex(String name, boolean ordered) {
InternalIndex index = indexesByName.get(name);
if (index != null) {
return index;
}
String[] components = PredicateUtils.parseOutCompositeIndexComponents(name);
if (components == null) {
name = PredicateUtils.canonicalizeAttribute(name);
} else {
name = PredicateUtils.constructCanonicalCompositeIndexName(components);
}
index = indexesByName.get(name);
if (index != null) {
return index;
}
index = indexProvider.createIndex(name, components, ordered, extractors, serializationService, indexCopyBehavior,
stats.createPerIndexStats(ordered, usesCachedQueryableEntries));
indexesByName.put(name, index);
attributeIndexRegistry.register(index);
converterCache.invalidate(index);
indexes = indexesByName.values().toArray(EMPTY_INDEXES);
if (components != null) {
InternalIndex[] oldCompositeIndexes = compositeIndexes;
InternalIndex[] newCompositeIndexes = Arrays.copyOf(oldCompositeIndexes, oldCompositeIndexes.length + 1);
newCompositeIndexes[oldCompositeIndexes.length] = index;
compositeIndexes = newCompositeIndexes;
}
return index;
} | [
"public",
"synchronized",
"InternalIndex",
"addOrGetIndex",
"(",
"String",
"name",
",",
"boolean",
"ordered",
")",
"{",
"InternalIndex",
"index",
"=",
"indexesByName",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"index",
"!=",
"null",
")",
"{",
"return",
... | Obtains the existing index or creates a new one (if an index doesn't exist
yet) for the given name in this indexes instance.
@param name the name of the index; the passed value might not
represent a canonical index name (as specified by
{@link Index#getName()), in this case the method
canonicalizes it.
@param ordered {@code true} if the new index should be ordered, {@code
false} otherwise.
@return the existing or created index. | [
"Obtains",
"the",
"existing",
"index",
"or",
"creates",
"a",
"new",
"one",
"(",
"if",
"an",
"index",
"doesn",
"t",
"exist",
"yet",
")",
"for",
"the",
"given",
"name",
"in",
"this",
"indexes",
"instance",
"."
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/impl/Indexes.java#L121-L154 |
alkacon/opencms-core | src/org/opencms/ui/contextmenu/CmsContextMenu.java | CmsContextMenu.openForTree | public void openForTree(ItemClickEvent event, Tree tree) {
"""
Opens the context menu of the given tree.<p>
@param event the click event
@param tree the tree
"""
fireEvent(new ContextMenuOpenedOnTreeItemEvent(this, tree, event.getItemId()));
open(event.getClientX(), event.getClientY());
} | java | public void openForTree(ItemClickEvent event, Tree tree) {
fireEvent(new ContextMenuOpenedOnTreeItemEvent(this, tree, event.getItemId()));
open(event.getClientX(), event.getClientY());
} | [
"public",
"void",
"openForTree",
"(",
"ItemClickEvent",
"event",
",",
"Tree",
"tree",
")",
"{",
"fireEvent",
"(",
"new",
"ContextMenuOpenedOnTreeItemEvent",
"(",
"this",
",",
"tree",
",",
"event",
".",
"getItemId",
"(",
")",
")",
")",
";",
"open",
"(",
"ev... | Opens the context menu of the given tree.<p>
@param event the click event
@param tree the tree | [
"Opens",
"the",
"context",
"menu",
"of",
"the",
"given",
"tree",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/contextmenu/CmsContextMenu.java#L1161-L1165 |
salesforce/Argus | ArgusSDK/src/main/java/com/salesforce/dva/argus/sdk/AlertService.java | AlertService.updateTrigger | public Trigger updateTrigger(BigInteger alertId, BigInteger triggerId, Trigger trigger) throws IOException, TokenExpiredException {
"""
Updates an existing trigger.
@param alertId The ID of the alert owning the trigger.
@param triggerId The ID of the trigger to update.
@param trigger The updated trigger information.
@return The updated trigger.
@throws IOException If the server cannot be reached.
@throws TokenExpiredException If the token sent along with the request has expired
"""
String requestUrl = RESOURCE + "/" + alertId.toString() + "/triggers/" + triggerId.toString();
ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.PUT, requestUrl, trigger);
assertValidResponse(response, requestUrl);
return fromJson(response.getResult(), Trigger.class);
} | java | public Trigger updateTrigger(BigInteger alertId, BigInteger triggerId, Trigger trigger) throws IOException, TokenExpiredException {
String requestUrl = RESOURCE + "/" + alertId.toString() + "/triggers/" + triggerId.toString();
ArgusResponse response = getClient().executeHttpRequest(ArgusHttpClient.RequestType.PUT, requestUrl, trigger);
assertValidResponse(response, requestUrl);
return fromJson(response.getResult(), Trigger.class);
} | [
"public",
"Trigger",
"updateTrigger",
"(",
"BigInteger",
"alertId",
",",
"BigInteger",
"triggerId",
",",
"Trigger",
"trigger",
")",
"throws",
"IOException",
",",
"TokenExpiredException",
"{",
"String",
"requestUrl",
"=",
"RESOURCE",
"+",
"\"/\"",
"+",
"alertId",
"... | Updates an existing trigger.
@param alertId The ID of the alert owning the trigger.
@param triggerId The ID of the trigger to update.
@param trigger The updated trigger information.
@return The updated trigger.
@throws IOException If the server cannot be reached.
@throws TokenExpiredException If the token sent along with the request has expired | [
"Updates",
"an",
"existing",
"trigger",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusSDK/src/main/java/com/salesforce/dva/argus/sdk/AlertService.java#L317-L323 |
rhuss/jolokia | agent/core/src/main/java/org/jolokia/converter/json/ObjectToJsonConverter.java | ObjectToJsonConverter.addSimplifiers | private void addSimplifiers(List<Extractor> pHandlers, Extractor[] pSimplifyHandlers) {
"""
Simplifiers are added either explicitely or by reflection from a subpackage
"""
if (pSimplifyHandlers != null && pSimplifyHandlers.length > 0) {
pHandlers.addAll(Arrays.asList(pSimplifyHandlers));
} else {
// Add all
pHandlers.addAll(ServiceObjectFactory.<Extractor>createServiceObjects(SIMPLIFIERS_DEFAULT_DEF, SIMPLIFIERS_DEF));
}
} | java | private void addSimplifiers(List<Extractor> pHandlers, Extractor[] pSimplifyHandlers) {
if (pSimplifyHandlers != null && pSimplifyHandlers.length > 0) {
pHandlers.addAll(Arrays.asList(pSimplifyHandlers));
} else {
// Add all
pHandlers.addAll(ServiceObjectFactory.<Extractor>createServiceObjects(SIMPLIFIERS_DEFAULT_DEF, SIMPLIFIERS_DEF));
}
} | [
"private",
"void",
"addSimplifiers",
"(",
"List",
"<",
"Extractor",
">",
"pHandlers",
",",
"Extractor",
"[",
"]",
"pSimplifyHandlers",
")",
"{",
"if",
"(",
"pSimplifyHandlers",
"!=",
"null",
"&&",
"pSimplifyHandlers",
".",
"length",
">",
"0",
")",
"{",
"pHan... | Simplifiers are added either explicitely or by reflection from a subpackage | [
"Simplifiers",
"are",
"added",
"either",
"explicitely",
"or",
"by",
"reflection",
"from",
"a",
"subpackage"
] | train | https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/converter/json/ObjectToJsonConverter.java#L345-L352 |
cdk/cdk | display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java | StandardAtomGenerator.positionHydrogenLabel | TextOutline positionHydrogenLabel(HydrogenPosition position, TextOutline element, TextOutline hydrogen) {
"""
Position the hydrogen label relative to the element label.
@param position relative position where the hydrogen is placed
@param element the outline of the element label
@param hydrogen the outline of the hydrogen
@return positioned hydrogen label
"""
final Rectangle2D elementBounds = element.getBounds();
final Rectangle2D hydrogenBounds = hydrogen.getBounds();
switch (position) {
case Above:
return hydrogen.translate(0, (elementBounds.getMinY() - padding) - hydrogenBounds.getMaxY());
case Right:
return hydrogen.translate((elementBounds.getMaxX() + padding) - hydrogenBounds.getMinX(), 0);
case Below:
return hydrogen.translate(0, (elementBounds.getMaxY() + padding) - hydrogenBounds.getMinY());
case Left:
return hydrogen.translate((elementBounds.getMinX() - padding) - hydrogenBounds.getMaxX(), 0);
}
return hydrogen; // never reached
} | java | TextOutline positionHydrogenLabel(HydrogenPosition position, TextOutline element, TextOutline hydrogen) {
final Rectangle2D elementBounds = element.getBounds();
final Rectangle2D hydrogenBounds = hydrogen.getBounds();
switch (position) {
case Above:
return hydrogen.translate(0, (elementBounds.getMinY() - padding) - hydrogenBounds.getMaxY());
case Right:
return hydrogen.translate((elementBounds.getMaxX() + padding) - hydrogenBounds.getMinX(), 0);
case Below:
return hydrogen.translate(0, (elementBounds.getMaxY() + padding) - hydrogenBounds.getMinY());
case Left:
return hydrogen.translate((elementBounds.getMinX() - padding) - hydrogenBounds.getMaxX(), 0);
}
return hydrogen; // never reached
} | [
"TextOutline",
"positionHydrogenLabel",
"(",
"HydrogenPosition",
"position",
",",
"TextOutline",
"element",
",",
"TextOutline",
"hydrogen",
")",
"{",
"final",
"Rectangle2D",
"elementBounds",
"=",
"element",
".",
"getBounds",
"(",
")",
";",
"final",
"Rectangle2D",
"h... | Position the hydrogen label relative to the element label.
@param position relative position where the hydrogen is placed
@param element the outline of the element label
@param hydrogen the outline of the hydrogen
@return positioned hydrogen label | [
"Position",
"the",
"hydrogen",
"label",
"relative",
"to",
"the",
"element",
"label",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java#L420-L434 |
SonarSource/sonarqube | server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentDao.java | ComponentDao.scrollAllFilesForFileMove | public void scrollAllFilesForFileMove(DbSession session, String projectUuid, ResultHandler<FileMoveRowDto> handler) {
"""
Scroll all <strong>enabled</strong> files of the specified project (same project_uuid) in no specific order with
'SOURCE' source and a non null path.
"""
mapper(session).scrollAllFilesForFileMove(projectUuid, handler);
} | java | public void scrollAllFilesForFileMove(DbSession session, String projectUuid, ResultHandler<FileMoveRowDto> handler) {
mapper(session).scrollAllFilesForFileMove(projectUuid, handler);
} | [
"public",
"void",
"scrollAllFilesForFileMove",
"(",
"DbSession",
"session",
",",
"String",
"projectUuid",
",",
"ResultHandler",
"<",
"FileMoveRowDto",
">",
"handler",
")",
"{",
"mapper",
"(",
"session",
")",
".",
"scrollAllFilesForFileMove",
"(",
"projectUuid",
",",... | Scroll all <strong>enabled</strong> files of the specified project (same project_uuid) in no specific order with
'SOURCE' source and a non null path. | [
"Scroll",
"all",
"<strong",
">",
"enabled<",
"/",
"strong",
">",
"files",
"of",
"the",
"specified",
"project",
"(",
"same",
"project_uuid",
")",
"in",
"no",
"specific",
"order",
"with",
"SOURCE",
"source",
"and",
"a",
"non",
"null",
"path",
"."
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-dao/src/main/java/org/sonar/db/component/ComponentDao.java#L379-L381 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLService.java | CQLService.getPreparedUpdate | public PreparedStatement getPreparedUpdate(Update update, String storeName) {
"""
Get the {@link PreparedStatement} for the given {@link CQLStatementCache.Update} to
the given table name. If needed, the update statement is compiled and cached.
@param update Update statement type.
@param storeName Store (ColumnFamily) name.
@return PreparedStatement for requested table/update.
"""
String tableName = storeToCQLName(storeName);
return m_statementCache.getPreparedUpdate(tableName, update);
} | java | public PreparedStatement getPreparedUpdate(Update update, String storeName) {
String tableName = storeToCQLName(storeName);
return m_statementCache.getPreparedUpdate(tableName, update);
} | [
"public",
"PreparedStatement",
"getPreparedUpdate",
"(",
"Update",
"update",
",",
"String",
"storeName",
")",
"{",
"String",
"tableName",
"=",
"storeToCQLName",
"(",
"storeName",
")",
";",
"return",
"m_statementCache",
".",
"getPreparedUpdate",
"(",
"tableName",
","... | Get the {@link PreparedStatement} for the given {@link CQLStatementCache.Update} to
the given table name. If needed, the update statement is compiled and cached.
@param update Update statement type.
@param storeName Store (ColumnFamily) name.
@return PreparedStatement for requested table/update. | [
"Get",
"the",
"{",
"@link",
"PreparedStatement",
"}",
"for",
"the",
"given",
"{",
"@link",
"CQLStatementCache",
".",
"Update",
"}",
"to",
"the",
"given",
"table",
"name",
".",
"If",
"needed",
"the",
"update",
"statement",
"is",
"compiled",
"and",
"cached",
... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLService.java#L262-L265 |
JOML-CI/JOML | src/org/joml/Vector4i.java | Vector4i.setComponent | public Vector4i setComponent(int component, int value) throws IllegalArgumentException {
"""
Set the value of the specified component of this vector.
@param component
the component whose value to set, within <code>[0..3]</code>
@param value
the value to set
@return this
@throws IllegalArgumentException if <code>component</code> is not within <code>[0..3]</code>
"""
switch (component) {
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
case 3:
w = value;
break;
default:
throw new IllegalArgumentException();
}
return this;
} | java | public Vector4i setComponent(int component, int value) throws IllegalArgumentException {
switch (component) {
case 0:
x = value;
break;
case 1:
y = value;
break;
case 2:
z = value;
break;
case 3:
w = value;
break;
default:
throw new IllegalArgumentException();
}
return this;
} | [
"public",
"Vector4i",
"setComponent",
"(",
"int",
"component",
",",
"int",
"value",
")",
"throws",
"IllegalArgumentException",
"{",
"switch",
"(",
"component",
")",
"{",
"case",
"0",
":",
"x",
"=",
"value",
";",
"break",
";",
"case",
"1",
":",
"y",
"=",
... | Set the value of the specified component of this vector.
@param component
the component whose value to set, within <code>[0..3]</code>
@param value
the value to set
@return this
@throws IllegalArgumentException if <code>component</code> is not within <code>[0..3]</code> | [
"Set",
"the",
"value",
"of",
"the",
"specified",
"component",
"of",
"this",
"vector",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Vector4i.java#L504-L522 |
OpenLiberty/open-liberty | dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/utils/DirUtils.java | DirUtils.createDirectoryPath | public static String createDirectoryPath(String source) {
"""
Replaces forward and backward slashes in the source string with 'File.separator'
characters.
"""
if (tc.isEntryEnabled()) Tr.entry(tc, "createDirectoryPath",source);
String directoryPath = null;
if (source != null)
{
directoryPath = "";
final StringTokenizer tokenizer = new StringTokenizer(source,"\\/");
while (tokenizer.hasMoreTokens())
{
final String pathChunk = tokenizer.nextToken();
directoryPath += pathChunk;
if (tokenizer.hasMoreTokens())
{
directoryPath += File.separator;
}
}
}
if (tc.isEntryEnabled()) Tr.exit(tc, "createDirectoryPath",directoryPath);
return directoryPath;
} | java | public static String createDirectoryPath(String source)
{
if (tc.isEntryEnabled()) Tr.entry(tc, "createDirectoryPath",source);
String directoryPath = null;
if (source != null)
{
directoryPath = "";
final StringTokenizer tokenizer = new StringTokenizer(source,"\\/");
while (tokenizer.hasMoreTokens())
{
final String pathChunk = tokenizer.nextToken();
directoryPath += pathChunk;
if (tokenizer.hasMoreTokens())
{
directoryPath += File.separator;
}
}
}
if (tc.isEntryEnabled()) Tr.exit(tc, "createDirectoryPath",directoryPath);
return directoryPath;
} | [
"public",
"static",
"String",
"createDirectoryPath",
"(",
"String",
"source",
")",
"{",
"if",
"(",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"Tr",
".",
"entry",
"(",
"tc",
",",
"\"createDirectoryPath\"",
",",
"source",
")",
";",
"String",
"directoryPath",
... | Replaces forward and backward slashes in the source string with 'File.separator'
characters. | [
"Replaces",
"forward",
"and",
"backward",
"slashes",
"in",
"the",
"source",
"string",
"with",
"File",
".",
"separator",
"characters",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/utils/DirUtils.java#L30-L58 |
casmi/casmi | src/main/java/casmi/graphics/element/Box.java | Box.setGradationColor | public void setGradationColor(GradationMode3D mode, Color color1, Color color2) {
"""
Sets the gradation mode and colors.
@param mode The mode of gradation.
@param color1 The color for gradation.
@param color2 The color for gradation.
@see casmi.GradationMode2D
"""
setGradation(true);
if (startColor == null || endColor == null) {
startColor = new RGBColor(0.0, 0.0, 0.0);
endColor = new RGBColor(0.0, 0.0, 0.0);
}
startColor = color1;
endColor = color2;
this.mode = mode;
setGradationCorner();
} | java | public void setGradationColor(GradationMode3D mode, Color color1, Color color2) {
setGradation(true);
if (startColor == null || endColor == null) {
startColor = new RGBColor(0.0, 0.0, 0.0);
endColor = new RGBColor(0.0, 0.0, 0.0);
}
startColor = color1;
endColor = color2;
this.mode = mode;
setGradationCorner();
} | [
"public",
"void",
"setGradationColor",
"(",
"GradationMode3D",
"mode",
",",
"Color",
"color1",
",",
"Color",
"color2",
")",
"{",
"setGradation",
"(",
"true",
")",
";",
"if",
"(",
"startColor",
"==",
"null",
"||",
"endColor",
"==",
"null",
")",
"{",
"startC... | Sets the gradation mode and colors.
@param mode The mode of gradation.
@param color1 The color for gradation.
@param color2 The color for gradation.
@see casmi.GradationMode2D | [
"Sets",
"the",
"gradation",
"mode",
"and",
"colors",
"."
] | train | https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Box.java#L368-L379 |
james-hu/jabb-core | src/main/java/net/sf/jabb/util/db/ConnectionUtility.java | ConnectionUtility.createDataSource | public static DataSource createDataSource(String source, String jndiName) {
"""
Create DataSource and bind it to JNDI
@param source configuration
@param jndiName JNDI name that the DataSource needs to be bind to
@return The DataSource created
"""
DataSource ds = createDataSource(source);
if (ds != null && jndiName != null){
InitialContext ic;
try {
ic = new InitialContext();
ic.bind(jndiName, ds);
} catch (NamingException e) {
log.error("Failed to bind data source '" + source + "' to JNDI name: " + jndiName, e);
}
}
return ds;
} | java | public static DataSource createDataSource(String source, String jndiName){
DataSource ds = createDataSource(source);
if (ds != null && jndiName != null){
InitialContext ic;
try {
ic = new InitialContext();
ic.bind(jndiName, ds);
} catch (NamingException e) {
log.error("Failed to bind data source '" + source + "' to JNDI name: " + jndiName, e);
}
}
return ds;
} | [
"public",
"static",
"DataSource",
"createDataSource",
"(",
"String",
"source",
",",
"String",
"jndiName",
")",
"{",
"DataSource",
"ds",
"=",
"createDataSource",
"(",
"source",
")",
";",
"if",
"(",
"ds",
"!=",
"null",
"&&",
"jndiName",
"!=",
"null",
")",
"{... | Create DataSource and bind it to JNDI
@param source configuration
@param jndiName JNDI name that the DataSource needs to be bind to
@return The DataSource created | [
"Create",
"DataSource",
"and",
"bind",
"it",
"to",
"JNDI"
] | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L246-L258 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/disktree/DiskTreeWriter.java | DiskTreeWriter.writeGeometries | public void writeGeometries( Geometry[] geometries ) throws IOException {
"""
Writes an array of {@link Geometry}s to the disk.
@param geometries the array of geoms to write.
@throws IOException
"""
File file = new File(path);
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
int major = JTSVersion.MAJOR;
int minor = JTSVersion.MINOR;
raf.writeChars("jts");
raf.writeInt(major);
raf.writeInt(minor);
long geometriesStart = INDEX_ADDRESS_POSITION + INDEX_ADDRESS_SIZE + INDEX_LENGTH_SIZE;
raf.seek(geometriesStart);
System.out.println("geometriesStart: " + geometriesStart);
long fileIndex = geometriesStart;
STRtree tree = new STRtree(geometries.length);
for( int i = 0; i < geometries.length; i++ ) {
Geometry geometry = geometries[i];
if (geometry.isEmpty()) {
continue;
}
Envelope envelope = geometry.getEnvelopeInternal();
byte[] geomBytes = serialize(geometry);
raf.write(geomBytes);
/*
* the tree contains the envelope of a geometry
* and the array with the exact position in the file where the
* geometry bytes start + the length.
*/
tree.insert(envelope, new long[]{fileIndex, geomBytes.length});
fileIndex = fileIndex + geomBytes.length;
System.out.println("geom: " + i + " finished at: " + fileIndex);
}
raf.seek(INDEX_ADDRESS_POSITION);
raf.writeLong(fileIndex);
System.out.println("INDEX_ADDRESS_POSITION: " + fileIndex);
/*
* serialize index
*/
byte[] treeBytes = serialize(tree);
long treeSize = treeBytes.length;
raf.seek(fileIndex);
raf.write(treeBytes, 0, (int) treeSize);
System.out.println("treeSize: " + treeSize);
raf.seek(INDEX_ADDRESS_POSITION + INDEX_ADDRESS_SIZE);
raf.writeLong(treeSize);
long length = raf.length();
System.out.println(length);
} finally {
System.out.println("close");
if (raf != null)
raf.close();
}
} | java | public void writeGeometries( Geometry[] geometries ) throws IOException {
File file = new File(path);
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
int major = JTSVersion.MAJOR;
int minor = JTSVersion.MINOR;
raf.writeChars("jts");
raf.writeInt(major);
raf.writeInt(minor);
long geometriesStart = INDEX_ADDRESS_POSITION + INDEX_ADDRESS_SIZE + INDEX_LENGTH_SIZE;
raf.seek(geometriesStart);
System.out.println("geometriesStart: " + geometriesStart);
long fileIndex = geometriesStart;
STRtree tree = new STRtree(geometries.length);
for( int i = 0; i < geometries.length; i++ ) {
Geometry geometry = geometries[i];
if (geometry.isEmpty()) {
continue;
}
Envelope envelope = geometry.getEnvelopeInternal();
byte[] geomBytes = serialize(geometry);
raf.write(geomBytes);
/*
* the tree contains the envelope of a geometry
* and the array with the exact position in the file where the
* geometry bytes start + the length.
*/
tree.insert(envelope, new long[]{fileIndex, geomBytes.length});
fileIndex = fileIndex + geomBytes.length;
System.out.println("geom: " + i + " finished at: " + fileIndex);
}
raf.seek(INDEX_ADDRESS_POSITION);
raf.writeLong(fileIndex);
System.out.println("INDEX_ADDRESS_POSITION: " + fileIndex);
/*
* serialize index
*/
byte[] treeBytes = serialize(tree);
long treeSize = treeBytes.length;
raf.seek(fileIndex);
raf.write(treeBytes, 0, (int) treeSize);
System.out.println("treeSize: " + treeSize);
raf.seek(INDEX_ADDRESS_POSITION + INDEX_ADDRESS_SIZE);
raf.writeLong(treeSize);
long length = raf.length();
System.out.println(length);
} finally {
System.out.println("close");
if (raf != null)
raf.close();
}
} | [
"public",
"void",
"writeGeometries",
"(",
"Geometry",
"[",
"]",
"geometries",
")",
"throws",
"IOException",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"path",
")",
";",
"RandomAccessFile",
"raf",
"=",
"null",
";",
"try",
"{",
"raf",
"=",
"new",
"Rando... | Writes an array of {@link Geometry}s to the disk.
@param geometries the array of geoms to write.
@throws IOException | [
"Writes",
"an",
"array",
"of",
"{",
"@link",
"Geometry",
"}",
"s",
"to",
"the",
"disk",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/disktree/DiskTreeWriter.java#L56-L124 |
infinispan/infinispan | query/src/main/java/org/infinispan/query/clustered/commandworkers/CQWorker.java | CQWorker.extractKey | Object extractKey(DocumentExtractor extractor, int docIndex) {
"""
Utility to extract the cache key of a DocumentExtractor and use the KeyTransformationHandler to turn the string
into the actual key object.
@param extractor
@param docIndex
@return
"""
String strKey;
try {
strKey = (String) extractor.extract(docIndex).getId();
} catch (IOException e) {
throw new SearchException("Error while extracting key", e);
}
return keyTransformationHandler.stringToKey(strKey);
} | java | Object extractKey(DocumentExtractor extractor, int docIndex) {
String strKey;
try {
strKey = (String) extractor.extract(docIndex).getId();
} catch (IOException e) {
throw new SearchException("Error while extracting key", e);
}
return keyTransformationHandler.stringToKey(strKey);
} | [
"Object",
"extractKey",
"(",
"DocumentExtractor",
"extractor",
",",
"int",
"docIndex",
")",
"{",
"String",
"strKey",
";",
"try",
"{",
"strKey",
"=",
"(",
"String",
")",
"extractor",
".",
"extract",
"(",
"docIndex",
")",
".",
"getId",
"(",
")",
";",
"}",
... | Utility to extract the cache key of a DocumentExtractor and use the KeyTransformationHandler to turn the string
into the actual key object.
@param extractor
@param docIndex
@return | [
"Utility",
"to",
"extract",
"the",
"cache",
"key",
"of",
"a",
"DocumentExtractor",
"and",
"use",
"the",
"KeyTransformationHandler",
"to",
"turn",
"the",
"string",
"into",
"the",
"actual",
"key",
"object",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/query/src/main/java/org/infinispan/query/clustered/commandworkers/CQWorker.java#L71-L80 |
demidenko05/beigesoft-accounting | src/main/java/org/beigesoft/accounting/holder/HldAccProcessorNames.java | HldAccProcessorNames.getFor | @Override
public final String getFor(final Class<?> pClass, final String pThingName) {
"""
<p>Get thing for given class and thing name.</p>
@param pClass a Class
@param pThingName Thing Name
@return a thing
"""
if ("list".equals(pThingName)) {
if (pClass == PaymentFrom.class || pClass == PaymentTo.class
|| pClass == PrepaymentFrom.class || pClass == PrepaymentTo.class
|| pClass == SubaccountLine.class || pClass == AdditionCostLine.class
|| pClass == Account.class) {
return PrcPageWithSubaccTypes.class.getSimpleName();
} else {
return PrcEntitiesPage.class.getSimpleName();
}
} else if ("about".equals(pThingName)) {
return PrcAbout.class.getSimpleName();
}
return null;
} | java | @Override
public final String getFor(final Class<?> pClass, final String pThingName) {
if ("list".equals(pThingName)) {
if (pClass == PaymentFrom.class || pClass == PaymentTo.class
|| pClass == PrepaymentFrom.class || pClass == PrepaymentTo.class
|| pClass == SubaccountLine.class || pClass == AdditionCostLine.class
|| pClass == Account.class) {
return PrcPageWithSubaccTypes.class.getSimpleName();
} else {
return PrcEntitiesPage.class.getSimpleName();
}
} else if ("about".equals(pThingName)) {
return PrcAbout.class.getSimpleName();
}
return null;
} | [
"@",
"Override",
"public",
"final",
"String",
"getFor",
"(",
"final",
"Class",
"<",
"?",
">",
"pClass",
",",
"final",
"String",
"pThingName",
")",
"{",
"if",
"(",
"\"list\"",
".",
"equals",
"(",
"pThingName",
")",
")",
"{",
"if",
"(",
"pClass",
"==",
... | <p>Get thing for given class and thing name.</p>
@param pClass a Class
@param pThingName Thing Name
@return a thing | [
"<p",
">",
"Get",
"thing",
"for",
"given",
"class",
"and",
"thing",
"name",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/demidenko05/beigesoft-accounting/blob/e6f423949008218ddd05953b078f1ea8805095c1/src/main/java/org/beigesoft/accounting/holder/HldAccProcessorNames.java#L42-L57 |
jayantk/jklol | src/com/jayantkrish/jklol/models/loglinear/DiscreteLogLinearFactor.java | DiscreteLogLinearFactor.fromFeatureGeneratorSparse | public static DiscreteLogLinearFactor fromFeatureGeneratorSparse(DiscreteFactor factor,
FeatureGenerator<Assignment, String> featureGen) {
"""
Creates a {@code DiscreteLogLinearFactor} by applying {@code featureGen}
to each assignment in {@code factor} with non-zero weight. Returns a
sparse factor where only these assignments are assigned non-zero weight.
@param factor
@param featureGen
@return
"""
Iterator<Outcome> iter = factor.outcomeIterator();
Set<String> featureNames = Sets.newHashSet();
while (iter.hasNext()) {
Outcome o = iter.next();
for (Map.Entry<String, Double> f : featureGen.generateFeatures(o.getAssignment()).entrySet()) {
featureNames.add(f.getKey());
}
}
List<String> featureNamesSorted = Lists.newArrayList(featureNames);
Collections.sort(featureNamesSorted);
DiscreteVariable featureType = new DiscreteVariable(FEATURE_VAR_NAME, featureNamesSorted);
VariableNumMap featureVar = VariableNumMap.singleton(
Ints.max(factor.getVars().getVariableNumsArray()) + 1, FEATURE_VAR_NAME, featureType);
TableFactorBuilder builder = new TableFactorBuilder(
factor.getVars().union(featureVar), SparseTensorBuilder.getFactory());
iter = factor.outcomeIterator();
while (iter.hasNext()) {
Outcome o = iter.next();
for (Map.Entry<String, Double> f : featureGen.generateFeatures(o.getAssignment()).entrySet()) {
Assignment featureAssignment = featureVar.outcomeArrayToAssignment(f.getKey());
builder.setWeight(o.getAssignment().union(featureAssignment), f.getValue());
}
}
DiscreteFactor featureFactor = builder.build();
return new DiscreteLogLinearFactor(factor.getVars(), featureVar, featureFactor, factor);
} | java | public static DiscreteLogLinearFactor fromFeatureGeneratorSparse(DiscreteFactor factor,
FeatureGenerator<Assignment, String> featureGen) {
Iterator<Outcome> iter = factor.outcomeIterator();
Set<String> featureNames = Sets.newHashSet();
while (iter.hasNext()) {
Outcome o = iter.next();
for (Map.Entry<String, Double> f : featureGen.generateFeatures(o.getAssignment()).entrySet()) {
featureNames.add(f.getKey());
}
}
List<String> featureNamesSorted = Lists.newArrayList(featureNames);
Collections.sort(featureNamesSorted);
DiscreteVariable featureType = new DiscreteVariable(FEATURE_VAR_NAME, featureNamesSorted);
VariableNumMap featureVar = VariableNumMap.singleton(
Ints.max(factor.getVars().getVariableNumsArray()) + 1, FEATURE_VAR_NAME, featureType);
TableFactorBuilder builder = new TableFactorBuilder(
factor.getVars().union(featureVar), SparseTensorBuilder.getFactory());
iter = factor.outcomeIterator();
while (iter.hasNext()) {
Outcome o = iter.next();
for (Map.Entry<String, Double> f : featureGen.generateFeatures(o.getAssignment()).entrySet()) {
Assignment featureAssignment = featureVar.outcomeArrayToAssignment(f.getKey());
builder.setWeight(o.getAssignment().union(featureAssignment), f.getValue());
}
}
DiscreteFactor featureFactor = builder.build();
return new DiscreteLogLinearFactor(factor.getVars(), featureVar, featureFactor, factor);
} | [
"public",
"static",
"DiscreteLogLinearFactor",
"fromFeatureGeneratorSparse",
"(",
"DiscreteFactor",
"factor",
",",
"FeatureGenerator",
"<",
"Assignment",
",",
"String",
">",
"featureGen",
")",
"{",
"Iterator",
"<",
"Outcome",
">",
"iter",
"=",
"factor",
".",
"outcom... | Creates a {@code DiscreteLogLinearFactor} by applying {@code featureGen}
to each assignment in {@code factor} with non-zero weight. Returns a
sparse factor where only these assignments are assigned non-zero weight.
@param factor
@param featureGen
@return | [
"Creates",
"a",
"{",
"@code",
"DiscreteLogLinearFactor",
"}",
"by",
"applying",
"{",
"@code",
"featureGen",
"}",
"to",
"each",
"assignment",
"in",
"{",
"@code",
"factor",
"}",
"with",
"non",
"-",
"zero",
"weight",
".",
"Returns",
"a",
"sparse",
"factor",
"... | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/loglinear/DiscreteLogLinearFactor.java#L283-L314 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/JsLocalizer.java | JsLocalizer.addLocalizationPoint | public boolean addLocalizationPoint(LWMConfig lp, DestinationDefinition dd) {
"""
Add a single localization point to this JsLocalizer object and tell MP
about it. This method is used by dynamic config in tWAS.
@param lp
@param dd
@return boolean success Whether the LP was successfully added
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, "addLocalizationPoint", lp);
}
boolean valid = false;
LocalizationDefinition ld = ((JsAdminFactoryImpl) jsaf).createLocalizationDefinition(lp);
if (!isInZOSServentRegion()) {
_mpAdmin = ((SIMPAdmin) _me.getMessageProcessor()).getAdministrator();
}
try {
_mpAdmin.createDestinationLocalization(dd, ld);
updatedDestDefList.add(dd);
updatedLocDefList.add(ld);
LocalizationEntry lEntry = new LocalizationEntry(ld);
lpMap.put(ld.getName(), lEntry);
MasterEntry newMasterEntry = new MasterEntry();
newMasterEntry.setDestinationLocalization(ld);
masterMap.put(dd.getName(), newMasterEntry);
valid = true;
} catch (Exception e) {
SibTr.error(tc, "LOCALIZATION_EXCEPTION_SIAS0113", e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.exit(tc, "addLocalizationPoint", Boolean.valueOf(valid));
}
return valid;
} | java | public boolean addLocalizationPoint(LWMConfig lp, DestinationDefinition dd) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, "addLocalizationPoint", lp);
}
boolean valid = false;
LocalizationDefinition ld = ((JsAdminFactoryImpl) jsaf).createLocalizationDefinition(lp);
if (!isInZOSServentRegion()) {
_mpAdmin = ((SIMPAdmin) _me.getMessageProcessor()).getAdministrator();
}
try {
_mpAdmin.createDestinationLocalization(dd, ld);
updatedDestDefList.add(dd);
updatedLocDefList.add(ld);
LocalizationEntry lEntry = new LocalizationEntry(ld);
lpMap.put(ld.getName(), lEntry);
MasterEntry newMasterEntry = new MasterEntry();
newMasterEntry.setDestinationLocalization(ld);
masterMap.put(dd.getName(), newMasterEntry);
valid = true;
} catch (Exception e) {
SibTr.error(tc, "LOCALIZATION_EXCEPTION_SIAS0113", e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.exit(tc, "addLocalizationPoint", Boolean.valueOf(valid));
}
return valid;
} | [
"public",
"boolean",
"addLocalizationPoint",
"(",
"LWMConfig",
"lp",
",",
"DestinationDefinition",
"dd",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"{",
"SibTr",
".",
"entry",
... | Add a single localization point to this JsLocalizer object and tell MP
about it. This method is used by dynamic config in tWAS.
@param lp
@param dd
@return boolean success Whether the LP was successfully added | [
"Add",
"a",
"single",
"localization",
"point",
"to",
"this",
"JsLocalizer",
"object",
"and",
"tell",
"MP",
"about",
"it",
".",
"This",
"method",
"is",
"used",
"by",
"dynamic",
"config",
"in",
"tWAS",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/admin/internal/JsLocalizer.java#L294-L324 |
santhosh-tekuri/jlibs | core/src/main/java/jlibs/core/io/IOUtil.java | IOUtil.readFully | public static int readFully(Reader reader, char ch[], int off, int len) throws IOException {
"""
Reads <code>len</code> chars from given reader into specified buffer.<br>
If the given reader doesn't have <code>len</code> chars available,
it simply reads only the availabel number of chars.
@param reader input stream from which data is read
@param ch the buffer into which the data is read.
@param off an int specifying the offset into the data.
@param len an int specifying the number of chars to read.
@return the number of chars read. if the reader doen't have <code>len</code> chars available
it returns the the number of chars read
@throws IOException if an I/O error occurs.
"""
if(len<0)
throw new IndexOutOfBoundsException();
int n = 0;
while(n<len){
int count = reader.read(ch, off+n, len-n);
if(count<0)
return n;
n += count;
}
return n;
} | java | public static int readFully(Reader reader, char ch[], int off, int len) throws IOException{
if(len<0)
throw new IndexOutOfBoundsException();
int n = 0;
while(n<len){
int count = reader.read(ch, off+n, len-n);
if(count<0)
return n;
n += count;
}
return n;
} | [
"public",
"static",
"int",
"readFully",
"(",
"Reader",
"reader",
",",
"char",
"ch",
"[",
"]",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"if",
"(",
"len",
"<",
"0",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")... | Reads <code>len</code> chars from given reader into specified buffer.<br>
If the given reader doesn't have <code>len</code> chars available,
it simply reads only the availabel number of chars.
@param reader input stream from which data is read
@param ch the buffer into which the data is read.
@param off an int specifying the offset into the data.
@param len an int specifying the number of chars to read.
@return the number of chars read. if the reader doen't have <code>len</code> chars available
it returns the the number of chars read
@throws IOException if an I/O error occurs. | [
"Reads",
"<code",
">",
"len<",
"/",
"code",
">",
"chars",
"from",
"given",
"reader",
"into",
"specified",
"buffer",
".",
"<br",
">",
"If",
"the",
"given",
"reader",
"doesn",
"t",
"have",
"<code",
">",
"len<",
"/",
"code",
">",
"chars",
"available",
"it... | train | https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/core/src/main/java/jlibs/core/io/IOUtil.java#L278-L289 |
op4j/op4j | src/main/java/org/op4j/functions/FnFunc.java | FnFunc.ifNullOrTrueThen | public static final <T> Function<T,T> ifNullOrTrueThen(final Type<T> targetType, final IFunction<? super T, Boolean> condition, final IFunction<? super T,? extends T> thenFunction) {
"""
<p>
Builds a function that will execute the specified function <tt>thenFunction</tt>
only if the target object is null or the result of executing <tt>condition</tt> on
it is true.
</p>
<p>
The built function cannot change the return type (receives <tt>T</tt> and returns <tt>T</tt>)
because the <tt>thenFunction</tt> could remain unexecuted, and so the type returned by
<tt>thenFunction</tt> must be the same as the type required as input, in order to keep
consistency.
</p>
@param targetType the target type
@param condition the condition to be executed on the target object
@param thenFunction the function to be executed on the target object if
target is null or the result of executing condition on it is true
@return a function that executes the "thenFunction" if target is null or "condition" is true.
"""
return ifTrueThen(targetType, FnBoolean.or(FnObject.isNull(),condition), thenFunction);
} | java | public static final <T> Function<T,T> ifNullOrTrueThen(final Type<T> targetType, final IFunction<? super T, Boolean> condition, final IFunction<? super T,? extends T> thenFunction) {
return ifTrueThen(targetType, FnBoolean.or(FnObject.isNull(),condition), thenFunction);
} | [
"public",
"static",
"final",
"<",
"T",
">",
"Function",
"<",
"T",
",",
"T",
">",
"ifNullOrTrueThen",
"(",
"final",
"Type",
"<",
"T",
">",
"targetType",
",",
"final",
"IFunction",
"<",
"?",
"super",
"T",
",",
"Boolean",
">",
"condition",
",",
"final",
... | <p>
Builds a function that will execute the specified function <tt>thenFunction</tt>
only if the target object is null or the result of executing <tt>condition</tt> on
it is true.
</p>
<p>
The built function cannot change the return type (receives <tt>T</tt> and returns <tt>T</tt>)
because the <tt>thenFunction</tt> could remain unexecuted, and so the type returned by
<tt>thenFunction</tt> must be the same as the type required as input, in order to keep
consistency.
</p>
@param targetType the target type
@param condition the condition to be executed on the target object
@param thenFunction the function to be executed on the target object if
target is null or the result of executing condition on it is true
@return a function that executes the "thenFunction" if target is null or "condition" is true. | [
"<p",
">",
"Builds",
"a",
"function",
"that",
"will",
"execute",
"the",
"specified",
"function",
"<tt",
">",
"thenFunction<",
"/",
"tt",
">",
"only",
"if",
"the",
"target",
"object",
"is",
"null",
"or",
"the",
"result",
"of",
"executing",
"<tt",
">",
"co... | train | https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/functions/FnFunc.java#L269-L271 |
aws/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/FailureDetails.java | FailureDetails.setDetails | public void setDetails(java.util.Map<String, java.util.List<String>> details) {
"""
<p>
Detailed information about the Automation step failure.
</p>
@param details
Detailed information about the Automation step failure.
"""
this.details = details;
} | java | public void setDetails(java.util.Map<String, java.util.List<String>> details) {
this.details = details;
} | [
"public",
"void",
"setDetails",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
">",
"details",
")",
"{",
"this",
".",
"details",
"=",
"details",
";",
"}"
] | <p>
Detailed information about the Automation step failure.
</p>
@param details
Detailed information about the Automation step failure. | [
"<p",
">",
"Detailed",
"information",
"about",
"the",
"Automation",
"step",
"failure",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/FailureDetails.java#L165-L167 |
apptentive/apptentive-android | apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java | Util.createLocalStoredFile | public static StoredFile createLocalStoredFile(String sourceUrl, String localFilePath, String mimeType) {
"""
This method creates a cached file exactly copying from the input stream.
@param sourceUrl the source file path or uri string
@param localFilePath the cache file path string
@param mimeType the mimeType of the source inputstream
@return null if failed, otherwise a StoredFile object
"""
InputStream is = null;
try {
Context context = ApptentiveInternal.getInstance().getApplicationContext();
if (URLUtil.isContentUrl(sourceUrl) && context != null) {
Uri uri = Uri.parse(sourceUrl);
is = context.getContentResolver().openInputStream(uri);
} else {
File file = new File(sourceUrl);
is = new FileInputStream(file);
}
return createLocalStoredFile(is, sourceUrl, localFilePath, mimeType);
} catch (FileNotFoundException e) {
return null;
} finally {
ensureClosed(is);
}
} | java | public static StoredFile createLocalStoredFile(String sourceUrl, String localFilePath, String mimeType) {
InputStream is = null;
try {
Context context = ApptentiveInternal.getInstance().getApplicationContext();
if (URLUtil.isContentUrl(sourceUrl) && context != null) {
Uri uri = Uri.parse(sourceUrl);
is = context.getContentResolver().openInputStream(uri);
} else {
File file = new File(sourceUrl);
is = new FileInputStream(file);
}
return createLocalStoredFile(is, sourceUrl, localFilePath, mimeType);
} catch (FileNotFoundException e) {
return null;
} finally {
ensureClosed(is);
}
} | [
"public",
"static",
"StoredFile",
"createLocalStoredFile",
"(",
"String",
"sourceUrl",
",",
"String",
"localFilePath",
",",
"String",
"mimeType",
")",
"{",
"InputStream",
"is",
"=",
"null",
";",
"try",
"{",
"Context",
"context",
"=",
"ApptentiveInternal",
".",
"... | This method creates a cached file exactly copying from the input stream.
@param sourceUrl the source file path or uri string
@param localFilePath the cache file path string
@param mimeType the mimeType of the source inputstream
@return null if failed, otherwise a StoredFile object | [
"This",
"method",
"creates",
"a",
"cached",
"file",
"exactly",
"copying",
"from",
"the",
"input",
"stream",
"."
] | train | https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L914-L932 |
joniles/mpxj | src/main/java/net/sf/mpxj/primavera/PrimaveraReader.java | PrimaveraReader.processCalendarHours | private void processCalendarHours(ProjectCalendar calendar, Record dayRecord) {
"""
Process hours in a working day.
@param calendar project calendar
@param dayRecord working day data
"""
// ... for each day of the week
Day day = Day.getInstance(Integer.parseInt(dayRecord.getField()));
// Get hours
List<Record> recHours = dayRecord.getChildren();
if (recHours.size() == 0)
{
// No data -> not working
calendar.setWorkingDay(day, false);
}
else
{
calendar.setWorkingDay(day, true);
// Read hours
ProjectCalendarHours hours = calendar.addCalendarHours(day);
for (Record recWorkingHours : recHours)
{
addHours(hours, recWorkingHours);
}
}
} | java | private void processCalendarHours(ProjectCalendar calendar, Record dayRecord)
{
// ... for each day of the week
Day day = Day.getInstance(Integer.parseInt(dayRecord.getField()));
// Get hours
List<Record> recHours = dayRecord.getChildren();
if (recHours.size() == 0)
{
// No data -> not working
calendar.setWorkingDay(day, false);
}
else
{
calendar.setWorkingDay(day, true);
// Read hours
ProjectCalendarHours hours = calendar.addCalendarHours(day);
for (Record recWorkingHours : recHours)
{
addHours(hours, recWorkingHours);
}
}
} | [
"private",
"void",
"processCalendarHours",
"(",
"ProjectCalendar",
"calendar",
",",
"Record",
"dayRecord",
")",
"{",
"// ... for each day of the week",
"Day",
"day",
"=",
"Day",
".",
"getInstance",
"(",
"Integer",
".",
"parseInt",
"(",
"dayRecord",
".",
"getField",
... | Process hours in a working day.
@param calendar project calendar
@param dayRecord working day data | [
"Process",
"hours",
"in",
"a",
"working",
"day",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/PrimaveraReader.java#L381-L402 |
DDTH/ddth-tsc | ddth-tsc-core/src/main/java/com/github/ddth/tsc/cassandra/internal/CounterMetadata.java | CounterMetadata.fromJsonString | @SuppressWarnings("unchecked")
public static CounterMetadata fromJsonString(String jsonString) {
"""
Creates a {@link CounterMetadata} object from a JSON string.
@param jsonString
@return
"""
try {
return fromMap(SerializationUtils.fromJsonString(jsonString, Map.class));
} catch (Exception e) {
return null;
}
} | java | @SuppressWarnings("unchecked")
public static CounterMetadata fromJsonString(String jsonString) {
try {
return fromMap(SerializationUtils.fromJsonString(jsonString, Map.class));
} catch (Exception e) {
return null;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"CounterMetadata",
"fromJsonString",
"(",
"String",
"jsonString",
")",
"{",
"try",
"{",
"return",
"fromMap",
"(",
"SerializationUtils",
".",
"fromJsonString",
"(",
"jsonString",
",",
"Map",
".... | Creates a {@link CounterMetadata} object from a JSON string.
@param jsonString
@return | [
"Creates",
"a",
"{",
"@link",
"CounterMetadata",
"}",
"object",
"from",
"a",
"JSON",
"string",
"."
] | train | https://github.com/DDTH/ddth-tsc/blob/d233c304c8fed2f3c069de42a36b7bbd5c8be01b/ddth-tsc-core/src/main/java/com/github/ddth/tsc/cassandra/internal/CounterMetadata.java#L62-L69 |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/io/InputStreamMonitor.java | InputStreamMonitor.onStart | @Handler
public void onStart(Start event) {
"""
Starts a thread that continuously reads available
data from the input stream.
@param event the event
"""
synchronized (this) {
if (runner != null) {
return;
}
buffers = new ManagedBufferPool<>(ManagedBuffer::new,
() -> {
return ByteBuffer.allocateDirect(bufferSize);
}, 2);
runner = new Thread(this, Components.simpleObjectName(this));
// Because this cannot reliably be stopped, it doesn't prevent
// shutdown.
runner.setDaemon(true);
runner.start();
}
} | java | @Handler
public void onStart(Start event) {
synchronized (this) {
if (runner != null) {
return;
}
buffers = new ManagedBufferPool<>(ManagedBuffer::new,
() -> {
return ByteBuffer.allocateDirect(bufferSize);
}, 2);
runner = new Thread(this, Components.simpleObjectName(this));
// Because this cannot reliably be stopped, it doesn't prevent
// shutdown.
runner.setDaemon(true);
runner.start();
}
} | [
"@",
"Handler",
"public",
"void",
"onStart",
"(",
"Start",
"event",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"runner",
"!=",
"null",
")",
"{",
"return",
";",
"}",
"buffers",
"=",
"new",
"ManagedBufferPool",
"<>",
"(",
"ManagedBuffer",
... | Starts a thread that continuously reads available
data from the input stream.
@param event the event | [
"Starts",
"a",
"thread",
"that",
"continuously",
"reads",
"available",
"data",
"from",
"the",
"input",
"stream",
"."
] | train | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/io/InputStreamMonitor.java#L135-L151 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/quantiles/DirectCompactDoublesSketch.java | DirectCompactDoublesSketch.checkCompact | static void checkCompact(final int serVer, final int flags) {
"""
Checks a sketch's serial version and flags to see if the sketch can be wrapped as a
DirectCompactDoubleSketch. Throws an exception if the sketch is neither empty nor compact
and ordered, unles the sketch uses serialization version 2.
@param serVer the serialization version
@param flags Flags from the sketch to evaluate
"""
final int compactFlagMask = COMPACT_FLAG_MASK | ORDERED_FLAG_MASK;
if ((serVer != 2)
&& ((flags & EMPTY_FLAG_MASK) == 0)
&& ((flags & compactFlagMask) != compactFlagMask)) {
throw new SketchesArgumentException(
"Possible corruption: Must be v2, empty, or compact and ordered. Flags field: "
+ Integer.toBinaryString(flags) + ", SerVer: " + serVer);
}
} | java | static void checkCompact(final int serVer, final int flags) {
final int compactFlagMask = COMPACT_FLAG_MASK | ORDERED_FLAG_MASK;
if ((serVer != 2)
&& ((flags & EMPTY_FLAG_MASK) == 0)
&& ((flags & compactFlagMask) != compactFlagMask)) {
throw new SketchesArgumentException(
"Possible corruption: Must be v2, empty, or compact and ordered. Flags field: "
+ Integer.toBinaryString(flags) + ", SerVer: " + serVer);
}
} | [
"static",
"void",
"checkCompact",
"(",
"final",
"int",
"serVer",
",",
"final",
"int",
"flags",
")",
"{",
"final",
"int",
"compactFlagMask",
"=",
"COMPACT_FLAG_MASK",
"|",
"ORDERED_FLAG_MASK",
";",
"if",
"(",
"(",
"serVer",
"!=",
"2",
")",
"&&",
"(",
"(",
... | Checks a sketch's serial version and flags to see if the sketch can be wrapped as a
DirectCompactDoubleSketch. Throws an exception if the sketch is neither empty nor compact
and ordered, unles the sketch uses serialization version 2.
@param serVer the serialization version
@param flags Flags from the sketch to evaluate | [
"Checks",
"a",
"sketch",
"s",
"serial",
"version",
"and",
"flags",
"to",
"see",
"if",
"the",
"sketch",
"can",
"be",
"wrapped",
"as",
"a",
"DirectCompactDoubleSketch",
".",
"Throws",
"an",
"exception",
"if",
"the",
"sketch",
"is",
"neither",
"empty",
"nor",
... | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/quantiles/DirectCompactDoublesSketch.java#L234-L243 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPP8Reader.java | MPP8Reader.processViewData | private void processViewData() throws IOException {
"""
This method extracts view data from the MPP file.
@throws IOException
"""
DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CV_iew");
FixFix ff = new FixFix(138, new DocumentInputStream(((DocumentEntry) dir.getEntry("FixFix 0"))));
int items = ff.getItemCount();
byte[] data;
View view;
for (int loop = 0; loop < items; loop++)
{
data = ff.getByteArrayValue(loop);
view = new View8(m_file, data);
m_file.getViews().add(view);
}
} | java | private void processViewData() throws IOException
{
DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CV_iew");
FixFix ff = new FixFix(138, new DocumentInputStream(((DocumentEntry) dir.getEntry("FixFix 0"))));
int items = ff.getItemCount();
byte[] data;
View view;
for (int loop = 0; loop < items; loop++)
{
data = ff.getByteArrayValue(loop);
view = new View8(m_file, data);
m_file.getViews().add(view);
}
} | [
"private",
"void",
"processViewData",
"(",
")",
"throws",
"IOException",
"{",
"DirectoryEntry",
"dir",
"=",
"(",
"DirectoryEntry",
")",
"m_viewDir",
".",
"getEntry",
"(",
"\"CV_iew\"",
")",
";",
"FixFix",
"ff",
"=",
"new",
"FixFix",
"(",
"138",
",",
"new",
... | This method extracts view data from the MPP file.
@throws IOException | [
"This",
"method",
"extracts",
"view",
"data",
"from",
"the",
"MPP",
"file",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP8Reader.java#L1198-L1212 |
liferay/com-liferay-commerce | commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java | CommerceTierPriceEntryPersistenceImpl.findAll | @Override
public List<CommerceTierPriceEntry> findAll(int start, int end) {
"""
Returns a range of all the commerce tier price entries.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTierPriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce tier price entries
@param end the upper bound of the range of commerce tier price entries (not inclusive)
@return the range of commerce tier price entries
"""
return findAll(start, end, null);
} | java | @Override
public List<CommerceTierPriceEntry> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceTierPriceEntry",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce tier price entries.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTierPriceEntryModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce tier price entries
@param end the upper bound of the range of commerce tier price entries (not inclusive)
@return the range of commerce tier price entries | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"tier",
"price",
"entries",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-price-list-service/src/main/java/com/liferay/commerce/price/list/service/persistence/impl/CommerceTierPriceEntryPersistenceImpl.java#L4855-L4858 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.