repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 188 | func_name stringlengths 7 127 | whole_func_string stringlengths 77 3.91k | language stringclasses 1
value | func_code_string stringlengths 77 3.91k | func_code_tokens listlengths 20 745 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 477 | split_name stringclasses 1
value | func_code_url stringlengths 111 288 |
|---|---|---|---|---|---|---|---|---|---|---|
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/FieldAccess.java | FieldAccess.snarfFieldValue | protected static Variable snarfFieldValue(FieldInstruction fieldIns, ConstantPoolGen cpg, ValueNumberFrame frame)
throws DataflowAnalysisException {
if (isLongOrDouble(fieldIns, cpg)) {
int numSlots = frame.getNumSlots();
ValueNumber topValue = frame.getValue(numSlots - 1);
ValueNumber nextValue = frame.getValue(numSlots - 2);
return new LongOrDoubleLocalVariable(topValue, nextValue);
} else {
return new LocalVariable(frame.getTopValue());
}
} | java | protected static Variable snarfFieldValue(FieldInstruction fieldIns, ConstantPoolGen cpg, ValueNumberFrame frame)
throws DataflowAnalysisException {
if (isLongOrDouble(fieldIns, cpg)) {
int numSlots = frame.getNumSlots();
ValueNumber topValue = frame.getValue(numSlots - 1);
ValueNumber nextValue = frame.getValue(numSlots - 2);
return new LongOrDoubleLocalVariable(topValue, nextValue);
} else {
return new LocalVariable(frame.getTopValue());
}
} | [
"protected",
"static",
"Variable",
"snarfFieldValue",
"(",
"FieldInstruction",
"fieldIns",
",",
"ConstantPoolGen",
"cpg",
",",
"ValueNumberFrame",
"frame",
")",
"throws",
"DataflowAnalysisException",
"{",
"if",
"(",
"isLongOrDouble",
"(",
"fieldIns",
",",
"cpg",
")",
... | Get a Variable representing the stack value which will either be stored
into or loaded from a field.
@param fieldIns
the FieldInstruction accessing the field
@param cpg
the ConstantPoolGen for the method
@param frame
the ValueNumberFrame containing the value to be stored or the
value loaded | [
"Get",
"a",
"Variable",
"representing",
"the",
"stack",
"value",
"which",
"will",
"either",
"be",
"stored",
"into",
"or",
"loaded",
"from",
"a",
"field",
"."
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/bcp/FieldAccess.java#L112-L124 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java | DnsBatch.createZoneCallback | private RpcBatch.Callback<ManagedZone> createZoneCallback(
final DnsOptions serviceOptions,
final DnsBatchResult<Zone> result,
final boolean nullForNotFound,
final boolean idempotent) {
return new RpcBatch.Callback<ManagedZone>() {
@Override
public void onSuccess(ManagedZone response) {
result.success(
response == null ? null : Zone.fromPb(serviceOptions.getService(), response));
}
@Override
public void onFailure(GoogleJsonError googleJsonError) {
DnsException serviceException = new DnsException(googleJsonError, idempotent);
if (nullForNotFound && serviceException.getCode() == HTTP_NOT_FOUND) {
result.success(null);
} else {
result.error(serviceException);
}
}
};
} | java | private RpcBatch.Callback<ManagedZone> createZoneCallback(
final DnsOptions serviceOptions,
final DnsBatchResult<Zone> result,
final boolean nullForNotFound,
final boolean idempotent) {
return new RpcBatch.Callback<ManagedZone>() {
@Override
public void onSuccess(ManagedZone response) {
result.success(
response == null ? null : Zone.fromPb(serviceOptions.getService(), response));
}
@Override
public void onFailure(GoogleJsonError googleJsonError) {
DnsException serviceException = new DnsException(googleJsonError, idempotent);
if (nullForNotFound && serviceException.getCode() == HTTP_NOT_FOUND) {
result.success(null);
} else {
result.error(serviceException);
}
}
};
} | [
"private",
"RpcBatch",
".",
"Callback",
"<",
"ManagedZone",
">",
"createZoneCallback",
"(",
"final",
"DnsOptions",
"serviceOptions",
",",
"final",
"DnsBatchResult",
"<",
"Zone",
">",
"result",
",",
"final",
"boolean",
"nullForNotFound",
",",
"final",
"boolean",
"i... | A joint callback for both "get zone" and "create zone" operations. | [
"A",
"joint",
"callback",
"for",
"both",
"get",
"zone",
"and",
"create",
"zone",
"operations",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java#L258-L280 |
RestComm/jain-slee.http | resources/http-client/ra/src/main/java/org/restcomm/client/slee/resource/http/HttpClientResourceAdaptor.java | HttpClientResourceAdaptor.processResponseEvent | public void processResponseEvent(ResponseEvent event, HttpClientActivity activity) throws ActivityIsEndingException {
HttpClientActivityHandle ah = new HttpClientActivityHandle(activity.getSessionId());
if (tracer.isFineEnabled())
tracer.fine("==== FIRING ResponseEvent EVENT TO LOCAL SLEE, Event: " + event + " ====");
try {
resourceAdaptorContext.getSleeEndpoint().fireEvent(ah, fireableEventType, event, null, null, EVENT_FLAGS);
} catch (Throwable e) {
throw new ActivityIsEndingException();
}
} | java | public void processResponseEvent(ResponseEvent event, HttpClientActivity activity) throws ActivityIsEndingException {
HttpClientActivityHandle ah = new HttpClientActivityHandle(activity.getSessionId());
if (tracer.isFineEnabled())
tracer.fine("==== FIRING ResponseEvent EVENT TO LOCAL SLEE, Event: " + event + " ====");
try {
resourceAdaptorContext.getSleeEndpoint().fireEvent(ah, fireableEventType, event, null, null, EVENT_FLAGS);
} catch (Throwable e) {
throw new ActivityIsEndingException();
}
} | [
"public",
"void",
"processResponseEvent",
"(",
"ResponseEvent",
"event",
",",
"HttpClientActivity",
"activity",
")",
"throws",
"ActivityIsEndingException",
"{",
"HttpClientActivityHandle",
"ah",
"=",
"new",
"HttpClientActivityHandle",
"(",
"activity",
".",
"getSessionId",
... | Receives an Event from the HTTP client and sends it to the SLEE.
@param event
@param activity | [
"Receives",
"an",
"Event",
"from",
"the",
"HTTP",
"client",
"and",
"sends",
"it",
"to",
"the",
"SLEE",
"."
] | train | https://github.com/RestComm/jain-slee.http/blob/938e502a60355b988d6998d2539bbb16207674e8/resources/http-client/ra/src/main/java/org/restcomm/client/slee/resource/http/HttpClientResourceAdaptor.java#L672-L684 |
roboconf/roboconf-platform | core/roboconf-plugin-puppet/src/main/java/net/roboconf/plugin/puppet/internal/PluginPuppet.java | PluginPuppet.formatExportedVariables | String formatExportedVariables( Map<String,String> instanceExports ) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for( Entry<String,String> entry : instanceExports.entrySet()) {
if( first )
first = false;
else
sb.append(", ");
String vname = VariableHelpers.parseVariableName( entry.getKey()).getValue();
sb.append( vname.toLowerCase() );
sb.append( " => " );
if( Utils.isEmptyOrWhitespaces( entry.getValue()))
sb.append( "undef" );
else
sb.append( "'" + entry.getValue() + "'" );
}
return sb.toString();
} | java | String formatExportedVariables( Map<String,String> instanceExports ) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for( Entry<String,String> entry : instanceExports.entrySet()) {
if( first )
first = false;
else
sb.append(", ");
String vname = VariableHelpers.parseVariableName( entry.getKey()).getValue();
sb.append( vname.toLowerCase() );
sb.append( " => " );
if( Utils.isEmptyOrWhitespaces( entry.getValue()))
sb.append( "undef" );
else
sb.append( "'" + entry.getValue() + "'" );
}
return sb.toString();
} | [
"String",
"formatExportedVariables",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"instanceExports",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"boolean",
"first",
"=",
"true",
";",
"for",
"(",
"Entry",
"<",
"String",
",... | Returns a String representing all the exported variables and their value.
<p>
Must be that way:<br>
{@code varName1 => 'varValue1', varName2 => undef, varName3 => 'varValue3'}
</p>
<p>
It is assumed the prefix of the exported variable (component or facet name)
is not required.
</p>
<p>
As an example...<br>
Export "Redis.port = 4040" will generate "port => 4040".<br>
Export "Redis.port = null" will generate "port => undef".
</p>
@param instanceExports the instance
@return a non-null string | [
"Returns",
"a",
"String",
"representing",
"all",
"the",
"exported",
"variables",
"and",
"their",
"value",
".",
"<p",
">",
"Must",
"be",
"that",
"way",
":",
"<br",
">",
"{",
"@code",
"varName1",
"=",
">",
"varValue1",
"varName2",
"=",
">",
"undef",
"varNa... | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-plugin-puppet/src/main/java/net/roboconf/plugin/puppet/internal/PluginPuppet.java#L429-L449 |
ansell/restlet-utils | src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java | FixedRedirectCookieAuthenticator.isLoggingIn | protected boolean isLoggingIn(final Request request, final Response response)
{
return this.isInterceptingLogin()
&& this.getLoginPath().equals(request.getResourceRef().getRemainingPart(false, false))
&& Method.POST.equals(request.getMethod());
} | java | protected boolean isLoggingIn(final Request request, final Response response)
{
return this.isInterceptingLogin()
&& this.getLoginPath().equals(request.getResourceRef().getRemainingPart(false, false))
&& Method.POST.equals(request.getMethod());
} | [
"protected",
"boolean",
"isLoggingIn",
"(",
"final",
"Request",
"request",
",",
"final",
"Response",
"response",
")",
"{",
"return",
"this",
".",
"isInterceptingLogin",
"(",
")",
"&&",
"this",
".",
"getLoginPath",
"(",
")",
".",
"equals",
"(",
"request",
"."... | Indicates if the request is an attempt to log in and should be intercepted.
@param request
The current request.
@param response
The current response.
@return True if the request is an attempt to log in and should be intercepted. | [
"Indicates",
"if",
"the",
"request",
"is",
"an",
"attempt",
"to",
"log",
"in",
"and",
"should",
"be",
"intercepted",
"."
] | train | https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L592-L597 |
geomajas/geomajas-project-client-gwt | common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java | HtmlBuilder.tdClass | public static String tdClass(String clazz, String... content) {
return tagClass(Html.Tag.TD, clazz, content);
} | java | public static String tdClass(String clazz, String... content) {
return tagClass(Html.Tag.TD, clazz, content);
} | [
"public",
"static",
"String",
"tdClass",
"(",
"String",
"clazz",
",",
"String",
"...",
"content",
")",
"{",
"return",
"tagClass",
"(",
"Html",
".",
"Tag",
".",
"TD",
",",
"clazz",
",",
"content",
")",
";",
"}"
] | Build a HTML TableRow with given CSS class for a string.
Given content does <b>not</b> consists of HTML snippets and
as such is being prepared with {@link HtmlBuilder#htmlEncode(String)}.
@param clazz class for tr element
@param content content string
@return HTML tr element as string | [
"Build",
"a",
"HTML",
"TableRow",
"with",
"given",
"CSS",
"class",
"for",
"a",
"string",
".",
"Given",
"content",
"does",
"<b",
">",
"not<",
"/",
"b",
">",
"consists",
"of",
"HTML",
"snippets",
"and",
"as",
"such",
"is",
"being",
"prepared",
"with",
"{... | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java#L190-L192 |
alibaba/jstorm | jstorm-core/src/main/java/backtype/storm/state/StateFactory.java | StateFactory.getState | public static State getState(String namespace, Map stormConf, TopologyContext context) {
State state;
try {
String provider;
if (stormConf.containsKey(Config.TOPOLOGY_STATE_PROVIDER)) {
provider = (String) stormConf.get(Config.TOPOLOGY_STATE_PROVIDER);
} else {
provider = DEFAULT_PROVIDER;
}
Class<?> klazz = Class.forName(provider);
Object object = klazz.newInstance();
if (object instanceof StateProvider) {
state = ((StateProvider) object).newState(namespace, stormConf, context);
} else {
String msg = "Invalid state provider '" + provider +
"'. Should implement org.apache.storm.state.StateProvider";
LOG.error(msg);
throw new RuntimeException(msg);
}
} catch (Exception ex) {
LOG.error("Got exception while loading the state provider", ex);
throw new RuntimeException(ex);
}
return state;
} | java | public static State getState(String namespace, Map stormConf, TopologyContext context) {
State state;
try {
String provider;
if (stormConf.containsKey(Config.TOPOLOGY_STATE_PROVIDER)) {
provider = (String) stormConf.get(Config.TOPOLOGY_STATE_PROVIDER);
} else {
provider = DEFAULT_PROVIDER;
}
Class<?> klazz = Class.forName(provider);
Object object = klazz.newInstance();
if (object instanceof StateProvider) {
state = ((StateProvider) object).newState(namespace, stormConf, context);
} else {
String msg = "Invalid state provider '" + provider +
"'. Should implement org.apache.storm.state.StateProvider";
LOG.error(msg);
throw new RuntimeException(msg);
}
} catch (Exception ex) {
LOG.error("Got exception while loading the state provider", ex);
throw new RuntimeException(ex);
}
return state;
} | [
"public",
"static",
"State",
"getState",
"(",
"String",
"namespace",
",",
"Map",
"stormConf",
",",
"TopologyContext",
"context",
")",
"{",
"State",
"state",
";",
"try",
"{",
"String",
"provider",
";",
"if",
"(",
"stormConf",
".",
"containsKey",
"(",
"Config"... | Returns a new state instance using the {@link Config#TOPOLOGY_STATE_PROVIDER} or a
{@link InMemoryKeyValueState} if no provider is configured.
@param namespace the state namespace
@param stormConf the storm conf
@param context the topology context
@return the state instance | [
"Returns",
"a",
"new",
"state",
"instance",
"using",
"the",
"{",
"@link",
"Config#TOPOLOGY_STATE_PROVIDER",
"}",
"or",
"a",
"{",
"@link",
"InMemoryKeyValueState",
"}",
"if",
"no",
"provider",
"is",
"configured",
"."
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/state/StateFactory.java#L45-L69 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nslimitidentifier_nslimitsessions_binding.java | nslimitidentifier_nslimitsessions_binding.count_filtered | public static long count_filtered(nitro_service service, String limitidentifier, String filter) throws Exception{
nslimitidentifier_nslimitsessions_binding obj = new nslimitidentifier_nslimitsessions_binding();
obj.set_limitidentifier(limitidentifier);
options option = new options();
option.set_count(true);
option.set_filter(filter);
nslimitidentifier_nslimitsessions_binding[] response = (nslimitidentifier_nslimitsessions_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} | java | public static long count_filtered(nitro_service service, String limitidentifier, String filter) throws Exception{
nslimitidentifier_nslimitsessions_binding obj = new nslimitidentifier_nslimitsessions_binding();
obj.set_limitidentifier(limitidentifier);
options option = new options();
option.set_count(true);
option.set_filter(filter);
nslimitidentifier_nslimitsessions_binding[] response = (nslimitidentifier_nslimitsessions_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} | [
"public",
"static",
"long",
"count_filtered",
"(",
"nitro_service",
"service",
",",
"String",
"limitidentifier",
",",
"String",
"filter",
")",
"throws",
"Exception",
"{",
"nslimitidentifier_nslimitsessions_binding",
"obj",
"=",
"new",
"nslimitidentifier_nslimitsessions_bind... | Use this API to count the filtered set of nslimitidentifier_nslimitsessions_binding resources.
filter string should be in JSON format.eg: "port:80,servicetype:HTTP". | [
"Use",
"this",
"API",
"to",
"count",
"the",
"filtered",
"set",
"of",
"nslimitidentifier_nslimitsessions_binding",
"resources",
".",
"filter",
"string",
"should",
"be",
"in",
"JSON",
"format",
".",
"eg",
":",
"port",
":",
"80",
"servicetype",
":",
"HTTP",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nslimitidentifier_nslimitsessions_binding.java#L145-L156 |
groupon/odo | client/src/main/java/com/groupon/odo/client/Client.java | Client.setMethodArguments | public boolean setMethodArguments(String pathName, String methodName, Integer ordinal, Object... arguments) {
try {
BasicNameValuePair[] params = new BasicNameValuePair[arguments.length + 2];
int x = 0;
for (Object argument : arguments) {
params[x] = new BasicNameValuePair("arguments[]", argument.toString());
x++;
}
params[x] = new BasicNameValuePair("profileIdentifier", this._profileName);
params[x + 1] = new BasicNameValuePair("ordinal", ordinal.toString());
JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + "/" + methodName, params));
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | java | public boolean setMethodArguments(String pathName, String methodName, Integer ordinal, Object... arguments) {
try {
BasicNameValuePair[] params = new BasicNameValuePair[arguments.length + 2];
int x = 0;
for (Object argument : arguments) {
params[x] = new BasicNameValuePair("arguments[]", argument.toString());
x++;
}
params[x] = new BasicNameValuePair("profileIdentifier", this._profileName);
params[x + 1] = new BasicNameValuePair("ordinal", ordinal.toString());
JSONObject response = new JSONObject(doPost(BASE_PATH + uriEncode(pathName) + "/" + methodName, params));
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | [
"public",
"boolean",
"setMethodArguments",
"(",
"String",
"pathName",
",",
"String",
"methodName",
",",
"Integer",
"ordinal",
",",
"Object",
"...",
"arguments",
")",
"{",
"try",
"{",
"BasicNameValuePair",
"[",
"]",
"params",
"=",
"new",
"BasicNameValuePair",
"["... | Set the method arguments for an enabled method override
@param pathName Path name
@param methodName Fully qualified method name
@param ordinal 1-based index of the override within the overrides of type methodName
@param arguments Array of arguments to set(specify all arguments)
@return true if success, false otherwise | [
"Set",
"the",
"method",
"arguments",
"for",
"an",
"enabled",
"method",
"override"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L704-L723 |
chhh/MSFTBX | MSFileToolbox/src/main/java/umich/ms/external/apache/cassandra/io/BufferedRandomAccessFile.java | BufferedRandomAccessFile.writeAtMost | private int writeAtMost(byte[] b, int off, int len) throws IOException {
if (this.curr_ >= this.hi_) {
if (this.hitEOF_ && this.hi_ < this.maxHi_) {
// at EOF -- bump "hi"
this.hi_ = this.maxHi_;
} else {
// slow path -- write current buffer; read next one
this.seek(this.curr_);
if (this.curr_ == this.hi_) {
// appending to EOF -- bump "hi"
this.hi_ = this.maxHi_;
}
}
}
len = Math.min(len, (int) (this.hi_ - this.curr_));
int buffOff = (int) (this.curr_ - this.lo_);
System.arraycopy(b, off, this.buff_, buffOff, len);
this.curr_ += len;
return len;
} | java | private int writeAtMost(byte[] b, int off, int len) throws IOException {
if (this.curr_ >= this.hi_) {
if (this.hitEOF_ && this.hi_ < this.maxHi_) {
// at EOF -- bump "hi"
this.hi_ = this.maxHi_;
} else {
// slow path -- write current buffer; read next one
this.seek(this.curr_);
if (this.curr_ == this.hi_) {
// appending to EOF -- bump "hi"
this.hi_ = this.maxHi_;
}
}
}
len = Math.min(len, (int) (this.hi_ - this.curr_));
int buffOff = (int) (this.curr_ - this.lo_);
System.arraycopy(b, off, this.buff_, buffOff, len);
this.curr_ += len;
return len;
} | [
"private",
"int",
"writeAtMost",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"if",
"(",
"this",
".",
"curr_",
">=",
"this",
".",
"hi_",
")",
"{",
"if",
"(",
"this",
".",
"hitEOF_",
"&&",
"t... | /*
Write at most "len" bytes to "b" starting at position "off", and return
the number of bytes written. | [
"/",
"*",
"Write",
"at",
"most",
"len",
"bytes",
"to",
"b",
"starting",
"at",
"position",
"off",
"and",
"return",
"the",
"number",
"of",
"bytes",
"written",
"."
] | train | https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/external/apache/cassandra/io/BufferedRandomAccessFile.java#L317-L336 |
wigforss/Ka-Web | servlet/src/main/java/org/kasource/web/servlet/filter/NoCacheFilter.java | NoCacheFilter.setHeader | private void setHeader(HttpServletResponse response, String name, String value) {
if(response.containsHeader(value)) {
response.setHeader(name, value);
} else {
response.addHeader(name, value);
}
} | java | private void setHeader(HttpServletResponse response, String name, String value) {
if(response.containsHeader(value)) {
response.setHeader(name, value);
} else {
response.addHeader(name, value);
}
} | [
"private",
"void",
"setHeader",
"(",
"HttpServletResponse",
"response",
",",
"String",
"name",
",",
"String",
"value",
")",
"{",
"if",
"(",
"response",
".",
"containsHeader",
"(",
"value",
")",
")",
"{",
"response",
".",
"setHeader",
"(",
"name",
",",
"val... | Set Cache header.
@param response The HttpResponse to set header on
@param name Name of the header to set
@param value Value of the header to set. | [
"Set",
"Cache",
"header",
"."
] | train | https://github.com/wigforss/Ka-Web/blob/bb6d8eacbefdeb7c8c6bb6135e55939d968fa433/servlet/src/main/java/org/kasource/web/servlet/filter/NoCacheFilter.java#L81-L87 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/de/julielab/jules/types/mmax/MMAXAnnotation.java | MMAXAnnotation.setSegmentList | public void setSegmentList(int i, AnnotationSegment v) {
if (MMAXAnnotation_Type.featOkTst && ((MMAXAnnotation_Type)jcasType).casFeat_segmentList == null)
jcasType.jcas.throwFeatMissing("segmentList", "de.julielab.jules.types.mmax.MMAXAnnotation");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((MMAXAnnotation_Type)jcasType).casFeatCode_segmentList), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((MMAXAnnotation_Type)jcasType).casFeatCode_segmentList), i, jcasType.ll_cas.ll_getFSRef(v));} | java | public void setSegmentList(int i, AnnotationSegment v) {
if (MMAXAnnotation_Type.featOkTst && ((MMAXAnnotation_Type)jcasType).casFeat_segmentList == null)
jcasType.jcas.throwFeatMissing("segmentList", "de.julielab.jules.types.mmax.MMAXAnnotation");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((MMAXAnnotation_Type)jcasType).casFeatCode_segmentList), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((MMAXAnnotation_Type)jcasType).casFeatCode_segmentList), i, jcasType.ll_cas.ll_getFSRef(v));} | [
"public",
"void",
"setSegmentList",
"(",
"int",
"i",
",",
"AnnotationSegment",
"v",
")",
"{",
"if",
"(",
"MMAXAnnotation_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"MMAXAnnotation_Type",
")",
"jcasType",
")",
".",
"casFeat_segmentList",
"==",
"null",
")",
"jcasT... | indexed setter for segmentList - sets an indexed value - List of MMAX annotation segements that make up the MMAX annotation.
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"segmentList",
"-",
"sets",
"an",
"indexed",
"value",
"-",
"List",
"of",
"MMAX",
"annotation",
"segements",
"that",
"make",
"up",
"the",
"MMAX",
"annotation",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/mmax/MMAXAnnotation.java#L163-L167 |
casmi/casmi | src/main/java/casmi/image/Image.java | Image.setA | public final void setA(double alpha, int x, int y){
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
int idx = x + y * width;
int tmpR = pixels[idx] >> 16 & 0x000000ff;
int tmpG = pixels[idx] >> 8 & 0x000000ff;
int tmpB = pixels[idx] & 0x000000ff;
pixels[idx] = (int)alpha << 24 |
tmpR << 16 |
tmpG << 8 |
tmpB;
} | java | public final void setA(double alpha, int x, int y){
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
int idx = x + y * width;
int tmpR = pixels[idx] >> 16 & 0x000000ff;
int tmpG = pixels[idx] >> 8 & 0x000000ff;
int tmpB = pixels[idx] & 0x000000ff;
pixels[idx] = (int)alpha << 24 |
tmpR << 16 |
tmpG << 8 |
tmpB;
} | [
"public",
"final",
"void",
"setA",
"(",
"double",
"alpha",
",",
"int",
"x",
",",
"int",
"y",
")",
"{",
"int",
"[",
"]",
"pixels",
"=",
"(",
"(",
"DataBufferInt",
")",
"img",
".",
"getRaster",
"(",
")",
".",
"getDataBuffer",
"(",
")",
")",
".",
"g... | Sets the alpha value of the pixel data in this Image.
@param alpha
The alpha value of the pixel.
@param x
The x-coordinate of the pixel.
@param y
The y-coordinate of the pixel. | [
"Sets",
"the",
"alpha",
"value",
"of",
"the",
"pixel",
"data",
"in",
"this",
"Image",
"."
] | train | https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/image/Image.java#L382-L392 |
jcuda/jcusparse | JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java | JCusparse.cusparseSdense2csc | public static int cusparseSdense2csc(
cusparseHandle handle,
int m,
int n,
cusparseMatDescr descrA,
Pointer A,
int lda,
Pointer nnzPerCol,
Pointer cscSortedValA,
Pointer cscSortedRowIndA,
Pointer cscSortedColPtrA)
{
return checkResult(cusparseSdense2cscNative(handle, m, n, descrA, A, lda, nnzPerCol, cscSortedValA, cscSortedRowIndA, cscSortedColPtrA));
} | java | public static int cusparseSdense2csc(
cusparseHandle handle,
int m,
int n,
cusparseMatDescr descrA,
Pointer A,
int lda,
Pointer nnzPerCol,
Pointer cscSortedValA,
Pointer cscSortedRowIndA,
Pointer cscSortedColPtrA)
{
return checkResult(cusparseSdense2cscNative(handle, m, n, descrA, A, lda, nnzPerCol, cscSortedValA, cscSortedRowIndA, cscSortedColPtrA));
} | [
"public",
"static",
"int",
"cusparseSdense2csc",
"(",
"cusparseHandle",
"handle",
",",
"int",
"m",
",",
"int",
"n",
",",
"cusparseMatDescr",
"descrA",
",",
"Pointer",
"A",
",",
"int",
"lda",
",",
"Pointer",
"nnzPerCol",
",",
"Pointer",
"cscSortedValA",
",",
... | Description: This routine converts a dense matrix to a sparse matrix
in the CSC storage format, using the information computed by the
nnz routine. | [
"Description",
":",
"This",
"routine",
"converts",
"a",
"dense",
"matrix",
"to",
"a",
"sparse",
"matrix",
"in",
"the",
"CSC",
"storage",
"format",
"using",
"the",
"information",
"computed",
"by",
"the",
"nnz",
"routine",
"."
] | train | https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L11387-L11400 |
Red5/red5-server-common | src/main/java/org/red5/server/Server.java | Server.addMapping | public boolean addMapping(String hostName, String contextPath, String globalName) {
log.info("Add mapping global: {} host: {} context: {}", new Object[] { globalName, hostName, contextPath });
final String key = getKey(hostName, contextPath);
log.debug("Add mapping: {} => {}", key, globalName);
return (mapping.putIfAbsent(key, globalName) == null);
} | java | public boolean addMapping(String hostName, String contextPath, String globalName) {
log.info("Add mapping global: {} host: {} context: {}", new Object[] { globalName, hostName, contextPath });
final String key = getKey(hostName, contextPath);
log.debug("Add mapping: {} => {}", key, globalName);
return (mapping.putIfAbsent(key, globalName) == null);
} | [
"public",
"boolean",
"addMapping",
"(",
"String",
"hostName",
",",
"String",
"contextPath",
",",
"String",
"globalName",
")",
"{",
"log",
".",
"info",
"(",
"\"Add mapping global: {} host: {} context: {}\"",
",",
"new",
"Object",
"[",
"]",
"{",
"globalName",
",",
... | Map key (host + / + context path) and global scope name
@param hostName
Host name
@param contextPath
Context path
@param globalName
Global scope name
@return true if mapping was added, false if already exist | [
"Map",
"key",
"(",
"host",
"+",
"/",
"+",
"context",
"path",
")",
"and",
"global",
"scope",
"name"
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/Server.java#L209-L214 |
ironjacamar/ironjacamar | core/src/main/java/org/ironjacamar/core/connectionmanager/pool/AbstractManagedConnectionPool.java | AbstractManagedConnectionPool.destroyAndRemoveConnectionListener | protected void destroyAndRemoveConnectionListener(ConnectionListener cl, Collection<ConnectionListener> listeners)
{
try
{
pool.destroyConnectionListener(cl);
}
catch (ResourceException e)
{
// TODO:
cl.setState(ZOMBIE);
}
finally
{
listeners.remove(cl);
}
} | java | protected void destroyAndRemoveConnectionListener(ConnectionListener cl, Collection<ConnectionListener> listeners)
{
try
{
pool.destroyConnectionListener(cl);
}
catch (ResourceException e)
{
// TODO:
cl.setState(ZOMBIE);
}
finally
{
listeners.remove(cl);
}
} | [
"protected",
"void",
"destroyAndRemoveConnectionListener",
"(",
"ConnectionListener",
"cl",
",",
"Collection",
"<",
"ConnectionListener",
">",
"listeners",
")",
"{",
"try",
"{",
"pool",
".",
"destroyConnectionListener",
"(",
"cl",
")",
";",
"}",
"catch",
"(",
"Res... | Destroy and remove a connection listener
@param cl The connection listener
@param listeners The listeners | [
"Destroy",
"and",
"remove",
"a",
"connection",
"listener"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/core/src/main/java/org/ironjacamar/core/connectionmanager/pool/AbstractManagedConnectionPool.java#L165-L180 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/CmsHighlightingBorder.java | CmsHighlightingBorder.setPosition | public void setPosition(int height, int width, int positionLeft, int positionTop) {
positionLeft -= m_borderOffset;
// make sure highlighting does not introduce additional horizontal scroll-bars
if ((m_positioningParent == null) && (positionLeft < 0)) {
// position left should not be negative
width += positionLeft;
positionLeft = 0;
}
width += (2 * m_borderOffset) - BORDER_WIDTH;
if ((m_positioningParent == null)
&& (Window.getClientWidth() < (width + positionLeft))
&& (Window.getScrollLeft() == 0)) {
// highlighting should not extend over the right hand
width = Window.getClientWidth() - (positionLeft + BORDER_WIDTH);
}
Style style = getElement().getStyle();
style.setLeft(positionLeft, Unit.PX);
style.setTop(positionTop - m_borderOffset, Unit.PX);
setHeight((height + (2 * m_borderOffset)) - BORDER_WIDTH);
setWidth(width);
} | java | public void setPosition(int height, int width, int positionLeft, int positionTop) {
positionLeft -= m_borderOffset;
// make sure highlighting does not introduce additional horizontal scroll-bars
if ((m_positioningParent == null) && (positionLeft < 0)) {
// position left should not be negative
width += positionLeft;
positionLeft = 0;
}
width += (2 * m_borderOffset) - BORDER_WIDTH;
if ((m_positioningParent == null)
&& (Window.getClientWidth() < (width + positionLeft))
&& (Window.getScrollLeft() == 0)) {
// highlighting should not extend over the right hand
width = Window.getClientWidth() - (positionLeft + BORDER_WIDTH);
}
Style style = getElement().getStyle();
style.setLeft(positionLeft, Unit.PX);
style.setTop(positionTop - m_borderOffset, Unit.PX);
setHeight((height + (2 * m_borderOffset)) - BORDER_WIDTH);
setWidth(width);
} | [
"public",
"void",
"setPosition",
"(",
"int",
"height",
",",
"int",
"width",
",",
"int",
"positionLeft",
",",
"int",
"positionTop",
")",
"{",
"positionLeft",
"-=",
"m_borderOffset",
";",
"// make sure highlighting does not introduce additional horizontal scroll-bars",
"if"... | Sets the border position.<p>
@param height the height
@param width the width
@param positionLeft the absolute left position
@param positionTop the absolute top position | [
"Sets",
"the",
"border",
"position",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsHighlightingBorder.java#L256-L278 |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlBlockedDataReaderDAO.java | CqlBlockedDataReaderDAO.newRecordFromCql | private Record newRecordFromCql(Key key, Iterable<Row> rows, Placement placement, String rowKey) {
Session session = placement.getKeyspace().getCqlSession();
ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
CodecRegistry codecRegistry = session.getCluster().getConfiguration().getCodecRegistry();
Iterator<Map.Entry<DeltaClusteringKey, Change>> changeIter = decodeChangesFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
Iterator<Map.Entry<DeltaClusteringKey, Compaction>> compactionIter = decodeCompactionsFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
Iterator<RecordEntryRawMetadata> rawMetadataIter = rawMetadataFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
return new RecordImpl(key, compactionIter, changeIter, rawMetadataIter);
} | java | private Record newRecordFromCql(Key key, Iterable<Row> rows, Placement placement, String rowKey) {
Session session = placement.getKeyspace().getCqlSession();
ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
CodecRegistry codecRegistry = session.getCluster().getConfiguration().getCodecRegistry();
Iterator<Map.Entry<DeltaClusteringKey, Change>> changeIter = decodeChangesFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
Iterator<Map.Entry<DeltaClusteringKey, Compaction>> compactionIter = decodeCompactionsFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
Iterator<RecordEntryRawMetadata> rawMetadataIter = rawMetadataFromCql(new CqlDeltaIterator(rows.iterator(), BLOCK_RESULT_SET_COLUMN, CHANGE_ID_RESULT_SET_COLUMN, VALUE_RESULT_SET_COLUMN, false, _deltaPrefixLength, protocolVersion, codecRegistry, rowKey));
return new RecordImpl(key, compactionIter, changeIter, rawMetadataIter);
} | [
"private",
"Record",
"newRecordFromCql",
"(",
"Key",
"key",
",",
"Iterable",
"<",
"Row",
">",
"rows",
",",
"Placement",
"placement",
",",
"String",
"rowKey",
")",
"{",
"Session",
"session",
"=",
"placement",
".",
"getKeyspace",
"(",
")",
".",
"getCqlSession"... | Creates a Record instance for a given key and list of rows. All rows must be from the same Cassandra row;
in other words, it is expected that row.getBytesUnsafe(ROW_KEY_RESULT_SET_COLUMN) returns the same value for
each row in rows. | [
"Creates",
"a",
"Record",
"instance",
"for",
"a",
"given",
"key",
"and",
"list",
"of",
"rows",
".",
"All",
"rows",
"must",
"be",
"from",
"the",
"same",
"Cassandra",
"row",
";",
"in",
"other",
"words",
"it",
"is",
"expected",
"that",
"row",
".",
"getByt... | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlBlockedDataReaderDAO.java#L248-L258 |
roboconf/roboconf-platform | core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java | Utils.copyStreamSafely | public static void copyStreamSafely( InputStream in, ByteArrayOutputStream os ) throws IOException {
try {
copyStreamUnsafelyUseWithCaution( in, os );
} finally {
in.close();
}
} | java | public static void copyStreamSafely( InputStream in, ByteArrayOutputStream os ) throws IOException {
try {
copyStreamUnsafelyUseWithCaution( in, os );
} finally {
in.close();
}
} | [
"public",
"static",
"void",
"copyStreamSafely",
"(",
"InputStream",
"in",
",",
"ByteArrayOutputStream",
"os",
")",
"throws",
"IOException",
"{",
"try",
"{",
"copyStreamUnsafelyUseWithCaution",
"(",
"in",
",",
"os",
")",
";",
"}",
"finally",
"{",
"in",
".",
"cl... | Copies the content from in into os.
<p>
This method closes the input stream.
<i>os</i> does not need to be closed.
</p>
@param in an input stream (not null)
@param os an output stream (not null)
@throws IOException if an error occurred | [
"Copies",
"the",
"content",
"from",
"in",
"into",
"os",
".",
"<p",
">",
"This",
"method",
"closes",
"the",
"input",
"stream",
".",
"<i",
">",
"os<",
"/",
"i",
">",
"does",
"not",
"need",
"to",
"be",
"closed",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L332-L340 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java | ApiOvhDedicatedCloud.serviceName_user_userId_changeProperties_POST | public OvhTask serviceName_user_userId_changeProperties_POST(String serviceName, Long userId, Boolean canManageIpFailOvers, Boolean canManageNetwork, Boolean canManageRights, String email, String firstName, Boolean fullAdminRo, String lastName, Boolean nsxRight, String phoneNumber, Boolean receiveAlerts, Boolean tokenValidator) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/user/{userId}/changeProperties";
StringBuilder sb = path(qPath, serviceName, userId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "canManageIpFailOvers", canManageIpFailOvers);
addBody(o, "canManageNetwork", canManageNetwork);
addBody(o, "canManageRights", canManageRights);
addBody(o, "email", email);
addBody(o, "firstName", firstName);
addBody(o, "fullAdminRo", fullAdminRo);
addBody(o, "lastName", lastName);
addBody(o, "nsxRight", nsxRight);
addBody(o, "phoneNumber", phoneNumber);
addBody(o, "receiveAlerts", receiveAlerts);
addBody(o, "tokenValidator", tokenValidator);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_user_userId_changeProperties_POST(String serviceName, Long userId, Boolean canManageIpFailOvers, Boolean canManageNetwork, Boolean canManageRights, String email, String firstName, Boolean fullAdminRo, String lastName, Boolean nsxRight, String phoneNumber, Boolean receiveAlerts, Boolean tokenValidator) throws IOException {
String qPath = "/dedicatedCloud/{serviceName}/user/{userId}/changeProperties";
StringBuilder sb = path(qPath, serviceName, userId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "canManageIpFailOvers", canManageIpFailOvers);
addBody(o, "canManageNetwork", canManageNetwork);
addBody(o, "canManageRights", canManageRights);
addBody(o, "email", email);
addBody(o, "firstName", firstName);
addBody(o, "fullAdminRo", fullAdminRo);
addBody(o, "lastName", lastName);
addBody(o, "nsxRight", nsxRight);
addBody(o, "phoneNumber", phoneNumber);
addBody(o, "receiveAlerts", receiveAlerts);
addBody(o, "tokenValidator", tokenValidator);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_user_userId_changeProperties_POST",
"(",
"String",
"serviceName",
",",
"Long",
"userId",
",",
"Boolean",
"canManageIpFailOvers",
",",
"Boolean",
"canManageNetwork",
",",
"Boolean",
"canManageRights",
",",
"String",
"email",
",",
"String",... | Change Private Cloud user properties
REST: POST /dedicatedCloud/{serviceName}/user/{userId}/changeProperties
@param fullAdminRo [required] Defines if the user is a full admin in readonly
@param canManageNetwork [required] Defines if the user can manage the network
@param canManageRights [required] Defines if the user can manage the users rights
@param receiveAlerts [required] Defines if the user receives technical alerts
@param nsxRight [required] Is this User able to access nsx interface (requires NSX option)
@param tokenValidator [required] Defines if the user can confirm security tokens (if a compatible option is enabled)
@param lastName [required] Last name of the user
@param firstName [required] First name of the user
@param phoneNumber [required] Mobile phone number of the user in international format (+prefix.number)
@param email [required] Email address of the user
@param canManageIpFailOvers [required] Defines if the user can manage ip failovers
@param serviceName [required] Domain of the service
@param userId [required] | [
"Change",
"Private",
"Cloud",
"user",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L801-L818 |
fommil/matrix-toolkits-java | src/main/java/no/uib/cipr/matrix/io/MatrixVectorWriter.java | MatrixVectorWriter.printPattern | public void printPattern(int[] index, int offset) {
int size = index.length;
for (int i = 0; i < size; ++i)
format(Locale.ENGLISH, "%10d%n", index[i] + offset);
} | java | public void printPattern(int[] index, int offset) {
int size = index.length;
for (int i = 0; i < size; ++i)
format(Locale.ENGLISH, "%10d%n", index[i] + offset);
} | [
"public",
"void",
"printPattern",
"(",
"int",
"[",
"]",
"index",
",",
"int",
"offset",
")",
"{",
"int",
"size",
"=",
"index",
".",
"length",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"++",
"i",
")",
"format",
"(",
"Loca... | Prints the coordinates to the underlying stream. One index on each line.
The offset is added to each index, typically, this can transform from a
0-based indicing to a 1-based. | [
"Prints",
"the",
"coordinates",
"to",
"the",
"underlying",
"stream",
".",
"One",
"index",
"on",
"each",
"line",
".",
"The",
"offset",
"is",
"added",
"to",
"each",
"index",
"typically",
"this",
"can",
"transform",
"from",
"a",
"0",
"-",
"based",
"indicing",... | train | https://github.com/fommil/matrix-toolkits-java/blob/6157618bc86bcda3749af2a60bf869d8f3292960/src/main/java/no/uib/cipr/matrix/io/MatrixVectorWriter.java#L400-L404 |
zandero/settings | src/main/java/com/zandero/settings/Settings.java | Settings.getInt | public int getInt(String name) {
Object value = super.get(name);
if (value instanceof Integer) {
return (Integer) value;
}
if (value == null) {
throw new IllegalArgumentException("Setting: '" + name + "', not found!");
}
try {
return Integer.parseInt(value.toString());
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Setting: '" + name + "', can't be converted to integer: '" + value + "'!");
}
} | java | public int getInt(String name) {
Object value = super.get(name);
if (value instanceof Integer) {
return (Integer) value;
}
if (value == null) {
throw new IllegalArgumentException("Setting: '" + name + "', not found!");
}
try {
return Integer.parseInt(value.toString());
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Setting: '" + name + "', can't be converted to integer: '" + value + "'!");
}
} | [
"public",
"int",
"getInt",
"(",
"String",
"name",
")",
"{",
"Object",
"value",
"=",
"super",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"value",
"instanceof",
"Integer",
")",
"{",
"return",
"(",
"Integer",
")",
"value",
";",
"}",
"if",
"(",
"val... | Get setting as integer
@param name setting key
@return setting value as integer
@throws IllegalArgumentException is setting is not present or can not be converted to an integer | [
"Get",
"setting",
"as",
"integer"
] | train | https://github.com/zandero/settings/blob/802b44f41bc75e7eb2761028db8c73b7e59620c7/src/main/java/com/zandero/settings/Settings.java#L68-L86 |
dadoonet/elasticsearch-beyonder | src/main/java/fr/pilato/elasticsearch/tools/index/IndexElasticsearchUpdater.java | IndexElasticsearchUpdater.createIndex | public static void createIndex(RestClient client, String index, boolean force) throws Exception {
String settings = IndexSettingsReader.readSettings(index);
createIndexWithSettings(client, index, settings, force);
} | java | public static void createIndex(RestClient client, String index, boolean force) throws Exception {
String settings = IndexSettingsReader.readSettings(index);
createIndexWithSettings(client, index, settings, force);
} | [
"public",
"static",
"void",
"createIndex",
"(",
"RestClient",
"client",
",",
"String",
"index",
",",
"boolean",
"force",
")",
"throws",
"Exception",
"{",
"String",
"settings",
"=",
"IndexSettingsReader",
".",
"readSettings",
"(",
"index",
")",
";",
"createIndexW... | Create a new index in Elasticsearch. Read also _settings.json if exists in default classpath dir.
@param client Elasticsearch client
@param index Index name
@param force Remove index if exists (Warning: remove all data)
@throws Exception if the elasticsearch API call is failing | [
"Create",
"a",
"new",
"index",
"in",
"Elasticsearch",
".",
"Read",
"also",
"_settings",
".",
"json",
"if",
"exists",
"in",
"default",
"classpath",
"dir",
"."
] | train | https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/index/IndexElasticsearchUpdater.java#L222-L225 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/query/Criteria.java | Criteria.addIn | public void addIn(String attribute, Collection values)
{
List list = splitInCriteria(attribute, values, false, IN_LIMIT);
int index = 0;
InCriteria inCrit;
Criteria allInCritaria;
inCrit = (InCriteria) list.get(index);
allInCritaria = new Criteria(inCrit);
for (index = 1; index < list.size(); index++)
{
inCrit = (InCriteria) list.get(index);
allInCritaria.addOrCriteria(new Criteria(inCrit));
}
addAndCriteria(allInCritaria);
} | java | public void addIn(String attribute, Collection values)
{
List list = splitInCriteria(attribute, values, false, IN_LIMIT);
int index = 0;
InCriteria inCrit;
Criteria allInCritaria;
inCrit = (InCriteria) list.get(index);
allInCritaria = new Criteria(inCrit);
for (index = 1; index < list.size(); index++)
{
inCrit = (InCriteria) list.get(index);
allInCritaria.addOrCriteria(new Criteria(inCrit));
}
addAndCriteria(allInCritaria);
} | [
"public",
"void",
"addIn",
"(",
"String",
"attribute",
",",
"Collection",
"values",
")",
"{",
"List",
"list",
"=",
"splitInCriteria",
"(",
"attribute",
",",
"values",
",",
"false",
",",
"IN_LIMIT",
")",
";",
"int",
"index",
"=",
"0",
";",
"InCriteria",
"... | Adds IN criteria,
customer_id in(1,10,33,44)
large values are split into multiple InCriteria
IN (1,10) OR IN(33, 44)
@param attribute The field name to be used
@param values The value Collection | [
"Adds",
"IN",
"criteria",
"customer_id",
"in",
"(",
"1",
"10",
"33",
"44",
")",
"large",
"values",
"are",
"split",
"into",
"multiple",
"InCriteria",
"IN",
"(",
"1",
"10",
")",
"OR",
"IN",
"(",
"33",
"44",
")"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L766-L783 |
geomajas/geomajas-project-server | plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/PdfContext.java | PdfContext.fillEllipse | public void fillEllipse(Rectangle rect, Color color) {
template.saveState();
setFill(color);
template.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),
origY + rect.getTop());
template.fill();
template.restoreState();
} | java | public void fillEllipse(Rectangle rect, Color color) {
template.saveState();
setFill(color);
template.ellipse(origX + rect.getLeft(), origY + rect.getBottom(), origX + rect.getRight(),
origY + rect.getTop());
template.fill();
template.restoreState();
} | [
"public",
"void",
"fillEllipse",
"(",
"Rectangle",
"rect",
",",
"Color",
"color",
")",
"{",
"template",
".",
"saveState",
"(",
")",
";",
"setFill",
"(",
"color",
")",
";",
"template",
".",
"ellipse",
"(",
"origX",
"+",
"rect",
".",
"getLeft",
"(",
")",... | Draw an elliptical interior with this color.
@param rect rectangle in which ellipse should fit
@param color colour to use for filling | [
"Draw",
"an",
"elliptical",
"interior",
"with",
"this",
"color",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/PdfContext.java#L286-L293 |
mapsforge/mapsforge | mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/Cluster.java | Cluster.addItem | public synchronized void addItem(T item) {
synchronized (items) {
items.add(item);
}
// clusterMarker.setMarkerBitmap();
if (center == null) {
center = item.getLatLong();
} else {
// computing the centroid
double lat = 0, lon = 0;
int n = 0;
synchronized (items) {
for (T object : items) {
if (object == null) {
throw new NullPointerException("object == null");
}
if (object.getLatLong() == null) {
throw new NullPointerException("object.getLatLong() == null");
}
lat += object.getLatLong().latitude;
lon += object.getLatLong().longitude;
n++;
}
}
center = new LatLong(lat / n, lon / n);
}
} | java | public synchronized void addItem(T item) {
synchronized (items) {
items.add(item);
}
// clusterMarker.setMarkerBitmap();
if (center == null) {
center = item.getLatLong();
} else {
// computing the centroid
double lat = 0, lon = 0;
int n = 0;
synchronized (items) {
for (T object : items) {
if (object == null) {
throw new NullPointerException("object == null");
}
if (object.getLatLong() == null) {
throw new NullPointerException("object.getLatLong() == null");
}
lat += object.getLatLong().latitude;
lon += object.getLatLong().longitude;
n++;
}
}
center = new LatLong(lat / n, lon / n);
}
} | [
"public",
"synchronized",
"void",
"addItem",
"(",
"T",
"item",
")",
"{",
"synchronized",
"(",
"items",
")",
"{",
"items",
".",
"add",
"(",
"item",
")",
";",
"}",
"// clusterMarker.setMarkerBitmap();",
"if",
"(",
"center",
"==",
"null",
")",
"{",
"ce... | add item to cluster object
@param item GeoItem object to be added. | [
"add",
"item",
"to",
"cluster",
"object"
] | train | https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/Cluster.java#L73-L99 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201902/creativeservice/GetImageCreatives.java | GetImageCreatives.runExample | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
CreativeServiceInterface creativeService =
adManagerServices.get(session, CreativeServiceInterface.class);
// Create a statement to select creatives.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("creativeType = :creativeType")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("creativeType", "ImageCreative");
// Retrieve a small amount of creatives at a time, paging through
// until all creatives have been retrieved.
int totalResultSetSize = 0;
do {
CreativePage page = creativeService.getCreativesByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each creative.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (Creative creative : page.getResults()) {
System.out.printf(
"%d) Creative with ID %d and name '%s' was found.%n",
i++, creative.getId(), creative.getName());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
CreativeServiceInterface creativeService =
adManagerServices.get(session, CreativeServiceInterface.class);
// Create a statement to select creatives.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("creativeType = :creativeType")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("creativeType", "ImageCreative");
// Retrieve a small amount of creatives at a time, paging through
// until all creatives have been retrieved.
int totalResultSetSize = 0;
do {
CreativePage page = creativeService.getCreativesByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each creative.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (Creative creative : page.getResults()) {
System.out.printf(
"%d) Creative with ID %d and name '%s' was found.%n",
i++, creative.getId(), creative.getName());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"RemoteException",
"{",
"CreativeServiceInterface",
"creativeService",
"=",
"adManagerServices",
".",
"get",
"(",
"session",
",",
... | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201902/creativeservice/GetImageCreatives.java#L51-L85 |
killbilling/recurly-java-library | src/main/java/com/ning/billing/recurly/RecurlyClient.java | RecurlyClient.getSubscriptionUsages | public Usages getSubscriptionUsages(final String subscriptionCode, final String addOnCode, final QueryParams params) {
return doGET(Subscription.SUBSCRIPTION_RESOURCE +
"/" +
subscriptionCode +
AddOn.ADDONS_RESOURCE +
"/" +
addOnCode +
Usage.USAGE_RESOURCE, Usages.class, params );
} | java | public Usages getSubscriptionUsages(final String subscriptionCode, final String addOnCode, final QueryParams params) {
return doGET(Subscription.SUBSCRIPTION_RESOURCE +
"/" +
subscriptionCode +
AddOn.ADDONS_RESOURCE +
"/" +
addOnCode +
Usage.USAGE_RESOURCE, Usages.class, params );
} | [
"public",
"Usages",
"getSubscriptionUsages",
"(",
"final",
"String",
"subscriptionCode",
",",
"final",
"String",
"addOnCode",
",",
"final",
"QueryParams",
"params",
")",
"{",
"return",
"doGET",
"(",
"Subscription",
".",
"SUBSCRIPTION_RESOURCE",
"+",
"\"/\"",
"+",
... | Get Subscription Addon Usages
<p>
@param subscriptionCode The recurly id of the {@link Subscription }
@param addOnCode recurly id of {@link AddOn}
@return {@link Usages} for the specified subscription and addOn | [
"Get",
"Subscription",
"Addon",
"Usages",
"<p",
">"
] | train | https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L728-L736 |
rundeck/rundeck | rundeckapp/src/main/groovy/com/dtolabs/rundeck/jetty/jaas/JNDILoginModule.java | JNDILoginModule.getUserInfo | public UserInfo getUserInfo(String username) throws Exception {
DirContext dir = context();
ArrayList roleList = new ArrayList(getUserRoles(username));
String credentials = getUserCredentials(username);
return new UserInfo(username, Credential.getCredential(credentials), roleList);
} | java | public UserInfo getUserInfo(String username) throws Exception {
DirContext dir = context();
ArrayList roleList = new ArrayList(getUserRoles(username));
String credentials = getUserCredentials(username);
return new UserInfo(username, Credential.getCredential(credentials), roleList);
} | [
"public",
"UserInfo",
"getUserInfo",
"(",
"String",
"username",
")",
"throws",
"Exception",
"{",
"DirContext",
"dir",
"=",
"context",
"(",
")",
";",
"ArrayList",
"roleList",
"=",
"new",
"ArrayList",
"(",
"getUserRoles",
"(",
"username",
")",
")",
";",
"Strin... | Get the UserInfo for a specified username
@param username username
@return the UserInfo
@throws Exception | [
"Get",
"the",
"UserInfo",
"for",
"a",
"specified",
"username"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/rundeckapp/src/main/groovy/com/dtolabs/rundeck/jetty/jaas/JNDILoginModule.java#L64-L70 |
aws/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/iterable/S3Versions.java | S3Versions.withPrefix | public static S3Versions withPrefix(AmazonS3 s3, String bucketName,
String prefix) {
S3Versions versions = new S3Versions(s3, bucketName);
versions.prefix = prefix;
return versions;
} | java | public static S3Versions withPrefix(AmazonS3 s3, String bucketName,
String prefix) {
S3Versions versions = new S3Versions(s3, bucketName);
versions.prefix = prefix;
return versions;
} | [
"public",
"static",
"S3Versions",
"withPrefix",
"(",
"AmazonS3",
"s3",
",",
"String",
"bucketName",
",",
"String",
"prefix",
")",
"{",
"S3Versions",
"versions",
"=",
"new",
"S3Versions",
"(",
"s3",
",",
"bucketName",
")",
";",
"versions",
".",
"prefix",
"=",... | Constructs an iterable that covers the versions in an Amazon S3 bucket
where the object key begins with the given prefix.
@param s3
The Amazon S3 client.
@param bucketName
The bucket name.
@param prefix
The prefix.
@return An iterator for object version summaries. | [
"Constructs",
"an",
"iterable",
"that",
"covers",
"the",
"versions",
"in",
"an",
"Amazon",
"S3",
"bucket",
"where",
"the",
"object",
"key",
"begins",
"with",
"the",
"given",
"prefix",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/iterable/S3Versions.java#L77-L82 |
apereo/cas | support/cas-server-support-throttle-core/src/main/java/org/apereo/cas/web/support/AbstractThrottledSubmissionHandlerInterceptorAdapter.java | AbstractThrottledSubmissionHandlerInterceptorAdapter.recordAuditAction | protected void recordAuditAction(final HttpServletRequest request, final String actionName) {
val userToUse = getUsernameParameterFromRequest(request);
val clientInfo = ClientInfoHolder.getClientInfo();
val resource = StringUtils.defaultString(request.getParameter(CasProtocolConstants.PARAMETER_SERVICE), "N/A");
val context = new AuditActionContext(
userToUse,
resource,
actionName,
configurationContext.getApplicationCode(),
DateTimeUtils.dateOf(ZonedDateTime.now(ZoneOffset.UTC)),
clientInfo.getClientIpAddress(),
clientInfo.getServerIpAddress());
LOGGER.debug("Recording throttled audit action [{}}", context);
configurationContext.getAuditTrailExecutionPlan().record(context);
} | java | protected void recordAuditAction(final HttpServletRequest request, final String actionName) {
val userToUse = getUsernameParameterFromRequest(request);
val clientInfo = ClientInfoHolder.getClientInfo();
val resource = StringUtils.defaultString(request.getParameter(CasProtocolConstants.PARAMETER_SERVICE), "N/A");
val context = new AuditActionContext(
userToUse,
resource,
actionName,
configurationContext.getApplicationCode(),
DateTimeUtils.dateOf(ZonedDateTime.now(ZoneOffset.UTC)),
clientInfo.getClientIpAddress(),
clientInfo.getServerIpAddress());
LOGGER.debug("Recording throttled audit action [{}}", context);
configurationContext.getAuditTrailExecutionPlan().record(context);
} | [
"protected",
"void",
"recordAuditAction",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"String",
"actionName",
")",
"{",
"val",
"userToUse",
"=",
"getUsernameParameterFromRequest",
"(",
"request",
")",
";",
"val",
"clientInfo",
"=",
"ClientInfoHolder",... | Records an audit action.
@param request The current HTTP request.
@param actionName Name of the action to be recorded. | [
"Records",
"an",
"audit",
"action",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-throttle-core/src/main/java/org/apereo/cas/web/support/AbstractThrottledSubmissionHandlerInterceptorAdapter.java#L181-L195 |
hortonworks/dstream | dstream-api/src/main/java/io/dstream/DStreamOperation.java | DStreamOperation.addStreamOperationFunction | @SuppressWarnings("unchecked")
void addStreamOperationFunction(String operationName, SerFunction<?,?> function){
this.operationNames.add(operationName);
this.streamOperationFunction = this.streamOperationFunction != null
? this.streamOperationFunction.andThen(function)
: function;
if (function instanceof KeyValueMappingFunction){
if ( ((KeyValueMappingFunction<?,?,?>)function).aggregatesValues() ) {
String lastOperationName = this.operationNames.get(this.operationNames.size()-1);
lastOperationName = lastOperationName + "{reducingValues}";
this.operationNames.set(this.operationNames.size()-1, lastOperationName);
}
}
} | java | @SuppressWarnings("unchecked")
void addStreamOperationFunction(String operationName, SerFunction<?,?> function){
this.operationNames.add(operationName);
this.streamOperationFunction = this.streamOperationFunction != null
? this.streamOperationFunction.andThen(function)
: function;
if (function instanceof KeyValueMappingFunction){
if ( ((KeyValueMappingFunction<?,?,?>)function).aggregatesValues() ) {
String lastOperationName = this.operationNames.get(this.operationNames.size()-1);
lastOperationName = lastOperationName + "{reducingValues}";
this.operationNames.set(this.operationNames.size()-1, lastOperationName);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"void",
"addStreamOperationFunction",
"(",
"String",
"operationName",
",",
"SerFunction",
"<",
"?",
",",
"?",
">",
"function",
")",
"{",
"this",
".",
"operationNames",
".",
"add",
"(",
"operationName",
")",
"... | Will add the given {@link SerFunction} to this {@link DStreamOperation} by
composing it with the previous function. If previous function is <i>null</i>
the given function becomes the root function of this operation.<br>
It also adds the given <i>operationName</i> to the list of operation names
which composes this {@link DStreamOperation}.<br>
The final (composed) function represents the function to applied on the
localized {@link Stream} of data processed by a target task. | [
"Will",
"add",
"the",
"given",
"{"
] | train | https://github.com/hortonworks/dstream/blob/3a106c0f14725b028fe7fe2dbc660406d9a5f142/dstream-api/src/main/java/io/dstream/DStreamOperation.java#L179-L193 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201808/reconciliationreportservice/GetAllReconciliationReports.java | GetAllReconciliationReports.runExample | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the ReconciliationReportService.
ReconciliationReportServiceInterface reconciliationReportService =
adManagerServices.get(session, ReconciliationReportServiceInterface.class);
// Create a statement to select all reconciliation reports.
StatementBuilder statementBuilder = new StatementBuilder()
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get reconciliation reports by statement.
ReconciliationReportPage page =
reconciliationReportService.getReconciliationReportsByStatement(
statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (ReconciliationReport reconciliationReport : page.getResults()) {
System.out.printf(
"%d) Reconciliation report with ID %d for month %d/%d was found.%n",
i++,
reconciliationReport.getId(),
reconciliationReport.getStartDate().getMonth(),
reconciliationReport.getStartDate().getYear());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
// Get the ReconciliationReportService.
ReconciliationReportServiceInterface reconciliationReportService =
adManagerServices.get(session, ReconciliationReportServiceInterface.class);
// Create a statement to select all reconciliation reports.
StatementBuilder statementBuilder = new StatementBuilder()
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get reconciliation reports by statement.
ReconciliationReportPage page =
reconciliationReportService.getReconciliationReportsByStatement(
statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (ReconciliationReport reconciliationReport : page.getResults()) {
System.out.printf(
"%d) Reconciliation report with ID %d for month %d/%d was found.%n",
i++,
reconciliationReport.getId(),
reconciliationReport.getStartDate().getMonth(),
reconciliationReport.getStartDate().getYear());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"RemoteException",
"{",
"// Get the ReconciliationReportService.",
"ReconciliationReportServiceInterface",
"reconciliationReportService",
"=",... | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/reconciliationreportservice/GetAllReconciliationReports.java#L51-L88 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/SerializationUtil.java | SerializationUtil.writeNullableCollection | public static <T> void writeNullableCollection(Collection<T> items, ObjectDataOutput out) throws IOException {
// write true when the collection is NOT null
out.writeBoolean(items != null);
if (items == null) {
return;
}
writeCollection(items, out);
} | java | public static <T> void writeNullableCollection(Collection<T> items, ObjectDataOutput out) throws IOException {
// write true when the collection is NOT null
out.writeBoolean(items != null);
if (items == null) {
return;
}
writeCollection(items, out);
} | [
"public",
"static",
"<",
"T",
">",
"void",
"writeNullableCollection",
"(",
"Collection",
"<",
"T",
">",
"items",
",",
"ObjectDataOutput",
"out",
")",
"throws",
"IOException",
"{",
"// write true when the collection is NOT null",
"out",
".",
"writeBoolean",
"(",
"ite... | Writes a collection to an {@link ObjectDataOutput}. The collection's size is written
to the data output, then each object in the collection is serialized.
The collection is allowed to be null.
@param items collection of items to be serialized
@param out data output to write to
@param <T> type of items
@throws IOException when an error occurs while writing to the output | [
"Writes",
"a",
"collection",
"to",
"an",
"{",
"@link",
"ObjectDataOutput",
"}",
".",
"The",
"collection",
"s",
"size",
"is",
"written",
"to",
"the",
"data",
"output",
"then",
"each",
"object",
"in",
"the",
"collection",
"is",
"serialized",
".",
"The",
"col... | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/SerializationUtil.java#L215-L222 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.listModelsWithServiceResponseAsync | public Observable<ServiceResponse<List<ModelInfoResponse>>> listModelsWithServiceResponseAsync(UUID appId, String versionId, ListModelsOptionalParameter listModelsOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final Integer skip = listModelsOptionalParameter != null ? listModelsOptionalParameter.skip() : null;
final Integer take = listModelsOptionalParameter != null ? listModelsOptionalParameter.take() : null;
return listModelsWithServiceResponseAsync(appId, versionId, skip, take);
} | java | public Observable<ServiceResponse<List<ModelInfoResponse>>> listModelsWithServiceResponseAsync(UUID appId, String versionId, ListModelsOptionalParameter listModelsOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
final Integer skip = listModelsOptionalParameter != null ? listModelsOptionalParameter.skip() : null;
final Integer take = listModelsOptionalParameter != null ? listModelsOptionalParameter.take() : null;
return listModelsWithServiceResponseAsync(appId, versionId, skip, take);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"List",
"<",
"ModelInfoResponse",
">",
">",
">",
"listModelsWithServiceResponseAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"ListModelsOptionalParameter",
"listModelsOptionalParameter",
")",
"{",
"if... | Gets information about the application version models.
@param appId The application ID.
@param versionId The version ID.
@param listModelsOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<ModelInfoResponse> object | [
"Gets",
"information",
"about",
"the",
"application",
"version",
"models",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L2490-L2504 |
jcuda/jcufft | JCufftJava/src/main/java/jcuda/jcufft/JCufft.java | JCufft.cufftExecZ2D | public static int cufftExecZ2D(cufftHandle plan, Pointer cIdata, Pointer rOdata)
{
return checkResult(cufftExecZ2DNative(plan, cIdata, rOdata));
} | java | public static int cufftExecZ2D(cufftHandle plan, Pointer cIdata, Pointer rOdata)
{
return checkResult(cufftExecZ2DNative(plan, cIdata, rOdata));
} | [
"public",
"static",
"int",
"cufftExecZ2D",
"(",
"cufftHandle",
"plan",
",",
"Pointer",
"cIdata",
",",
"Pointer",
"rOdata",
")",
"{",
"return",
"checkResult",
"(",
"cufftExecZ2DNative",
"(",
"plan",
",",
"cIdata",
",",
"rOdata",
")",
")",
";",
"}"
] | <pre>
Executes a CUFFT complex-to-real (implicitly inverse) transform plan
for double precision values.
cufftResult cufftExecZ2D( cufftHandle plan, cufftDoubleComplex *idata, cufftDoubleReal *odata );
CUFFT uses as input data the GPU memory pointed to by the idata
parameter. The input array holds only the non-redundant complex
Fourier coefficients. This function stores the real output values in the
odata array. If idata and odata are the same, this method does an inplace
transform. (See CUFFT documentation for details on real data FFTs.)
Input
----
plan The cufftHandle object for the plan to update
idata Pointer to the complex input data (in GPU memory) to transform
odata Pointer to the real output data (in GPU memory)
Output
----
odata Contains the real-valued output data
Return Values
----
CUFFT_SETUP_FAILED CUFFT library failed to initialize.
CUFFT_INVALID_PLAN The plan parameter is not a valid handle.
CUFFT_INVALID_VALUE The idata and/or odata parameter is not valid.
CUFFT_EXEC_FAILED CUFFT failed to execute the transform on GPU.
CUFFT_SUCCESS CUFFT successfully executed the FFT plan.
JCUFFT_INTERNAL_ERROR If an internal JCufft error occurred
<pre> | [
"<pre",
">",
"Executes",
"a",
"CUFFT",
"complex",
"-",
"to",
"-",
"real",
"(",
"implicitly",
"inverse",
")",
"transform",
"plan",
"for",
"double",
"precision",
"values",
"."
] | train | https://github.com/jcuda/jcufft/blob/833c87ffb0864f7ee7270fddef8af57f48939b3a/JCufftJava/src/main/java/jcuda/jcufft/JCufft.java#L1665-L1668 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/Indices.java | Indices.rowNumber | public static int rowNumber(int index, INDArray arr) {
double otherTest = ((double) index) / arr.size(-1);
int test = (int) Math.floor(otherTest);
// FIXME: int cast
int vectors = (int) arr.vectorsAlongDimension(-1);
if (test >= vectors)
return vectors - 1;
return test;
} | java | public static int rowNumber(int index, INDArray arr) {
double otherTest = ((double) index) / arr.size(-1);
int test = (int) Math.floor(otherTest);
// FIXME: int cast
int vectors = (int) arr.vectorsAlongDimension(-1);
if (test >= vectors)
return vectors - 1;
return test;
} | [
"public",
"static",
"int",
"rowNumber",
"(",
"int",
"index",
",",
"INDArray",
"arr",
")",
"{",
"double",
"otherTest",
"=",
"(",
"(",
"double",
")",
"index",
")",
"/",
"arr",
".",
"size",
"(",
"-",
"1",
")",
";",
"int",
"test",
"=",
"(",
"int",
")... | Compute the linear offset
for an index in an ndarray.
For c ordering this is just the index itself.
For fortran ordering, the following algorithm is used.
Assuming an ndarray is a list of vectors.
The index of the vector relative to the given index is calculated.
vectorAlongDimension is then used along the last dimension
using the computed index.
The offset + the computed column wrt the index: (index % the size of the last dimension)
will render the given index in fortran ordering
@param index the index
@param arr the array
@return the linear offset | [
"Compute",
"the",
"linear",
"offset",
"for",
"an",
"index",
"in",
"an",
"ndarray",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/Indices.java#L58-L68 |
belaban/JGroups | src/org/jgroups/util/Table.java | Table.forEach | @GuardedBy("lock")
public void forEach(long from, long to, Visitor<T> visitor) {
if(from - to > 0) // same as if(from > to), but prevents long overflow
return;
int row=computeRow(from), column=computeIndex(from);
int distance=(int)(to - from +1);
T[] current_row=row+1 > matrix.length? null : matrix[row];
for(int i=0; i < distance; i++) {
T element=current_row == null? null : current_row[column];
if(!visitor.visit(from, element, row, column))
break;
from++;
if(++column >= elements_per_row) {
column=0;
row++;
current_row=row+1 > matrix.length? null : matrix[row];
}
}
} | java | @GuardedBy("lock")
public void forEach(long from, long to, Visitor<T> visitor) {
if(from - to > 0) // same as if(from > to), but prevents long overflow
return;
int row=computeRow(from), column=computeIndex(from);
int distance=(int)(to - from +1);
T[] current_row=row+1 > matrix.length? null : matrix[row];
for(int i=0; i < distance; i++) {
T element=current_row == null? null : current_row[column];
if(!visitor.visit(from, element, row, column))
break;
from++;
if(++column >= elements_per_row) {
column=0;
row++;
current_row=row+1 > matrix.length? null : matrix[row];
}
}
} | [
"@",
"GuardedBy",
"(",
"\"lock\"",
")",
"public",
"void",
"forEach",
"(",
"long",
"from",
",",
"long",
"to",
",",
"Visitor",
"<",
"T",
">",
"visitor",
")",
"{",
"if",
"(",
"from",
"-",
"to",
">",
"0",
")",
"// same as if(from > to), but prevents long overf... | Iterates over the matrix with range [from .. to] (including from and to), and calls
{@link Visitor#visit(long,Object,int,int)}. If the visit() method returns false, the iteration is terminated.
<p/>
This method must be called with the lock held
@param from The starting seqno
@param to The ending seqno, the range is [from .. to] including from and to
@param visitor An instance of Visitor | [
"Iterates",
"over",
"the",
"matrix",
"with",
"range",
"[",
"from",
"..",
"to",
"]",
"(",
"including",
"from",
"and",
"to",
")",
"and",
"calls",
"{"
] | train | https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/Table.java#L487-L507 |
LGoodDatePicker/LGoodDatePicker | Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java | FormLayout.layoutComponents | private void layoutComponents(int[] x, int[] y) {
Rectangle cellBounds = new Rectangle();
for (Object element : constraintMap.entrySet()) {
Map.Entry entry = (Map.Entry) element;
Component component = (Component) entry.getKey();
CellConstraints constraints = (CellConstraints) entry.getValue();
int gridX = constraints.gridX - 1;
int gridY = constraints.gridY - 1;
int gridWidth = constraints.gridWidth;
int gridHeight = constraints.gridHeight;
cellBounds.x = x[gridX];
cellBounds.y = y[gridY];
cellBounds.width = x[gridX + gridWidth] - cellBounds.x;
cellBounds.height = y[gridY + gridHeight] - cellBounds.y;
constraints.setBounds(component, this, cellBounds,
minimumWidthMeasure, minimumHeightMeasure,
preferredWidthMeasure, preferredHeightMeasure);
}
} | java | private void layoutComponents(int[] x, int[] y) {
Rectangle cellBounds = new Rectangle();
for (Object element : constraintMap.entrySet()) {
Map.Entry entry = (Map.Entry) element;
Component component = (Component) entry.getKey();
CellConstraints constraints = (CellConstraints) entry.getValue();
int gridX = constraints.gridX - 1;
int gridY = constraints.gridY - 1;
int gridWidth = constraints.gridWidth;
int gridHeight = constraints.gridHeight;
cellBounds.x = x[gridX];
cellBounds.y = y[gridY];
cellBounds.width = x[gridX + gridWidth] - cellBounds.x;
cellBounds.height = y[gridY + gridHeight] - cellBounds.y;
constraints.setBounds(component, this, cellBounds,
minimumWidthMeasure, minimumHeightMeasure,
preferredWidthMeasure, preferredHeightMeasure);
}
} | [
"private",
"void",
"layoutComponents",
"(",
"int",
"[",
"]",
"x",
",",
"int",
"[",
"]",
"y",
")",
"{",
"Rectangle",
"cellBounds",
"=",
"new",
"Rectangle",
"(",
")",
";",
"for",
"(",
"Object",
"element",
":",
"constraintMap",
".",
"entrySet",
"(",
")",
... | Lays out the components using the given x and y origins, the column and row specifications,
and the component constraints.<p>
The actual computation is done by each component's form constraint object. We just compute
the cell, the cell bounds and then hand over the component, cell bounds, and measure to the
form constraints. This will allow potential subclasses of {@code CellConstraints} to do
special micro-layout corrections. For example, such a subclass could map JComponent classes
to visual layout bounds that may lead to a slightly different bounds.
@param x an int array of the horizontal origins
@param y an int array of the vertical origins | [
"Lays",
"out",
"the",
"components",
"using",
"the",
"given",
"x",
"and",
"y",
"origins",
"the",
"column",
"and",
"row",
"specifications",
"and",
"the",
"component",
"constraints",
".",
"<p",
">"
] | train | https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java#L1389-L1409 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheOnDisk.java | CacheOnDisk.writeTemplate | public int writeTemplate(String template, ValueSet vs) {
int returnCode = htod.writeTemplate(template, vs);
if (returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(this.htod.diskCacheException);
}
return returnCode;
} | java | public int writeTemplate(String template, ValueSet vs) {
int returnCode = htod.writeTemplate(template, vs);
if (returnCode == HTODDynacache.DISK_EXCEPTION) {
stopOnError(this.htod.diskCacheException);
}
return returnCode;
} | [
"public",
"int",
"writeTemplate",
"(",
"String",
"template",
",",
"ValueSet",
"vs",
")",
"{",
"int",
"returnCode",
"=",
"htod",
".",
"writeTemplate",
"(",
"template",
",",
"vs",
")",
";",
"if",
"(",
"returnCode",
"==",
"HTODDynacache",
".",
"DISK_EXCEPTION",... | Call this method to write a template with a collection of cache ids to the disk.
@param template
- template id.
@param vs
- a collection of cache ids. | [
"Call",
"this",
"method",
"to",
"write",
"a",
"template",
"with",
"a",
"collection",
"of",
"cache",
"ids",
"to",
"the",
"disk",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheOnDisk.java#L1580-L1586 |
googleads/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java | ProductPartitionTreeImpl.createEmptyAdGroupTree | private static ProductPartitionTreeImpl createEmptyAdGroupTree(Long adGroupId,
BiddingStrategyConfiguration biddingStrategyConfig) {
Preconditions.checkNotNull(adGroupId, "Null ad group ID");
Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration");
ProductPartitionNode rootNode =
new ProductPartitionNode(null, null, -1L, new ProductDimensionComparator());
return new ProductPartitionTreeImpl(adGroupId, biddingStrategyConfig, rootNode);
} | java | private static ProductPartitionTreeImpl createEmptyAdGroupTree(Long adGroupId,
BiddingStrategyConfiguration biddingStrategyConfig) {
Preconditions.checkNotNull(adGroupId, "Null ad group ID");
Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration");
ProductPartitionNode rootNode =
new ProductPartitionNode(null, null, -1L, new ProductDimensionComparator());
return new ProductPartitionTreeImpl(adGroupId, biddingStrategyConfig, rootNode);
} | [
"private",
"static",
"ProductPartitionTreeImpl",
"createEmptyAdGroupTree",
"(",
"Long",
"adGroupId",
",",
"BiddingStrategyConfiguration",
"biddingStrategyConfig",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"adGroupId",
",",
"\"Null ad group ID\"",
")",
";",
"Preco... | Returns a new empty tree.
@param adGroupId the ID of the ad group
@param biddingStrategyConfig the bidding strategy configuration of the ad group | [
"Returns",
"a",
"new",
"empty",
"tree",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/utils/v201809/shopping/ProductPartitionTreeImpl.java#L326-L333 |
jbundle/jbundle | app/program/packages/src/main/java/org/jbundle/app/program/packages/screen/JnlpFileScreen.java | JnlpFileScreen.doCommand | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
if (JnlpFileScreen.WRITE_FILE.equals(strCommand))
{
return true; // Command handled
}
else
return super.doCommand(strCommand, sourceSField, iCommandOptions);
} | java | public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
if (JnlpFileScreen.WRITE_FILE.equals(strCommand))
{
return true; // Command handled
}
else
return super.doCommand(strCommand, sourceSField, iCommandOptions);
} | [
"public",
"boolean",
"doCommand",
"(",
"String",
"strCommand",
",",
"ScreenField",
"sourceSField",
",",
"int",
"iCommandOptions",
")",
"{",
"if",
"(",
"JnlpFileScreen",
".",
"WRITE_FILE",
".",
"equals",
"(",
"strCommand",
")",
")",
"{",
"return",
"true",
";",
... | Process the command.
<br />Step 1 - Process the command if possible and return true if processed.
<br />Step 2 - If I can't process, pass to all children (with me as the source).
<br />Step 3 - If children didn't process, pass to parent (with me as the source).
<br />Note: Never pass to a parent or child that matches the source (to avoid an endless loop).
@param strCommand The command to process.
@param sourceSField The source screen field (to avoid echos).
@param iCommandOptions If this command creates a new screen, create in a new window?
@return true if success. | [
"Process",
"the",
"command",
".",
"<br",
"/",
">",
"Step",
"1",
"-",
"Process",
"the",
"command",
"if",
"possible",
"and",
"return",
"true",
"if",
"processed",
".",
"<br",
"/",
">",
"Step",
"2",
"-",
"If",
"I",
"can",
"t",
"process",
"pass",
"to",
... | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/packages/src/main/java/org/jbundle/app/program/packages/screen/JnlpFileScreen.java#L88-L96 |
sarl/sarl | main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/launching/shortcuts/AbstractSarlLaunchShortcut.java | AbstractSarlLaunchShortcut.searchAndLaunch | private void searchAndLaunch(String mode, Object... scope) {
final ElementDescription element = searchAndSelect(true, scope);
if (element != null) {
try {
launch(element.projectName, element.elementName, mode);
} catch (CoreException e) {
SARLEclipsePlugin.getDefault().openError(getShell(),
io.sarl.eclipse.util.Messages.AbstractSarlScriptInteractiveSelector_1,
e.getStatus().getMessage(), e);
}
}
} | java | private void searchAndLaunch(String mode, Object... scope) {
final ElementDescription element = searchAndSelect(true, scope);
if (element != null) {
try {
launch(element.projectName, element.elementName, mode);
} catch (CoreException e) {
SARLEclipsePlugin.getDefault().openError(getShell(),
io.sarl.eclipse.util.Messages.AbstractSarlScriptInteractiveSelector_1,
e.getStatus().getMessage(), e);
}
}
} | [
"private",
"void",
"searchAndLaunch",
"(",
"String",
"mode",
",",
"Object",
"...",
"scope",
")",
"{",
"final",
"ElementDescription",
"element",
"=",
"searchAndSelect",
"(",
"true",
",",
"scope",
")",
";",
"if",
"(",
"element",
"!=",
"null",
")",
"{",
"try"... | Resolves an element type that can be launched from the given scope and launches in the
specified mode.
@param mode launch mode.
@param scope the elements to consider for an element type that can be launched. | [
"Resolves",
"an",
"element",
"type",
"that",
"can",
"be",
"launched",
"from",
"the",
"given",
"scope",
"and",
"launches",
"in",
"the",
"specified",
"mode",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/launching/shortcuts/AbstractSarlLaunchShortcut.java#L219-L230 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java | WaveformFinder.deliverWaveformPreviewUpdate | private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {
final Set<WaveformListener> listeners = getWaveformListeners();
if (!listeners.isEmpty()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);
for (final WaveformListener listener : listeners) {
try {
listener.previewChanged(update);
} catch (Throwable t) {
logger.warn("Problem delivering waveform preview update to listener", t);
}
}
}
});
}
} | java | private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {
final Set<WaveformListener> listeners = getWaveformListeners();
if (!listeners.isEmpty()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);
for (final WaveformListener listener : listeners) {
try {
listener.previewChanged(update);
} catch (Throwable t) {
logger.warn("Problem delivering waveform preview update to listener", t);
}
}
}
});
}
} | [
"private",
"void",
"deliverWaveformPreviewUpdate",
"(",
"final",
"int",
"player",
",",
"final",
"WaveformPreview",
"preview",
")",
"{",
"final",
"Set",
"<",
"WaveformListener",
">",
"listeners",
"=",
"getWaveformListeners",
"(",
")",
";",
"if",
"(",
"!",
"listen... | Send a waveform preview update announcement to all registered listeners.
@param player the player whose waveform preview has changed
@param preview the new waveform preview, if any | [
"Send",
"a",
"waveform",
"preview",
"update",
"announcement",
"to",
"all",
"registered",
"listeners",
"."
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java#L671-L689 |
apache/groovy | src/main/java/org/codehaus/groovy/ast/tools/ClosureUtils.java | ClosureUtils.convertClosureToSource | public static String convertClosureToSource(ReaderSource readerSource, ClosureExpression expression) throws Exception {
String source = GeneralUtils.convertASTToSource(readerSource, expression);
if (!source.startsWith("{")) {
throw new Exception("Error converting ClosureExpression into source code. Closures must start with {. Found: " + source);
}
return source;
} | java | public static String convertClosureToSource(ReaderSource readerSource, ClosureExpression expression) throws Exception {
String source = GeneralUtils.convertASTToSource(readerSource, expression);
if (!source.startsWith("{")) {
throw new Exception("Error converting ClosureExpression into source code. Closures must start with {. Found: " + source);
}
return source;
} | [
"public",
"static",
"String",
"convertClosureToSource",
"(",
"ReaderSource",
"readerSource",
",",
"ClosureExpression",
"expression",
")",
"throws",
"Exception",
"{",
"String",
"source",
"=",
"GeneralUtils",
".",
"convertASTToSource",
"(",
"readerSource",
",",
"expressio... | Converts a ClosureExpression into the String source.
@param readerSource a source
@param expression a closure. Can't be null
@return the source the closure was created from
@throws java.lang.IllegalArgumentException when expression is null
@throws java.lang.Exception when closure can't be read from source | [
"Converts",
"a",
"ClosureExpression",
"into",
"the",
"String",
"source",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/tools/ClosureUtils.java#L40-L46 |
groovyfx-project/groovyfx | src/main/groovy/groovyx/javafx/beans/FXBindableASTTransformation.java | FXBindableASTTransformation.createFXProperty | private PropertyNode createFXProperty(PropertyNode orig) {
ClassNode origType = orig.getType();
ClassNode newType = PROPERTY_TYPE_MAP.get(origType);
// For the ObjectProperty, we need to add the generic type to it.
if (newType == null) {
if (isTypeCompatible(ClassHelper.LIST_TYPE, origType) || isTypeCompatible(OBSERVABLE_LIST_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_LIST_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else if (isTypeCompatible(ClassHelper.MAP_TYPE, origType) || isTypeCompatible(OBSERVABLE_MAP_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_MAP_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else if (isTypeCompatible(SET_TYPE, origType) || isTypeCompatible(OBSERVABLE_SET_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_SET_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else { // Object Type
newType = makeClassSafe(OBJECT_PROPERTY_CNODE);
ClassNode genericType = origType;
if (genericType.isPrimaryClassNode()) {
genericType = ClassHelper.getWrapper(genericType);
}
newType.setGenericsTypes(new GenericsType[]{new GenericsType(genericType)});
}
}
FieldNode fieldNode = createFieldNodeCopy(orig.getName() + "Property", newType, orig.getField());
return new PropertyNode(fieldNode, orig.getModifiers(), orig.getGetterBlock(), orig.getSetterBlock());
} | java | private PropertyNode createFXProperty(PropertyNode orig) {
ClassNode origType = orig.getType();
ClassNode newType = PROPERTY_TYPE_MAP.get(origType);
// For the ObjectProperty, we need to add the generic type to it.
if (newType == null) {
if (isTypeCompatible(ClassHelper.LIST_TYPE, origType) || isTypeCompatible(OBSERVABLE_LIST_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_LIST_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else if (isTypeCompatible(ClassHelper.MAP_TYPE, origType) || isTypeCompatible(OBSERVABLE_MAP_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_MAP_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else if (isTypeCompatible(SET_TYPE, origType) || isTypeCompatible(OBSERVABLE_SET_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_SET_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else { // Object Type
newType = makeClassSafe(OBJECT_PROPERTY_CNODE);
ClassNode genericType = origType;
if (genericType.isPrimaryClassNode()) {
genericType = ClassHelper.getWrapper(genericType);
}
newType.setGenericsTypes(new GenericsType[]{new GenericsType(genericType)});
}
}
FieldNode fieldNode = createFieldNodeCopy(orig.getName() + "Property", newType, orig.getField());
return new PropertyNode(fieldNode, orig.getModifiers(), orig.getGetterBlock(), orig.getSetterBlock());
} | [
"private",
"PropertyNode",
"createFXProperty",
"(",
"PropertyNode",
"orig",
")",
"{",
"ClassNode",
"origType",
"=",
"orig",
".",
"getType",
"(",
")",
";",
"ClassNode",
"newType",
"=",
"PROPERTY_TYPE_MAP",
".",
"get",
"(",
"origType",
")",
";",
"// For the Object... | Creates a new PropertyNode for the JavaFX property based on the original property. The new property
will have "Property" appended to its name and its type will be one of the *Property types in JavaFX.
@param orig The original property
@return A new PropertyNode for the JavaFX property | [
"Creates",
"a",
"new",
"PropertyNode",
"for",
"the",
"JavaFX",
"property",
"based",
"on",
"the",
"original",
"property",
".",
"The",
"new",
"property",
"will",
"have",
"Property",
"appended",
"to",
"its",
"name",
"and",
"its",
"type",
"will",
"be",
"one",
... | train | https://github.com/groovyfx-project/groovyfx/blob/7067d76793601ce4de9c642d4c0c0e11db7907cb/src/main/groovy/groovyx/javafx/beans/FXBindableASTTransformation.java#L331-L361 |
SeaCloudsEU/SeaCloudsPlatform | sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/EnforcementJobRest.java | EnforcementJobRest.getEnforcementJobByAgreementId | @GET
@Path("{agreementId}")
@Produces(MediaType.APPLICATION_XML)
public Response getEnforcementJobByAgreementId(@PathParam("agreementId") String agreementId){
logger.debug("StartOf getEnforcementJobByAgreementId - REQUEST for /enforcementJobs/" + agreementId);
try {
EnforcementJobHelper enforcementJobService = getHelper();
String serializedEnforcement = enforcementJobService.getEnforcementJobByUUID(agreementId);
if (serializedEnforcement!=null){
logger.debug("EndOf getEnforcementJobByAgreementId");
return buildResponse(200, serializedEnforcement);
}else{
logger.debug("EndOf getEnforcementJobByAgreementId");
return buildResponse(404, printError(404, "There is no enforcement with uuid " + agreementId
+ " in the SLA Repository Database"));
}
} catch (HelperException e) {
logger.info("getEnforcementJobByAgreementId exception:"+e.getMessage());
return buildResponse(e);
}
} | java | @GET
@Path("{agreementId}")
@Produces(MediaType.APPLICATION_XML)
public Response getEnforcementJobByAgreementId(@PathParam("agreementId") String agreementId){
logger.debug("StartOf getEnforcementJobByAgreementId - REQUEST for /enforcementJobs/" + agreementId);
try {
EnforcementJobHelper enforcementJobService = getHelper();
String serializedEnforcement = enforcementJobService.getEnforcementJobByUUID(agreementId);
if (serializedEnforcement!=null){
logger.debug("EndOf getEnforcementJobByAgreementId");
return buildResponse(200, serializedEnforcement);
}else{
logger.debug("EndOf getEnforcementJobByAgreementId");
return buildResponse(404, printError(404, "There is no enforcement with uuid " + agreementId
+ " in the SLA Repository Database"));
}
} catch (HelperException e) {
logger.info("getEnforcementJobByAgreementId exception:"+e.getMessage());
return buildResponse(e);
}
} | [
"@",
"GET",
"@",
"Path",
"(",
"\"{agreementId}\"",
")",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_XML",
")",
"public",
"Response",
"getEnforcementJobByAgreementId",
"(",
"@",
"PathParam",
"(",
"\"agreementId\"",
")",
"String",
"agreementId",
")",
"{",
... | Gets an specific enforcements given a agreementId If the enforcementJob
it is not in the database, it returns 404 with empty payload
<pre>
GET /enforcements/{agreementId}
Request:
GET /enforcements HTTP/1.1
Response:
{@code
<?xml version="1.0" encoding="UTF-8"?>
<enforcement_job>
<agreement_id>agreement04</agreement_id>
<enabled>false</enabled>
</enforcement_job>
}
</pre>
Example: <li>curl
http://localhost:8080/sla-service/enforcements/agreement04</li>
@param agreementId
of the enforcementJob
@return XML information with the different details of the enforcementJob | [
"Gets",
"an",
"specific",
"enforcements",
"given",
"a",
"agreementId",
"If",
"the",
"enforcementJob",
"it",
"is",
"not",
"in",
"the",
"database",
"it",
"returns",
"404",
"with",
"empty",
"payload"
] | train | https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/EnforcementJobRest.java#L151-L173 |
google/j2objc | jre_emul/android/frameworks/base/core/java/android/util/SparseArray.java | SparseArray.removeAtRange | public void removeAtRange(int index, int size) {
final int end = Math.min(mSize, index + size);
for (int i = index; i < end; i++) {
removeAt(i);
}
} | java | public void removeAtRange(int index, int size) {
final int end = Math.min(mSize, index + size);
for (int i = index; i < end; i++) {
removeAt(i);
}
} | [
"public",
"void",
"removeAtRange",
"(",
"int",
"index",
",",
"int",
"size",
")",
"{",
"final",
"int",
"end",
"=",
"Math",
".",
"min",
"(",
"mSize",
",",
"index",
"+",
"size",
")",
";",
"for",
"(",
"int",
"i",
"=",
"index",
";",
"i",
"<",
"end",
... | Remove a range of mappings as a batch.
@param index Index to begin at
@param size Number of mappings to remove | [
"Remove",
"a",
"range",
"of",
"mappings",
"as",
"a",
"batch",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/frameworks/base/core/java/android/util/SparseArray.java#L157-L162 |
santhosh-tekuri/jlibs | xml/src/main/java/jlibs/xml/DefaultNamespaceContext.java | DefaultNamespaceContext.declarePrefix | public void declarePrefix(String prefix, String uri){
if(prefix.length()==0)
defaultURI = uri;
prefix2uriMap.put(prefix, uri);
uri2prefixMap.put(uri, prefix);
} | java | public void declarePrefix(String prefix, String uri){
if(prefix.length()==0)
defaultURI = uri;
prefix2uriMap.put(prefix, uri);
uri2prefixMap.put(uri, prefix);
} | [
"public",
"void",
"declarePrefix",
"(",
"String",
"prefix",
",",
"String",
"uri",
")",
"{",
"if",
"(",
"prefix",
".",
"length",
"(",
")",
"==",
"0",
")",
"defaultURI",
"=",
"uri",
";",
"prefix2uriMap",
".",
"put",
"(",
"prefix",
",",
"uri",
")",
";",... | Binds specified {@code prefix} to the given {@code uri}
@param prefix the prefix to be bound
@param uri the uri to which specified {@code prefix} to be bound | [
"Binds",
"specified",
"{",
"@code",
"prefix",
"}",
"to",
"the",
"given",
"{",
"@code",
"uri",
"}"
] | train | https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/xml/src/main/java/jlibs/xml/DefaultNamespaceContext.java#L128-L133 |
apache/incubator-gobblin | gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java | MRCompactor.addRunningHadoopJob | public static void addRunningHadoopJob(Dataset dataset, Job job) {
MRCompactor.RUNNING_MR_JOBS.put(dataset, job);
} | java | public static void addRunningHadoopJob(Dataset dataset, Job job) {
MRCompactor.RUNNING_MR_JOBS.put(dataset, job);
} | [
"public",
"static",
"void",
"addRunningHadoopJob",
"(",
"Dataset",
"dataset",
",",
"Job",
"job",
")",
"{",
"MRCompactor",
".",
"RUNNING_MR_JOBS",
".",
"put",
"(",
"dataset",
",",
"job",
")",
";",
"}"
] | Keep track of running MR jobs, so if the compaction is cancelled, the MR jobs can be killed. | [
"Keep",
"track",
"of",
"running",
"MR",
"jobs",
"so",
"if",
"the",
"compaction",
"is",
"cancelled",
"the",
"MR",
"jobs",
"can",
"be",
"killed",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L839-L841 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/opengl/InternalTextureLoader.java | InternalTextureLoader.getTexture | public Texture getTexture(ImageData dataSource, int filter) throws IOException
{
int target = SGL.GL_TEXTURE_2D;
ByteBuffer textureBuffer;
textureBuffer = dataSource.getImageBufferData();
// create the texture ID for this texture
int textureID = createTextureID();
TextureImpl texture = new TextureImpl("generated:"+dataSource, target ,textureID);
int minFilter = filter;
int magFilter = filter;
boolean flipped = false;
// bind this texture
GL.glBindTexture(target, textureID);
int width;
int height;
int texWidth;
int texHeight;
boolean hasAlpha;
width = dataSource.getWidth();
height = dataSource.getHeight();
hasAlpha = dataSource.getDepth() == 32;
texture.setTextureWidth(dataSource.getTexWidth());
texture.setTextureHeight(dataSource.getTexHeight());
texWidth = texture.getTextureWidth();
texHeight = texture.getTextureHeight();
int srcPixelFormat = hasAlpha ? SGL.GL_RGBA : SGL.GL_RGB;
int componentCount = hasAlpha ? 4 : 3;
texture.setWidth(width);
texture.setHeight(height);
texture.setAlpha(hasAlpha);
IntBuffer temp = BufferUtils.createIntBuffer(16);
GL.glGetInteger(SGL.GL_MAX_TEXTURE_SIZE, temp);
int max = temp.get(0);
if ((texWidth > max) || (texHeight > max)) {
throw new IOException("Attempt to allocate a texture to big for the current hardware");
}
if (holdTextureData) {
texture.setTextureData(srcPixelFormat, componentCount, minFilter, magFilter, textureBuffer);
}
GL.glTexParameteri(target, SGL.GL_TEXTURE_MIN_FILTER, minFilter);
GL.glTexParameteri(target, SGL.GL_TEXTURE_MAG_FILTER, magFilter);
// produce a texture from the byte buffer
GL.glTexImage2D(target,
0,
dstPixelFormat,
get2Fold(width),
get2Fold(height),
0,
srcPixelFormat,
SGL.GL_UNSIGNED_BYTE,
textureBuffer);
return texture;
} | java | public Texture getTexture(ImageData dataSource, int filter) throws IOException
{
int target = SGL.GL_TEXTURE_2D;
ByteBuffer textureBuffer;
textureBuffer = dataSource.getImageBufferData();
// create the texture ID for this texture
int textureID = createTextureID();
TextureImpl texture = new TextureImpl("generated:"+dataSource, target ,textureID);
int minFilter = filter;
int magFilter = filter;
boolean flipped = false;
// bind this texture
GL.glBindTexture(target, textureID);
int width;
int height;
int texWidth;
int texHeight;
boolean hasAlpha;
width = dataSource.getWidth();
height = dataSource.getHeight();
hasAlpha = dataSource.getDepth() == 32;
texture.setTextureWidth(dataSource.getTexWidth());
texture.setTextureHeight(dataSource.getTexHeight());
texWidth = texture.getTextureWidth();
texHeight = texture.getTextureHeight();
int srcPixelFormat = hasAlpha ? SGL.GL_RGBA : SGL.GL_RGB;
int componentCount = hasAlpha ? 4 : 3;
texture.setWidth(width);
texture.setHeight(height);
texture.setAlpha(hasAlpha);
IntBuffer temp = BufferUtils.createIntBuffer(16);
GL.glGetInteger(SGL.GL_MAX_TEXTURE_SIZE, temp);
int max = temp.get(0);
if ((texWidth > max) || (texHeight > max)) {
throw new IOException("Attempt to allocate a texture to big for the current hardware");
}
if (holdTextureData) {
texture.setTextureData(srcPixelFormat, componentCount, minFilter, magFilter, textureBuffer);
}
GL.glTexParameteri(target, SGL.GL_TEXTURE_MIN_FILTER, minFilter);
GL.glTexParameteri(target, SGL.GL_TEXTURE_MAG_FILTER, magFilter);
// produce a texture from the byte buffer
GL.glTexImage2D(target,
0,
dstPixelFormat,
get2Fold(width),
get2Fold(height),
0,
srcPixelFormat,
SGL.GL_UNSIGNED_BYTE,
textureBuffer);
return texture;
} | [
"public",
"Texture",
"getTexture",
"(",
"ImageData",
"dataSource",
",",
"int",
"filter",
")",
"throws",
"IOException",
"{",
"int",
"target",
"=",
"SGL",
".",
"GL_TEXTURE_2D",
";",
"ByteBuffer",
"textureBuffer",
";",
"textureBuffer",
"=",
"dataSource",
".",
"getI... | Get a texture from a image file
@param dataSource The image data to generate the texture from
@param filter The filter to use when scaling the texture
@return The texture created
@throws IOException Indicates the texture is too big for the hardware | [
"Get",
"a",
"texture",
"from",
"a",
"image",
"file"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/opengl/InternalTextureLoader.java#L385-L453 |
apiman/apiman | manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/util/ExceptionFactory.java | ExceptionFactory.clientVersionAlreadyExistsException | public static final ClientVersionAlreadyExistsException clientVersionAlreadyExistsException(String clientName, String version) {
return new ClientVersionAlreadyExistsException(Messages.i18n.format("clientVersionAlreadyExists", clientName, version)); //$NON-NLS-1$
} | java | public static final ClientVersionAlreadyExistsException clientVersionAlreadyExistsException(String clientName, String version) {
return new ClientVersionAlreadyExistsException(Messages.i18n.format("clientVersionAlreadyExists", clientName, version)); //$NON-NLS-1$
} | [
"public",
"static",
"final",
"ClientVersionAlreadyExistsException",
"clientVersionAlreadyExistsException",
"(",
"String",
"clientName",
",",
"String",
"version",
")",
"{",
"return",
"new",
"ClientVersionAlreadyExistsException",
"(",
"Messages",
".",
"i18n",
".",
"format",
... | Creates an exception from an client name.
@param clientName the client name
@param version the version
@return the exception | [
"Creates",
"an",
"exception",
"from",
"an",
"client",
"name",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/util/ExceptionFactory.java#L147-L149 |
stratosphere/stratosphere | stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/task/DataSinkTask.java | DataSinkTask.initOutputFormat | private void initOutputFormat() {
if (this.userCodeClassLoader == null) {
try {
this.userCodeClassLoader = LibraryCacheManager.getClassLoader(getEnvironment().getJobID());
} catch (IOException ioe) {
throw new RuntimeException("Library cache manager could not be instantiated.", ioe);
}
}
// obtain task configuration (including stub parameters)
Configuration taskConf = getTaskConfiguration();
taskConf.setClassLoader(this.userCodeClassLoader);
this.config = new TaskConfig(taskConf);
try {
this.format = config.<OutputFormat<IT>>getStubWrapper(this.userCodeClassLoader).getUserCodeObject(OutputFormat.class, this.userCodeClassLoader);
// check if the class is a subclass, if the check is required
if (!OutputFormat.class.isAssignableFrom(this.format.getClass())) {
throw new RuntimeException("The class '" + this.format.getClass().getName() + "' is not a subclass of '" +
OutputFormat.class.getName() + "' as is required.");
}
}
catch (ClassCastException ccex) {
throw new RuntimeException("The stub class is not a proper subclass of " + OutputFormat.class.getName(), ccex);
}
// configure the stub. catch exceptions here extra, to report them as originating from the user code
try {
this.format.configure(this.config.getStubParameters());
}
catch (Throwable t) {
throw new RuntimeException("The user defined 'configure()' method in the Output Format caused an error: "
+ t.getMessage(), t);
}
} | java | private void initOutputFormat() {
if (this.userCodeClassLoader == null) {
try {
this.userCodeClassLoader = LibraryCacheManager.getClassLoader(getEnvironment().getJobID());
} catch (IOException ioe) {
throw new RuntimeException("Library cache manager could not be instantiated.", ioe);
}
}
// obtain task configuration (including stub parameters)
Configuration taskConf = getTaskConfiguration();
taskConf.setClassLoader(this.userCodeClassLoader);
this.config = new TaskConfig(taskConf);
try {
this.format = config.<OutputFormat<IT>>getStubWrapper(this.userCodeClassLoader).getUserCodeObject(OutputFormat.class, this.userCodeClassLoader);
// check if the class is a subclass, if the check is required
if (!OutputFormat.class.isAssignableFrom(this.format.getClass())) {
throw new RuntimeException("The class '" + this.format.getClass().getName() + "' is not a subclass of '" +
OutputFormat.class.getName() + "' as is required.");
}
}
catch (ClassCastException ccex) {
throw new RuntimeException("The stub class is not a proper subclass of " + OutputFormat.class.getName(), ccex);
}
// configure the stub. catch exceptions here extra, to report them as originating from the user code
try {
this.format.configure(this.config.getStubParameters());
}
catch (Throwable t) {
throw new RuntimeException("The user defined 'configure()' method in the Output Format caused an error: "
+ t.getMessage(), t);
}
} | [
"private",
"void",
"initOutputFormat",
"(",
")",
"{",
"if",
"(",
"this",
".",
"userCodeClassLoader",
"==",
"null",
")",
"{",
"try",
"{",
"this",
".",
"userCodeClassLoader",
"=",
"LibraryCacheManager",
".",
"getClassLoader",
"(",
"getEnvironment",
"(",
")",
"."... | Initializes the OutputFormat implementation and configuration.
@throws RuntimeException
Throws if instance of OutputFormat implementation can not be
obtained. | [
"Initializes",
"the",
"OutputFormat",
"implementation",
"and",
"configuration",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/pact/runtime/task/DataSinkTask.java#L268-L302 |
shevek/qemu-java | qemu-exec/src/main/java/org/anarres/qemu/exec/util/QEmuIdAllocator.java | QEmuIdAllocator.newPciAddresses | @Nonnull
public String newPciAddresses(@Nonnegative int count, @Nonnull String separator) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < count; i++) {
if (i > 0)
buf.append(separator);
buf.append(newPciAddress());
}
return buf.toString();
} | java | @Nonnull
public String newPciAddresses(@Nonnegative int count, @Nonnull String separator) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < count; i++) {
if (i > 0)
buf.append(separator);
buf.append(newPciAddress());
}
return buf.toString();
} | [
"@",
"Nonnull",
"public",
"String",
"newPciAddresses",
"(",
"@",
"Nonnegative",
"int",
"count",
",",
"@",
"Nonnull",
"String",
"separator",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";... | Returns a comma-separated list of new PCI addresses.
@param count How many addresses to return.
@param separator The separator to use between addresses.
@return A separated String of new PCI addresses. | [
"Returns",
"a",
"comma",
"-",
"separated",
"list",
"of",
"new",
"PCI",
"addresses",
"."
] | train | https://github.com/shevek/qemu-java/blob/ef4cc2c991df36d5f450b49ec8e341f6ed3362f2/qemu-exec/src/main/java/org/anarres/qemu/exec/util/QEmuIdAllocator.java#L61-L70 |
jenkinsci/jenkins | core/src/main/java/jenkins/org/apache/commons/validator/routines/DomainValidator.java | DomainValidator.isValidInfrastructureTld | public boolean isValidInfrastructureTld(String iTld) {
final String key = chompLeadingDot(unicodeToASCII(iTld).toLowerCase(Locale.ENGLISH));
return arrayContains(INFRASTRUCTURE_TLDS, key);
} | java | public boolean isValidInfrastructureTld(String iTld) {
final String key = chompLeadingDot(unicodeToASCII(iTld).toLowerCase(Locale.ENGLISH));
return arrayContains(INFRASTRUCTURE_TLDS, key);
} | [
"public",
"boolean",
"isValidInfrastructureTld",
"(",
"String",
"iTld",
")",
"{",
"final",
"String",
"key",
"=",
"chompLeadingDot",
"(",
"unicodeToASCII",
"(",
"iTld",
")",
".",
"toLowerCase",
"(",
"Locale",
".",
"ENGLISH",
")",
")",
";",
"return",
"arrayConta... | Returns true if the specified <code>String</code> matches any
IANA-defined infrastructure top-level domain. Leading dots are
ignored if present. The search is case-insensitive.
@param iTld the parameter to check for infrastructure TLD status, not null
@return true if the parameter is an infrastructure TLD | [
"Returns",
"true",
"if",
"the",
"specified",
"<code",
">",
"String<",
"/",
"code",
">",
"matches",
"any",
"IANA",
"-",
"defined",
"infrastructure",
"top",
"-",
"level",
"domain",
".",
"Leading",
"dots",
"are",
"ignored",
"if",
"present",
".",
"The",
"searc... | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/org/apache/commons/validator/routines/DomainValidator.java#L220-L223 |
offbynull/coroutines | instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java | GenericGenerators.forEach | public static InsnList forEach(Variable counterVar, Variable arrayLenVar, InsnList array, InsnList action) {
Validate.notNull(counterVar);
Validate.notNull(arrayLenVar);
Validate.notNull(array);
Validate.notNull(action);
Validate.isTrue(counterVar.getType().equals(Type.INT_TYPE));
Validate.isTrue(arrayLenVar.getType().equals(Type.INT_TYPE));
InsnList ret = new InsnList();
LabelNode doneLabelNode = new LabelNode();
LabelNode loopLabelNode = new LabelNode();
// put zero in to counterVar
ret.add(new LdcInsnNode(0)); // int
ret.add(new VarInsnNode(Opcodes.ISTORE, counterVar.getIndex())); //
// load array we'll be traversing over
ret.add(array); // object[]
// put array length in to arrayLenVar
ret.add(new InsnNode(Opcodes.DUP)); // object[], object[]
ret.add(new InsnNode(Opcodes.ARRAYLENGTH)); // object[], int
ret.add(new VarInsnNode(Opcodes.ISTORE, arrayLenVar.getIndex())); // object[]
// loopLabelNode: test if counterVar == arrayLenVar, if it does then jump to doneLabelNode
ret.add(loopLabelNode);
ret.add(new VarInsnNode(Opcodes.ILOAD, counterVar.getIndex())); // object[], int
ret.add(new VarInsnNode(Opcodes.ILOAD, arrayLenVar.getIndex())); // object[], int, int
ret.add(new JumpInsnNode(Opcodes.IF_ICMPEQ, doneLabelNode)); // object[]
// load object from object[]
ret.add(new InsnNode(Opcodes.DUP)); // object[], object[]
ret.add(new VarInsnNode(Opcodes.ILOAD, counterVar.getIndex())); // object[], object[], int
ret.add(new InsnNode(Opcodes.AALOAD)); // object[], object
// call action
ret.add(action); // object[]
// increment counter var and goto loopLabelNode
ret.add(new IincInsnNode(counterVar.getIndex(), 1)); // object[]
ret.add(new JumpInsnNode(Opcodes.GOTO, loopLabelNode)); // object[]
// doneLabelNode: pop object[] off of stack
ret.add(doneLabelNode);
ret.add(new InsnNode(Opcodes.POP)); //
return ret;
} | java | public static InsnList forEach(Variable counterVar, Variable arrayLenVar, InsnList array, InsnList action) {
Validate.notNull(counterVar);
Validate.notNull(arrayLenVar);
Validate.notNull(array);
Validate.notNull(action);
Validate.isTrue(counterVar.getType().equals(Type.INT_TYPE));
Validate.isTrue(arrayLenVar.getType().equals(Type.INT_TYPE));
InsnList ret = new InsnList();
LabelNode doneLabelNode = new LabelNode();
LabelNode loopLabelNode = new LabelNode();
// put zero in to counterVar
ret.add(new LdcInsnNode(0)); // int
ret.add(new VarInsnNode(Opcodes.ISTORE, counterVar.getIndex())); //
// load array we'll be traversing over
ret.add(array); // object[]
// put array length in to arrayLenVar
ret.add(new InsnNode(Opcodes.DUP)); // object[], object[]
ret.add(new InsnNode(Opcodes.ARRAYLENGTH)); // object[], int
ret.add(new VarInsnNode(Opcodes.ISTORE, arrayLenVar.getIndex())); // object[]
// loopLabelNode: test if counterVar == arrayLenVar, if it does then jump to doneLabelNode
ret.add(loopLabelNode);
ret.add(new VarInsnNode(Opcodes.ILOAD, counterVar.getIndex())); // object[], int
ret.add(new VarInsnNode(Opcodes.ILOAD, arrayLenVar.getIndex())); // object[], int, int
ret.add(new JumpInsnNode(Opcodes.IF_ICMPEQ, doneLabelNode)); // object[]
// load object from object[]
ret.add(new InsnNode(Opcodes.DUP)); // object[], object[]
ret.add(new VarInsnNode(Opcodes.ILOAD, counterVar.getIndex())); // object[], object[], int
ret.add(new InsnNode(Opcodes.AALOAD)); // object[], object
// call action
ret.add(action); // object[]
// increment counter var and goto loopLabelNode
ret.add(new IincInsnNode(counterVar.getIndex(), 1)); // object[]
ret.add(new JumpInsnNode(Opcodes.GOTO, loopLabelNode)); // object[]
// doneLabelNode: pop object[] off of stack
ret.add(doneLabelNode);
ret.add(new InsnNode(Opcodes.POP)); //
return ret;
} | [
"public",
"static",
"InsnList",
"forEach",
"(",
"Variable",
"counterVar",
",",
"Variable",
"arrayLenVar",
",",
"InsnList",
"array",
",",
"InsnList",
"action",
")",
"{",
"Validate",
".",
"notNull",
"(",
"counterVar",
")",
";",
"Validate",
".",
"notNull",
"(",
... | For each element in an object array, performs an action.
@param counterVar parameter used to keep track of count in loop
@param arrayLenVar parameter used to keep track of array length
@param array object array instruction list -- must leave an array on the stack
@param action action to perform on each element -- element will be at top of stack and must be consumed by these instructions
@return instructions instruction list to perform some action if two ints are equal
@throws NullPointerException if any argument is {@code null} | [
"For",
"each",
"element",
"in",
"an",
"object",
"array",
"performs",
"an",
"action",
"."
] | train | https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/generators/GenericGenerators.java#L702-L751 |
wcm-io/wcm-io-wcm | ui/granite/src/main/java/io/wcm/wcm/ui/granite/components/pathfield/ColumnView.java | ColumnView.getRootColumn | private static Column getRootColumn(Resource rootResource, String itemResourceType) {
/*
* Put a special path for columnId to avoid having the same columnId with the next column to avoid breaking the contract of columnId.
* The contract of columnId is that it should be a path of the current column, i.e. the path should be a path representing a parent.
* e.g. When columnId = "/", then the column will show the children of this path, such as "/a", "/b".
* So for showRoot scenario, if we want to show the item with path = "/", we need to generate the column having a columnId with value of the parent of "/".
* Since the cannot have a parent of "/", then we decide to just use a special convention ("parentof:<path>") to indicate this.
* Other component (e.g. `.granite-collection-navigator`) reading the columnId can then understand this convention and handle it accordingly.
*/
String columnId = "parentof:" + rootResource.getPath();
Column column = new Column()
.columnId(columnId)
.hasMore(false);
column.addItem(new ColumnItem(rootResource)
.resourceType(itemResourceType)
.active(true));
return column;
} | java | private static Column getRootColumn(Resource rootResource, String itemResourceType) {
/*
* Put a special path for columnId to avoid having the same columnId with the next column to avoid breaking the contract of columnId.
* The contract of columnId is that it should be a path of the current column, i.e. the path should be a path representing a parent.
* e.g. When columnId = "/", then the column will show the children of this path, such as "/a", "/b".
* So for showRoot scenario, if we want to show the item with path = "/", we need to generate the column having a columnId with value of the parent of "/".
* Since the cannot have a parent of "/", then we decide to just use a special convention ("parentof:<path>") to indicate this.
* Other component (e.g. `.granite-collection-navigator`) reading the columnId can then understand this convention and handle it accordingly.
*/
String columnId = "parentof:" + rootResource.getPath();
Column column = new Column()
.columnId(columnId)
.hasMore(false);
column.addItem(new ColumnItem(rootResource)
.resourceType(itemResourceType)
.active(true));
return column;
} | [
"private",
"static",
"Column",
"getRootColumn",
"(",
"Resource",
"rootResource",
",",
"String",
"itemResourceType",
")",
"{",
"/*\n * Put a special path for columnId to avoid having the same columnId with the next column to avoid breaking the contract of columnId.\n * The contract of... | Generate extra column representing the root resource.
@param rootResource Root resource
@param itemResourceType Item resource type
@return Column | [
"Generate",
"extra",
"column",
"representing",
"the",
"root",
"resource",
"."
] | train | https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/ui/granite/src/main/java/io/wcm/wcm/ui/granite/components/pathfield/ColumnView.java#L190-L208 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/handler/ResourceBundlesHandlerImpl.java | ResourceBundlesHandlerImpl.joinAndPostProcessBundle | private void joinAndPostProcessBundle(JoinableResourceBundle bundle, BundleProcessingStatus status) {
JoinableResourceBundleContent store;
List<Map<String, String>> allVariants = VariantUtils.getAllVariants(bundle.getVariants());
// Add the default bundle variant (the non variant one)
allVariants.add(null);
for (Map<String, String> variantMap : allVariants) {
status.setBundleVariants(variantMap);
String variantKey = VariantUtils.getVariantKey(variantMap);
String name = VariantUtils.getVariantBundleName(bundle.getId(), variantKey, false);
store = joinAndPostprocessBundle(bundle, variantMap, status);
storeBundle(name, store);
initBundleDataHashcode(bundle, store, variantKey);
}
} | java | private void joinAndPostProcessBundle(JoinableResourceBundle bundle, BundleProcessingStatus status) {
JoinableResourceBundleContent store;
List<Map<String, String>> allVariants = VariantUtils.getAllVariants(bundle.getVariants());
// Add the default bundle variant (the non variant one)
allVariants.add(null);
for (Map<String, String> variantMap : allVariants) {
status.setBundleVariants(variantMap);
String variantKey = VariantUtils.getVariantKey(variantMap);
String name = VariantUtils.getVariantBundleName(bundle.getId(), variantKey, false);
store = joinAndPostprocessBundle(bundle, variantMap, status);
storeBundle(name, store);
initBundleDataHashcode(bundle, store, variantKey);
}
} | [
"private",
"void",
"joinAndPostProcessBundle",
"(",
"JoinableResourceBundle",
"bundle",
",",
"BundleProcessingStatus",
"status",
")",
"{",
"JoinableResourceBundleContent",
"store",
";",
"List",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"allVariants",
"=",
... | Join and post process the bundle taking in account all its variants.
@param bundle
the bundle
@param status
the bundle processing status | [
"Join",
"and",
"post",
"process",
"the",
"bundle",
"taking",
"in",
"account",
"all",
"its",
"variants",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/handler/ResourceBundlesHandlerImpl.java#L1292-L1307 |
wouterd/docker-maven-plugin | src/main/java/net/wouterdanes/docker/remoteapi/MiscService.java | MiscService.getVersionInfo | public DockerVersionInfo getVersionInfo() {
String json = getServiceEndPoint()
.path("/version")
.request(MediaType.APPLICATION_JSON_TYPE)
.get(String.class);
return toObject(json, DockerVersionInfo.class);
} | java | public DockerVersionInfo getVersionInfo() {
String json = getServiceEndPoint()
.path("/version")
.request(MediaType.APPLICATION_JSON_TYPE)
.get(String.class);
return toObject(json, DockerVersionInfo.class);
} | [
"public",
"DockerVersionInfo",
"getVersionInfo",
"(",
")",
"{",
"String",
"json",
"=",
"getServiceEndPoint",
"(",
")",
".",
"path",
"(",
"\"/version\"",
")",
".",
"request",
"(",
"MediaType",
".",
"APPLICATION_JSON_TYPE",
")",
".",
"get",
"(",
"String",
".",
... | Returns the Docker version information
@return a {@link DockerVersionInfo} instance describing this docker installation. | [
"Returns",
"the",
"Docker",
"version",
"information"
] | train | https://github.com/wouterd/docker-maven-plugin/blob/ea15f9e6c273989bb91f4228fb52cb73d00e07b3/src/main/java/net/wouterdanes/docker/remoteapi/MiscService.java#L69-L76 |
micronaut-projects/micronaut-core | core/src/main/java/io/micronaut/core/io/scan/AnnotationClassReader.java | AnnotationClassReader.readLabel | protected Label readLabel(int offset, Label[] labels) {
// SPRING PATCH: leniently handle offset mismatch
if (offset >= labels.length) {
return new Label();
}
// END OF PATCH
if (labels[offset] == null) {
labels[offset] = new Label();
}
return labels[offset];
} | java | protected Label readLabel(int offset, Label[] labels) {
// SPRING PATCH: leniently handle offset mismatch
if (offset >= labels.length) {
return new Label();
}
// END OF PATCH
if (labels[offset] == null) {
labels[offset] = new Label();
}
return labels[offset];
} | [
"protected",
"Label",
"readLabel",
"(",
"int",
"offset",
",",
"Label",
"[",
"]",
"labels",
")",
"{",
"// SPRING PATCH: leniently handle offset mismatch",
"if",
"(",
"offset",
">=",
"labels",
".",
"length",
")",
"{",
"return",
"new",
"Label",
"(",
")",
";",
"... | Returns the label corresponding to the given offset. The default
implementation of this method creates a label for the given offset if it
has not been already created.
@param offset a bytecode offset in a method.
@param labels the already created labels, indexed by their offset. If a
label already exists for offset this method must not create a
new one. Otherwise it must store the new label in this array.
@return a non null Label, which must be equal to labels[offset]. | [
"Returns",
"the",
"label",
"corresponding",
"to",
"the",
"given",
"offset",
".",
"The",
"default",
"implementation",
"of",
"this",
"method",
"creates",
"a",
"label",
"for",
"the",
"given",
"offset",
"if",
"it",
"has",
"not",
"been",
"already",
"created",
"."... | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/io/scan/AnnotationClassReader.java#L746-L756 |
emfjson/emfjson-jackson | src/main/java/org/emfjson/jackson/utils/EObjects.java | EObjects.isContainmentProxy | public static boolean isContainmentProxy(DatabindContext ctxt, EObject owner, EObject contained) {
if (contained.eIsProxy())
return true;
Resource ownerResource = EMFContext.getResource(ctxt, owner);
Resource containedResource = EMFContext.getResource(ctxt, contained);
return ownerResource != null && ownerResource != containedResource;
} | java | public static boolean isContainmentProxy(DatabindContext ctxt, EObject owner, EObject contained) {
if (contained.eIsProxy())
return true;
Resource ownerResource = EMFContext.getResource(ctxt, owner);
Resource containedResource = EMFContext.getResource(ctxt, contained);
return ownerResource != null && ownerResource != containedResource;
} | [
"public",
"static",
"boolean",
"isContainmentProxy",
"(",
"DatabindContext",
"ctxt",
",",
"EObject",
"owner",
",",
"EObject",
"contained",
")",
"{",
"if",
"(",
"contained",
".",
"eIsProxy",
"(",
")",
")",
"return",
"true",
";",
"Resource",
"ownerResource",
"="... | Checks that the contained object is in a different resource than it's owner, making
it a contained proxy.
@param owner
@param contained
@return true if proxy | [
"Checks",
"that",
"the",
"contained",
"object",
"is",
"in",
"a",
"different",
"resource",
"than",
"it",
"s",
"owner",
"making",
"it",
"a",
"contained",
"proxy",
"."
] | train | https://github.com/emfjson/emfjson-jackson/blob/5f4488d1b07d499003351606cf76ee0c4ac39964/src/main/java/org/emfjson/jackson/utils/EObjects.java#L58-L66 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/RayleighDistribution.java | RayleighDistribution.logpdf | public static double logpdf(double x, double sigma) {
if(!(x > 0.) || x == Double.POSITIVE_INFINITY) {
return x == x ? Double.NEGATIVE_INFINITY : Double.NaN;
}
final double xs = x / sigma, xs2 = xs * xs;
return xs2 < Double.POSITIVE_INFINITY ? FastMath.log(xs / sigma) - .5 * xs2 : Double.NEGATIVE_INFINITY;
} | java | public static double logpdf(double x, double sigma) {
if(!(x > 0.) || x == Double.POSITIVE_INFINITY) {
return x == x ? Double.NEGATIVE_INFINITY : Double.NaN;
}
final double xs = x / sigma, xs2 = xs * xs;
return xs2 < Double.POSITIVE_INFINITY ? FastMath.log(xs / sigma) - .5 * xs2 : Double.NEGATIVE_INFINITY;
} | [
"public",
"static",
"double",
"logpdf",
"(",
"double",
"x",
",",
"double",
"sigma",
")",
"{",
"if",
"(",
"!",
"(",
"x",
">",
"0.",
")",
"||",
"x",
"==",
"Double",
".",
"POSITIVE_INFINITY",
")",
"{",
"return",
"x",
"==",
"x",
"?",
"Double",
".",
"... | PDF of Rayleigh distribution
@param x Value
@param sigma Scale
@return PDF at position x. | [
"PDF",
"of",
"Rayleigh",
"distribution"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/distribution/RayleighDistribution.java#L153-L159 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-container/src/main/java/com/google/cloud/container/v1/ClusterManagerClient.java | ClusterManagerClient.createCluster | public final Operation createCluster(String projectId, String zone, Cluster cluster) {
CreateClusterRequest request =
CreateClusterRequest.newBuilder()
.setProjectId(projectId)
.setZone(zone)
.setCluster(cluster)
.build();
return createCluster(request);
} | java | public final Operation createCluster(String projectId, String zone, Cluster cluster) {
CreateClusterRequest request =
CreateClusterRequest.newBuilder()
.setProjectId(projectId)
.setZone(zone)
.setCluster(cluster)
.build();
return createCluster(request);
} | [
"public",
"final",
"Operation",
"createCluster",
"(",
"String",
"projectId",
",",
"String",
"zone",
",",
"Cluster",
"cluster",
")",
"{",
"CreateClusterRequest",
"request",
"=",
"CreateClusterRequest",
".",
"newBuilder",
"(",
")",
".",
"setProjectId",
"(",
"project... | Creates a cluster, consisting of the specified number and type of Google Compute Engine
instances.
<p>By default, the cluster is created in the project's [default
network](/compute/docs/networks-and-firewalls#networks).
<p>One firewall is added for the cluster. After cluster creation, the cluster creates routes
for each node to allow the containers on that node to communicate with all other instances in
the cluster.
<p>Finally, an entry is added to the project's global metadata indicating which CIDR range is
being used by the cluster.
<p>Sample code:
<pre><code>
try (ClusterManagerClient clusterManagerClient = ClusterManagerClient.create()) {
String projectId = "";
String zone = "";
Cluster cluster = Cluster.newBuilder().build();
Operation response = clusterManagerClient.createCluster(projectId, zone, cluster);
}
</code></pre>
@param projectId Deprecated. The Google Developers Console [project ID or project
number](https://support.google.com/cloud/answer/6158840). This field has been deprecated
and replaced by the parent field.
@param zone Deprecated. The name of the Google Compute Engine
[zone](/compute/docs/zones#available) in which the cluster resides. This field has been
deprecated and replaced by the parent field.
@param cluster A [cluster
resource](/container-engine/reference/rest/v1/projects.zones.clusters)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"cluster",
"consisting",
"of",
"the",
"specified",
"number",
"and",
"type",
"of",
"Google",
"Compute",
"Engine",
"instances",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-container/src/main/java/com/google/cloud/container/v1/ClusterManagerClient.java#L394-L403 |
square/okhttp | okhttp/src/main/java/okhttp3/internal/connection/Transmitter.java | Transmitter.maybeReleaseConnection | private @Nullable IOException maybeReleaseConnection(@Nullable IOException e, boolean force) {
Socket socket;
Connection releasedConnection;
boolean callEnd;
synchronized (connectionPool) {
if (force && exchange != null) {
throw new IllegalStateException("cannot release connection while it is in use");
}
releasedConnection = this.connection;
socket = this.connection != null && exchange == null && (force || noMoreExchanges)
? releaseConnectionNoEvents()
: null;
if (this.connection != null) releasedConnection = null;
callEnd = noMoreExchanges && exchange == null;
}
closeQuietly(socket);
if (releasedConnection != null) {
eventListener.connectionReleased(call, releasedConnection);
}
if (callEnd) {
boolean callFailed = (e != null);
e = timeoutExit(e);
if (callFailed) {
eventListener.callFailed(call, e);
} else {
eventListener.callEnd(call);
}
}
return e;
} | java | private @Nullable IOException maybeReleaseConnection(@Nullable IOException e, boolean force) {
Socket socket;
Connection releasedConnection;
boolean callEnd;
synchronized (connectionPool) {
if (force && exchange != null) {
throw new IllegalStateException("cannot release connection while it is in use");
}
releasedConnection = this.connection;
socket = this.connection != null && exchange == null && (force || noMoreExchanges)
? releaseConnectionNoEvents()
: null;
if (this.connection != null) releasedConnection = null;
callEnd = noMoreExchanges && exchange == null;
}
closeQuietly(socket);
if (releasedConnection != null) {
eventListener.connectionReleased(call, releasedConnection);
}
if (callEnd) {
boolean callFailed = (e != null);
e = timeoutExit(e);
if (callFailed) {
eventListener.callFailed(call, e);
} else {
eventListener.callEnd(call);
}
}
return e;
} | [
"private",
"@",
"Nullable",
"IOException",
"maybeReleaseConnection",
"(",
"@",
"Nullable",
"IOException",
"e",
",",
"boolean",
"force",
")",
"{",
"Socket",
"socket",
";",
"Connection",
"releasedConnection",
";",
"boolean",
"callEnd",
";",
"synchronized",
"(",
"con... | Release the connection if it is no longer needed. This is called after each exchange completes
and after the call signals that no more exchanges are expected.
<p>If the transmitter was canceled or timed out, this will wrap {@code e} in an exception that
provides that additional context. Otherwise {@code e} is returned as-is.
@param force true to release the connection even if more exchanges are expected for the call. | [
"Release",
"the",
"connection",
"if",
"it",
"is",
"no",
"longer",
"needed",
".",
"This",
"is",
"called",
"after",
"each",
"exchange",
"completes",
"and",
"after",
"the",
"call",
"signals",
"that",
"no",
"more",
"exchanges",
"are",
"expected",
"."
] | train | https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/okhttp/src/main/java/okhttp3/internal/connection/Transmitter.java#L279-L310 |
assertthat/selenium-shutterbug | src/main/java/com/assertthat/selenium_shutterbug/core/Snapshot.java | Snapshot.withCroppedThumbnail | public T withCroppedThumbnail(double scale, double cropWidth, double cropHeight) {
return withCroppedThumbnail(Paths.get(location.toString(), "./thumbnails").toString(), "thumb_" + fileName, scale,cropWidth,cropHeight);
} | java | public T withCroppedThumbnail(double scale, double cropWidth, double cropHeight) {
return withCroppedThumbnail(Paths.get(location.toString(), "./thumbnails").toString(), "thumb_" + fileName, scale,cropWidth,cropHeight);
} | [
"public",
"T",
"withCroppedThumbnail",
"(",
"double",
"scale",
",",
"double",
"cropWidth",
",",
"double",
"cropHeight",
")",
"{",
"return",
"withCroppedThumbnail",
"(",
"Paths",
".",
"get",
"(",
"location",
".",
"toString",
"(",
")",
",",
"\"./thumbnails\"",
"... | Generate cropped thumbnail of the original screenshot.
Will save different thumbnails depends on when it was called in the chain.
@param scale to apply
@param cropWidth e.g. 0.2 will leave 20% of the initial width
@param cropHeight e.g. 0.1 will leave 10% of the initial width
@return instance of type Snapshot | [
"Generate",
"cropped",
"thumbnail",
"of",
"the",
"original",
"screenshot",
".",
"Will",
"save",
"different",
"thumbnails",
"depends",
"on",
"when",
"it",
"was",
"called",
"in",
"the",
"chain",
"."
] | train | https://github.com/assertthat/selenium-shutterbug/blob/770d9b92423200d262c9ab70e40405921d81e262/src/main/java/com/assertthat/selenium_shutterbug/core/Snapshot.java#L132-L134 |
classgraph/classgraph | src/main/java/nonapi/io/github/classgraph/utils/JarUtils.java | JarUtils.appendPathElt | private static void appendPathElt(final Object pathElt, final StringBuilder buf) {
if (buf.length() > 0) {
buf.append(File.pathSeparatorChar);
}
// Escape any rogue path separators, as long as file separator is not '\\' (on Windows, if there are any
// extra ';' characters in a path element, there's really nothing we can do to escape them, since they can't
// be escaped as "\\;")
final String path = File.separatorChar == '\\' ? pathElt.toString()
: pathElt.toString().replaceAll(File.pathSeparator, "\\" + File.pathSeparator);
buf.append(path);
} | java | private static void appendPathElt(final Object pathElt, final StringBuilder buf) {
if (buf.length() > 0) {
buf.append(File.pathSeparatorChar);
}
// Escape any rogue path separators, as long as file separator is not '\\' (on Windows, if there are any
// extra ';' characters in a path element, there's really nothing we can do to escape them, since they can't
// be escaped as "\\;")
final String path = File.separatorChar == '\\' ? pathElt.toString()
: pathElt.toString().replaceAll(File.pathSeparator, "\\" + File.pathSeparator);
buf.append(path);
} | [
"private",
"static",
"void",
"appendPathElt",
"(",
"final",
"Object",
"pathElt",
",",
"final",
"StringBuilder",
"buf",
")",
"{",
"if",
"(",
"buf",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"buf",
".",
"append",
"(",
"File",
".",
"pathSeparatorChar",
... | Append a path element to a buffer.
@param pathElt
the path element
@param buf
the buf | [
"Append",
"a",
"path",
"element",
"to",
"a",
"buffer",
"."
] | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/utils/JarUtils.java#L191-L201 |
apache/flink | flink-mesos/src/main/java/org/apache/flink/mesos/runtime/clusterframework/LaunchableMesosWorker.java | LaunchableMesosWorker.configureArtifactServer | static void configureArtifactServer(MesosArtifactServer server, ContainerSpecification container) throws IOException {
// serve the artifacts associated with the container environment
for (ContainerSpecification.Artifact artifact : container.getArtifacts()) {
server.addPath(artifact.source, artifact.dest);
}
} | java | static void configureArtifactServer(MesosArtifactServer server, ContainerSpecification container) throws IOException {
// serve the artifacts associated with the container environment
for (ContainerSpecification.Artifact artifact : container.getArtifacts()) {
server.addPath(artifact.source, artifact.dest);
}
} | [
"static",
"void",
"configureArtifactServer",
"(",
"MesosArtifactServer",
"server",
",",
"ContainerSpecification",
"container",
")",
"throws",
"IOException",
"{",
"// serve the artifacts associated with the container environment",
"for",
"(",
"ContainerSpecification",
".",
"Artifa... | Configures an artifact server to serve the artifacts associated with a container specification.
@param server the server to configure.
@param container the container with artifacts to serve.
@throws IOException if the artifacts cannot be accessed. | [
"Configures",
"an",
"artifact",
"server",
"to",
"serve",
"the",
"artifacts",
"associated",
"with",
"a",
"container",
"specification",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-mesos/src/main/java/org/apache/flink/mesos/runtime/clusterframework/LaunchableMesosWorker.java#L379-L384 |
Stratio/deep-spark | deep-elasticsearch/src/main/java/com/stratio/deep/es/utils/UtilES.java | UtilES.getObjectFromJson | public static <T> T getObjectFromJson(Class<T> classEntity, LinkedMapWritable jsonObject)
throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
T t = classEntity.newInstance();
Field[] fields = AnnotationUtils.filterDeepFields(classEntity);
Object insert;
for (Field field : fields) {
Method method = Utils.findSetter(field.getName(), classEntity, field.getType());
Class<?> classField = field.getType();
String key = AnnotationUtils.deepFieldName(field);
Text text = new org.apache.hadoop.io.Text(key);
Writable currentJson = jsonObject.get(text);
if (currentJson != null) {
if (Iterable.class.isAssignableFrom(classField)) {
Type type = field.getGenericType();
insert = subDocumentListCase(type, (ArrayWritable) currentJson);
method.invoke(t, (insert));
} else if (IDeepType.class.isAssignableFrom(classField)) {
insert = getObjectFromJson(classField, (LinkedMapWritable) currentJson);
method.invoke(t, (insert));
} else {
insert = currentJson;
try {
method.invoke(t, getObjectFromWritable((Writable) insert));
} catch (Exception e) {
LOG.error("impossible to convert field " + t + " :" + field + " error: " + e.getMessage());
method.invoke(t, Utils.castNumberType(getObjectFromWritable((Writable) insert), t.getClass()));
}
}
}
}
return t;
} | java | public static <T> T getObjectFromJson(Class<T> classEntity, LinkedMapWritable jsonObject)
throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
T t = classEntity.newInstance();
Field[] fields = AnnotationUtils.filterDeepFields(classEntity);
Object insert;
for (Field field : fields) {
Method method = Utils.findSetter(field.getName(), classEntity, field.getType());
Class<?> classField = field.getType();
String key = AnnotationUtils.deepFieldName(field);
Text text = new org.apache.hadoop.io.Text(key);
Writable currentJson = jsonObject.get(text);
if (currentJson != null) {
if (Iterable.class.isAssignableFrom(classField)) {
Type type = field.getGenericType();
insert = subDocumentListCase(type, (ArrayWritable) currentJson);
method.invoke(t, (insert));
} else if (IDeepType.class.isAssignableFrom(classField)) {
insert = getObjectFromJson(classField, (LinkedMapWritable) currentJson);
method.invoke(t, (insert));
} else {
insert = currentJson;
try {
method.invoke(t, getObjectFromWritable((Writable) insert));
} catch (Exception e) {
LOG.error("impossible to convert field " + t + " :" + field + " error: " + e.getMessage());
method.invoke(t, Utils.castNumberType(getObjectFromWritable((Writable) insert), t.getClass()));
}
}
}
}
return t;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getObjectFromJson",
"(",
"Class",
"<",
"T",
">",
"classEntity",
",",
"LinkedMapWritable",
"jsonObject",
")",
"throws",
"IllegalAccessException",
",",
"InstantiationException",
",",
"InvocationTargetException",
",",
"NoSuchMetho... | converts from JSONObject to an entity class with deep's anotations
@param classEntity the entity name.
@param jsonObject the instance of the JSONObject to convert.
@param <T> return type.
@return the provided JSONObject converted to an instance of T.
@throws IllegalAccessException
@throws InstantiationException
@throws java.lang.reflect.InvocationTargetException | [
"converts",
"from",
"JSONObject",
"to",
"an",
"entity",
"class",
"with",
"deep",
"s",
"anotations"
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-elasticsearch/src/main/java/com/stratio/deep/es/utils/UtilES.java#L88-L128 |
Jasig/uPortal | uPortal-web/src/main/java/org/apereo/portal/portlet/marketplace/MarketplaceSearchService.java | MarketplaceSearchService.getSearchResults | @Override
public SearchResults getSearchResults(PortletRequest request, SearchRequest query) {
final String queryString = query.getSearchTerms().toLowerCase();
final List<IPortletDefinition> portlets =
portletDefinitionRegistry.getAllPortletDefinitions();
final HttpServletRequest httpServletRequest =
this.portalRequestUtils.getPortletHttpRequest(request);
final SearchResults results = new SearchResults();
for (IPortletDefinition portlet : portlets) {
if (this.matches(
queryString,
new MarketplacePortletDefinition(
portlet, this.marketplaceService, this.portletCategoryRegistry))) {
final SearchResult result = new SearchResult();
result.setTitle(portlet.getTitle());
result.setSummary(portlet.getDescription());
result.getType().add("marketplace");
final IPortletWindow portletWindow =
this.portletWindowRegistry.getOrCreateDefaultPortletWindowByFname(
httpServletRequest, portlet.getFName());
// portletWindow is null if user does not have access to portlet.
// If user does not have browse permission, exclude the portlet.
if (portletWindow != null
&& authorizationService.canPrincipalBrowse(
authorizationService.newPrincipal(
request.getRemoteUser(), EntityEnum.PERSON.getClazz()),
portlet)) {
final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId();
final IPortalUrlBuilder portalUrlBuilder =
this.portalUrlProvider.getPortalUrlBuilderByPortletFName(
httpServletRequest, portlet.getFName(), UrlType.RENDER);
final IPortletUrlBuilder portletUrlBuilder =
portalUrlBuilder.getPortletUrlBuilder(portletWindowId);
portletUrlBuilder.setWindowState(PortletUtils.getWindowState("maximized"));
result.setExternalUrl(portalUrlBuilder.getUrlString());
PortletUrl url = new PortletUrl();
url.setType(PortletUrlType.RENDER);
url.setPortletMode("VIEW");
url.setWindowState("maximized");
PortletUrlParameter actionParam = new PortletUrlParameter();
actionParam.setName("action");
actionParam.getValue().add("view");
url.getParam().add(actionParam);
PortletUrlParameter fNameParam = new PortletUrlParameter();
fNameParam.setName("fName");
fNameParam.getValue().add(portlet.getFName());
url.getParam().add(fNameParam);
result.setPortletUrl(url);
// Add the result to list to return
results.getSearchResult().add(result);
}
}
}
return results;
} | java | @Override
public SearchResults getSearchResults(PortletRequest request, SearchRequest query) {
final String queryString = query.getSearchTerms().toLowerCase();
final List<IPortletDefinition> portlets =
portletDefinitionRegistry.getAllPortletDefinitions();
final HttpServletRequest httpServletRequest =
this.portalRequestUtils.getPortletHttpRequest(request);
final SearchResults results = new SearchResults();
for (IPortletDefinition portlet : portlets) {
if (this.matches(
queryString,
new MarketplacePortletDefinition(
portlet, this.marketplaceService, this.portletCategoryRegistry))) {
final SearchResult result = new SearchResult();
result.setTitle(portlet.getTitle());
result.setSummary(portlet.getDescription());
result.getType().add("marketplace");
final IPortletWindow portletWindow =
this.portletWindowRegistry.getOrCreateDefaultPortletWindowByFname(
httpServletRequest, portlet.getFName());
// portletWindow is null if user does not have access to portlet.
// If user does not have browse permission, exclude the portlet.
if (portletWindow != null
&& authorizationService.canPrincipalBrowse(
authorizationService.newPrincipal(
request.getRemoteUser(), EntityEnum.PERSON.getClazz()),
portlet)) {
final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId();
final IPortalUrlBuilder portalUrlBuilder =
this.portalUrlProvider.getPortalUrlBuilderByPortletFName(
httpServletRequest, portlet.getFName(), UrlType.RENDER);
final IPortletUrlBuilder portletUrlBuilder =
portalUrlBuilder.getPortletUrlBuilder(portletWindowId);
portletUrlBuilder.setWindowState(PortletUtils.getWindowState("maximized"));
result.setExternalUrl(portalUrlBuilder.getUrlString());
PortletUrl url = new PortletUrl();
url.setType(PortletUrlType.RENDER);
url.setPortletMode("VIEW");
url.setWindowState("maximized");
PortletUrlParameter actionParam = new PortletUrlParameter();
actionParam.setName("action");
actionParam.getValue().add("view");
url.getParam().add(actionParam);
PortletUrlParameter fNameParam = new PortletUrlParameter();
fNameParam.setName("fName");
fNameParam.getValue().add(portlet.getFName());
url.getParam().add(fNameParam);
result.setPortletUrl(url);
// Add the result to list to return
results.getSearchResult().add(result);
}
}
}
return results;
} | [
"@",
"Override",
"public",
"SearchResults",
"getSearchResults",
"(",
"PortletRequest",
"request",
",",
"SearchRequest",
"query",
")",
"{",
"final",
"String",
"queryString",
"=",
"query",
".",
"getSearchTerms",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"final"... | Returns a list of search results that pertain to the marketplace query is the query to search
will search name, title, description, fname, and captions | [
"Returns",
"a",
"list",
"of",
"search",
"results",
"that",
"pertain",
"to",
"the",
"marketplace",
"query",
"is",
"the",
"query",
"to",
"search",
"will",
"search",
"name",
"title",
"description",
"fname",
"and",
"captions"
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/marketplace/MarketplaceSearchService.java#L93-L152 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java | CommonOps_DDF4.elementMult | public static void elementMult( DMatrix4x4 a , DMatrix4x4 b , DMatrix4x4 c ) {
c.a11 = a.a11*b.a11; c.a12 = a.a12*b.a12; c.a13 = a.a13*b.a13; c.a14 = a.a14*b.a14;
c.a21 = a.a21*b.a21; c.a22 = a.a22*b.a22; c.a23 = a.a23*b.a23; c.a24 = a.a24*b.a24;
c.a31 = a.a31*b.a31; c.a32 = a.a32*b.a32; c.a33 = a.a33*b.a33; c.a34 = a.a34*b.a34;
c.a41 = a.a41*b.a41; c.a42 = a.a42*b.a42; c.a43 = a.a43*b.a43; c.a44 = a.a44*b.a44;
} | java | public static void elementMult( DMatrix4x4 a , DMatrix4x4 b , DMatrix4x4 c ) {
c.a11 = a.a11*b.a11; c.a12 = a.a12*b.a12; c.a13 = a.a13*b.a13; c.a14 = a.a14*b.a14;
c.a21 = a.a21*b.a21; c.a22 = a.a22*b.a22; c.a23 = a.a23*b.a23; c.a24 = a.a24*b.a24;
c.a31 = a.a31*b.a31; c.a32 = a.a32*b.a32; c.a33 = a.a33*b.a33; c.a34 = a.a34*b.a34;
c.a41 = a.a41*b.a41; c.a42 = a.a42*b.a42; c.a43 = a.a43*b.a43; c.a44 = a.a44*b.a44;
} | [
"public",
"static",
"void",
"elementMult",
"(",
"DMatrix4x4",
"a",
",",
"DMatrix4x4",
"b",
",",
"DMatrix4x4",
"c",
")",
"{",
"c",
".",
"a11",
"=",
"a",
".",
"a11",
"*",
"b",
".",
"a11",
";",
"c",
".",
"a12",
"=",
"a",
".",
"a12",
"*",
"b",
".",... | <p>Performs an element by element multiplication operation:<br>
<br>
c<sub>ij</sub> = a<sub>ij</sub> * b<sub>ij</sub> <br>
</p>
@param a The left matrix in the multiplication operation. Not modified.
@param b The right matrix in the multiplication operation. Not modified.
@param c Where the results of the operation are stored. Modified. | [
"<p",
">",
"Performs",
"an",
"element",
"by",
"element",
"multiplication",
"operation",
":",
"<br",
">",
"<br",
">",
"c<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"*",
"b<sub",
">",
"ij<",
"/",
"sub",
">",
"<br",
... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java#L1323-L1328 |
jglobus/JGlobus | ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java | BouncyCastleCertProcessingFactory.createCertificateRequest | public byte[] createCertificateRequest(X509Name subjectDN, String sigAlgName, KeyPair keyPair)
throws GeneralSecurityException {
DERSet attrs = null;
PKCS10CertificationRequest certReq = null;
certReq = new PKCS10CertificationRequest(sigAlgName, subjectDN, keyPair.getPublic(), attrs, keyPair
.getPrivate());
return certReq.getEncoded();
} | java | public byte[] createCertificateRequest(X509Name subjectDN, String sigAlgName, KeyPair keyPair)
throws GeneralSecurityException {
DERSet attrs = null;
PKCS10CertificationRequest certReq = null;
certReq = new PKCS10CertificationRequest(sigAlgName, subjectDN, keyPair.getPublic(), attrs, keyPair
.getPrivate());
return certReq.getEncoded();
} | [
"public",
"byte",
"[",
"]",
"createCertificateRequest",
"(",
"X509Name",
"subjectDN",
",",
"String",
"sigAlgName",
",",
"KeyPair",
"keyPair",
")",
"throws",
"GeneralSecurityException",
"{",
"DERSet",
"attrs",
"=",
"null",
";",
"PKCS10CertificationRequest",
"certReq",
... | Creates a certificate request from the specified subject name, signing algorithm, and a key pair.
@param subjectDN
the subject name of the certificate request.
@param sigAlgName
the signing algorithm name.
@param keyPair
the key pair of the certificate request
@return the certificate request.
@exception GeneralSecurityException
if security error occurs. | [
"Creates",
"a",
"certificate",
"request",
"from",
"the",
"specified",
"subject",
"name",
"signing",
"algorithm",
"and",
"a",
"key",
"pair",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java#L983-L991 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/tree/MapPolylineTreeSet.java | MapPolylineTreeSet.getNearestEnd | @Override
@Pure
public final P getNearestEnd(Point2D<?, ?> position) {
return getNearestEnd(position.getX(), position.getY());
} | java | @Override
@Pure
public final P getNearestEnd(Point2D<?, ?> position) {
return getNearestEnd(position.getX(), position.getY());
} | [
"@",
"Override",
"@",
"Pure",
"public",
"final",
"P",
"getNearestEnd",
"(",
"Point2D",
"<",
"?",
",",
"?",
">",
"position",
")",
"{",
"return",
"getNearestEnd",
"(",
"position",
".",
"getX",
"(",
")",
",",
"position",
".",
"getY",
"(",
")",
")",
";",... | {@inheritDoc}
The nearest neighbor (NN) algorithm, to find the NN to a given target
point not in the tree, relies on the ability to discard large portions
of the tree by performing a simple test. To perform the NN calculation,
the tree is searched in a depth-first fashion, refining the nearest
distance. First the root node is examined with an initial assumption
that the smallest distance to the next point is infinite. The subdomain
(right or left), which is a hyperrectangle, containing the target point
is searched. This is done recursively until a final minimum region
containing the node is found. The algorithm then (through recursion)
examines each parent node, seeing if it is possible for the other
domain to contain a point that is closer. This is performed by
testing for the possibility of intersection between the hyperrectangle
and the hypersphere (formed by target node and current minimum radius).
If the rectangle that has not been recursively examined yet does not
intersect this sphere, then there is no way that the rectangle can
contain a point that is a better nearest neighbour. This is repeated
until all domains are either searched or discarded, thus leaving the
nearest neighbour as the final result. In addition to this one also
has the distance to the nearest neighbour on hand as well. Finding the
nearest point is an O(logN) operation. | [
"{"
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/tree/MapPolylineTreeSet.java#L124-L128 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java | StrSubstitutor.replaceIn | public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
if (source == null) {
return false;
}
final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
if (substitute(buf, 0, length) == false) {
return false;
}
source.replace(offset, offset + length, buf.toString());
return true;
} | java | public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
if (source == null) {
return false;
}
final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
if (substitute(buf, 0, length) == false) {
return false;
}
source.replace(offset, offset + length, buf.toString());
return true;
} | [
"public",
"boolean",
"replaceIn",
"(",
"final",
"StringBuffer",
"source",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"length",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"final",
"StrBuilder",
"buf",
"=",... | Replaces all the occurrences of variables within the given source buffer
with their matching values from the resolver.
The buffer is updated with the result.
<p>
Only the specified portion of the buffer will be processed.
The rest of the buffer is not processed, but it is not deleted.
@param source the buffer to replace in, updated, null returns zero
@param offset the start offset within the array, must be valid
@param length the length within the buffer to be processed, must be valid
@return true if altered | [
"Replaces",
"all",
"the",
"occurrences",
"of",
"variables",
"within",
"the",
"given",
"source",
"buffer",
"with",
"their",
"matching",
"values",
"from",
"the",
"resolver",
".",
"The",
"buffer",
"is",
"updated",
"with",
"the",
"result",
".",
"<p",
">",
"Only"... | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java#L641-L651 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/util/LruCache.java | LruCache.put | public synchronized void put(Key key, Value value) {
long valueSize = value.getSize();
if (maxSizeBytes == 0 || maxSizeEntries == 0 || valueSize * 2 > maxSizeBytes) {
// Just destroy the value if cache is disabled or if entry would consume more than a half of
// the cache
evictValue(value);
return;
}
currentSize += valueSize;
Value prev = cache.put(key, value);
if (prev == null) {
return;
}
// This should be a rare case
currentSize -= prev.getSize();
if (prev != value) {
evictValue(prev);
}
} | java | public synchronized void put(Key key, Value value) {
long valueSize = value.getSize();
if (maxSizeBytes == 0 || maxSizeEntries == 0 || valueSize * 2 > maxSizeBytes) {
// Just destroy the value if cache is disabled or if entry would consume more than a half of
// the cache
evictValue(value);
return;
}
currentSize += valueSize;
Value prev = cache.put(key, value);
if (prev == null) {
return;
}
// This should be a rare case
currentSize -= prev.getSize();
if (prev != value) {
evictValue(prev);
}
} | [
"public",
"synchronized",
"void",
"put",
"(",
"Key",
"key",
",",
"Value",
"value",
")",
"{",
"long",
"valueSize",
"=",
"value",
".",
"getSize",
"(",
")",
";",
"if",
"(",
"maxSizeBytes",
"==",
"0",
"||",
"maxSizeEntries",
"==",
"0",
"||",
"valueSize",
"... | Returns given value to the cache.
@param key key
@param value value | [
"Returns",
"given",
"value",
"to",
"the",
"cache",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/util/LruCache.java#L127-L145 |
jtmelton/appsensor | analysis-engines/appsensor-analysis-rules/src/main/java/org/owasp/appsensor/analysis/AggregateEventAnalysisEngine.java | AggregateEventAnalysisEngine.checkExpression | protected boolean checkExpression(Expression expression, Queue<Notification> notifications) {
for (Clause clause : expression.getClauses()) {
if (checkClause(clause, notifications)) {
return true;
}
}
return false;
} | java | protected boolean checkExpression(Expression expression, Queue<Notification> notifications) {
for (Clause clause : expression.getClauses()) {
if (checkClause(clause, notifications)) {
return true;
}
}
return false;
} | [
"protected",
"boolean",
"checkExpression",
"(",
"Expression",
"expression",
",",
"Queue",
"<",
"Notification",
">",
"notifications",
")",
"{",
"for",
"(",
"Clause",
"clause",
":",
"expression",
".",
"getClauses",
"(",
")",
")",
"{",
"if",
"(",
"checkClause",
... | Evaluates an {@link Expression}'s logic by evaluating all {@link Clause}s. Any
{@link Clause} must evaluate to true for the {@link Expression} to evaluate to true.
Equivalent to checking "OR" logic between {@link Clause}s.
@param expression the {@link Expression} being evaluated
@param notifications the {@link Notification}s in the current "sliding window"
@return the boolean evaluation of the {@link Expression} | [
"Evaluates",
"an",
"{",
"@link",
"Expression",
"}",
"s",
"logic",
"by",
"evaluating",
"all",
"{",
"@link",
"Clause",
"}",
"s",
".",
"Any",
"{",
"@link",
"Clause",
"}",
"must",
"evaluate",
"to",
"true",
"for",
"the",
"{",
"@link",
"Expression",
"}",
"to... | train | https://github.com/jtmelton/appsensor/blob/c3b4e9ada50fdee974e0d618ec4bdfabc2163798/analysis-engines/appsensor-analysis-rules/src/main/java/org/owasp/appsensor/analysis/AggregateEventAnalysisEngine.java#L119-L127 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_trunk_serviceName_externalDisplayedNumber_number_GET | public OvhTrunkExternalDisplayedNumber billingAccount_trunk_serviceName_externalDisplayedNumber_number_GET(String billingAccount, String serviceName, String number) throws IOException {
String qPath = "/telephony/{billingAccount}/trunk/{serviceName}/externalDisplayedNumber/{number}";
StringBuilder sb = path(qPath, billingAccount, serviceName, number);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhTrunkExternalDisplayedNumber.class);
} | java | public OvhTrunkExternalDisplayedNumber billingAccount_trunk_serviceName_externalDisplayedNumber_number_GET(String billingAccount, String serviceName, String number) throws IOException {
String qPath = "/telephony/{billingAccount}/trunk/{serviceName}/externalDisplayedNumber/{number}";
StringBuilder sb = path(qPath, billingAccount, serviceName, number);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhTrunkExternalDisplayedNumber.class);
} | [
"public",
"OvhTrunkExternalDisplayedNumber",
"billingAccount_trunk_serviceName_externalDisplayedNumber_number_GET",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"String",
"number",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{... | Get this object properties
REST: GET /telephony/{billingAccount}/trunk/{serviceName}/externalDisplayedNumber/{number}
@param billingAccount [required] The name of your billingAccount
@param serviceName [required] Name of the service
@param number [required] External displayed number linked to a trunk | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L8135-L8140 |
menacher/java-game-server | jetclient/src/main/java/org/menacheri/jetclient/util/NettyUtils.java | NettyUtils.writeString | public static ChannelBuffer writeString(String msg, Charset charset)
{
ChannelBuffer buffer = null;
try
{
ChannelBuffer stringBuffer = null;
if (null == charset)
{
charset = CharsetUtil.UTF_8;
}
stringBuffer = copiedBuffer(ByteOrder.BIG_ENDIAN, msg, charset);
int length = stringBuffer.readableBytes();
ChannelBuffer lengthBuffer = ChannelBuffers.buffer(2);
lengthBuffer.writeShort(length);
buffer = ChannelBuffers.wrappedBuffer(lengthBuffer, stringBuffer);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return buffer;
} | java | public static ChannelBuffer writeString(String msg, Charset charset)
{
ChannelBuffer buffer = null;
try
{
ChannelBuffer stringBuffer = null;
if (null == charset)
{
charset = CharsetUtil.UTF_8;
}
stringBuffer = copiedBuffer(ByteOrder.BIG_ENDIAN, msg, charset);
int length = stringBuffer.readableBytes();
ChannelBuffer lengthBuffer = ChannelBuffers.buffer(2);
lengthBuffer.writeShort(length);
buffer = ChannelBuffers.wrappedBuffer(lengthBuffer, stringBuffer);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return buffer;
} | [
"public",
"static",
"ChannelBuffer",
"writeString",
"(",
"String",
"msg",
",",
"Charset",
"charset",
")",
"{",
"ChannelBuffer",
"buffer",
"=",
"null",
";",
"try",
"{",
"ChannelBuffer",
"stringBuffer",
"=",
"null",
";",
"if",
"(",
"null",
"==",
"charset",
")"... | Creates a channel buffer of which the first 2 bytes contain the length of
the string in bytes and the remaining is the actual string in binary with
specified format. Defaults to UTF-8 encoding in case charset passed in is
null
@param msg
The string to be written.
@param charset
The Charset say 'UTF-8' in which the encoding needs to be
done.
@return The Netty channel buffer containing the string encoded as bytes
in the provided charset. It will return <code>null</code> if the
string parameter is null. | [
"Creates",
"a",
"channel",
"buffer",
"of",
"which",
"the",
"first",
"2",
"bytes",
"contain",
"the",
"length",
"of",
"the",
"string",
"in",
"bytes",
"and",
"the",
"remaining",
"is",
"the",
"actual",
"string",
"in",
"binary",
"with",
"specified",
"format",
"... | train | https://github.com/menacher/java-game-server/blob/668ca49e8bd1dac43add62378cf6c22a93125d48/jetclient/src/main/java/org/menacheri/jetclient/util/NettyUtils.java#L270-L291 |
beanshell/beanshell | src/main/java/bsh/Reflect.java | Reflect.getLHSObjectField | static LHS getLHSObjectField( Object object, String fieldName )
throws UtilEvalError, ReflectError {
if ( object instanceof This )
return new LHS( ((This)object).namespace, fieldName, false );
try {
Invocable f = resolveExpectedJavaField(
object.getClass(), fieldName, false/*staticOnly*/ );
return new LHS(object, f);
} catch ( ReflectError e ) {
NameSpace ns = getThisNS(object);
if (isGeneratedClass(object.getClass()) && null != ns && ns.isClass) {
Variable var = ns.getVariableImpl(fieldName, true);
if ( null != var && (!var.hasModifier("private")
|| haveAccessibility()) )
return new LHS(ns, fieldName);
}
// not a field, try property access
if ( hasObjectPropertySetter( object.getClass(), fieldName ) )
return new LHS( object, fieldName );
else
throw e;
}
} | java | static LHS getLHSObjectField( Object object, String fieldName )
throws UtilEvalError, ReflectError {
if ( object instanceof This )
return new LHS( ((This)object).namespace, fieldName, false );
try {
Invocable f = resolveExpectedJavaField(
object.getClass(), fieldName, false/*staticOnly*/ );
return new LHS(object, f);
} catch ( ReflectError e ) {
NameSpace ns = getThisNS(object);
if (isGeneratedClass(object.getClass()) && null != ns && ns.isClass) {
Variable var = ns.getVariableImpl(fieldName, true);
if ( null != var && (!var.hasModifier("private")
|| haveAccessibility()) )
return new LHS(ns, fieldName);
}
// not a field, try property access
if ( hasObjectPropertySetter( object.getClass(), fieldName ) )
return new LHS( object, fieldName );
else
throw e;
}
} | [
"static",
"LHS",
"getLHSObjectField",
"(",
"Object",
"object",
",",
"String",
"fieldName",
")",
"throws",
"UtilEvalError",
",",
"ReflectError",
"{",
"if",
"(",
"object",
"instanceof",
"This",
")",
"return",
"new",
"LHS",
"(",
"(",
"(",
"This",
")",
"object",... | Get an LHS reference to an object field.
This method also deals with the field style property access.
In the field does not exist we check for a property setter. | [
"Get",
"an",
"LHS",
"reference",
"to",
"an",
"object",
"field",
"."
] | train | https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Reflect.java#L189-L211 |
Azure/azure-sdk-for-java | cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java | DatabaseAccountsInner.beginCreateOrUpdate | public DatabaseAccountInner beginCreateOrUpdate(String resourceGroupName, String accountName, DatabaseAccountCreateUpdateParameters createUpdateParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, createUpdateParameters).toBlocking().single().body();
} | java | public DatabaseAccountInner beginCreateOrUpdate(String resourceGroupName, String accountName, DatabaseAccountCreateUpdateParameters createUpdateParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, createUpdateParameters).toBlocking().single().body();
} | [
"public",
"DatabaseAccountInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
",",
"DatabaseAccountCreateUpdateParameters",
"createUpdateParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupN... | Creates or updates an Azure Cosmos DB database account.
@param resourceGroupName Name of an Azure resource group.
@param accountName Cosmos DB database account name.
@param createUpdateParameters The parameters to provide for the current database account.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DatabaseAccountInner object if successful. | [
"Creates",
"or",
"updates",
"an",
"Azure",
"Cosmos",
"DB",
"database",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cosmosdb/resource-manager/v2015_04_08/src/main/java/com/microsoft/azure/management/cosmosdb/v2015_04_08/implementation/DatabaseAccountsInner.java#L522-L524 |
morimekta/utils | io-util/src/main/java/net/morimekta/util/io/BinaryReader.java | BinaryReader.expectInt | public int expectInt() throws IOException {
int b1 = in.read();
if (b1 < 0) {
throw new IOException("Missing byte 1 to expected int");
}
int b2 = in.read();
if (b2 < 0) {
throw new IOException("Missing byte 2 to expected int");
}
int b3 = in.read();
if (b3 < 0) {
throw new IOException("Missing byte 3 to expected int");
}
int b4 = in.read();
if (b4 < 0) {
throw new IOException("Missing byte 4 to expected int");
}
return unshift4bytes(b1, b2, b3, b4);
} | java | public int expectInt() throws IOException {
int b1 = in.read();
if (b1 < 0) {
throw new IOException("Missing byte 1 to expected int");
}
int b2 = in.read();
if (b2 < 0) {
throw new IOException("Missing byte 2 to expected int");
}
int b3 = in.read();
if (b3 < 0) {
throw new IOException("Missing byte 3 to expected int");
}
int b4 = in.read();
if (b4 < 0) {
throw new IOException("Missing byte 4 to expected int");
}
return unshift4bytes(b1, b2, b3, b4);
} | [
"public",
"int",
"expectInt",
"(",
")",
"throws",
"IOException",
"{",
"int",
"b1",
"=",
"in",
".",
"read",
"(",
")",
";",
"if",
"(",
"b1",
"<",
"0",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Missing byte 1 to expected int\"",
")",
";",
"}",
"int... | Read an int from the input stream.
@return The number read.
@throws IOException if unable to read from stream. | [
"Read",
"an",
"int",
"from",
"the",
"input",
"stream",
"."
] | train | https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/io/BinaryReader.java#L147-L165 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.java | CheckReturnValue.matchClass | @Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (hasDirectAnnotationWithSimpleName(ASTHelpers.getSymbol(tree), CHECK_RETURN_VALUE)
&& hasDirectAnnotationWithSimpleName(ASTHelpers.getSymbol(tree), CAN_IGNORE_RETURN_VALUE)) {
return buildDescription(tree).setMessage(String.format(BOTH_ERROR, "class")).build();
}
return Description.NO_MATCH;
} | java | @Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (hasDirectAnnotationWithSimpleName(ASTHelpers.getSymbol(tree), CHECK_RETURN_VALUE)
&& hasDirectAnnotationWithSimpleName(ASTHelpers.getSymbol(tree), CAN_IGNORE_RETURN_VALUE)) {
return buildDescription(tree).setMessage(String.format(BOTH_ERROR, "class")).build();
}
return Description.NO_MATCH;
} | [
"@",
"Override",
"public",
"Description",
"matchClass",
"(",
"ClassTree",
"tree",
",",
"VisitorState",
"state",
")",
"{",
"if",
"(",
"hasDirectAnnotationWithSimpleName",
"(",
"ASTHelpers",
".",
"getSymbol",
"(",
"tree",
")",
",",
"CHECK_RETURN_VALUE",
")",
"&&",
... | Validate that at most one of {@code CheckReturnValue} and {@code CanIgnoreReturnValue} are
applied to a class (or interface or enum). | [
"Validate",
"that",
"at",
"most",
"one",
"of",
"{"
] | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.java#L162-L169 |
jhunters/jprotobuf | src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java | MiniTemplator.setVariableOptEsc | public void setVariableOptEsc(String variableName, String variableValue) {
setVariable(variableName, escapeHtml(variableValue), true);
} | java | public void setVariableOptEsc(String variableName, String variableValue) {
setVariable(variableName, escapeHtml(variableValue), true);
} | [
"public",
"void",
"setVariableOptEsc",
"(",
"String",
"variableName",
",",
"String",
"variableValue",
")",
"{",
"setVariable",
"(",
"variableName",
",",
"escapeHtml",
"(",
"variableValue",
")",
",",
"true",
")",
";",
"}"
] | Sets an optional template variable to an escaped value.
<p>
Convenience method for: <code>setVariable (variableName, MiniTemplator.escapeHtml(variableValue), true)</code>
@param variableName the name of the variable to be set. Case-insensitive.
@param variableValue the new value of the variable. May be <code>null</code>. Special HTML/XML characters are
escaped.
@see #setVariable(String, String, boolean)
@see #escapeHtml(String) | [
"Sets",
"an",
"optional",
"template",
"variable",
"to",
"an",
"escaped",
"value",
".",
"<p",
">",
"Convenience",
"method",
"for",
":",
"<code",
">",
"setVariable",
"(",
"variableName",
"MiniTemplator",
".",
"escapeHtml",
"(",
"variableValue",
")",
"true",
")",... | train | https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/utils/MiniTemplator.java#L483-L485 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/lib/MultipleOutputs.java | MultipleOutputs.getCollector | @SuppressWarnings({"unchecked"})
public OutputCollector getCollector(String namedOutput, String multiName,
Reporter reporter)
throws IOException {
checkNamedOutputName(namedOutput);
if (!namedOutputs.contains(namedOutput)) {
throw new IllegalArgumentException("Undefined named output '" +
namedOutput + "'");
}
boolean multi = isMultiNamedOutput(conf, namedOutput);
if (!multi && multiName != null) {
throw new IllegalArgumentException("Name output '" + namedOutput +
"' has not been defined as multi");
}
if (multi) {
checkTokenName(multiName);
}
String baseFileName = (multi) ? namedOutput + "_" + multiName : namedOutput;
final RecordWriter writer =
getRecordWriter(namedOutput, baseFileName, reporter);
return new OutputCollector() {
@SuppressWarnings({"unchecked"})
public void collect(Object key, Object value) throws IOException {
writer.write(key, value);
}
};
} | java | @SuppressWarnings({"unchecked"})
public OutputCollector getCollector(String namedOutput, String multiName,
Reporter reporter)
throws IOException {
checkNamedOutputName(namedOutput);
if (!namedOutputs.contains(namedOutput)) {
throw new IllegalArgumentException("Undefined named output '" +
namedOutput + "'");
}
boolean multi = isMultiNamedOutput(conf, namedOutput);
if (!multi && multiName != null) {
throw new IllegalArgumentException("Name output '" + namedOutput +
"' has not been defined as multi");
}
if (multi) {
checkTokenName(multiName);
}
String baseFileName = (multi) ? namedOutput + "_" + multiName : namedOutput;
final RecordWriter writer =
getRecordWriter(namedOutput, baseFileName, reporter);
return new OutputCollector() {
@SuppressWarnings({"unchecked"})
public void collect(Object key, Object value) throws IOException {
writer.write(key, value);
}
};
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
"}",
")",
"public",
"OutputCollector",
"getCollector",
"(",
"String",
"namedOutput",
",",
"String",
"multiName",
",",
"Reporter",
"reporter",
")",
"throws",
"IOException",
"{",
"checkNamedOutputName",
"(",
"namedOu... | Gets the output collector for a multi named output.
<p/>
@param namedOutput the named output name
@param multiName the multi name part
@param reporter the reporter
@return the output collector for the given named output
@throws IOException thrown if output collector could not be created | [
"Gets",
"the",
"output",
"collector",
"for",
"a",
"multi",
"named",
"output",
".",
"<p",
"/",
">"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/lib/MultipleOutputs.java#L489-L522 |
amaembo/streamex | src/main/java/one/util/streamex/IntStreamEx.java | IntStreamEx.chain | @Override
public <U> U chain(Function<? super IntStreamEx, U> mapper) {
return mapper.apply(this);
} | java | @Override
public <U> U chain(Function<? super IntStreamEx, U> mapper) {
return mapper.apply(this);
} | [
"@",
"Override",
"public",
"<",
"U",
">",
"U",
"chain",
"(",
"Function",
"<",
"?",
"super",
"IntStreamEx",
",",
"U",
">",
"mapper",
")",
"{",
"return",
"mapper",
".",
"apply",
"(",
"this",
")",
";",
"}"
] | does not add overhead as it appears in bytecode anyways as bridge method | [
"does",
"not",
"add",
"overhead",
"as",
"it",
"appears",
"in",
"bytecode",
"anyways",
"as",
"bridge",
"method"
] | train | https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/IntStreamEx.java#L1766-L1769 |
hawtio/hawtio | tooling/hawtio-junit/src/main/java/io/hawt/junit/ThrowableDTO.java | ThrowableDTO.addThrowableAndCauses | public static void addThrowableAndCauses(List<ThrowableDTO> exceptions, Throwable exception) {
if (exception != null) {
ThrowableDTO dto = new ThrowableDTO(exception);
exceptions.add(dto);
Throwable cause = exception.getCause();
if (cause != null && cause != exception) {
addThrowableAndCauses(exceptions, cause);
}
}
} | java | public static void addThrowableAndCauses(List<ThrowableDTO> exceptions, Throwable exception) {
if (exception != null) {
ThrowableDTO dto = new ThrowableDTO(exception);
exceptions.add(dto);
Throwable cause = exception.getCause();
if (cause != null && cause != exception) {
addThrowableAndCauses(exceptions, cause);
}
}
} | [
"public",
"static",
"void",
"addThrowableAndCauses",
"(",
"List",
"<",
"ThrowableDTO",
">",
"exceptions",
",",
"Throwable",
"exception",
")",
"{",
"if",
"(",
"exception",
"!=",
"null",
")",
"{",
"ThrowableDTO",
"dto",
"=",
"new",
"ThrowableDTO",
"(",
"exceptio... | Adds the exception and all of the causes to the given list of exceptions | [
"Adds",
"the",
"exception",
"and",
"all",
"of",
"the",
"causes",
"to",
"the",
"given",
"list",
"of",
"exceptions"
] | train | https://github.com/hawtio/hawtio/blob/d8b1c8f246307c0313ba297a494106d0859f3ffd/tooling/hawtio-junit/src/main/java/io/hawt/junit/ThrowableDTO.java#L35-L44 |
dbracewell/mango | src/main/java/com/davidbracewell/tuple/Tuple.java | Tuple.mapValues | public Tuple mapValues(@NonNull Function<Object, ? extends Object> function) {
return NTuple.of(Arrays.stream(array()).map(function).collect(Collectors.toList()));
} | java | public Tuple mapValues(@NonNull Function<Object, ? extends Object> function) {
return NTuple.of(Arrays.stream(array()).map(function).collect(Collectors.toList()));
} | [
"public",
"Tuple",
"mapValues",
"(",
"@",
"NonNull",
"Function",
"<",
"Object",
",",
"?",
"extends",
"Object",
">",
"function",
")",
"{",
"return",
"NTuple",
".",
"of",
"(",
"Arrays",
".",
"stream",
"(",
"array",
"(",
")",
")",
".",
"map",
"(",
"func... | Maps the values of the tuple to another data type
@param function the mapping function
@return A new tuple of same degree whose values are the result of the mapping function applied to the this tuple's
elements. | [
"Maps",
"the",
"values",
"of",
"the",
"tuple",
"to",
"another",
"data",
"type"
] | train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/tuple/Tuple.java#L93-L95 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/theta/UnionImpl.java | UnionImpl.fastWrap | static UnionImpl fastWrap(final WritableMemory srcMem, final long seed) {
Family.UNION.checkFamilyID(extractFamilyID(srcMem));
final UpdateSketch gadget = DirectQuickSelectSketch.fastWritableWrap(srcMem, seed);
final UnionImpl unionImpl = new UnionImpl(gadget, seed);
unionImpl.unionThetaLong_ = extractUnionThetaLong(srcMem);
unionImpl.unionEmpty_ = PreambleUtil.isEmpty(srcMem);
return unionImpl;
} | java | static UnionImpl fastWrap(final WritableMemory srcMem, final long seed) {
Family.UNION.checkFamilyID(extractFamilyID(srcMem));
final UpdateSketch gadget = DirectQuickSelectSketch.fastWritableWrap(srcMem, seed);
final UnionImpl unionImpl = new UnionImpl(gadget, seed);
unionImpl.unionThetaLong_ = extractUnionThetaLong(srcMem);
unionImpl.unionEmpty_ = PreambleUtil.isEmpty(srcMem);
return unionImpl;
} | [
"static",
"UnionImpl",
"fastWrap",
"(",
"final",
"WritableMemory",
"srcMem",
",",
"final",
"long",
"seed",
")",
"{",
"Family",
".",
"UNION",
".",
"checkFamilyID",
"(",
"extractFamilyID",
"(",
"srcMem",
")",
")",
";",
"final",
"UpdateSketch",
"gadget",
"=",
"... | Fast-wrap a Union object around a Union Memory object containing data.
This does NO validity checking of the given Memory.
@param srcMem The source Memory object.
<a href="{@docRoot}/resources/dictionary.html#mem">See Memory</a>
@param seed <a href="{@docRoot}/resources/dictionary.html#seed">See seed</a>
@return this class | [
"Fast",
"-",
"wrap",
"a",
"Union",
"object",
"around",
"a",
"Union",
"Memory",
"object",
"containing",
"data",
".",
"This",
"does",
"NO",
"validity",
"checking",
"of",
"the",
"given",
"Memory",
"."
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/UnionImpl.java#L153-L160 |
trustathsh/ifmapj | src/main/java/de/hshannover/f4/trust/ifmapj/identifier/Identifiers.java | Identifiers.createExtendedIdentity | public static Identity createExtendedIdentity(String extendedIdentifier,
Charset c) throws MarshalException {
return createExtendedIdentity(DomHelpers.toDocument(extendedIdentifier, c));
} | java | public static Identity createExtendedIdentity(String extendedIdentifier,
Charset c) throws MarshalException {
return createExtendedIdentity(DomHelpers.toDocument(extendedIdentifier, c));
} | [
"public",
"static",
"Identity",
"createExtendedIdentity",
"(",
"String",
"extendedIdentifier",
",",
"Charset",
"c",
")",
"throws",
"MarshalException",
"{",
"return",
"createExtendedIdentity",
"(",
"DomHelpers",
".",
"toDocument",
"(",
"extendedIdentifier",
",",
"c",
"... | Create an extended {@link Identity} identifier.
@param extendedIdentifier the extended identifier XML
@param c charset used for encoding the string
@return the new extended identity instance
@throws IfmapException | [
"Create",
"an",
"extended",
"{",
"@link",
"Identity",
"}",
"identifier",
"."
] | train | https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/de/hshannover/f4/trust/ifmapj/identifier/Identifiers.java#L593-L596 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/collection/FastHashMap.java | FastHashMap.put | public V put(K key, V value) {
EntryImpl<K, V> entry = _entries[keyHash(key) & _mask];
while (entry != null) {
if (key.equals(entry._key)) {
V prevValue = entry._value;
entry._value = value;
return prevValue;
}
entry = entry._next;
}
// No previous mapping.
addEntry(key, value);
return null;
} | java | public V put(K key, V value) {
EntryImpl<K, V> entry = _entries[keyHash(key) & _mask];
while (entry != null) {
if (key.equals(entry._key)) {
V prevValue = entry._value;
entry._value = value;
return prevValue;
}
entry = entry._next;
}
// No previous mapping.
addEntry(key, value);
return null;
} | [
"public",
"V",
"put",
"(",
"K",
"key",
",",
"V",
"value",
")",
"{",
"EntryImpl",
"<",
"K",
",",
"V",
">",
"entry",
"=",
"_entries",
"[",
"keyHash",
"(",
"key",
")",
"&",
"_mask",
"]",
";",
"while",
"(",
"entry",
"!=",
"null",
")",
"{",
"if",
... | Associates the specified value with the specified key in this {@link FastMap}. If the
{@link FastMap} previously contained a mapping
for this key, the old value is replaced.
@param key the key with which the specified value is to be associated.
@param value the value to be associated with the specified key.
@return the previous value associated with specified key,
or <code>null</code> if there was no mapping for key.
A <code>null</code> return can also indicate that the map
previously associated <code>null</code> with the specified key.
@throws NullPointerException if the key is <code>null</code>. | [
"Associates",
"the",
"specified",
"value",
"with",
"the",
"specified",
"key",
"in",
"this",
"{",
"@link",
"FastMap",
"}",
".",
"If",
"the",
"{",
"@link",
"FastMap",
"}",
"previously",
"contained",
"a",
"mapping",
"for",
"this",
"key",
"the",
"old",
"value"... | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/collection/FastHashMap.java#L221-L234 |
Azure/autorest-clientruntime-for-java | azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/resources/ResourceUtilsCore.java | ResourceUtilsCore.extractFromResourceId | public static String extractFromResourceId(String id, String identifier) {
if (id == null || identifier == null) {
return id;
}
Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+");
Matcher matcher = pattern.matcher(id);
if (matcher.find()) {
return matcher.group().split("/")[1];
} else {
return null;
}
} | java | public static String extractFromResourceId(String id, String identifier) {
if (id == null || identifier == null) {
return id;
}
Pattern pattern = Pattern.compile(identifier + "/[-\\w._]+");
Matcher matcher = pattern.matcher(id);
if (matcher.find()) {
return matcher.group().split("/")[1];
} else {
return null;
}
} | [
"public",
"static",
"String",
"extractFromResourceId",
"(",
"String",
"id",
",",
"String",
"identifier",
")",
"{",
"if",
"(",
"id",
"==",
"null",
"||",
"identifier",
"==",
"null",
")",
"{",
"return",
"id",
";",
"}",
"Pattern",
"pattern",
"=",
"Pattern",
... | Extract information from a resource ID string with the resource type
as the identifier.
@param id the resource ID
@param identifier the identifier to match, e.g. "resourceGroups", "storageAccounts"
@return the information extracted from the identifier | [
"Extract",
"information",
"from",
"a",
"resource",
"ID",
"string",
"with",
"the",
"resource",
"type",
"as",
"the",
"identifier",
"."
] | train | https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-arm-client-runtime/src/main/java/com/microsoft/azure/arm/resources/ResourceUtilsCore.java#L121-L132 |
deeplearning4j/deeplearning4j | nd4j/nd4j-common/src/main/java/org/nd4j/tools/BTools.java | BTools.getSInt | public static String getSInt( int Value, int CharsCount, char LeadingChar ) {
//
String Result = "";
//
if ( CharsCount <= 0 ) {
return getSInt( Value );
}
//
String FormatS = "";
if ( LeadingChar == '0' ) {
FormatS = "%" + LeadingChar + Integer.toString( CharsCount ) + "d";
}
else {
FormatS = "%" + Integer.toString( CharsCount ) + "d";
}
//
Result = String.format( FormatS, Value );
//
return Result;
} | java | public static String getSInt( int Value, int CharsCount, char LeadingChar ) {
//
String Result = "";
//
if ( CharsCount <= 0 ) {
return getSInt( Value );
}
//
String FormatS = "";
if ( LeadingChar == '0' ) {
FormatS = "%" + LeadingChar + Integer.toString( CharsCount ) + "d";
}
else {
FormatS = "%" + Integer.toString( CharsCount ) + "d";
}
//
Result = String.format( FormatS, Value );
//
return Result;
} | [
"public",
"static",
"String",
"getSInt",
"(",
"int",
"Value",
",",
"int",
"CharsCount",
",",
"char",
"LeadingChar",
")",
"{",
"//",
"String",
"Result",
"=",
"\"\"",
";",
"//",
"if",
"(",
"CharsCount",
"<=",
"0",
")",
"{",
"return",
"getSInt",
"(",
"Val... | <b>getSInt</b><br>
public static String getSInt( int Value, int CharsCount, char LeadingChar )<br>
Returns int converted to string.<br>
If CharsCount > base int string length<br>
before base int string adds relevant leading chars.<br>
If CharsCount <= base int string length<br>
returns base int string.<br>
@param Value - value
@param CharsCount - chars count
@param LeadingChar - leading char
@return int as string | [
"<b",
">",
"getSInt<",
"/",
"b",
">",
"<br",
">",
"public",
"static",
"String",
"getSInt",
"(",
"int",
"Value",
"int",
"CharsCount",
"char",
"LeadingChar",
")",
"<br",
">",
"Returns",
"int",
"converted",
"to",
"string",
".",
"<br",
">",
"If",
"CharsCount... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-common/src/main/java/org/nd4j/tools/BTools.java#L269-L288 |
JodaOrg/joda-money | src/main/java/org/joda/money/BigMoney.java | BigMoney.ofMajor | public static BigMoney ofMajor(CurrencyUnit currency, long amountMajor) {
MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null");
return BigMoney.of(currency, BigDecimal.valueOf(amountMajor));
} | java | public static BigMoney ofMajor(CurrencyUnit currency, long amountMajor) {
MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null");
return BigMoney.of(currency, BigDecimal.valueOf(amountMajor));
} | [
"public",
"static",
"BigMoney",
"ofMajor",
"(",
"CurrencyUnit",
"currency",
",",
"long",
"amountMajor",
")",
"{",
"MoneyUtils",
".",
"checkNotNull",
"(",
"currency",
",",
"\"CurrencyUnit must not be null\"",
")",
";",
"return",
"BigMoney",
".",
"of",
"(",
"currenc... | Obtains an instance of {@code BigMoney} from an amount in major units.
<p>
This allows you to create an instance with a specific currency and amount.
The scale of the money will be zero.
<p>
The amount is a whole number only. Thus you can initialise the value
'USD 20', but not the value 'USD 20.32'.
For example, {@code ofMajor(USD, 25)} creates the instance {@code USD 25}.
@param currency the currency, not null
@param amountMajor the amount of money in the major division of the currency
@return the new instance, never null | [
"Obtains",
"an",
"instance",
"of",
"{",
"@code",
"BigMoney",
"}",
"from",
"an",
"amount",
"in",
"major",
"units",
".",
"<p",
">",
"This",
"allows",
"you",
"to",
"create",
"an",
"instance",
"with",
"a",
"specific",
"currency",
"and",
"amount",
".",
"The",... | train | https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L193-L196 |
glookast/commons-timecode | src/main/java/com/glookast/commons/timecode/AbstractMutableTimecode.java | AbstractMutableTimecode.setHMSF | public void setHMSF(int hours, int minutes, int seconds, int frames)
{
innerSetHMSF(hours, minutes, seconds, frames);
} | java | public void setHMSF(int hours, int minutes, int seconds, int frames)
{
innerSetHMSF(hours, minutes, seconds, frames);
} | [
"public",
"void",
"setHMSF",
"(",
"int",
"hours",
",",
"int",
"minutes",
",",
"int",
"seconds",
",",
"int",
"frames",
")",
"{",
"innerSetHMSF",
"(",
"hours",
",",
"minutes",
",",
"seconds",
",",
"frames",
")",
";",
"}"
] | Sets the timecode to the provided hours, minutes, seconds and frames
@param hours
@param minutes
@param seconds
@param frames | [
"Sets",
"the",
"timecode",
"to",
"the",
"provided",
"hours",
"minutes",
"seconds",
"and",
"frames"
] | train | https://github.com/glookast/commons-timecode/blob/ec2f682a51d1cc435d0b42d80de48ff15adb4ee8/src/main/java/com/glookast/commons/timecode/AbstractMutableTimecode.java#L98-L101 |
haifengl/smile | nlp/src/main/java/smile/nlp/pos/HMMPOSTagger.java | HMMPOSTagger.walkin | public static void walkin(File dir, List<File> files) {
String pattern = ".POS";
File[] listFile = dir.listFiles();
if (listFile != null) {
for (File file : listFile) {
if (file.isDirectory()) {
walkin(file, files);
} else {
if (file.getName().endsWith(pattern)) {
files.add(file);
}
}
}
}
} | java | public static void walkin(File dir, List<File> files) {
String pattern = ".POS";
File[] listFile = dir.listFiles();
if (listFile != null) {
for (File file : listFile) {
if (file.isDirectory()) {
walkin(file, files);
} else {
if (file.getName().endsWith(pattern)) {
files.add(file);
}
}
}
}
} | [
"public",
"static",
"void",
"walkin",
"(",
"File",
"dir",
",",
"List",
"<",
"File",
">",
"files",
")",
"{",
"String",
"pattern",
"=",
"\".POS\"",
";",
"File",
"[",
"]",
"listFile",
"=",
"dir",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"listFile",
... | Recursive function to descend into the directory tree and find all the files
that end with ".POS"
@param dir a file object defining the top directory | [
"Recursive",
"function",
"to",
"descend",
"into",
"the",
"directory",
"tree",
"and",
"find",
"all",
"the",
"files",
"that",
"end",
"with",
".",
"POS"
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/nlp/src/main/java/smile/nlp/pos/HMMPOSTagger.java#L400-L414 |
liferay/com-liferay-commerce | commerce-product-api/src/main/java/com/liferay/commerce/product/service/persistence/CPOptionValueUtil.java | CPOptionValueUtil.removeByUUID_G | public static CPOptionValue removeByUUID_G(String uuid, long groupId)
throws com.liferay.commerce.product.exception.NoSuchCPOptionValueException {
return getPersistence().removeByUUID_G(uuid, groupId);
} | java | public static CPOptionValue removeByUUID_G(String uuid, long groupId)
throws com.liferay.commerce.product.exception.NoSuchCPOptionValueException {
return getPersistence().removeByUUID_G(uuid, groupId);
} | [
"public",
"static",
"CPOptionValue",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"com",
".",
"liferay",
".",
"commerce",
".",
"product",
".",
"exception",
".",
"NoSuchCPOptionValueException",
"{",
"return",
"getPersistence",
"("... | Removes the cp option value where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the cp option value that was removed | [
"Removes",
"the",
"cp",
"option",
"value",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/service/persistence/CPOptionValueUtil.java#L313-L316 |
before/uadetector | modules/uadetector-core/src/main/java/net/sf/uadetector/VersionNumber.java | VersionNumber.parseOperatingSystemVersion | public static VersionNumber parseOperatingSystemVersion(@Nonnull final OperatingSystemFamily family, @Nonnull final String userAgent) {
Check.notNull(family, "family");
Check.notNull(userAgent, "userAgent");
return VersionParser.parseOperatingSystemVersion(family, userAgent);
} | java | public static VersionNumber parseOperatingSystemVersion(@Nonnull final OperatingSystemFamily family, @Nonnull final String userAgent) {
Check.notNull(family, "family");
Check.notNull(userAgent, "userAgent");
return VersionParser.parseOperatingSystemVersion(family, userAgent);
} | [
"public",
"static",
"VersionNumber",
"parseOperatingSystemVersion",
"(",
"@",
"Nonnull",
"final",
"OperatingSystemFamily",
"family",
",",
"@",
"Nonnull",
"final",
"String",
"userAgent",
")",
"{",
"Check",
".",
"notNull",
"(",
"family",
",",
"\"family\"",
")",
";",... | Try to determine the version number of the operating system by parsing the user agent string.
@param family
family of the operating system
@param userAgent
user agent string
@return extracted version number | [
"Try",
"to",
"determine",
"the",
"version",
"number",
"of",
"the",
"operating",
"system",
"by",
"parsing",
"the",
"user",
"agent",
"string",
"."
] | train | https://github.com/before/uadetector/blob/215fb652723c52866572cff885f52a3fe67b9db5/modules/uadetector-core/src/main/java/net/sf/uadetector/VersionNumber.java#L109-L113 |
msgpack/msgpack-java | msgpack-core/src/main/java/org/msgpack/core/MessagePacker.java | MessagePacker.writePayload | public MessagePacker writePayload(byte[] src, int off, int len)
throws IOException
{
if (buffer == null || buffer.size() - position < len || len > bufferFlushThreshold) {
flush(); // call flush before write
// Directly write payload to the output without using the buffer
out.write(src, off, len);
totalFlushBytes += len;
}
else {
buffer.putBytes(position, src, off, len);
position += len;
}
return this;
} | java | public MessagePacker writePayload(byte[] src, int off, int len)
throws IOException
{
if (buffer == null || buffer.size() - position < len || len > bufferFlushThreshold) {
flush(); // call flush before write
// Directly write payload to the output without using the buffer
out.write(src, off, len);
totalFlushBytes += len;
}
else {
buffer.putBytes(position, src, off, len);
position += len;
}
return this;
} | [
"public",
"MessagePacker",
"writePayload",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"if",
"(",
"buffer",
"==",
"null",
"||",
"buffer",
".",
"size",
"(",
")",
"-",
"position",
"<",
"len",
"... | Writes a byte array to the output.
<p>
This method is used with {@link #packRawStringHeader(int)} or {@link #packBinaryHeader(int)} methods.
@param src the data to add
@param off the start offset in the data
@param len the number of bytes to add
@return this
@throws IOException when underlying output throws IOException | [
"Writes",
"a",
"byte",
"array",
"to",
"the",
"output",
".",
"<p",
">",
"This",
"method",
"is",
"used",
"with",
"{",
"@link",
"#packRawStringHeader",
"(",
"int",
")",
"}",
"or",
"{",
"@link",
"#packBinaryHeader",
"(",
"int",
")",
"}",
"methods",
"."
] | train | https://github.com/msgpack/msgpack-java/blob/16e370e348215a72a14c210b42d448d513aee015/msgpack-core/src/main/java/org/msgpack/core/MessagePacker.java#L1009-L1023 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPOut.java | JBBPOut.Bits | public JBBPOut Bits(final JBBPBitNumber numberOfBits, final int value) throws IOException {
assertNotEnded();
JBBPUtils.assertNotNull(numberOfBits, "Number of bits must not be null");
if (this.processCommands) {
_writeBits(numberOfBits, value);
}
return this;
} | java | public JBBPOut Bits(final JBBPBitNumber numberOfBits, final int value) throws IOException {
assertNotEnded();
JBBPUtils.assertNotNull(numberOfBits, "Number of bits must not be null");
if (this.processCommands) {
_writeBits(numberOfBits, value);
}
return this;
} | [
"public",
"JBBPOut",
"Bits",
"(",
"final",
"JBBPBitNumber",
"numberOfBits",
",",
"final",
"int",
"value",
")",
"throws",
"IOException",
"{",
"assertNotEnded",
"(",
")",
";",
"JBBPUtils",
".",
"assertNotNull",
"(",
"numberOfBits",
",",
"\"Number of bits must not be n... | Write bits from a value into the output stream
@param numberOfBits the number of bits to be saved
@param value the value which bits must be saved
@return the DSL session
@throws IOException it will be thrown for transport errors | [
"Write",
"bits",
"from",
"a",
"value",
"into",
"the",
"output",
"stream"
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/io/JBBPOut.java#L380-L387 |
apache/flink | flink-mesos/src/main/java/org/apache/flink/mesos/entrypoint/MesosEntrypointUtils.java | MesosEntrypointUtils.createMesosSchedulerConfiguration | public static MesosConfiguration createMesosSchedulerConfiguration(Configuration flinkConfig, String hostname) {
Protos.FrameworkInfo.Builder frameworkInfo = Protos.FrameworkInfo.newBuilder()
.setHostname(hostname);
Protos.Credential.Builder credential = null;
if (!flinkConfig.contains(MesosOptions.MASTER_URL)) {
throw new IllegalConfigurationException(MesosOptions.MASTER_URL.key() + " must be configured.");
}
String masterUrl = flinkConfig.getString(MesosOptions.MASTER_URL);
Duration failoverTimeout = FiniteDuration.apply(
flinkConfig.getInteger(
MesosOptions.FAILOVER_TIMEOUT_SECONDS),
TimeUnit.SECONDS);
frameworkInfo.setFailoverTimeout(failoverTimeout.toSeconds());
frameworkInfo.setName(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_NAME));
frameworkInfo.setRole(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_ROLE));
frameworkInfo.setUser(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_USER));
if (flinkConfig.contains(MesosOptions.RESOURCEMANAGER_FRAMEWORK_PRINCIPAL)) {
frameworkInfo.setPrincipal(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_PRINCIPAL));
credential = Protos.Credential.newBuilder();
credential.setPrincipal(frameworkInfo.getPrincipal());
// some environments use a side-channel to communicate the secret to Mesos,
// and thus don't set the 'secret' configuration setting
if (flinkConfig.contains(MesosOptions.RESOURCEMANAGER_FRAMEWORK_SECRET)) {
credential.setSecret(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_SECRET));
}
}
MesosConfiguration mesos =
new MesosConfiguration(masterUrl, frameworkInfo, scala.Option.apply(credential));
return mesos;
} | java | public static MesosConfiguration createMesosSchedulerConfiguration(Configuration flinkConfig, String hostname) {
Protos.FrameworkInfo.Builder frameworkInfo = Protos.FrameworkInfo.newBuilder()
.setHostname(hostname);
Protos.Credential.Builder credential = null;
if (!flinkConfig.contains(MesosOptions.MASTER_URL)) {
throw new IllegalConfigurationException(MesosOptions.MASTER_URL.key() + " must be configured.");
}
String masterUrl = flinkConfig.getString(MesosOptions.MASTER_URL);
Duration failoverTimeout = FiniteDuration.apply(
flinkConfig.getInteger(
MesosOptions.FAILOVER_TIMEOUT_SECONDS),
TimeUnit.SECONDS);
frameworkInfo.setFailoverTimeout(failoverTimeout.toSeconds());
frameworkInfo.setName(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_NAME));
frameworkInfo.setRole(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_ROLE));
frameworkInfo.setUser(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_USER));
if (flinkConfig.contains(MesosOptions.RESOURCEMANAGER_FRAMEWORK_PRINCIPAL)) {
frameworkInfo.setPrincipal(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_PRINCIPAL));
credential = Protos.Credential.newBuilder();
credential.setPrincipal(frameworkInfo.getPrincipal());
// some environments use a side-channel to communicate the secret to Mesos,
// and thus don't set the 'secret' configuration setting
if (flinkConfig.contains(MesosOptions.RESOURCEMANAGER_FRAMEWORK_SECRET)) {
credential.setSecret(flinkConfig.getString(
MesosOptions.RESOURCEMANAGER_FRAMEWORK_SECRET));
}
}
MesosConfiguration mesos =
new MesosConfiguration(masterUrl, frameworkInfo, scala.Option.apply(credential));
return mesos;
} | [
"public",
"static",
"MesosConfiguration",
"createMesosSchedulerConfiguration",
"(",
"Configuration",
"flinkConfig",
",",
"String",
"hostname",
")",
"{",
"Protos",
".",
"FrameworkInfo",
".",
"Builder",
"frameworkInfo",
"=",
"Protos",
".",
"FrameworkInfo",
".",
"newBuilde... | Loads and validates the Mesos scheduler configuration.
@param flinkConfig the global configuration.
@param hostname the hostname to advertise to the Mesos master. | [
"Loads",
"and",
"validates",
"the",
"Mesos",
"scheduler",
"configuration",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-mesos/src/main/java/org/apache/flink/mesos/entrypoint/MesosEntrypointUtils.java#L58-L103 |
lightblueseas/file-worker | src/main/java/de/alpharogroup/file/copy/CopyFileExtensions.java | CopyFileExtensions.copyDirectory | public static boolean copyDirectory(final File source, final File destination,
final boolean lastModified) throws FileIsSecurityRestrictedException, IOException,
FileIsADirectoryException, FileIsNotADirectoryException, DirectoryAlreadyExistsException
{
return copyDirectoryWithFileFilter(source, destination, null, lastModified);
} | java | public static boolean copyDirectory(final File source, final File destination,
final boolean lastModified) throws FileIsSecurityRestrictedException, IOException,
FileIsADirectoryException, FileIsNotADirectoryException, DirectoryAlreadyExistsException
{
return copyDirectoryWithFileFilter(source, destination, null, lastModified);
} | [
"public",
"static",
"boolean",
"copyDirectory",
"(",
"final",
"File",
"source",
",",
"final",
"File",
"destination",
",",
"final",
"boolean",
"lastModified",
")",
"throws",
"FileIsSecurityRestrictedException",
",",
"IOException",
",",
"FileIsADirectoryException",
",",
... | Copies the given source directory to the given destination directory with the option to set
the lastModified time from the given destination file or directory.
@param source
The source directory.
@param destination
The destination directory.
@param lastModified
Flag the tells if the attribute lastModified has to be set with the attribute from
the destination file.
@return 's true if the directory is copied, otherwise false.
@throws FileIsSecurityRestrictedException
Is thrown if the source file is security restricted.
@throws IOException
Is thrown if an error occurs by reading or writing.
@throws FileIsADirectoryException
Is thrown if the destination file is a directory.
@throws FileIsNotADirectoryException
Is thrown if the source file is not a directory.
@throws DirectoryAlreadyExistsException
Is thrown if the directory all ready exists. | [
"Copies",
"the",
"given",
"source",
"directory",
"to",
"the",
"given",
"destination",
"directory",
"with",
"the",
"option",
"to",
"set",
"the",
"lastModified",
"time",
"from",
"the",
"given",
"destination",
"file",
"or",
"directory",
"."
] | train | https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/copy/CopyFileExtensions.java#L112-L117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.