repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
rholder/moar-concurrent | src/main/java/com/github/rholder/moar/concurrent/partition/Parts.java | Parts.among | public static List<Part> among(long offset, long totalLength, long chunkSize) {
"""
Return a list of {@link Part}'s with the given offset where the total
length is split up into equal partitions up to the last chunk that may
contain a range of length <= the given chunk size.
For instance, an offset of 23 and total length of 21 with a chunkSize of
10 would result in the following list of returned parts:
<pre>
[23, 32], [33, 42], [43, 43]
</pre>
Notice that the final chunk contains the same start and end. This should
be expected in cases where the last chunk would only contain one value.
@param offset add this offset to the start and end of the calculated {@link Part}'s
@param totalLength the total length of the range to partition
@param chunkSize partition the range in chunks of this size, with the
last chunk containing <= this value
@return a list of {@link Part}'s
"""
List<Part> parts = new ArrayList<Part>();
int i = 0;
long start = 0;
long end = Math.min(start + chunkSize, totalLength) - 1;
do {
parts.add(new Part(start + offset, end + offset));
start = ++i * chunkSize;
end = Math.min(start + chunkSize, totalLength) - 1;
} while (start < totalLength);
return parts;
} | java | public static List<Part> among(long offset, long totalLength, long chunkSize) {
List<Part> parts = new ArrayList<Part>();
int i = 0;
long start = 0;
long end = Math.min(start + chunkSize, totalLength) - 1;
do {
parts.add(new Part(start + offset, end + offset));
start = ++i * chunkSize;
end = Math.min(start + chunkSize, totalLength) - 1;
} while (start < totalLength);
return parts;
} | [
"public",
"static",
"List",
"<",
"Part",
">",
"among",
"(",
"long",
"offset",
",",
"long",
"totalLength",
",",
"long",
"chunkSize",
")",
"{",
"List",
"<",
"Part",
">",
"parts",
"=",
"new",
"ArrayList",
"<",
"Part",
">",
"(",
")",
";",
"int",
"i",
"... | Return a list of {@link Part}'s with the given offset where the total
length is split up into equal partitions up to the last chunk that may
contain a range of length <= the given chunk size.
For instance, an offset of 23 and total length of 21 with a chunkSize of
10 would result in the following list of returned parts:
<pre>
[23, 32], [33, 42], [43, 43]
</pre>
Notice that the final chunk contains the same start and end. This should
be expected in cases where the last chunk would only contain one value.
@param offset add this offset to the start and end of the calculated {@link Part}'s
@param totalLength the total length of the range to partition
@param chunkSize partition the range in chunks of this size, with the
last chunk containing <= this value
@return a list of {@link Part}'s | [
"Return",
"a",
"list",
"of",
"{",
"@link",
"Part",
"}",
"s",
"with",
"the",
"given",
"offset",
"where",
"the",
"total",
"length",
"is",
"split",
"up",
"into",
"equal",
"partitions",
"up",
"to",
"the",
"last",
"chunk",
"that",
"may",
"contain",
"a",
"ra... | train | https://github.com/rholder/moar-concurrent/blob/c28facbf02e628cc37266c051c23d4a7654b4eba/src/main/java/com/github/rholder/moar/concurrent/partition/Parts.java#L91-L102 |
lessthanoptimal/ejml | main/ejml-simple/src/org/ejml/simple/SimpleEVD.java | SimpleEVD.getEigenvalue | public Complex_F64 getEigenvalue(int index ) {
"""
<p>
Returns an eigenvalue as a complex number. For symmetric matrices the returned eigenvalue will always be a real
number, which means the imaginary component will be equal to zero.
</p>
<p>
NOTE: The order of the eigenvalues is dependent upon the decomposition algorithm used. This means that they may
or may not be ordered by magnitude. For example the QR algorithm will returns results that are partially
ordered by magnitude, but this behavior should not be relied upon.
</p>
@param index Index of the eigenvalue eigenvector pair.
@return An eigenvalue.
"""
if( is64 )
return ((EigenDecomposition_F64)eig).getEigenvalue(index);
else {
Complex_F64 c = ((EigenDecomposition_F64)eig).getEigenvalue(index);
return new Complex_F64(c.real, c.imaginary);
}
} | java | public Complex_F64 getEigenvalue(int index ) {
if( is64 )
return ((EigenDecomposition_F64)eig).getEigenvalue(index);
else {
Complex_F64 c = ((EigenDecomposition_F64)eig).getEigenvalue(index);
return new Complex_F64(c.real, c.imaginary);
}
} | [
"public",
"Complex_F64",
"getEigenvalue",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"is64",
")",
"return",
"(",
"(",
"EigenDecomposition_F64",
")",
"eig",
")",
".",
"getEigenvalue",
"(",
"index",
")",
";",
"else",
"{",
"Complex_F64",
"c",
"=",
"(",
"(",
... | <p>
Returns an eigenvalue as a complex number. For symmetric matrices the returned eigenvalue will always be a real
number, which means the imaginary component will be equal to zero.
</p>
<p>
NOTE: The order of the eigenvalues is dependent upon the decomposition algorithm used. This means that they may
or may not be ordered by magnitude. For example the QR algorithm will returns results that are partially
ordered by magnitude, but this behavior should not be relied upon.
</p>
@param index Index of the eigenvalue eigenvector pair.
@return An eigenvalue. | [
"<p",
">",
"Returns",
"an",
"eigenvalue",
"as",
"a",
"complex",
"number",
".",
"For",
"symmetric",
"matrices",
"the",
"returned",
"eigenvalue",
"will",
"always",
"be",
"a",
"real",
"number",
"which",
"means",
"the",
"imaginary",
"component",
"will",
"be",
"e... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-simple/src/org/ejml/simple/SimpleEVD.java#L106-L113 |
google/closure-compiler | src/com/google/javascript/jscomp/PureFunctionIdentifier.java | ExternFunctionAnnotationAnalyzer.isLocalValueType | private boolean isLocalValueType(JSType typei, AbstractCompiler compiler) {
"""
Return whether {@code type} is guaranteed to be a that of a "local value".
<p>For the purposes of purity analysis we really only care whether a return value is
immutable and identity-less; such values can't contribute to side-effects. Therefore, this
method is implemented to check if {@code type} is that of a primitive, since primitives
exhibit both relevant behaviours.
"""
checkNotNull(typei);
JSType nativeObj = compiler.getTypeRegistry().getNativeType(JSTypeNative.OBJECT_TYPE);
JSType subtype = typei.meetWith(nativeObj);
// If the type includes anything related to a object type, don't assume
// anything about the locality of the value.
return subtype.isEmptyType();
} | java | private boolean isLocalValueType(JSType typei, AbstractCompiler compiler) {
checkNotNull(typei);
JSType nativeObj = compiler.getTypeRegistry().getNativeType(JSTypeNative.OBJECT_TYPE);
JSType subtype = typei.meetWith(nativeObj);
// If the type includes anything related to a object type, don't assume
// anything about the locality of the value.
return subtype.isEmptyType();
} | [
"private",
"boolean",
"isLocalValueType",
"(",
"JSType",
"typei",
",",
"AbstractCompiler",
"compiler",
")",
"{",
"checkNotNull",
"(",
"typei",
")",
";",
"JSType",
"nativeObj",
"=",
"compiler",
".",
"getTypeRegistry",
"(",
")",
".",
"getNativeType",
"(",
"JSTypeN... | Return whether {@code type} is guaranteed to be a that of a "local value".
<p>For the purposes of purity analysis we really only care whether a return value is
immutable and identity-less; such values can't contribute to side-effects. Therefore, this
method is implemented to check if {@code type} is that of a primitive, since primitives
exhibit both relevant behaviours. | [
"Return",
"whether",
"{",
"@code",
"type",
"}",
"is",
"guaranteed",
"to",
"be",
"a",
"that",
"of",
"a",
"local",
"value",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PureFunctionIdentifier.java#L615-L622 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/distance/ReferenceBasedOutlierDetection.java | ReferenceBasedOutlierDetection.computeDensity | protected double computeDensity(DoubleDBIDList referenceDists, DoubleDBIDListIter iter, int index) {
"""
Computes the density of an object. The density of an object is the
distances to the k nearest neighbors. Neighbors and distances are computed
approximately. (approximation for kNN distance: instead of a normal NN
search the NN of an object are those objects that have a similar distance
to a reference point. The k- nearest neighbors of an object are those
objects that lay close to the object in the reference distance vector)
@param referenceDists vector of the reference distances
@param iter Iterator to this list (will be reused)
@param index index of the current object
@return density for one object and reference point
"""
final int size = referenceDists.size();
final double xDist = iter.seek(index).doubleValue();
int lef = index, rig = index;
double sum = 0.;
double lef_d = (--lef >= 0) ? xDist - iter.seek(lef).doubleValue() : Double.POSITIVE_INFINITY;
double rig_d = (++rig < size) ? iter.seek(rig).doubleValue() - xDist : Double.POSITIVE_INFINITY;
for(int i = 0; i < k; ++i) {
if(lef >= 0 && rig < size) {
// Prefer n or m?
if(lef_d < rig_d) {
sum += lef_d;
// Update left
lef_d = (--lef >= 0) ? xDist - iter.seek(lef).doubleValue() : Double.POSITIVE_INFINITY;
}
else {
sum += rig_d;
// Update right
rig_d = (++rig < size) ? iter.seek(rig).doubleValue() - xDist : Double.POSITIVE_INFINITY;
}
}
else if(lef >= 0) {
// Choose left, since right is not available.
sum += lef_d;
// update left
lef_d = (--lef >= 0) ? xDist - iter.seek(lef).doubleValue() : Double.POSITIVE_INFINITY;
}
else if(rig < size) {
// Choose right, since left is not available
sum += rig_d;
// Update right
rig_d = (++rig < size) ? iter.seek(rig).doubleValue() - xDist : Double.POSITIVE_INFINITY;
}
else {
// Not enough objects in database?
throw new IndexOutOfBoundsException("Less than k objects?");
}
}
return k / sum;
} | java | protected double computeDensity(DoubleDBIDList referenceDists, DoubleDBIDListIter iter, int index) {
final int size = referenceDists.size();
final double xDist = iter.seek(index).doubleValue();
int lef = index, rig = index;
double sum = 0.;
double lef_d = (--lef >= 0) ? xDist - iter.seek(lef).doubleValue() : Double.POSITIVE_INFINITY;
double rig_d = (++rig < size) ? iter.seek(rig).doubleValue() - xDist : Double.POSITIVE_INFINITY;
for(int i = 0; i < k; ++i) {
if(lef >= 0 && rig < size) {
// Prefer n or m?
if(lef_d < rig_d) {
sum += lef_d;
// Update left
lef_d = (--lef >= 0) ? xDist - iter.seek(lef).doubleValue() : Double.POSITIVE_INFINITY;
}
else {
sum += rig_d;
// Update right
rig_d = (++rig < size) ? iter.seek(rig).doubleValue() - xDist : Double.POSITIVE_INFINITY;
}
}
else if(lef >= 0) {
// Choose left, since right is not available.
sum += lef_d;
// update left
lef_d = (--lef >= 0) ? xDist - iter.seek(lef).doubleValue() : Double.POSITIVE_INFINITY;
}
else if(rig < size) {
// Choose right, since left is not available
sum += rig_d;
// Update right
rig_d = (++rig < size) ? iter.seek(rig).doubleValue() - xDist : Double.POSITIVE_INFINITY;
}
else {
// Not enough objects in database?
throw new IndexOutOfBoundsException("Less than k objects?");
}
}
return k / sum;
} | [
"protected",
"double",
"computeDensity",
"(",
"DoubleDBIDList",
"referenceDists",
",",
"DoubleDBIDListIter",
"iter",
",",
"int",
"index",
")",
"{",
"final",
"int",
"size",
"=",
"referenceDists",
".",
"size",
"(",
")",
";",
"final",
"double",
"xDist",
"=",
"ite... | Computes the density of an object. The density of an object is the
distances to the k nearest neighbors. Neighbors and distances are computed
approximately. (approximation for kNN distance: instead of a normal NN
search the NN of an object are those objects that have a similar distance
to a reference point. The k- nearest neighbors of an object are those
objects that lay close to the object in the reference distance vector)
@param referenceDists vector of the reference distances
@param iter Iterator to this list (will be reused)
@param index index of the current object
@return density for one object and reference point | [
"Computes",
"the",
"density",
"of",
"an",
"object",
".",
"The",
"density",
"of",
"an",
"object",
"is",
"the",
"distances",
"to",
"the",
"k",
"nearest",
"neighbors",
".",
"Neighbors",
"and",
"distances",
"are",
"computed",
"approximately",
".",
"(",
"approxim... | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/distance/ReferenceBasedOutlierDetection.java#L223-L263 |
ironjacamar/ironjacamar | common/src/main/java/org/ironjacamar/common/metadata/common/CommonIronJacamarParser.java | CommonIronJacamarParser.storeTimeout | protected void storeTimeout(Timeout t, XMLStreamWriter writer) throws Exception {
"""
Store timeout
@param t The timeout
@param writer The writer
@exception Exception Thrown if an error occurs
"""
writer.writeStartElement(CommonXML.ELEMENT_TIMEOUT);
if (t.getBlockingTimeoutMillis() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_BLOCKING_TIMEOUT_MILLIS);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_BLOCKING_TIMEOUT_MILLIS,
t.getBlockingTimeoutMillis().toString()));
writer.writeEndElement();
}
if (t.getIdleTimeoutMinutes() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_IDLE_TIMEOUT_MINUTES);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_IDLE_TIMEOUT_MINUTES,
t.getIdleTimeoutMinutes().toString()));
writer.writeEndElement();
}
if (t.getAllocationRetry() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_ALLOCATION_RETRY);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_ALLOCATION_RETRY,
t.getAllocationRetry().toString()));
writer.writeEndElement();
}
if (t.getAllocationRetryWaitMillis() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_ALLOCATION_RETRY_WAIT_MILLIS);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_ALLOCATION_RETRY_WAIT_MILLIS,
t.getAllocationRetryWaitMillis().toString()));
writer.writeEndElement();
}
if (t.getXaResourceTimeout() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_XA_RESOURCE_TIMEOUT);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_XA_RESOURCE_TIMEOUT,
t.getXaResourceTimeout().toString()));
writer.writeEndElement();
}
writer.writeEndElement();
} | java | protected void storeTimeout(Timeout t, XMLStreamWriter writer) throws Exception
{
writer.writeStartElement(CommonXML.ELEMENT_TIMEOUT);
if (t.getBlockingTimeoutMillis() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_BLOCKING_TIMEOUT_MILLIS);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_BLOCKING_TIMEOUT_MILLIS,
t.getBlockingTimeoutMillis().toString()));
writer.writeEndElement();
}
if (t.getIdleTimeoutMinutes() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_IDLE_TIMEOUT_MINUTES);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_IDLE_TIMEOUT_MINUTES,
t.getIdleTimeoutMinutes().toString()));
writer.writeEndElement();
}
if (t.getAllocationRetry() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_ALLOCATION_RETRY);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_ALLOCATION_RETRY,
t.getAllocationRetry().toString()));
writer.writeEndElement();
}
if (t.getAllocationRetryWaitMillis() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_ALLOCATION_RETRY_WAIT_MILLIS);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_ALLOCATION_RETRY_WAIT_MILLIS,
t.getAllocationRetryWaitMillis().toString()));
writer.writeEndElement();
}
if (t.getXaResourceTimeout() != null)
{
writer.writeStartElement(CommonXML.ELEMENT_XA_RESOURCE_TIMEOUT);
writer.writeCharacters(t.getValue(CommonXML.ELEMENT_XA_RESOURCE_TIMEOUT,
t.getXaResourceTimeout().toString()));
writer.writeEndElement();
}
writer.writeEndElement();
} | [
"protected",
"void",
"storeTimeout",
"(",
"Timeout",
"t",
",",
"XMLStreamWriter",
"writer",
")",
"throws",
"Exception",
"{",
"writer",
".",
"writeStartElement",
"(",
"CommonXML",
".",
"ELEMENT_TIMEOUT",
")",
";",
"if",
"(",
"t",
".",
"getBlockingTimeoutMillis",
... | Store timeout
@param t The timeout
@param writer The writer
@exception Exception Thrown if an error occurs | [
"Store",
"timeout"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/common/CommonIronJacamarParser.java#L1045-L1090 |
apache/flink | flink-core/src/main/java/org/apache/flink/configuration/Configuration.java | Configuration.getInteger | public int getInteger(String key, int defaultValue) {
"""
Returns the value associated with the given key as an integer.
@param key
the key pointing to the associated value
@param defaultValue
the default value which is returned in case there is no value associated with the given key
@return the (default) value associated with the given key
"""
Object o = getRawValue(key);
if (o == null) {
return defaultValue;
}
return convertToInt(o, defaultValue);
} | java | public int getInteger(String key, int defaultValue) {
Object o = getRawValue(key);
if (o == null) {
return defaultValue;
}
return convertToInt(o, defaultValue);
} | [
"public",
"int",
"getInteger",
"(",
"String",
"key",
",",
"int",
"defaultValue",
")",
"{",
"Object",
"o",
"=",
"getRawValue",
"(",
"key",
")",
";",
"if",
"(",
"o",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"return",
"convertToInt",
"(... | Returns the value associated with the given key as an integer.
@param key
the key pointing to the associated value
@param defaultValue
the default value which is returned in case there is no value associated with the given key
@return the (default) value associated with the given key | [
"Returns",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
"as",
"an",
"integer",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/configuration/Configuration.java#L204-L211 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java | ServiceDirectoryConfig.getDouble | public double getDouble(String name, double defaultVal) {
"""
Get the property object as double, or return defaultVal if property is not defined.
@param name
property name.
@param defaultVal
default property value.
@return
property value as double, return defaultVal if property is undefined.
"""
if(this.configuration.containsKey(name)){
return this.configuration.getDouble(name);
} else {
return defaultVal;
}
} | java | public double getDouble(String name, double defaultVal){
if(this.configuration.containsKey(name)){
return this.configuration.getDouble(name);
} else {
return defaultVal;
}
} | [
"public",
"double",
"getDouble",
"(",
"String",
"name",
",",
"double",
"defaultVal",
")",
"{",
"if",
"(",
"this",
".",
"configuration",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"return",
"this",
".",
"configuration",
".",
"getDouble",
"(",
"name",
... | Get the property object as double, or return defaultVal if property is not defined.
@param name
property name.
@param defaultVal
default property value.
@return
property value as double, return defaultVal if property is undefined. | [
"Get",
"the",
"property",
"object",
"as",
"double",
"or",
"return",
"defaultVal",
"if",
"property",
"is",
"not",
"defined",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java#L147-L153 |
RestComm/media-core | ice/src/main/java/org/restcomm/media/core/ice/harvest/HostCandidateHarvester.java | HostCandidateHarvester.useNetworkInterface | private boolean useNetworkInterface(NetworkInterface networkInterface) throws HarvestException {
"""
Decides whether a certain network interface can be used as a host
candidate.
@param networkInterface
The network interface to evaluate
@return <code>true</code> if the interface can be used. Returns
<code>false</code>, otherwise.
@throws HarvestException
When an error occurs while inspecting the interface.
"""
try {
return !networkInterface.isLoopback() && networkInterface.isUp();
} catch (SocketException e) {
throw new HarvestException("Could not evaluate whether network interface is loopback.", e);
}
} | java | private boolean useNetworkInterface(NetworkInterface networkInterface) throws HarvestException {
try {
return !networkInterface.isLoopback() && networkInterface.isUp();
} catch (SocketException e) {
throw new HarvestException("Could not evaluate whether network interface is loopback.", e);
}
} | [
"private",
"boolean",
"useNetworkInterface",
"(",
"NetworkInterface",
"networkInterface",
")",
"throws",
"HarvestException",
"{",
"try",
"{",
"return",
"!",
"networkInterface",
".",
"isLoopback",
"(",
")",
"&&",
"networkInterface",
".",
"isUp",
"(",
")",
";",
"}",... | Decides whether a certain network interface can be used as a host
candidate.
@param networkInterface
The network interface to evaluate
@return <code>true</code> if the interface can be used. Returns
<code>false</code>, otherwise.
@throws HarvestException
When an error occurs while inspecting the interface. | [
"Decides",
"whether",
"a",
"certain",
"network",
"interface",
"can",
"be",
"used",
"as",
"a",
"host",
"candidate",
"."
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/ice/src/main/java/org/restcomm/media/core/ice/harvest/HostCandidateHarvester.java#L90-L96 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/basic/server_binding.java | server_binding.get | public static server_binding get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch server_binding resource of given name .
"""
server_binding obj = new server_binding();
obj.set_name(name);
server_binding response = (server_binding) obj.get_resource(service);
return response;
} | java | public static server_binding get(nitro_service service, String name) throws Exception{
server_binding obj = new server_binding();
obj.set_name(name);
server_binding response = (server_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"server_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"server_binding",
"obj",
"=",
"new",
"server_binding",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"server... | Use this API to fetch server_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"server_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/basic/server_binding.java#L114-L119 |
lessthanoptimal/BoofCV | integration/boofcv-android/src/main/java/boofcv/android/ConvertBitmap.java | ConvertBitmap.planarToBitmap | public static <T extends ImageGray<T>>
void planarToBitmap(Planar<T> input , Bitmap output , byte[] storage ) {
"""
Converts Planar image into Bitmap.
@see #declareStorage(android.graphics.Bitmap, byte[])
@param input Input Planar image.
@param output Output Bitmap image.
@param storage Byte array used for internal storage. If null it will be declared internally.
"""
if( output.getWidth() != input.getWidth() || output.getHeight() != input.getHeight() ) {
throw new IllegalArgumentException("Image shapes are not the same");
}
if( storage == null )
storage = declareStorage(output,null);
if( input.getBandType() == GrayU8.class )
ImplConvertBitmap.planarToArray_U8((Planar)input, storage,output.getConfig());
else if( input.getBandType() == GrayF32.class )
ImplConvertBitmap.planarToArray_F32((Planar)input, storage,output.getConfig());
else
throw new IllegalArgumentException("Unsupported BoofCV Type");
output.copyPixelsFromBuffer(ByteBuffer.wrap(storage));
} | java | public static <T extends ImageGray<T>>
void planarToBitmap(Planar<T> input , Bitmap output , byte[] storage ) {
if( output.getWidth() != input.getWidth() || output.getHeight() != input.getHeight() ) {
throw new IllegalArgumentException("Image shapes are not the same");
}
if( storage == null )
storage = declareStorage(output,null);
if( input.getBandType() == GrayU8.class )
ImplConvertBitmap.planarToArray_U8((Planar)input, storage,output.getConfig());
else if( input.getBandType() == GrayF32.class )
ImplConvertBitmap.planarToArray_F32((Planar)input, storage,output.getConfig());
else
throw new IllegalArgumentException("Unsupported BoofCV Type");
output.copyPixelsFromBuffer(ByteBuffer.wrap(storage));
} | [
"public",
"static",
"<",
"T",
"extends",
"ImageGray",
"<",
"T",
">",
">",
"void",
"planarToBitmap",
"(",
"Planar",
"<",
"T",
">",
"input",
",",
"Bitmap",
"output",
",",
"byte",
"[",
"]",
"storage",
")",
"{",
"if",
"(",
"output",
".",
"getWidth",
"(",... | Converts Planar image into Bitmap.
@see #declareStorage(android.graphics.Bitmap, byte[])
@param input Input Planar image.
@param output Output Bitmap image.
@param storage Byte array used for internal storage. If null it will be declared internally. | [
"Converts",
"Planar",
"image",
"into",
"Bitmap",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/ConvertBitmap.java#L311-L327 |
facebook/fresco | samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/data/impl/ContentProviderSimpleAdapter.java | ContentProviderSimpleAdapter.getInternalPhotoSimpleAdapter | public static ContentProviderSimpleAdapter getInternalPhotoSimpleAdapter(Context context) {
"""
Creates and returns a SimpleAdapter for Internal Photos
@param context The Context
@return The SimpleAdapter for local photo
"""
return new ContentProviderSimpleAdapter(MediaStore.Images.Media.INTERNAL_CONTENT_URI, context);
} | java | public static ContentProviderSimpleAdapter getInternalPhotoSimpleAdapter(Context context) {
return new ContentProviderSimpleAdapter(MediaStore.Images.Media.INTERNAL_CONTENT_URI, context);
} | [
"public",
"static",
"ContentProviderSimpleAdapter",
"getInternalPhotoSimpleAdapter",
"(",
"Context",
"context",
")",
"{",
"return",
"new",
"ContentProviderSimpleAdapter",
"(",
"MediaStore",
".",
"Images",
".",
"Media",
".",
"INTERNAL_CONTENT_URI",
",",
"context",
")",
"... | Creates and returns a SimpleAdapter for Internal Photos
@param context The Context
@return The SimpleAdapter for local photo | [
"Creates",
"and",
"returns",
"a",
"SimpleAdapter",
"for",
"Internal",
"Photos"
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/data/impl/ContentProviderSimpleAdapter.java#L47-L49 |
apache/spark | common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java | ExternalShuffleBlockResolver.getBlockData | public ManagedBuffer getBlockData(
String appId,
String execId,
int shuffleId,
int mapId,
int reduceId) {
"""
Obtains a FileSegmentManagedBuffer from (shuffleId, mapId, reduceId). We make assumptions
about how the hash and sort based shuffles store their data.
"""
ExecutorShuffleInfo executor = executors.get(new AppExecId(appId, execId));
if (executor == null) {
throw new RuntimeException(
String.format("Executor is not registered (appId=%s, execId=%s)", appId, execId));
}
return getSortBasedShuffleBlockData(executor, shuffleId, mapId, reduceId);
} | java | public ManagedBuffer getBlockData(
String appId,
String execId,
int shuffleId,
int mapId,
int reduceId) {
ExecutorShuffleInfo executor = executors.get(new AppExecId(appId, execId));
if (executor == null) {
throw new RuntimeException(
String.format("Executor is not registered (appId=%s, execId=%s)", appId, execId));
}
return getSortBasedShuffleBlockData(executor, shuffleId, mapId, reduceId);
} | [
"public",
"ManagedBuffer",
"getBlockData",
"(",
"String",
"appId",
",",
"String",
"execId",
",",
"int",
"shuffleId",
",",
"int",
"mapId",
",",
"int",
"reduceId",
")",
"{",
"ExecutorShuffleInfo",
"executor",
"=",
"executors",
".",
"get",
"(",
"new",
"AppExecId"... | Obtains a FileSegmentManagedBuffer from (shuffleId, mapId, reduceId). We make assumptions
about how the hash and sort based shuffles store their data. | [
"Obtains",
"a",
"FileSegmentManagedBuffer",
"from",
"(",
"shuffleId",
"mapId",
"reduceId",
")",
".",
"We",
"make",
"assumptions",
"about",
"how",
"the",
"hash",
"and",
"sort",
"based",
"shuffles",
"store",
"their",
"data",
"."
] | train | https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolver.java#L168-L180 |
apereo/cas | core/cas-server-core/src/main/java/org/apereo/cas/AbstractCentralAuthenticationService.java | AbstractCentralAuthenticationService.getTicket | @Transactional(transactionManager = "ticketTransactionManager", noRollbackFor = InvalidTicketException.class)
@Override
public <T extends Ticket> T getTicket(final @NonNull String ticketId, final Class<T> clazz) throws InvalidTicketException {
"""
{@inheritDoc}
<p>
Note:
Synchronization on ticket object in case of cache based registry doesn't serialize
access to critical section. The reason is that cache pulls serialized data and
builds new object, most likely for each pull. Is this synchronization needed here?
"""
val ticket = this.ticketRegistry.getTicket(ticketId, clazz);
verifyTicketState(ticket, ticketId, clazz);
return (T) ticket;
} | java | @Transactional(transactionManager = "ticketTransactionManager", noRollbackFor = InvalidTicketException.class)
@Override
public <T extends Ticket> T getTicket(final @NonNull String ticketId, final Class<T> clazz) throws InvalidTicketException {
val ticket = this.ticketRegistry.getTicket(ticketId, clazz);
verifyTicketState(ticket, ticketId, clazz);
return (T) ticket;
} | [
"@",
"Transactional",
"(",
"transactionManager",
"=",
"\"ticketTransactionManager\"",
",",
"noRollbackFor",
"=",
"InvalidTicketException",
".",
"class",
")",
"@",
"Override",
"public",
"<",
"T",
"extends",
"Ticket",
">",
"T",
"getTicket",
"(",
"final",
"@",
"NonNu... | {@inheritDoc}
<p>
Note:
Synchronization on ticket object in case of cache based registry doesn't serialize
access to critical section. The reason is that cache pulls serialized data and
builds new object, most likely for each pull. Is this synchronization needed here? | [
"{"
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core/src/main/java/org/apereo/cas/AbstractCentralAuthenticationService.java#L134-L140 |
windup/windup | config/api/src/main/java/org/jboss/windup/config/RuleSubset.java | RuleSubset.logTimeTakenByRuleProvider | private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken) {
"""
Logs the time taken by this rule, and attaches this to the total for the RuleProvider
"""
AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);
if (ruleProvider == null)
return;
if (!timeTakenByProvider.containsKey(ruleProvider))
{
RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)
.create();
model.setRuleIndex(ruleIndex);
model.setRuleProviderID(ruleProvider.getMetadata().getID());
model.setTimeTaken(timeTaken);
timeTakenByProvider.put(ruleProvider, model.getElement().id());
}
else
{
RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);
RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));
int prevTimeTaken = model.getTimeTaken();
model.setTimeTaken(prevTimeTaken + timeTaken);
}
logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);
} | java | private void logTimeTakenByRuleProvider(GraphContext graphContext, Context context, int ruleIndex, int timeTaken)
{
AbstractRuleProvider ruleProvider = (AbstractRuleProvider) context.get(RuleMetadataType.RULE_PROVIDER);
if (ruleProvider == null)
return;
if (!timeTakenByProvider.containsKey(ruleProvider))
{
RuleProviderExecutionStatisticsModel model = new RuleProviderExecutionStatisticsService(graphContext)
.create();
model.setRuleIndex(ruleIndex);
model.setRuleProviderID(ruleProvider.getMetadata().getID());
model.setTimeTaken(timeTaken);
timeTakenByProvider.put(ruleProvider, model.getElement().id());
}
else
{
RuleProviderExecutionStatisticsService service = new RuleProviderExecutionStatisticsService(graphContext);
RuleProviderExecutionStatisticsModel model = service.getById(timeTakenByProvider.get(ruleProvider));
int prevTimeTaken = model.getTimeTaken();
model.setTimeTaken(prevTimeTaken + timeTaken);
}
logTimeTakenByPhase(graphContext, ruleProvider.getMetadata().getPhase(), timeTaken);
} | [
"private",
"void",
"logTimeTakenByRuleProvider",
"(",
"GraphContext",
"graphContext",
",",
"Context",
"context",
",",
"int",
"ruleIndex",
",",
"int",
"timeTaken",
")",
"{",
"AbstractRuleProvider",
"ruleProvider",
"=",
"(",
"AbstractRuleProvider",
")",
"context",
".",
... | Logs the time taken by this rule, and attaches this to the total for the RuleProvider | [
"Logs",
"the",
"time",
"taken",
"by",
"this",
"rule",
"and",
"attaches",
"this",
"to",
"the",
"total",
"for",
"the",
"RuleProvider"
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/RuleSubset.java#L138-L162 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java | FaceListsImpl.addFaceFromStreamWithServiceResponseAsync | public Observable<ServiceResponse<PersistedFace>> addFaceFromStreamWithServiceResponseAsync(String faceListId, byte[] image, AddFaceFromStreamOptionalParameter addFaceFromStreamOptionalParameter) {
"""
Add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire.
@param faceListId Id referencing a particular face list.
@param image An image stream.
@param addFaceFromStreamOptionalParameter 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 PersistedFace object
"""
if (this.client.azureRegion() == null) {
throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null.");
}
if (faceListId == null) {
throw new IllegalArgumentException("Parameter faceListId is required and cannot be null.");
}
if (image == null) {
throw new IllegalArgumentException("Parameter image is required and cannot be null.");
}
final String userData = addFaceFromStreamOptionalParameter != null ? addFaceFromStreamOptionalParameter.userData() : null;
final List<Integer> targetFace = addFaceFromStreamOptionalParameter != null ? addFaceFromStreamOptionalParameter.targetFace() : null;
return addFaceFromStreamWithServiceResponseAsync(faceListId, image, userData, targetFace);
} | java | public Observable<ServiceResponse<PersistedFace>> addFaceFromStreamWithServiceResponseAsync(String faceListId, byte[] image, AddFaceFromStreamOptionalParameter addFaceFromStreamOptionalParameter) {
if (this.client.azureRegion() == null) {
throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null.");
}
if (faceListId == null) {
throw new IllegalArgumentException("Parameter faceListId is required and cannot be null.");
}
if (image == null) {
throw new IllegalArgumentException("Parameter image is required and cannot be null.");
}
final String userData = addFaceFromStreamOptionalParameter != null ? addFaceFromStreamOptionalParameter.userData() : null;
final List<Integer> targetFace = addFaceFromStreamOptionalParameter != null ? addFaceFromStreamOptionalParameter.targetFace() : null;
return addFaceFromStreamWithServiceResponseAsync(faceListId, image, userData, targetFace);
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"PersistedFace",
">",
">",
"addFaceFromStreamWithServiceResponseAsync",
"(",
"String",
"faceListId",
",",
"byte",
"[",
"]",
"image",
",",
"AddFaceFromStreamOptionalParameter",
"addFaceFromStreamOptionalParameter",
")",
"{... | Add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire.
@param faceListId Id referencing a particular face list.
@param image An image stream.
@param addFaceFromStreamOptionalParameter 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 PersistedFace object | [
"Add",
"a",
"face",
"to",
"a",
"face",
"list",
".",
"The",
"input",
"face",
"is",
"specified",
"as",
"an",
"image",
"with",
"a",
"targetFace",
"rectangle",
".",
"It",
"returns",
"a",
"persistedFaceId",
"representing",
"the",
"added",
"face",
"and",
"persis... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java#L978-L992 |
PunchThrough/bean-sdk-android | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | OADProfile.needsUpdate | private boolean needsUpdate(Long bundleVersion, String beanVersion) {
"""
Helper function to determine whether a Bean needs a FW update given a specific Bundle version
@param bundleVersion the version string from the provided firmware bundle
@param beanVersion the version string provided from the Bean Device Information Service
@return boolean value stating whether the Bean needs an update
"""
if (beanVersion.contains("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
try {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
} catch (NumberFormatException e) {
Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion);
fail(BeanError.UNPARSABLE_FW_VERSION);
}
}
return false;
} | java | private boolean needsUpdate(Long bundleVersion, String beanVersion) {
if (beanVersion.contains("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
try {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
} catch (NumberFormatException e) {
Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion);
fail(BeanError.UNPARSABLE_FW_VERSION);
}
}
return false;
} | [
"private",
"boolean",
"needsUpdate",
"(",
"Long",
"bundleVersion",
",",
"String",
"beanVersion",
")",
"{",
"if",
"(",
"beanVersion",
".",
"contains",
"(",
"\"OAD\"",
")",
")",
"{",
"Log",
".",
"i",
"(",
"TAG",
",",
"\"Bundle version: \"",
"+",
"bundleVersion... | Helper function to determine whether a Bean needs a FW update given a specific Bundle version
@param bundleVersion the version string from the provided firmware bundle
@param beanVersion the version string provided from the Bean Device Information Service
@return boolean value stating whether the Bean needs an update | [
"Helper",
"function",
"to",
"determine",
"whether",
"a",
"Bean",
"needs",
"a",
"FW",
"update",
"given",
"a",
"specific",
"Bundle",
"version"
] | train | https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java#L337-L358 |
onepf/OpenIAB | library/src/main/java/org/onepf/oms/appstore/nokiaUtils/NokiaStoreHelper.java | NokiaStoreHelper.processPurchaseSuccess | private void processPurchaseSuccess(final String purchaseData) {
"""
Called if purchase has been successful
@param purchaseData Response code for IabResult
"""
Logger.i("NokiaStoreHelper.processPurchaseSuccess");
Logger.d("purchaseData = ", purchaseData);
Purchase purchase;
try {
final JSONObject obj = new JSONObject(purchaseData);
final String sku = SkuManager.getInstance().getSku(OpenIabHelper.NAME_NOKIA, obj.getString("productId"));
Logger.d("sku = ", sku);
purchase = new Purchase(OpenIabHelper.NAME_NOKIA);
purchase.setItemType(IabHelper.ITEM_TYPE_INAPP);
purchase.setOrderId(obj.getString("orderId"));
purchase.setPackageName(obj.getString("packageName"));
purchase.setSku(sku);
purchase.setToken(obj.getString("purchaseToken"));
purchase.setDeveloperPayload(obj.getString("developerPayload"));
} catch (JSONException e) {
Logger.e(e, "JSONException: ", e);
final IabResult result = new NokiaResult(IabHelper.IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
if (mPurchaseListener != null) {
mPurchaseListener.onIabPurchaseFinished(result, null);
}
return;
}
if (mPurchaseListener != null) {
mPurchaseListener.onIabPurchaseFinished(new NokiaResult(RESULT_OK, "Success"), purchase);
}
} | java | private void processPurchaseSuccess(final String purchaseData) {
Logger.i("NokiaStoreHelper.processPurchaseSuccess");
Logger.d("purchaseData = ", purchaseData);
Purchase purchase;
try {
final JSONObject obj = new JSONObject(purchaseData);
final String sku = SkuManager.getInstance().getSku(OpenIabHelper.NAME_NOKIA, obj.getString("productId"));
Logger.d("sku = ", sku);
purchase = new Purchase(OpenIabHelper.NAME_NOKIA);
purchase.setItemType(IabHelper.ITEM_TYPE_INAPP);
purchase.setOrderId(obj.getString("orderId"));
purchase.setPackageName(obj.getString("packageName"));
purchase.setSku(sku);
purchase.setToken(obj.getString("purchaseToken"));
purchase.setDeveloperPayload(obj.getString("developerPayload"));
} catch (JSONException e) {
Logger.e(e, "JSONException: ", e);
final IabResult result = new NokiaResult(IabHelper.IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
if (mPurchaseListener != null) {
mPurchaseListener.onIabPurchaseFinished(result, null);
}
return;
}
if (mPurchaseListener != null) {
mPurchaseListener.onIabPurchaseFinished(new NokiaResult(RESULT_OK, "Success"), purchase);
}
} | [
"private",
"void",
"processPurchaseSuccess",
"(",
"final",
"String",
"purchaseData",
")",
"{",
"Logger",
".",
"i",
"(",
"\"NokiaStoreHelper.processPurchaseSuccess\"",
")",
";",
"Logger",
".",
"d",
"(",
"\"purchaseData = \"",
",",
"purchaseData",
")",
";",
"Purchase"... | Called if purchase has been successful
@param purchaseData Response code for IabResult | [
"Called",
"if",
"purchase",
"has",
"been",
"successful"
] | train | https://github.com/onepf/OpenIAB/blob/90552d53c5303b322940d96a0c4b7cb797d78760/library/src/main/java/org/onepf/oms/appstore/nokiaUtils/NokiaStoreHelper.java#L344-L380 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/WSEJBProxy.java | WSEJBProxy.addCtor | private static void addCtor(ClassWriter cw, String parent) {
"""
Adds the default (no arg) constructor. <p>
There are no exceptions in the throws clause; none are required
for the constructors of EJB Proxys. <p>
Currently, the generated method body is intentionally empty;
EJB Proxys require no initialization in the constructor. <p>
@param cw ASM ClassWriter to add the constructor to.
@param parent fully qualified name of the parent class
with '/' as the separator character
(i.e. internal name).
"""
MethodVisitor mv;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, INDENT + "adding method : <init> ()V");
// -----------------------------------------------------------------------
// public <Class Name>()
// {
// }
// -----------------------------------------------------------------------
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, parent, "<init>", "()V");
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
} | java | private static void addCtor(ClassWriter cw, String parent)
{
MethodVisitor mv;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, INDENT + "adding method : <init> ()V");
// -----------------------------------------------------------------------
// public <Class Name>()
// {
// }
// -----------------------------------------------------------------------
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, parent, "<init>", "()V");
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
} | [
"private",
"static",
"void",
"addCtor",
"(",
"ClassWriter",
"cw",
",",
"String",
"parent",
")",
"{",
"MethodVisitor",
"mv",
";",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"Tr",
".",... | Adds the default (no arg) constructor. <p>
There are no exceptions in the throws clause; none are required
for the constructors of EJB Proxys. <p>
Currently, the generated method body is intentionally empty;
EJB Proxys require no initialization in the constructor. <p>
@param cw ASM ClassWriter to add the constructor to.
@param parent fully qualified name of the parent class
with '/' as the separator character
(i.e. internal name). | [
"Adds",
"the",
"default",
"(",
"no",
"arg",
")",
"constructor",
".",
"<p",
">"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/ejbcontainer/jitdeploy/WSEJBProxy.java#L224-L243 |
aws/aws-sdk-java | aws-java-sdk-appstream/src/main/java/com/amazonaws/services/appstream/model/CreateImageBuilderRequest.java | CreateImageBuilderRequest.withTags | public CreateImageBuilderRequest withTags(java.util.Map<String, String> tags) {
"""
<p>
The tags to associate with the image builder. A tag is a key-value pair, and the value is optional. For example,
Environment=Test. If you do not specify a value, Environment=.
</p>
<p>
If you do not specify a value, the value is set to an empty string.
</p>
<p>
For more information about tags, see <a
href="https://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html">Tagging Your Resources</a>
in the <i>Amazon AppStream 2.0 Developer Guide</i>.
</p>
@param tags
The tags to associate with the image builder. A tag is a key-value pair, and the value is optional. For
example, Environment=Test. If you do not specify a value, Environment=. </p>
<p>
If you do not specify a value, the value is set to an empty string.
</p>
<p>
For more information about tags, see <a
href="https://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html">Tagging Your
Resources</a> in the <i>Amazon AppStream 2.0 Developer Guide</i>.
@return Returns a reference to this object so that method calls can be chained together.
"""
setTags(tags);
return this;
} | java | public CreateImageBuilderRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
} | [
"public",
"CreateImageBuilderRequest",
"withTags",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"tags",
")",
"{",
"setTags",
"(",
"tags",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The tags to associate with the image builder. A tag is a key-value pair, and the value is optional. For example,
Environment=Test. If you do not specify a value, Environment=.
</p>
<p>
If you do not specify a value, the value is set to an empty string.
</p>
<p>
For more information about tags, see <a
href="https://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html">Tagging Your Resources</a>
in the <i>Amazon AppStream 2.0 Developer Guide</i>.
</p>
@param tags
The tags to associate with the image builder. A tag is a key-value pair, and the value is optional. For
example, Environment=Test. If you do not specify a value, Environment=. </p>
<p>
If you do not specify a value, the value is set to an empty string.
</p>
<p>
For more information about tags, see <a
href="https://docs.aws.amazon.com/appstream2/latest/developerguide/tagging-basic.html">Tagging Your
Resources</a> in the <i>Amazon AppStream 2.0 Developer Guide</i>.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"tags",
"to",
"associate",
"with",
"the",
"image",
"builder",
".",
"A",
"tag",
"is",
"a",
"key",
"-",
"value",
"pair",
"and",
"the",
"value",
"is",
"optional",
".",
"For",
"example",
"Environment",
"=",
"Test",
".",
"If",
"you",
"do... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-appstream/src/main/java/com/amazonaws/services/appstream/model/CreateImageBuilderRequest.java#L616-L619 |
jfinal/jfinal | src/main/java/com/jfinal/plugin/activerecord/DbPro.java | DbPro.batchSave | public int[] batchSave(String tableName, List<Record> recordList, int batchSize) {
"""
Batch save records using the "insert into ..." sql generated by the first record in recordList.
Ensure all the record can use the same sql as the first record.
@param tableName the table name
"""
if (recordList == null || recordList.size() == 0)
return new int[0];
Record record = recordList.get(0);
Map<String, Object> cols = record.getColumns();
int index = 0;
StringBuilder columns = new StringBuilder();
// the same as the iterator in Dialect.forDbSave() to ensure the order of the columns
for (Entry<String, Object> e : cols.entrySet()) {
if (config.dialect.isOracle()) { // 支持 oracle 自增主键
Object value = e.getValue();
if (value instanceof String && ((String)value).endsWith(".nextval")) {
continue ;
}
}
if (index++ > 0) {
columns.append(',');
}
columns.append(e.getKey());
}
String[] pKeysNoUse = new String[0];
StringBuilder sql = new StringBuilder();
List<Object> parasNoUse = new ArrayList<Object>();
config.dialect.forDbSave(tableName, pKeysNoUse, record, sql, parasNoUse);
return batch(sql.toString(), columns.toString(), recordList, batchSize);
} | java | public int[] batchSave(String tableName, List<Record> recordList, int batchSize) {
if (recordList == null || recordList.size() == 0)
return new int[0];
Record record = recordList.get(0);
Map<String, Object> cols = record.getColumns();
int index = 0;
StringBuilder columns = new StringBuilder();
// the same as the iterator in Dialect.forDbSave() to ensure the order of the columns
for (Entry<String, Object> e : cols.entrySet()) {
if (config.dialect.isOracle()) { // 支持 oracle 自增主键
Object value = e.getValue();
if (value instanceof String && ((String)value).endsWith(".nextval")) {
continue ;
}
}
if (index++ > 0) {
columns.append(',');
}
columns.append(e.getKey());
}
String[] pKeysNoUse = new String[0];
StringBuilder sql = new StringBuilder();
List<Object> parasNoUse = new ArrayList<Object>();
config.dialect.forDbSave(tableName, pKeysNoUse, record, sql, parasNoUse);
return batch(sql.toString(), columns.toString(), recordList, batchSize);
} | [
"public",
"int",
"[",
"]",
"batchSave",
"(",
"String",
"tableName",
",",
"List",
"<",
"Record",
">",
"recordList",
",",
"int",
"batchSize",
")",
"{",
"if",
"(",
"recordList",
"==",
"null",
"||",
"recordList",
".",
"size",
"(",
")",
"==",
"0",
")",
"r... | Batch save records using the "insert into ..." sql generated by the first record in recordList.
Ensure all the record can use the same sql as the first record.
@param tableName the table name | [
"Batch",
"save",
"records",
"using",
"the",
"insert",
"into",
"...",
"sql",
"generated",
"by",
"the",
"first",
"record",
"in",
"recordList",
".",
"Ensure",
"all",
"the",
"record",
"can",
"use",
"the",
"same",
"sql",
"as",
"the",
"first",
"record",
"."
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/DbPro.java#L1157-L1185 |
yavijava/yavijava | src/main/java/com/vmware/vim25/mo/HostVsanSystem.java | HostVsanSystem.evacuateVsanNode_Task | public Task evacuateVsanNode_Task(HostMaintenanceSpec maintenanceSpec, int timeout) throws InvalidState, RequestCanceled, RuntimeFault, Timedout, VsanFault, RemoteException {
"""
Evacuate this host from VSAN cluster.
The task is cancellable.
@param maintenanceSpec -
Specifies the data evacuation mode. See {@link com.vmware.vim25.HostMaintenanceSpec HostMaintenanceSpec}.
If unspecified, the default mode chosen will be ensureObjectAccessibility.
@param timeout -
Time to wait for the task to complete in seconds. If the value is less than or equal to zero,
there is no timeout. The operation fails with a Timedout exception if it timed out.
@return This method returns a Task object with which to monitor the operation.
@throws InvalidState
@throws RequestCanceled
@throws RuntimeFault
@throws Timedout
@throws VsanFault
@throws RemoteException
@since 6.0
"""
return new Task(getServerConnection(), getVimService().evacuateVsanNode_Task(getMOR(), maintenanceSpec, timeout));
} | java | public Task evacuateVsanNode_Task(HostMaintenanceSpec maintenanceSpec, int timeout) throws InvalidState, RequestCanceled, RuntimeFault, Timedout, VsanFault, RemoteException {
return new Task(getServerConnection(), getVimService().evacuateVsanNode_Task(getMOR(), maintenanceSpec, timeout));
} | [
"public",
"Task",
"evacuateVsanNode_Task",
"(",
"HostMaintenanceSpec",
"maintenanceSpec",
",",
"int",
"timeout",
")",
"throws",
"InvalidState",
",",
"RequestCanceled",
",",
"RuntimeFault",
",",
"Timedout",
",",
"VsanFault",
",",
"RemoteException",
"{",
"return",
"new"... | Evacuate this host from VSAN cluster.
The task is cancellable.
@param maintenanceSpec -
Specifies the data evacuation mode. See {@link com.vmware.vim25.HostMaintenanceSpec HostMaintenanceSpec}.
If unspecified, the default mode chosen will be ensureObjectAccessibility.
@param timeout -
Time to wait for the task to complete in seconds. If the value is less than or equal to zero,
there is no timeout. The operation fails with a Timedout exception if it timed out.
@return This method returns a Task object with which to monitor the operation.
@throws InvalidState
@throws RequestCanceled
@throws RuntimeFault
@throws Timedout
@throws VsanFault
@throws RemoteException
@since 6.0 | [
"Evacuate",
"this",
"host",
"from",
"VSAN",
"cluster",
".",
"The",
"task",
"is",
"cancellable",
"."
] | train | https://github.com/yavijava/yavijava/blob/27fd2c5826115782d5eeb934f86e3e39240179cd/src/main/java/com/vmware/vim25/mo/HostVsanSystem.java#L139-L141 |
joniles/mpxj | src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java | ProjectTreeController.addFilters | private void addFilters(MpxjTreeNode parentNode, List<Filter> filters) {
"""
Add filters to the tree.
@param parentNode parent tree node
@param filters list of filters
"""
for (Filter field : filters)
{
final Filter f = field;
MpxjTreeNode childNode = new MpxjTreeNode(field)
{
@Override public String toString()
{
return f.getName();
}
};
parentNode.add(childNode);
}
} | java | private void addFilters(MpxjTreeNode parentNode, List<Filter> filters)
{
for (Filter field : filters)
{
final Filter f = field;
MpxjTreeNode childNode = new MpxjTreeNode(field)
{
@Override public String toString()
{
return f.getName();
}
};
parentNode.add(childNode);
}
} | [
"private",
"void",
"addFilters",
"(",
"MpxjTreeNode",
"parentNode",
",",
"List",
"<",
"Filter",
">",
"filters",
")",
"{",
"for",
"(",
"Filter",
"field",
":",
"filters",
")",
"{",
"final",
"Filter",
"f",
"=",
"field",
";",
"MpxjTreeNode",
"childNode",
"=",
... | Add filters to the tree.
@param parentNode parent tree node
@param filters list of filters | [
"Add",
"filters",
"to",
"the",
"tree",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java#L466-L480 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/LifecycleChaincodePackage.java | LifecycleChaincodePackage.toFile | public void toFile(Path path, OpenOption... options) throws IOException {
"""
Write Lifecycle chaincode package bytes to file.
@param path of the file to write to.
@param options Options on creating file.
@throws IOException
"""
Files.write(path, pBytes, options);
} | java | public void toFile(Path path, OpenOption... options) throws IOException {
Files.write(path, pBytes, options);
} | [
"public",
"void",
"toFile",
"(",
"Path",
"path",
",",
"OpenOption",
"...",
"options",
")",
"throws",
"IOException",
"{",
"Files",
".",
"write",
"(",
"path",
",",
"pBytes",
",",
"options",
")",
";",
"}"
] | Write Lifecycle chaincode package bytes to file.
@param path of the file to write to.
@param options Options on creating file.
@throws IOException | [
"Write",
"Lifecycle",
"chaincode",
"package",
"bytes",
"to",
"file",
"."
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/LifecycleChaincodePackage.java#L138-L141 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/telemetry/TelemetryUtil.java | TelemetryUtil.buildJobData | public static TelemetryData buildJobData(String queryId, TelemetryField field, long value) {
"""
Create a simple TelemetryData instance for Job metrics using given parameters
@param queryId the id of the query
@param field the field to log (represents the "type" field in telemetry)
@param value the value to log for the field
@return TelemetryData instance constructed from parameters
"""
ObjectNode obj = mapper.createObjectNode();
obj.put(TYPE, field.toString());
obj.put(QUERY_ID, queryId);
obj.put(VALUE, value);
return new TelemetryData(obj, System.currentTimeMillis());
} | java | public static TelemetryData buildJobData(String queryId, TelemetryField field, long value)
{
ObjectNode obj = mapper.createObjectNode();
obj.put(TYPE, field.toString());
obj.put(QUERY_ID, queryId);
obj.put(VALUE, value);
return new TelemetryData(obj, System.currentTimeMillis());
} | [
"public",
"static",
"TelemetryData",
"buildJobData",
"(",
"String",
"queryId",
",",
"TelemetryField",
"field",
",",
"long",
"value",
")",
"{",
"ObjectNode",
"obj",
"=",
"mapper",
".",
"createObjectNode",
"(",
")",
";",
"obj",
".",
"put",
"(",
"TYPE",
",",
... | Create a simple TelemetryData instance for Job metrics using given parameters
@param queryId the id of the query
@param field the field to log (represents the "type" field in telemetry)
@param value the value to log for the field
@return TelemetryData instance constructed from parameters | [
"Create",
"a",
"simple",
"TelemetryData",
"instance",
"for",
"Job",
"metrics",
"using",
"given",
"parameters"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/telemetry/TelemetryUtil.java#L24-L31 |
cdk/cdk | base/standard/src/main/java/org/openscience/cdk/fingerprint/IntArrayFingerprint.java | IntArrayFingerprint.set | @Override
public void set(int index, boolean value) {
"""
/*
This method is VERY INNEFICIENT when called multiple times. It is the
cost of keeping down the memory footprint. Avoid using it for building up
IntArrayFingerprints -- instead use the constructor taking a so called
raw fingerprint.
"""
int i = Arrays.binarySearch(trueBits, index);
// bit at index is set to true and shall be set to false
if (i >= 0 && !value) {
int[] tmp = new int[trueBits.length - 1];
System.arraycopy(trueBits, 0, tmp, 0, i);
System.arraycopy(trueBits, i + 1, tmp, i, trueBits.length - i - 1);
trueBits = tmp;
}
// bit at index is set to false and shall be set to true
else if (i < 0 && value) {
int[] tmp = new int[trueBits.length + 1];
System.arraycopy(trueBits, 0, tmp, 0, trueBits.length);
tmp[tmp.length - 1] = index;
trueBits = tmp;
Arrays.sort(trueBits);
}
} | java | @Override
public void set(int index, boolean value) {
int i = Arrays.binarySearch(trueBits, index);
// bit at index is set to true and shall be set to false
if (i >= 0 && !value) {
int[] tmp = new int[trueBits.length - 1];
System.arraycopy(trueBits, 0, tmp, 0, i);
System.arraycopy(trueBits, i + 1, tmp, i, trueBits.length - i - 1);
trueBits = tmp;
}
// bit at index is set to false and shall be set to true
else if (i < 0 && value) {
int[] tmp = new int[trueBits.length + 1];
System.arraycopy(trueBits, 0, tmp, 0, trueBits.length);
tmp[tmp.length - 1] = index;
trueBits = tmp;
Arrays.sort(trueBits);
}
} | [
"@",
"Override",
"public",
"void",
"set",
"(",
"int",
"index",
",",
"boolean",
"value",
")",
"{",
"int",
"i",
"=",
"Arrays",
".",
"binarySearch",
"(",
"trueBits",
",",
"index",
")",
";",
"// bit at index is set to true and shall be set to false",
"if",
"(",
"i... | /*
This method is VERY INNEFICIENT when called multiple times. It is the
cost of keeping down the memory footprint. Avoid using it for building up
IntArrayFingerprints -- instead use the constructor taking a so called
raw fingerprint. | [
"/",
"*",
"This",
"method",
"is",
"VERY",
"INNEFICIENT",
"when",
"called",
"multiple",
"times",
".",
"It",
"is",
"the",
"cost",
"of",
"keeping",
"down",
"the",
"memory",
"footprint",
".",
"Avoid",
"using",
"it",
"for",
"building",
"up",
"IntArrayFingerprints... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/fingerprint/IntArrayFingerprint.java#L164-L182 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jAssociationQueries.java | EmbeddedNeo4jAssociationQueries.removeAssociationRow | @Override
public void removeAssociationRow(GraphDatabaseService executionEngine, AssociationKey associationKey, RowKey rowKey) {
"""
Remove an association row
@param executionEngine the {@link GraphDatabaseService} used to run the query
@param associationKey represents the association
@param rowKey represents a row in an association
"""
Object[] queryValues = relationshipValues( associationKey, rowKey );
executionEngine.execute( removeAssociationRowQuery, params( queryValues ) );
} | java | @Override
public void removeAssociationRow(GraphDatabaseService executionEngine, AssociationKey associationKey, RowKey rowKey) {
Object[] queryValues = relationshipValues( associationKey, rowKey );
executionEngine.execute( removeAssociationRowQuery, params( queryValues ) );
} | [
"@",
"Override",
"public",
"void",
"removeAssociationRow",
"(",
"GraphDatabaseService",
"executionEngine",
",",
"AssociationKey",
"associationKey",
",",
"RowKey",
"rowKey",
")",
"{",
"Object",
"[",
"]",
"queryValues",
"=",
"relationshipValues",
"(",
"associationKey",
... | Remove an association row
@param executionEngine the {@link GraphDatabaseService} used to run the query
@param associationKey represents the association
@param rowKey represents a row in an association | [
"Remove",
"an",
"association",
"row"
] | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/embedded/dialect/impl/EmbeddedNeo4jAssociationQueries.java#L100-L104 |
ModeShape/modeshape | web/modeshape-webdav/src/main/java/org/modeshape/webdav/fromcatalina/RequestUtil.java | RequestUtil.URLDecode | public static String URLDecode( String str,
String enc ) {
"""
Decode and return the specified URL-encoded String.
@param str The url-encoded string
@param enc The encoding to use; if null, the default encoding is used
@return the decoded URL
@throws IllegalArgumentException if a '%' character is not followed by a valid 2-digit hexadecimal number
"""
if (str == null) {
return (null);
}
// use the specified encoding to extract bytes out of the
// given string so that the encoding is not lost. If an
// encoding is not specified, let it use platform default
byte[] bytes = null;
try {
if (enc == null) {
bytes = str.getBytes();
} else {
bytes = str.getBytes(enc);
}
} catch (UnsupportedEncodingException uee) {
}
return URLDecode(bytes, enc);
} | java | public static String URLDecode( String str,
String enc ) {
if (str == null) {
return (null);
}
// use the specified encoding to extract bytes out of the
// given string so that the encoding is not lost. If an
// encoding is not specified, let it use platform default
byte[] bytes = null;
try {
if (enc == null) {
bytes = str.getBytes();
} else {
bytes = str.getBytes(enc);
}
} catch (UnsupportedEncodingException uee) {
}
return URLDecode(bytes, enc);
} | [
"public",
"static",
"String",
"URLDecode",
"(",
"String",
"str",
",",
"String",
"enc",
")",
"{",
"if",
"(",
"str",
"==",
"null",
")",
"{",
"return",
"(",
"null",
")",
";",
"}",
"// use the specified encoding to extract bytes out of the",
"// given string so that t... | Decode and return the specified URL-encoded String.
@param str The url-encoded string
@param enc The encoding to use; if null, the default encoding is used
@return the decoded URL
@throws IllegalArgumentException if a '%' character is not followed by a valid 2-digit hexadecimal number | [
"Decode",
"and",
"return",
"the",
"specified",
"URL",
"-",
"encoded",
"String",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/web/modeshape-webdav/src/main/java/org/modeshape/webdav/fromcatalina/RequestUtil.java#L320-L342 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java | TransformerRegistry.registerSubsystemTransformers | public TransformersSubRegistration registerSubsystemTransformers(final String name, final ModelVersionRange range, final ResourceTransformer subsystemTransformer) {
"""
Register a subsystem transformer.
@param name the subsystem name
@param range the version range
@param subsystemTransformer the resource transformer
@return the sub registry
"""
return registerSubsystemTransformers(name, range, subsystemTransformer, OperationTransformer.DEFAULT, false);
} | java | public TransformersSubRegistration registerSubsystemTransformers(final String name, final ModelVersionRange range, final ResourceTransformer subsystemTransformer) {
return registerSubsystemTransformers(name, range, subsystemTransformer, OperationTransformer.DEFAULT, false);
} | [
"public",
"TransformersSubRegistration",
"registerSubsystemTransformers",
"(",
"final",
"String",
"name",
",",
"final",
"ModelVersionRange",
"range",
",",
"final",
"ResourceTransformer",
"subsystemTransformer",
")",
"{",
"return",
"registerSubsystemTransformers",
"(",
"name",... | Register a subsystem transformer.
@param name the subsystem name
@param range the version range
@param subsystemTransformer the resource transformer
@return the sub registry | [
"Register",
"a",
"subsystem",
"transformer",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/TransformerRegistry.java#L135-L137 |
elki-project/elki | elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java | DBIDUtil.randomSplit | public static ArrayDBIDs[] randomSplit(DBIDs oids, int p, Random random) {
"""
Randomly split IDs into {@code p} partitions of almost-equal size.
@param oids Original DBIDs
@param p Desired number of partitions.
@param random Random generator
"""
// Fast, and we're single-threaded here anyway.
random = random != null ? random : new FastNonThreadsafeRandom();
ArrayModifiableDBIDs ids = newArray(oids);
final int size = ids.size();
ArrayDBIDs[] split = new ArrayDBIDs[p];
// Shuffle
for(int i = 1; i < size; i++) {
ids.swap(i - 1, i + random.nextInt(size - i));
}
final int minsize = size / p, // Floor.
extra = size % p; // Remainder
for(int beg = 0, part = 0; part < p; part++) {
// First partitions are smaller, last partitions are larger.
final int psize = minsize + ((part < extra) ? 1 : 0);
split[part] = ids.slice(beg, beg + psize);
beg += psize;
}
return split;
} | java | public static ArrayDBIDs[] randomSplit(DBIDs oids, int p, Random random) {
// Fast, and we're single-threaded here anyway.
random = random != null ? random : new FastNonThreadsafeRandom();
ArrayModifiableDBIDs ids = newArray(oids);
final int size = ids.size();
ArrayDBIDs[] split = new ArrayDBIDs[p];
// Shuffle
for(int i = 1; i < size; i++) {
ids.swap(i - 1, i + random.nextInt(size - i));
}
final int minsize = size / p, // Floor.
extra = size % p; // Remainder
for(int beg = 0, part = 0; part < p; part++) {
// First partitions are smaller, last partitions are larger.
final int psize = minsize + ((part < extra) ? 1 : 0);
split[part] = ids.slice(beg, beg + psize);
beg += psize;
}
return split;
} | [
"public",
"static",
"ArrayDBIDs",
"[",
"]",
"randomSplit",
"(",
"DBIDs",
"oids",
",",
"int",
"p",
",",
"Random",
"random",
")",
"{",
"// Fast, and we're single-threaded here anyway.",
"random",
"=",
"random",
"!=",
"null",
"?",
"random",
":",
"new",
"FastNonThre... | Randomly split IDs into {@code p} partitions of almost-equal size.
@param oids Original DBIDs
@param p Desired number of partitions.
@param random Random generator | [
"Randomly",
"split",
"IDs",
"into",
"{",
"@code",
"p",
"}",
"partitions",
"of",
"almost",
"-",
"equal",
"size",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-dbids/src/main/java/de/lmu/ifi/dbs/elki/database/ids/DBIDUtil.java#L747-L766 |
JOML-CI/JOML | src/org/joml/Quaterniond.java | Quaterniond.nlerpIterative | public Quaterniond nlerpIterative(Quaterniondc q, double alpha, double dotThreshold) {
"""
Compute linear (non-spherical) interpolations of <code>this</code> and the given quaternion <code>q</code>
iteratively and store the result in <code>this</code>.
<p>
This method performs a series of small-step nlerp interpolations to avoid doing a costly spherical linear interpolation, like
{@link #slerp(Quaterniondc, double, Quaterniond) slerp},
by subdividing the rotation arc between <code>this</code> and <code>q</code> via non-spherical linear interpolations as long as
the absolute dot product of <code>this</code> and <code>q</code> is greater than the given <code>dotThreshold</code> parameter.
<p>
Thanks to <code>@theagentd</code> at <a href="http://www.java-gaming.org/">http://www.java-gaming.org/</a> for providing the code.
@param q
the other quaternion
@param alpha
the interpolation factor, between 0.0 and 1.0
@param dotThreshold
the threshold for the dot product of <code>this</code> and <code>q</code> above which this method performs another iteration
of a small-step linear interpolation
@return this
"""
return nlerpIterative(q, alpha, dotThreshold, this);
} | java | public Quaterniond nlerpIterative(Quaterniondc q, double alpha, double dotThreshold) {
return nlerpIterative(q, alpha, dotThreshold, this);
} | [
"public",
"Quaterniond",
"nlerpIterative",
"(",
"Quaterniondc",
"q",
",",
"double",
"alpha",
",",
"double",
"dotThreshold",
")",
"{",
"return",
"nlerpIterative",
"(",
"q",
",",
"alpha",
",",
"dotThreshold",
",",
"this",
")",
";",
"}"
] | Compute linear (non-spherical) interpolations of <code>this</code> and the given quaternion <code>q</code>
iteratively and store the result in <code>this</code>.
<p>
This method performs a series of small-step nlerp interpolations to avoid doing a costly spherical linear interpolation, like
{@link #slerp(Quaterniondc, double, Quaterniond) slerp},
by subdividing the rotation arc between <code>this</code> and <code>q</code> via non-spherical linear interpolations as long as
the absolute dot product of <code>this</code> and <code>q</code> is greater than the given <code>dotThreshold</code> parameter.
<p>
Thanks to <code>@theagentd</code> at <a href="http://www.java-gaming.org/">http://www.java-gaming.org/</a> for providing the code.
@param q
the other quaternion
@param alpha
the interpolation factor, between 0.0 and 1.0
@param dotThreshold
the threshold for the dot product of <code>this</code> and <code>q</code> above which this method performs another iteration
of a small-step linear interpolation
@return this | [
"Compute",
"linear",
"(",
"non",
"-",
"spherical",
")",
"interpolations",
"of",
"<code",
">",
"this<",
"/",
"code",
">",
"and",
"the",
"given",
"quaternion",
"<code",
">",
"q<",
"/",
"code",
">",
"iteratively",
"and",
"store",
"the",
"result",
"in",
"<co... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaterniond.java#L1606-L1608 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorParser.java | TransliteratorParser.parseSet | private final char parseSet(String rule, ParsePosition pos) {
"""
Parse a UnicodeSet out, store it, and return the stand-in character
used to represent it.
"""
UnicodeSet set = new UnicodeSet(rule, pos, parseData);
if (variableNext >= variableLimit) {
throw new RuntimeException("Private use variables exhausted");
}
set.compact();
return generateStandInFor(set);
} | java | private final char parseSet(String rule, ParsePosition pos) {
UnicodeSet set = new UnicodeSet(rule, pos, parseData);
if (variableNext >= variableLimit) {
throw new RuntimeException("Private use variables exhausted");
}
set.compact();
return generateStandInFor(set);
} | [
"private",
"final",
"char",
"parseSet",
"(",
"String",
"rule",
",",
"ParsePosition",
"pos",
")",
"{",
"UnicodeSet",
"set",
"=",
"new",
"UnicodeSet",
"(",
"rule",
",",
"pos",
",",
"parseData",
")",
";",
"if",
"(",
"variableNext",
">=",
"variableLimit",
")",... | Parse a UnicodeSet out, store it, and return the stand-in character
used to represent it. | [
"Parse",
"a",
"UnicodeSet",
"out",
"store",
"it",
"and",
"return",
"the",
"stand",
"-",
"in",
"character",
"used",
"to",
"represent",
"it",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/TransliteratorParser.java#L1453-L1460 |
google/closure-compiler | src/com/google/javascript/jscomp/TypedScopeCreator.java | TypedScopeCreator.initializeModuleScope | private void initializeModuleScope(Node moduleBody, Module module, TypedScope moduleScope) {
"""
Builds the beginning of a module-scope. This can be an ES module or a goog.module.
"""
if (module.metadata().isGoogModule()) {
declareExportsInModuleScope(module, moduleBody, moduleScope);
markGoogModuleExportsAsConst(module);
}
} | java | private void initializeModuleScope(Node moduleBody, Module module, TypedScope moduleScope) {
if (module.metadata().isGoogModule()) {
declareExportsInModuleScope(module, moduleBody, moduleScope);
markGoogModuleExportsAsConst(module);
}
} | [
"private",
"void",
"initializeModuleScope",
"(",
"Node",
"moduleBody",
",",
"Module",
"module",
",",
"TypedScope",
"moduleScope",
")",
"{",
"if",
"(",
"module",
".",
"metadata",
"(",
")",
".",
"isGoogModule",
"(",
")",
")",
"{",
"declareExportsInModuleScope",
... | Builds the beginning of a module-scope. This can be an ES module or a goog.module. | [
"Builds",
"the",
"beginning",
"of",
"a",
"module",
"-",
"scope",
".",
"This",
"can",
"be",
"an",
"ES",
"module",
"or",
"a",
"goog",
".",
"module",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypedScopeCreator.java#L465-L470 |
citiususc/hipster | hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/FibonacciHeap.java | FibonacciHeap.decreaseKey | public void decreaseKey(Entry<T> entry, double newPriority) {
"""
Decreases the key of the specified element to the new priority. If the
new priority is greater than the old priority, this function throws an
IllegalArgumentException. The new priority must be a finite double,
so you cannot set the priority to be NaN, or +/- infinity. Doing
so also throws an IllegalArgumentException.
<p/>
It is assumed that the entry belongs in this heap. For efficiency
reasons, this is not checked at runtime.
@param entry The element whose priority should be decreased.
@param newPriority The new priority to associate with this entry.
@throws IllegalArgumentException If the new priority exceeds the old
priority, or if the argument is not a finite double.
"""
checkPriority(newPriority);
if (newPriority > entry.mPriority)
throw new IllegalArgumentException("New priority exceeds old.");
/* Forward this to a helper function. */
decreaseKeyUnchecked(entry, newPriority);
} | java | public void decreaseKey(Entry<T> entry, double newPriority) {
checkPriority(newPriority);
if (newPriority > entry.mPriority)
throw new IllegalArgumentException("New priority exceeds old.");
/* Forward this to a helper function. */
decreaseKeyUnchecked(entry, newPriority);
} | [
"public",
"void",
"decreaseKey",
"(",
"Entry",
"<",
"T",
">",
"entry",
",",
"double",
"newPriority",
")",
"{",
"checkPriority",
"(",
"newPriority",
")",
";",
"if",
"(",
"newPriority",
">",
"entry",
".",
"mPriority",
")",
"throw",
"new",
"IllegalArgumentExcep... | Decreases the key of the specified element to the new priority. If the
new priority is greater than the old priority, this function throws an
IllegalArgumentException. The new priority must be a finite double,
so you cannot set the priority to be NaN, or +/- infinity. Doing
so also throws an IllegalArgumentException.
<p/>
It is assumed that the entry belongs in this heap. For efficiency
reasons, this is not checked at runtime.
@param entry The element whose priority should be decreased.
@param newPriority The new priority to associate with this entry.
@throws IllegalArgumentException If the new priority exceeds the old
priority, or if the argument is not a finite double. | [
"Decreases",
"the",
"key",
"of",
"the",
"specified",
"element",
"to",
"the",
"new",
"priority",
".",
"If",
"the",
"new",
"priority",
"is",
"greater",
"than",
"the",
"old",
"priority",
"this",
"function",
"throws",
"an",
"IllegalArgumentException",
".",
"The",
... | train | https://github.com/citiususc/hipster/blob/9ab1236abb833a27641ae73ba9ca890d5c17598e/hipster-core/src/main/java/es/usc/citius/lab/hipster/collections/FibonacciHeap.java#L405-L412 |
gallandarakhneorg/afc | core/vmutils/src/main/java/org/arakhne/afc/vmutil/VMCommandLine.java | VMCommandLine.saveVMParametersIfNotSet | @Inline(value = "VMCommandLine.saveVMParametersIfNotSet(($1).getCanonicalName(), ($2))",
imported = {
"""
Save parameters that permit to relaunch a VM with
{@link #relaunchVM()}.
@param classToLaunch is the class which contains a <code>main</code>.
@param parameters is the parameters to pass to the <code>main</code>.
"""VMCommandLine.class}, statementExpression = true)
public static void saveVMParametersIfNotSet(Class<?> classToLaunch, String... parameters) {
saveVMParametersIfNotSet(classToLaunch.getCanonicalName(), parameters);
} | java | @Inline(value = "VMCommandLine.saveVMParametersIfNotSet(($1).getCanonicalName(), ($2))",
imported = {VMCommandLine.class}, statementExpression = true)
public static void saveVMParametersIfNotSet(Class<?> classToLaunch, String... parameters) {
saveVMParametersIfNotSet(classToLaunch.getCanonicalName(), parameters);
} | [
"@",
"Inline",
"(",
"value",
"=",
"\"VMCommandLine.saveVMParametersIfNotSet(($1).getCanonicalName(), ($2))\"",
",",
"imported",
"=",
"{",
"VMCommandLine",
".",
"class",
"}",
",",
"statementExpression",
"=",
"true",
")",
"public",
"static",
"void",
"saveVMParametersIfNotSe... | Save parameters that permit to relaunch a VM with
{@link #relaunchVM()}.
@param classToLaunch is the class which contains a <code>main</code>.
@param parameters is the parameters to pass to the <code>main</code>. | [
"Save",
"parameters",
"that",
"permit",
"to",
"relaunch",
"a",
"VM",
"with",
"{",
"@link",
"#relaunchVM",
"()",
"}",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/VMCommandLine.java#L341-L345 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java | BNFHeadersImpl.setSpecialHeader | protected void setSpecialHeader(HeaderKeys key, byte[] value) {
"""
Set one of the special headers that does not require the headerkey
filterX methods to be called.
@param key
@param value
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "setSpecialHeader(h,b[]): " + key.getName());
}
removeHdrInstances(findHeader(key), FILTER_NO);
HeaderElement elem = getElement(key);
elem.setByteArrayValue(value);
addHeader(elem, FILTER_NO);
} | java | protected void setSpecialHeader(HeaderKeys key, byte[] value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "setSpecialHeader(h,b[]): " + key.getName());
}
removeHdrInstances(findHeader(key), FILTER_NO);
HeaderElement elem = getElement(key);
elem.setByteArrayValue(value);
addHeader(elem, FILTER_NO);
} | [
"protected",
"void",
"setSpecialHeader",
"(",
"HeaderKeys",
"key",
",",
"byte",
"[",
"]",
"value",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"Tr",
".",
"debug",
"("... | Set one of the special headers that does not require the headerkey
filterX methods to be called.
@param key
@param value | [
"Set",
"one",
"of",
"the",
"special",
"headers",
"that",
"does",
"not",
"require",
"the",
"headerkey",
"filterX",
"methods",
"to",
"be",
"called",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java#L2312-L2320 |
kenyee/android-ddp-client | src/com/keysolutions/ddpclient/android/MeteorAuthCommands.java | MeteorAuthCommands.login | public void login(String username, String password) {
"""
Logs in using username/password
@param username username/email
@param password password
"""
Object[] methodArgs = new Object[1];
if (username != null && username.indexOf('@') > 1) {
EmailAuth emailpass = new EmailAuth(username, password);
methodArgs[0] = emailpass;
} else {
UsernameAuth userpass = new UsernameAuth(username, password);
methodArgs[0] = userpass;
}
getDDP().call("login", methodArgs, new DDPListener() {
@Override
public void onResult(Map<String, Object> jsonFields) {
handleLoginResult(jsonFields);
}
});
} | java | public void login(String username, String password) {
Object[] methodArgs = new Object[1];
if (username != null && username.indexOf('@') > 1) {
EmailAuth emailpass = new EmailAuth(username, password);
methodArgs[0] = emailpass;
} else {
UsernameAuth userpass = new UsernameAuth(username, password);
methodArgs[0] = userpass;
}
getDDP().call("login", methodArgs, new DDPListener() {
@Override
public void onResult(Map<String, Object> jsonFields) {
handleLoginResult(jsonFields);
}
});
} | [
"public",
"void",
"login",
"(",
"String",
"username",
",",
"String",
"password",
")",
"{",
"Object",
"[",
"]",
"methodArgs",
"=",
"new",
"Object",
"[",
"1",
"]",
";",
"if",
"(",
"username",
"!=",
"null",
"&&",
"username",
".",
"indexOf",
"(",
"'",
"'... | Logs in using username/password
@param username username/email
@param password password | [
"Logs",
"in",
"using",
"username",
"/",
"password"
] | train | https://github.com/kenyee/android-ddp-client/blob/6ab416e415570a03f96c383497144dd742de3f08/src/com/keysolutions/ddpclient/android/MeteorAuthCommands.java#L55-L71 |
voldemort/voldemort | src/java/voldemort/utils/JmxUtils.java | JmxUtils.registerMbean | public static void registerMbean(Object mbean, ObjectName name) {
"""
Register the given mbean with the platform mbean server
@param mbean The mbean to register
@param name The name to register under
"""
registerMbean(ManagementFactory.getPlatformMBeanServer(),
JmxUtils.createModelMBean(mbean),
name);
} | java | public static void registerMbean(Object mbean, ObjectName name) {
registerMbean(ManagementFactory.getPlatformMBeanServer(),
JmxUtils.createModelMBean(mbean),
name);
} | [
"public",
"static",
"void",
"registerMbean",
"(",
"Object",
"mbean",
",",
"ObjectName",
"name",
")",
"{",
"registerMbean",
"(",
"ManagementFactory",
".",
"getPlatformMBeanServer",
"(",
")",
",",
"JmxUtils",
".",
"createModelMBean",
"(",
"mbean",
")",
",",
"name"... | Register the given mbean with the platform mbean server
@param mbean The mbean to register
@param name The name to register under | [
"Register",
"the",
"given",
"mbean",
"with",
"the",
"platform",
"mbean",
"server"
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L284-L288 |
intendia-oss/rxjava-gwt | src/main/modified/io/reactivex/super/io/reactivex/Completable.java | Completable.timeout0 | @CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
private Completable timeout0(long timeout, TimeUnit unit, Scheduler scheduler, CompletableSource other) {
"""
Returns a Completable that runs this Completable and optionally switches to the other Completable
in case this Completable doesn't complete within the given time while "waiting" on
the specified scheduler.
<dl>
<dt><b>Scheduler:</b></dt>
<dd>You specify the {@link Scheduler} this operator runs on.</dd>
</dl>
@param timeout the timeout value
@param unit the timeout unit
@param scheduler the scheduler to use to wait for completion
@param other the other Completable instance to switch to in case of a timeout,
if null a TimeoutException is emitted instead
@return the new Completable instance
@throws NullPointerException if unit or scheduler
"""
ObjectHelper.requireNonNull(unit, "unit is null");
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new CompletableTimeout(this, timeout, unit, scheduler, other));
} | java | @CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
private Completable timeout0(long timeout, TimeUnit unit, Scheduler scheduler, CompletableSource other) {
ObjectHelper.requireNonNull(unit, "unit is null");
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new CompletableTimeout(this, timeout, unit, scheduler, other));
} | [
"@",
"CheckReturnValue",
"@",
"SchedulerSupport",
"(",
"SchedulerSupport",
".",
"CUSTOM",
")",
"private",
"Completable",
"timeout0",
"(",
"long",
"timeout",
",",
"TimeUnit",
"unit",
",",
"Scheduler",
"scheduler",
",",
"CompletableSource",
"other",
")",
"{",
"Objec... | Returns a Completable that runs this Completable and optionally switches to the other Completable
in case this Completable doesn't complete within the given time while "waiting" on
the specified scheduler.
<dl>
<dt><b>Scheduler:</b></dt>
<dd>You specify the {@link Scheduler} this operator runs on.</dd>
</dl>
@param timeout the timeout value
@param unit the timeout unit
@param scheduler the scheduler to use to wait for completion
@param other the other Completable instance to switch to in case of a timeout,
if null a TimeoutException is emitted instead
@return the new Completable instance
@throws NullPointerException if unit or scheduler | [
"Returns",
"a",
"Completable",
"that",
"runs",
"this",
"Completable",
"and",
"optionally",
"switches",
"to",
"the",
"other",
"Completable",
"in",
"case",
"this",
"Completable",
"doesn",
"t",
"complete",
"within",
"the",
"given",
"time",
"while",
"waiting",
"on",... | train | https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Completable.java#L2441-L2447 |
thymeleaf/thymeleaf-spring | thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/linkbuilder/webflux/SpringWebFluxLinkBuilder.java | SpringWebFluxLinkBuilder.processLink | @Override
protected String processLink(final IExpressionContext context, final String link) {
"""
<p>
Process an already-built URL just before returning it.
</p>
<p>
This method can be overridden by any subclasses that want to change this behaviour.
</p>
@param context the execution context.
@param link the already-built URL.
@return the processed URL, ready to be used.
"""
if (!(context instanceof ISpringWebFluxContext)) {
return link;
}
final ServerWebExchange exchange = ((ISpringWebFluxContext)context).getExchange();
return exchange.transformUrl(link);
} | java | @Override
protected String processLink(final IExpressionContext context, final String link) {
if (!(context instanceof ISpringWebFluxContext)) {
return link;
}
final ServerWebExchange exchange = ((ISpringWebFluxContext)context).getExchange();
return exchange.transformUrl(link);
} | [
"@",
"Override",
"protected",
"String",
"processLink",
"(",
"final",
"IExpressionContext",
"context",
",",
"final",
"String",
"link",
")",
"{",
"if",
"(",
"!",
"(",
"context",
"instanceof",
"ISpringWebFluxContext",
")",
")",
"{",
"return",
"link",
";",
"}",
... | <p>
Process an already-built URL just before returning it.
</p>
<p>
This method can be overridden by any subclasses that want to change this behaviour.
</p>
@param context the execution context.
@param link the already-built URL.
@return the processed URL, ready to be used. | [
"<p",
">",
"Process",
"an",
"already",
"-",
"built",
"URL",
"just",
"before",
"returning",
"it",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"method",
"can",
"be",
"overridden",
"by",
"any",
"subclasses",
"that",
"want",
"to",
"change",
"this",
"behavi... | train | https://github.com/thymeleaf/thymeleaf-spring/blob/9aa15a19017a0938e57646e3deefb8a90ab78dcb/thymeleaf-spring5/src/main/java/org/thymeleaf/spring5/linkbuilder/webflux/SpringWebFluxLinkBuilder.java#L108-L118 |
evernote/android-job | library/src/main/java/com/evernote/android/job/util/JobPreconditions.java | JobPreconditions.checkArgumentFinite | public static float checkArgumentFinite(final float value, final String valueName) {
"""
Ensures that the argument floating point value is a finite number.
<p>A finite number is defined to be both representable (that is, not NaN) and
not infinite (that is neither positive or negative infinity).</p>
@param value a floating point value
@param valueName the name of the argument to use if the check fails
@return the validated floating point value
@throws IllegalArgumentException if {@code value} was not finite
"""
if (Float.isNaN(value)) {
throw new IllegalArgumentException(valueName + " must not be NaN");
} else if (Float.isInfinite(value)) {
throw new IllegalArgumentException(valueName + " must not be infinite");
}
return value;
} | java | public static float checkArgumentFinite(final float value, final String valueName) {
if (Float.isNaN(value)) {
throw new IllegalArgumentException(valueName + " must not be NaN");
} else if (Float.isInfinite(value)) {
throw new IllegalArgumentException(valueName + " must not be infinite");
}
return value;
} | [
"public",
"static",
"float",
"checkArgumentFinite",
"(",
"final",
"float",
"value",
",",
"final",
"String",
"valueName",
")",
"{",
"if",
"(",
"Float",
".",
"isNaN",
"(",
"value",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"valueName",
"+... | Ensures that the argument floating point value is a finite number.
<p>A finite number is defined to be both representable (that is, not NaN) and
not infinite (that is neither positive or negative infinity).</p>
@param value a floating point value
@param valueName the name of the argument to use if the check fails
@return the validated floating point value
@throws IllegalArgumentException if {@code value} was not finite | [
"Ensures",
"that",
"the",
"argument",
"floating",
"point",
"value",
"is",
"a",
"finite",
"number",
"."
] | train | https://github.com/evernote/android-job/blob/5ae3d776ad9d80b5b7f60ae3e382d44d0d193faf/library/src/main/java/com/evernote/android/job/util/JobPreconditions.java#L186-L194 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/SynonymTypesProvider.java | SynonymTypesProvider.announceSynonym | protected final boolean announceSynonym(LightweightTypeReference synonym, int flags, Acceptor acceptor) {
"""
Announce a synonym type with the given conformance flags.
@see ConformanceFlags
"""
if (synonym.isUnknown()) {
return true;
}
return acceptor.accept(synonym, flags | ConformanceFlags.CHECKED_SUCCESS);
} | java | protected final boolean announceSynonym(LightweightTypeReference synonym, int flags, Acceptor acceptor) {
if (synonym.isUnknown()) {
return true;
}
return acceptor.accept(synonym, flags | ConformanceFlags.CHECKED_SUCCESS);
} | [
"protected",
"final",
"boolean",
"announceSynonym",
"(",
"LightweightTypeReference",
"synonym",
",",
"int",
"flags",
",",
"Acceptor",
"acceptor",
")",
"{",
"if",
"(",
"synonym",
".",
"isUnknown",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"acc... | Announce a synonym type with the given conformance flags.
@see ConformanceFlags | [
"Announce",
"a",
"synonym",
"type",
"with",
"the",
"given",
"conformance",
"flags",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/computation/SynonymTypesProvider.java#L181-L186 |
mijecu25/dsa | src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java | LinearSearch.searchLast | public static int searchLast(double[] doubleArray, double value, int occurrence) {
"""
Search for the value in the double array and return the index of the first occurrence from the
end of the array.
@param doubleArray array that we are searching in.
@param value value that is being searched in the array.
@param occurrence number of times we have seen the value before returning the index.
@return the index where the value is found in the array, else -1.
"""
if(occurrence <= 0 || occurrence > doubleArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = doubleArray.length-1; i >=0; i--) {
if(doubleArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | java | public static int searchLast(double[] doubleArray, double value, int occurrence) {
if(occurrence <= 0 || occurrence > doubleArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = doubleArray.length-1; i >=0; i--) {
if(doubleArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | [
"public",
"static",
"int",
"searchLast",
"(",
"double",
"[",
"]",
"doubleArray",
",",
"double",
"value",
",",
"int",
"occurrence",
")",
"{",
"if",
"(",
"occurrence",
"<=",
"0",
"||",
"occurrence",
">",
"doubleArray",
".",
"length",
")",
"{",
"throw",
"ne... | Search for the value in the double array and return the index of the first occurrence from the
end of the array.
@param doubleArray array that we are searching in.
@param value value that is being searched in the array.
@param occurrence number of times we have seen the value before returning the index.
@return the index where the value is found in the array, else -1. | [
"Search",
"for",
"the",
"value",
"in",
"the",
"double",
"array",
"and",
"return",
"the",
"index",
"of",
"the",
"first",
"occurrence",
"from",
"the",
"end",
"of",
"the",
"array",
"."
] | train | https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java#L1710-L1729 |
killbill/killbill | entitlement/src/main/java/org/killbill/billing/entitlement/engine/core/DefaultEventsStream.java | DefaultEventsStream.computeAddonsBlockingStatesForFutureSubscriptionBaseEvents | @Override
public Collection<BlockingState> computeAddonsBlockingStatesForFutureSubscriptionBaseEvents() {
"""
Compute future blocking states not on disk for add-ons associated to this (base) events stream
"""
if (!ProductCategory.BASE.equals(subscription.getCategory())) {
// Only base subscriptions have add-ons
return ImmutableList.of();
}
// We need to find the first "trigger" transition, from which we will create the add-ons cancellation events.
// This can either be a future entitlement cancel...
if (isEntitlementFutureCancelled()) {
// Note that in theory we could always only look subscription base as we assume entitlement cancel means subscription base cancel
// but we want to use the effective date of the entitlement cancel event to create the add-on cancel event
final BlockingState futureEntitlementCancelEvent = getEntitlementCancellationEvent(subscription.getId());
return computeAddonsBlockingStatesForNextSubscriptionBaseEvent(futureEntitlementCancelEvent.getEffectiveDate(), false);
} else if (isEntitlementFutureChanged()) {
// ...or a subscription change (i.e. a change plan where the new plan has an impact on the existing add-on).
// We need to go back to subscription base as entitlement doesn't know about these
return computeAddonsBlockingStatesForNextSubscriptionBaseEvent(utcNow, true);
} else {
return ImmutableList.of();
}
} | java | @Override
public Collection<BlockingState> computeAddonsBlockingStatesForFutureSubscriptionBaseEvents() {
if (!ProductCategory.BASE.equals(subscription.getCategory())) {
// Only base subscriptions have add-ons
return ImmutableList.of();
}
// We need to find the first "trigger" transition, from which we will create the add-ons cancellation events.
// This can either be a future entitlement cancel...
if (isEntitlementFutureCancelled()) {
// Note that in theory we could always only look subscription base as we assume entitlement cancel means subscription base cancel
// but we want to use the effective date of the entitlement cancel event to create the add-on cancel event
final BlockingState futureEntitlementCancelEvent = getEntitlementCancellationEvent(subscription.getId());
return computeAddonsBlockingStatesForNextSubscriptionBaseEvent(futureEntitlementCancelEvent.getEffectiveDate(), false);
} else if (isEntitlementFutureChanged()) {
// ...or a subscription change (i.e. a change plan where the new plan has an impact on the existing add-on).
// We need to go back to subscription base as entitlement doesn't know about these
return computeAddonsBlockingStatesForNextSubscriptionBaseEvent(utcNow, true);
} else {
return ImmutableList.of();
}
} | [
"@",
"Override",
"public",
"Collection",
"<",
"BlockingState",
">",
"computeAddonsBlockingStatesForFutureSubscriptionBaseEvents",
"(",
")",
"{",
"if",
"(",
"!",
"ProductCategory",
".",
"BASE",
".",
"equals",
"(",
"subscription",
".",
"getCategory",
"(",
")",
")",
... | Compute future blocking states not on disk for add-ons associated to this (base) events stream | [
"Compute",
"future",
"blocking",
"states",
"not",
"on",
"disk",
"for",
"add",
"-",
"ons",
"associated",
"to",
"this",
"(",
"base",
")",
"events",
"stream"
] | train | https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/entitlement/src/main/java/org/killbill/billing/entitlement/engine/core/DefaultEventsStream.java#L300-L321 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/SessionsInner.java | SessionsInner.createOrUpdateAsync | public Observable<IntegrationAccountSessionInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String sessionName, IntegrationAccountSessionInner session) {
"""
Creates or updates an integration account session.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param sessionName The integration account session name.
@param session The integration account session.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IntegrationAccountSessionInner object
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, sessionName, session).map(new Func1<ServiceResponse<IntegrationAccountSessionInner>, IntegrationAccountSessionInner>() {
@Override
public IntegrationAccountSessionInner call(ServiceResponse<IntegrationAccountSessionInner> response) {
return response.body();
}
});
} | java | public Observable<IntegrationAccountSessionInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String sessionName, IntegrationAccountSessionInner session) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, sessionName, session).map(new Func1<ServiceResponse<IntegrationAccountSessionInner>, IntegrationAccountSessionInner>() {
@Override
public IntegrationAccountSessionInner call(ServiceResponse<IntegrationAccountSessionInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"IntegrationAccountSessionInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
",",
"String",
"sessionName",
",",
"IntegrationAccountSessionInner",
"session",
")",
"{",
"return",
"creat... | Creates or updates an integration account session.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param sessionName The integration account session name.
@param session The integration account session.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IntegrationAccountSessionInner object | [
"Creates",
"or",
"updates",
"an",
"integration",
"account",
"session",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/SessionsInner.java#L471-L478 |
susom/database | src/main/java/com/github/susom/database/DatabaseProviderVertx.java | DatabaseProviderVertx.pooledBuilder | @CheckReturnValue
public static Builder pooledBuilder(Vertx vertx, Config config) {
"""
Configure the database from the following properties read from the provided configuration:
<br/>
<pre>
database.url=... Database connect string (required)
database.user=... Authenticate as this user (optional if provided in url)
database.password=... User password (optional if user and password provided in
url; prompted on standard input if user is provided and
password is not)
database.pool.size=... How many connections in the connection pool (default 10).
database.driver.class The driver to initialize with Class.forName(). This will
be guessed from the database.url if not provided.
database.flavor One of the enumerated values in {@link Flavor}. If this
is not provided the flavor will be guessed based on the
value for database.url, if possible.
</pre>
<p>The database flavor will be guessed based on the URL.</p>
<p>A database pool will be created using HikariCP.</p>
<p>Be sure to retain a copy of the builder so you can call close() later to
destroy the pool. You will most likely want to register a JVM shutdown hook
to make sure this happens. See VertxServer.java in the demo directory for
an example of how to do this.</p>
"""
return fromPool(vertx, DatabaseProvider.createPool(config));
} | java | @CheckReturnValue
public static Builder pooledBuilder(Vertx vertx, Config config) {
return fromPool(vertx, DatabaseProvider.createPool(config));
} | [
"@",
"CheckReturnValue",
"public",
"static",
"Builder",
"pooledBuilder",
"(",
"Vertx",
"vertx",
",",
"Config",
"config",
")",
"{",
"return",
"fromPool",
"(",
"vertx",
",",
"DatabaseProvider",
".",
"createPool",
"(",
"config",
")",
")",
";",
"}"
] | Configure the database from the following properties read from the provided configuration:
<br/>
<pre>
database.url=... Database connect string (required)
database.user=... Authenticate as this user (optional if provided in url)
database.password=... User password (optional if user and password provided in
url; prompted on standard input if user is provided and
password is not)
database.pool.size=... How many connections in the connection pool (default 10).
database.driver.class The driver to initialize with Class.forName(). This will
be guessed from the database.url if not provided.
database.flavor One of the enumerated values in {@link Flavor}. If this
is not provided the flavor will be guessed based on the
value for database.url, if possible.
</pre>
<p>The database flavor will be guessed based on the URL.</p>
<p>A database pool will be created using HikariCP.</p>
<p>Be sure to retain a copy of the builder so you can call close() later to
destroy the pool. You will most likely want to register a JVM shutdown hook
to make sure this happens. See VertxServer.java in the demo directory for
an example of how to do this.</p> | [
"Configure",
"the",
"database",
"from",
"the",
"following",
"properties",
"read",
"from",
"the",
"provided",
"configuration",
":",
"<br",
"/",
">",
"<pre",
">",
"database",
".",
"url",
"=",
"...",
"Database",
"connect",
"string",
"(",
"required",
")",
"datab... | train | https://github.com/susom/database/blob/25add9e08ad863712f9b5e319b6cb826f6f97640/src/main/java/com/github/susom/database/DatabaseProviderVertx.java#L101-L104 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.verifyAsync | public Observable<KeyVerifyResult> verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
"""
Verifies a signature using a specified key.
The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public portion of the key but this operation is supported as a convenience for callers that only have a key-reference and not the public portion of the key. This operation requires the keys/verify permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName The name of the key.
@param keyVersion The version of the key.
@param algorithm The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'RSNULL', 'ES256', 'ES384', 'ES512', 'ES256K'
@param digest The digest used for signing.
@param signature The signature to be verified.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the KeyVerifyResult object
"""
return verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).map(new Func1<ServiceResponse<KeyVerifyResult>, KeyVerifyResult>() {
@Override
public KeyVerifyResult call(ServiceResponse<KeyVerifyResult> response) {
return response.body();
}
});
} | java | public Observable<KeyVerifyResult> verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
return verifyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature).map(new Func1<ServiceResponse<KeyVerifyResult>, KeyVerifyResult>() {
@Override
public KeyVerifyResult call(ServiceResponse<KeyVerifyResult> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"KeyVerifyResult",
">",
"verifyAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"keyName",
",",
"String",
"keyVersion",
",",
"JsonWebKeySignatureAlgorithm",
"algorithm",
",",
"byte",
"[",
"]",
"digest",
",",
"byte",
"[",
"]",
"s... | Verifies a signature using a specified key.
The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public portion of the key but this operation is supported as a convenience for callers that only have a key-reference and not the public portion of the key. This operation requires the keys/verify permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param keyName The name of the key.
@param keyVersion The version of the key.
@param algorithm The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'RSNULL', 'ES256', 'ES384', 'ES512', 'ES256K'
@param digest The digest used for signing.
@param signature The signature to be verified.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the KeyVerifyResult object | [
"Verifies",
"a",
"signature",
"using",
"a",
"specified",
"key",
".",
"The",
"VERIFY",
"operation",
"is",
"applicable",
"to",
"symmetric",
"keys",
"stored",
"in",
"Azure",
"Key",
"Vault",
".",
"VERIFY",
"is",
"not",
"strictly",
"necessary",
"for",
"asymmetric",... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L2518-L2525 |
albfernandez/itext2 | src/main/java/com/lowagie/text/html/simpleparser/FactoryProperties.java | FactoryProperties.getHyphenation | public static HyphenationEvent getHyphenation(String s) {
"""
Gets a HyphenationEvent based on a String.
For instance "en_UK,3,2" returns new HyphenationAuto("en", "UK", 3, 2);
@param s a String, for instance "en_UK,2,2"
@return a HyphenationEvent
@since 2.1.2
"""
if (s == null || s.length() == 0) {
return null;
}
String lang = s;
String country = null;
int leftMin = 2;
int rightMin = 2;
int pos = s.indexOf('_');
if (pos == -1) {
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
lang = s.substring(0, pos);
country = s.substring(pos + 1);
pos = country.indexOf(',');
if (pos == -1) {
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
s = country.substring(pos + 1);
country = country.substring(0, pos);
pos = s.indexOf(',');
if (pos == -1) {
leftMin = Integer.parseInt(s);
} else {
leftMin = Integer.parseInt(s.substring(0, pos));
rightMin = Integer.parseInt(s.substring(pos + 1));
}
return new HyphenationAuto(lang, country, leftMin, rightMin);
} | java | public static HyphenationEvent getHyphenation(String s) {
if (s == null || s.length() == 0) {
return null;
}
String lang = s;
String country = null;
int leftMin = 2;
int rightMin = 2;
int pos = s.indexOf('_');
if (pos == -1) {
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
lang = s.substring(0, pos);
country = s.substring(pos + 1);
pos = country.indexOf(',');
if (pos == -1) {
return new HyphenationAuto(lang, country, leftMin, rightMin);
}
s = country.substring(pos + 1);
country = country.substring(0, pos);
pos = s.indexOf(',');
if (pos == -1) {
leftMin = Integer.parseInt(s);
} else {
leftMin = Integer.parseInt(s.substring(0, pos));
rightMin = Integer.parseInt(s.substring(pos + 1));
}
return new HyphenationAuto(lang, country, leftMin, rightMin);
} | [
"public",
"static",
"HyphenationEvent",
"getHyphenation",
"(",
"String",
"s",
")",
"{",
"if",
"(",
"s",
"==",
"null",
"||",
"s",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"String",
"lang",
"=",
"s",
";",
"String",
"c... | Gets a HyphenationEvent based on a String.
For instance "en_UK,3,2" returns new HyphenationAuto("en", "UK", 3, 2);
@param s a String, for instance "en_UK,2,2"
@return a HyphenationEvent
@since 2.1.2 | [
"Gets",
"a",
"HyphenationEvent",
"based",
"on",
"a",
"String",
".",
"For",
"instance",
"en_UK",
"3",
"2",
"returns",
"new",
"HyphenationAuto",
"(",
"en",
"UK",
"3",
"2",
")",
";"
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/html/simpleparser/FactoryProperties.java#L227-L256 |
gturri/aXMLRPC | src/main/java/de/timroes/axmlrpc/XMLRPCClient.java | XMLRPCClient.createCall | private Call createCall(String method, Object[] params) {
"""
Create a call object from a given method string and parameters.
@param method The method that should be called.
@param params An array of parameters or null if no parameters needed.
@return A call object.
"""
if(isFlagSet(FLAGS_STRICT) && !method.matches("^[A-Za-z0-9\\._:/]*$")) {
throw new XMLRPCRuntimeException("Method name must only contain A-Z a-z . : _ / ");
}
return new Call(serializerHandler, method, params);
} | java | private Call createCall(String method, Object[] params) {
if(isFlagSet(FLAGS_STRICT) && !method.matches("^[A-Za-z0-9\\._:/]*$")) {
throw new XMLRPCRuntimeException("Method name must only contain A-Z a-z . : _ / ");
}
return new Call(serializerHandler, method, params);
} | [
"private",
"Call",
"createCall",
"(",
"String",
"method",
",",
"Object",
"[",
"]",
"params",
")",
"{",
"if",
"(",
"isFlagSet",
"(",
"FLAGS_STRICT",
")",
"&&",
"!",
"method",
".",
"matches",
"(",
"\"^[A-Za-z0-9\\\\._:/]*$\"",
")",
")",
"{",
"throw",
"new",
... | Create a call object from a given method string and parameters.
@param method The method that should be called.
@param params An array of parameters or null if no parameters needed.
@return A call object. | [
"Create",
"a",
"call",
"object",
"from",
"a",
"given",
"method",
"string",
"and",
"parameters",
"."
] | train | https://github.com/gturri/aXMLRPC/blob/8ca6f95f7eb3a28efaef3569d53adddeb32b6bda/src/main/java/de/timroes/axmlrpc/XMLRPCClient.java#L523-L530 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/form/builder/TableFormBuilder.java | TableFormBuilder.addSeparator | public JComponent addSeparator(String text, String attributes) {
"""
Adds a labeled separator to the form
@param text
the key for the label. Must not be null
@param attributes
optional attributes. See {@link TableLayoutBuilder} for syntax details
"""
JComponent separator = getComponentFactory().createLabeledSeparator(text);
getLayoutBuilder().cell(separator, attributes);
return separator;
} | java | public JComponent addSeparator(String text, String attributes) {
JComponent separator = getComponentFactory().createLabeledSeparator(text);
getLayoutBuilder().cell(separator, attributes);
return separator;
} | [
"public",
"JComponent",
"addSeparator",
"(",
"String",
"text",
",",
"String",
"attributes",
")",
"{",
"JComponent",
"separator",
"=",
"getComponentFactory",
"(",
")",
".",
"createLabeledSeparator",
"(",
"text",
")",
";",
"getLayoutBuilder",
"(",
")",
".",
"cell"... | Adds a labeled separator to the form
@param text
the key for the label. Must not be null
@param attributes
optional attributes. See {@link TableLayoutBuilder} for syntax details | [
"Adds",
"a",
"labeled",
"separator",
"to",
"the",
"form"
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/builder/TableFormBuilder.java#L335-L339 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/handler/ResourceBundlesHandlerImpl.java | ResourceBundlesHandlerImpl.getJawrConfigHashcode | protected String getJawrConfigHashcode() {
"""
Returns the jawr config hashcode
@return the jawr config hashcode
"""
try {
return CheckSumUtils.getMD5Checksum(config.getConfigProperties().toString());
} catch (IOException e) {
throw new BundlingProcessException("Unable to calculate Jawr config checksum", e);
}
} | java | protected String getJawrConfigHashcode() {
try {
return CheckSumUtils.getMD5Checksum(config.getConfigProperties().toString());
} catch (IOException e) {
throw new BundlingProcessException("Unable to calculate Jawr config checksum", e);
}
} | [
"protected",
"String",
"getJawrConfigHashcode",
"(",
")",
"{",
"try",
"{",
"return",
"CheckSumUtils",
".",
"getMD5Checksum",
"(",
"config",
".",
"getConfigProperties",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",... | Returns the jawr config hashcode
@return the jawr config hashcode | [
"Returns",
"the",
"jawr",
"config",
"hashcode"
] | 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#L713-L719 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RegionAutoscalerClient.java | RegionAutoscalerClient.insertRegionAutoscaler | @BetaApi
public final Operation insertRegionAutoscaler(String region, Autoscaler autoscalerResource) {
"""
Creates an autoscaler in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (RegionAutoscalerClient regionAutoscalerClient = RegionAutoscalerClient.create()) {
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
Autoscaler autoscalerResource = Autoscaler.newBuilder().build();
Operation response = regionAutoscalerClient.insertRegionAutoscaler(region.toString(), autoscalerResource);
}
</code></pre>
@param region Name of the region scoping this request.
@param autoscalerResource Represents an Autoscaler resource. Autoscalers allow you to
automatically scale virtual machine instances in managed instance groups according to an
autoscaling policy that you define. For more information, read Autoscaling Groups of
Instances. (== resource_for beta.autoscalers ==) (== resource_for v1.autoscalers ==) (==
resource_for beta.regionAutoscalers ==) (== resource_for v1.regionAutoscalers ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails
"""
InsertRegionAutoscalerHttpRequest request =
InsertRegionAutoscalerHttpRequest.newBuilder()
.setRegion(region)
.setAutoscalerResource(autoscalerResource)
.build();
return insertRegionAutoscaler(request);
} | java | @BetaApi
public final Operation insertRegionAutoscaler(String region, Autoscaler autoscalerResource) {
InsertRegionAutoscalerHttpRequest request =
InsertRegionAutoscalerHttpRequest.newBuilder()
.setRegion(region)
.setAutoscalerResource(autoscalerResource)
.build();
return insertRegionAutoscaler(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"insertRegionAutoscaler",
"(",
"String",
"region",
",",
"Autoscaler",
"autoscalerResource",
")",
"{",
"InsertRegionAutoscalerHttpRequest",
"request",
"=",
"InsertRegionAutoscalerHttpRequest",
".",
"newBuilder",
"(",
")",
"."... | Creates an autoscaler in the specified project using the data included in the request.
<p>Sample code:
<pre><code>
try (RegionAutoscalerClient regionAutoscalerClient = RegionAutoscalerClient.create()) {
ProjectRegionName region = ProjectRegionName.of("[PROJECT]", "[REGION]");
Autoscaler autoscalerResource = Autoscaler.newBuilder().build();
Operation response = regionAutoscalerClient.insertRegionAutoscaler(region.toString(), autoscalerResource);
}
</code></pre>
@param region Name of the region scoping this request.
@param autoscalerResource Represents an Autoscaler resource. Autoscalers allow you to
automatically scale virtual machine instances in managed instance groups according to an
autoscaling policy that you define. For more information, read Autoscaling Groups of
Instances. (== resource_for beta.autoscalers ==) (== resource_for v1.autoscalers ==) (==
resource_for beta.regionAutoscalers ==) (== resource_for v1.regionAutoscalers ==)
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"an",
"autoscaler",
"in",
"the",
"specified",
"project",
"using",
"the",
"data",
"included",
"in",
"the",
"request",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RegionAutoscalerClient.java#L409-L418 |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.createRoleFromUpdateRequest | @POST
@Path(" {
"""
Alternate endpoint for creating a role. Although slightly less REST compliant it provides a more flexible
interface for specifying role attributes.
"""group}/{id}")
@Consumes("application/x.json-create-role")
public Response createRoleFromUpdateRequest(@PathParam("group") String group, @PathParam("id") String id,
CreateEmoRoleRequest request,
@Authenticated Subject subject) {
_uac.createRole(subject, request.setRoleKey(new EmoRoleKey(group, id)));
return Response.created(URI.create(""))
.entity(SuccessResponse.instance())
.build();
} | java | @POST
@Path("{group}/{id}")
@Consumes("application/x.json-create-role")
public Response createRoleFromUpdateRequest(@PathParam("group") String group, @PathParam("id") String id,
CreateEmoRoleRequest request,
@Authenticated Subject subject) {
_uac.createRole(subject, request.setRoleKey(new EmoRoleKey(group, id)));
return Response.created(URI.create(""))
.entity(SuccessResponse.instance())
.build();
} | [
"@",
"POST",
"@",
"Path",
"(",
"\"{group}/{id}\"",
")",
"@",
"Consumes",
"(",
"\"application/x.json-create-role\"",
")",
"public",
"Response",
"createRoleFromUpdateRequest",
"(",
"@",
"PathParam",
"(",
"\"group\"",
")",
"String",
"group",
",",
"@",
"PathParam",
"(... | Alternate endpoint for creating a role. Although slightly less REST compliant it provides a more flexible
interface for specifying role attributes. | [
"Alternate",
"endpoint",
"for",
"creating",
"a",
"role",
".",
"Although",
"slightly",
"less",
"REST",
"compliant",
"it",
"provides",
"a",
"more",
"flexible",
"interface",
"for",
"specifying",
"role",
"attributes",
"."
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L100-L110 |
Microsoft/azure-maven-plugins | azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/auth/AzureAuthHelper.java | AzureAuthHelper.getAuthObjFromServerId | protected Authenticated getAuthObjFromServerId(final Settings settings, final String serverId) {
"""
Get Authenticated object by referencing server definition in Maven settings.xml
@param settings Settings object
@param serverId Server Id to search in settings.xml
@return Authenticated object if configurations are correct; otherwise return null.
"""
if (StringUtils.isEmpty(serverId)) {
getLog().debug(SERVER_ID_NOT_CONFIG);
return null;
}
final Server server = Utils.getServer(settings, serverId);
try {
assureServerExist(server, serverId);
} catch (MojoExecutionException ex) {
getLog().error(ex.getMessage());
return null;
}
final ApplicationTokenCredentials credential = getAppTokenCredentialsFromServer(server);
if (credential == null) {
getLog().error(AZURE_AUTH_INVALID + serverId);
return null;
}
final Authenticated auth = azureConfigure().authenticate(credential);
if (auth != null) {
getLog().info(AUTH_WITH_SERVER_ID + serverId);
}
return auth;
} | java | protected Authenticated getAuthObjFromServerId(final Settings settings, final String serverId) {
if (StringUtils.isEmpty(serverId)) {
getLog().debug(SERVER_ID_NOT_CONFIG);
return null;
}
final Server server = Utils.getServer(settings, serverId);
try {
assureServerExist(server, serverId);
} catch (MojoExecutionException ex) {
getLog().error(ex.getMessage());
return null;
}
final ApplicationTokenCredentials credential = getAppTokenCredentialsFromServer(server);
if (credential == null) {
getLog().error(AZURE_AUTH_INVALID + serverId);
return null;
}
final Authenticated auth = azureConfigure().authenticate(credential);
if (auth != null) {
getLog().info(AUTH_WITH_SERVER_ID + serverId);
}
return auth;
} | [
"protected",
"Authenticated",
"getAuthObjFromServerId",
"(",
"final",
"Settings",
"settings",
",",
"final",
"String",
"serverId",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"serverId",
")",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"SERV... | Get Authenticated object by referencing server definition in Maven settings.xml
@param settings Settings object
@param serverId Server Id to search in settings.xml
@return Authenticated object if configurations are correct; otherwise return null. | [
"Get",
"Authenticated",
"object",
"by",
"referencing",
"server",
"definition",
"in",
"Maven",
"settings",
".",
"xml"
] | train | https://github.com/Microsoft/azure-maven-plugins/blob/a254902e820185df1823b1d692c7c1d119490b1e/azure-maven-plugin-lib/src/main/java/com/microsoft/azure/maven/auth/AzureAuthHelper.java#L154-L179 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/BuildStepsInner.java | BuildStepsInner.getAsync | public Observable<BuildStepInner> getAsync(String resourceGroupName, String registryName, String buildTaskName, String stepName) {
"""
Gets the build step for a build task.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param buildTaskName The name of the container registry build task.
@param stepName The name of a build step for a container registry build task.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BuildStepInner object
"""
return getWithServiceResponseAsync(resourceGroupName, registryName, buildTaskName, stepName).map(new Func1<ServiceResponse<BuildStepInner>, BuildStepInner>() {
@Override
public BuildStepInner call(ServiceResponse<BuildStepInner> response) {
return response.body();
}
});
} | java | public Observable<BuildStepInner> getAsync(String resourceGroupName, String registryName, String buildTaskName, String stepName) {
return getWithServiceResponseAsync(resourceGroupName, registryName, buildTaskName, stepName).map(new Func1<ServiceResponse<BuildStepInner>, BuildStepInner>() {
@Override
public BuildStepInner call(ServiceResponse<BuildStepInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"BuildStepInner",
">",
"getAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"String",
"buildTaskName",
",",
"String",
"stepName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
"... | Gets the build step for a build task.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param buildTaskName The name of the container registry build task.
@param stepName The name of a build step for a container registry build task.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the BuildStepInner object | [
"Gets",
"the",
"build",
"step",
"for",
"a",
"build",
"task",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/BuildStepsInner.java#L284-L291 |
lecousin/java-framework-core | net.lecousin.core/src/main/java/net/lecousin/framework/xml/XMLStreamReader.java | XMLStreamReader.start | public static AsyncWork<XMLStreamReader, Exception> start(IO.Readable.Buffered io, int charactersBufferSize, int maxBuffers) {
"""
Utility method that initialize a XMLStreamReader, initialize it, and
return an AsyncWork which is unblocked when characters are available to be read.
"""
AsyncWork<XMLStreamReader, Exception> result = new AsyncWork<>();
new Task.Cpu.FromRunnable("Start reading XML " + io.getSourceDescription(), io.getPriority(), () -> {
XMLStreamReader reader = new XMLStreamReader(io, charactersBufferSize, maxBuffers);
try {
Starter start = new Starter(io, reader.defaultEncoding, reader.charactersBuffersSize, reader.maxBuffers);
reader.stream = start.start();
reader.stream.canStartReading().listenAsync(
new Task.Cpu.FromRunnable("Start reading XML " + io.getSourceDescription(), io.getPriority(), () -> {
try {
reader.next();
result.unblockSuccess(reader);
} catch (Exception e) {
result.unblockError(e);
}
}), true);
} catch (Exception e) {
result.unblockError(e);
}
}).startOn(io.canStartReading(), true);
return result;
} | java | public static AsyncWork<XMLStreamReader, Exception> start(IO.Readable.Buffered io, int charactersBufferSize, int maxBuffers) {
AsyncWork<XMLStreamReader, Exception> result = new AsyncWork<>();
new Task.Cpu.FromRunnable("Start reading XML " + io.getSourceDescription(), io.getPriority(), () -> {
XMLStreamReader reader = new XMLStreamReader(io, charactersBufferSize, maxBuffers);
try {
Starter start = new Starter(io, reader.defaultEncoding, reader.charactersBuffersSize, reader.maxBuffers);
reader.stream = start.start();
reader.stream.canStartReading().listenAsync(
new Task.Cpu.FromRunnable("Start reading XML " + io.getSourceDescription(), io.getPriority(), () -> {
try {
reader.next();
result.unblockSuccess(reader);
} catch (Exception e) {
result.unblockError(e);
}
}), true);
} catch (Exception e) {
result.unblockError(e);
}
}).startOn(io.canStartReading(), true);
return result;
} | [
"public",
"static",
"AsyncWork",
"<",
"XMLStreamReader",
",",
"Exception",
">",
"start",
"(",
"IO",
".",
"Readable",
".",
"Buffered",
"io",
",",
"int",
"charactersBufferSize",
",",
"int",
"maxBuffers",
")",
"{",
"AsyncWork",
"<",
"XMLStreamReader",
",",
"Excep... | Utility method that initialize a XMLStreamReader, initialize it, and
return an AsyncWork which is unblocked when characters are available to be read. | [
"Utility",
"method",
"that",
"initialize",
"a",
"XMLStreamReader",
"initialize",
"it",
"and",
"return",
"an",
"AsyncWork",
"which",
"is",
"unblocked",
"when",
"characters",
"are",
"available",
"to",
"be",
"read",
"."
] | train | https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/xml/XMLStreamReader.java#L61-L82 |
cdk/cdk | tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java | ModelBuilder3D.setForceField | private void setForceField(String ffname, IChemObjectBuilder builder) throws CDKException {
"""
Sets the forceField attribute of the ModelBuilder3D object.
@param ffname forceField name
"""
if (ffname == null) {
ffname = "mm2";
}
try {
forceFieldName = ffname;
ffc.setForceFieldConfigurator(ffname, builder);
parameterSet = ffc.getParameterSet();
} catch (CDKException ex1) {
logger.error("Problem with ForceField configuration due to>" + ex1.getMessage());
logger.debug(ex1);
throw new CDKException("Problem with ForceField configuration due to>" + ex1.getMessage(), ex1);
}
} | java | private void setForceField(String ffname, IChemObjectBuilder builder) throws CDKException {
if (ffname == null) {
ffname = "mm2";
}
try {
forceFieldName = ffname;
ffc.setForceFieldConfigurator(ffname, builder);
parameterSet = ffc.getParameterSet();
} catch (CDKException ex1) {
logger.error("Problem with ForceField configuration due to>" + ex1.getMessage());
logger.debug(ex1);
throw new CDKException("Problem with ForceField configuration due to>" + ex1.getMessage(), ex1);
}
} | [
"private",
"void",
"setForceField",
"(",
"String",
"ffname",
",",
"IChemObjectBuilder",
"builder",
")",
"throws",
"CDKException",
"{",
"if",
"(",
"ffname",
"==",
"null",
")",
"{",
"ffname",
"=",
"\"mm2\"",
";",
"}",
"try",
"{",
"forceFieldName",
"=",
"ffname... | Sets the forceField attribute of the ModelBuilder3D object.
@param ffname forceField name | [
"Sets",
"the",
"forceField",
"attribute",
"of",
"the",
"ModelBuilder3D",
"object",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java#L134-L147 |
netty/netty | resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java | DnsNameResolver.resolveAll | public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals) {
"""
Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike
{@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers.
If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured
{@link HostsFileEntries} before sending a query to the name servers. If a match is found in the
{@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned.
@param question the question
@param additionals additional records ({@code OPT})
@return the list of the {@link DnsRecord}s as the result of the resolution
"""
return resolveAll(question, additionals, executor().<List<DnsRecord>>newPromise());
} | java | public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals) {
return resolveAll(question, additionals, executor().<List<DnsRecord>>newPromise());
} | [
"public",
"final",
"Future",
"<",
"List",
"<",
"DnsRecord",
">",
">",
"resolveAll",
"(",
"DnsQuestion",
"question",
",",
"Iterable",
"<",
"DnsRecord",
">",
"additionals",
")",
"{",
"return",
"resolveAll",
"(",
"question",
",",
"additionals",
",",
"executor",
... | Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike
{@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers.
If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured
{@link HostsFileEntries} before sending a query to the name servers. If a match is found in the
{@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned.
@param question the question
@param additionals additional records ({@code OPT})
@return the list of the {@link DnsRecord}s as the result of the resolution | [
"Resolves",
"the",
"{",
"@link",
"DnsRecord",
"}",
"s",
"that",
"are",
"matched",
"by",
"the",
"specified",
"{",
"@link",
"DnsQuestion",
"}",
".",
"Unlike",
"{",
"@link",
"#query",
"(",
"DnsQuestion",
")",
"}",
"this",
"method",
"handles",
"redirection",
"... | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java#L727-L729 |
fozziethebeat/S-Space | src/main/java/edu/ucla/sspace/matrix/MatrixIO.java | MatrixIO.readMatrix | public static Matrix readMatrix(File matrix, Format format,
Type matrixType)
throws IOException {
"""
Converts the contents of a matrix file as a {@link Matrix} object, using
the provided type description as a hint for what kind to create. The
type of {@code Matrix} object created will be based on an estimate of
whether the data will fit into the available memory. Note that the
returned {@link Matrix} instance is not backed by the data on file;
changes to the {@code Matrix} will <i>not</i> be reflected in the
original file's data.
@param matrix a file contain matrix data
@param format the format of the file
@param matrixType the expected type and behavior of the matrix in
relation to memory. This value will be used as a hint for what
kind of {@code Matrix} instance to create
@return the {@code Matrix} instance that contains the data in the
provided file
"""
return readMatrix(matrix, format, matrixType, false);
} | java | public static Matrix readMatrix(File matrix, Format format,
Type matrixType)
throws IOException {
return readMatrix(matrix, format, matrixType, false);
} | [
"public",
"static",
"Matrix",
"readMatrix",
"(",
"File",
"matrix",
",",
"Format",
"format",
",",
"Type",
"matrixType",
")",
"throws",
"IOException",
"{",
"return",
"readMatrix",
"(",
"matrix",
",",
"format",
",",
"matrixType",
",",
"false",
")",
";",
"}"
] | Converts the contents of a matrix file as a {@link Matrix} object, using
the provided type description as a hint for what kind to create. The
type of {@code Matrix} object created will be based on an estimate of
whether the data will fit into the available memory. Note that the
returned {@link Matrix} instance is not backed by the data on file;
changes to the {@code Matrix} will <i>not</i> be reflected in the
original file's data.
@param matrix a file contain matrix data
@param format the format of the file
@param matrixType the expected type and behavior of the matrix in
relation to memory. This value will be used as a hint for what
kind of {@code Matrix} instance to create
@return the {@code Matrix} instance that contains the data in the
provided file | [
"Converts",
"the",
"contents",
"of",
"a",
"matrix",
"file",
"as",
"a",
"{",
"@link",
"Matrix",
"}",
"object",
"using",
"the",
"provided",
"type",
"description",
"as",
"a",
"hint",
"for",
"what",
"kind",
"to",
"create",
".",
"The",
"type",
"of",
"{",
"@... | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/matrix/MatrixIO.java#L760-L764 |
Red5/red5-server-common | src/main/java/org/red5/server/util/HttpConnectionUtil.java | HttpConnectionUtil.getSecureClient | public static final HttpClient getSecureClient() {
"""
Returns a client with all our selected properties / params and SSL enabled.
@return client
"""
HttpClientBuilder client = HttpClientBuilder.create();
// set the ssl verifier to accept all
client.setSSLHostnameVerifier(new NoopHostnameVerifier());
// set the connection manager
client.setConnectionManager(connectionManager);
// dont retry
client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
// establish a connection within x seconds
RequestConfig config = RequestConfig.custom().setSocketTimeout(connectionTimeout).build();
client.setDefaultRequestConfig(config);
// no redirects
client.disableRedirectHandling();
// set custom ua
client.setUserAgent(userAgent);
return client.build();
} | java | public static final HttpClient getSecureClient() {
HttpClientBuilder client = HttpClientBuilder.create();
// set the ssl verifier to accept all
client.setSSLHostnameVerifier(new NoopHostnameVerifier());
// set the connection manager
client.setConnectionManager(connectionManager);
// dont retry
client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
// establish a connection within x seconds
RequestConfig config = RequestConfig.custom().setSocketTimeout(connectionTimeout).build();
client.setDefaultRequestConfig(config);
// no redirects
client.disableRedirectHandling();
// set custom ua
client.setUserAgent(userAgent);
return client.build();
} | [
"public",
"static",
"final",
"HttpClient",
"getSecureClient",
"(",
")",
"{",
"HttpClientBuilder",
"client",
"=",
"HttpClientBuilder",
".",
"create",
"(",
")",
";",
"// set the ssl verifier to accept all\r",
"client",
".",
"setSSLHostnameVerifier",
"(",
"new",
"NoopHostn... | Returns a client with all our selected properties / params and SSL enabled.
@return client | [
"Returns",
"a",
"client",
"with",
"all",
"our",
"selected",
"properties",
"/",
"params",
"and",
"SSL",
"enabled",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/HttpConnectionUtil.java#L103-L119 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java | ServicesInner.beginStop | public void beginStop(String groupName, String serviceName) {
"""
Stop service.
The services resource is the top-level resource that represents the Data Migration Service. This action stops the service and the service cannot be used for data migration. The service owner won't be billed when the service is stopped.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
"""
beginStopWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | java | public void beginStop(String groupName, String serviceName) {
beginStopWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | [
"public",
"void",
"beginStop",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
")",
"{",
"beginStopWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")",
".",
"body",
"(",
")",
";... | Stop service.
The services resource is the top-level resource that represents the Data Migration Service. This action stops the service and the service cannot be used for data migration. The service owner won't be billed when the service is stopped.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent | [
"Stop",
"service",
".",
"The",
"services",
"resource",
"is",
"the",
"top",
"-",
"level",
"resource",
"that",
"represents",
"the",
"Data",
"Migration",
"Service",
".",
"This",
"action",
"stops",
"the",
"service",
"and",
"the",
"service",
"cannot",
"be",
"used... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L1263-L1265 |
aol/cyclops | cyclops/src/main/java/com/oath/cyclops/util/box/MutableDouble.java | MutableDouble.fromExternal | public static MutableDouble fromExternal(final DoubleSupplier s, final DoubleConsumer c) {
"""
Construct a MutableDouble that gets and sets an external value using the provided Supplier and Consumer
e.g.
<pre>
{@code
MutableDouble mutable = MutableDouble.fromExternal(()->!this.value,val->!this.value);
}
</pre>
@param s Supplier of an external value
@param c Consumer that sets an external value
@return MutableDouble that gets / sets an external (mutable) value
"""
return new MutableDouble() {
@Override
public double getAsDouble() {
return s.getAsDouble();
}
@Override
public Double get() {
return getAsDouble();
}
@Override
public MutableDouble set(final double value) {
c.accept(value);
return this;
}
};
} | java | public static MutableDouble fromExternal(final DoubleSupplier s, final DoubleConsumer c) {
return new MutableDouble() {
@Override
public double getAsDouble() {
return s.getAsDouble();
}
@Override
public Double get() {
return getAsDouble();
}
@Override
public MutableDouble set(final double value) {
c.accept(value);
return this;
}
};
} | [
"public",
"static",
"MutableDouble",
"fromExternal",
"(",
"final",
"DoubleSupplier",
"s",
",",
"final",
"DoubleConsumer",
"c",
")",
"{",
"return",
"new",
"MutableDouble",
"(",
")",
"{",
"@",
"Override",
"public",
"double",
"getAsDouble",
"(",
")",
"{",
"return... | Construct a MutableDouble that gets and sets an external value using the provided Supplier and Consumer
e.g.
<pre>
{@code
MutableDouble mutable = MutableDouble.fromExternal(()->!this.value,val->!this.value);
}
</pre>
@param s Supplier of an external value
@param c Consumer that sets an external value
@return MutableDouble that gets / sets an external (mutable) value | [
"Construct",
"a",
"MutableDouble",
"that",
"gets",
"and",
"sets",
"an",
"external",
"value",
"using",
"the",
"provided",
"Supplier",
"and",
"Consumer"
] | train | https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/com/oath/cyclops/util/box/MutableDouble.java#L81-L99 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/raw/DataDecoder.java | DataDecoder.decodeLongObj | public static Long decodeLongObj(byte[] src, int srcOffset)
throws CorruptEncodingException {
"""
Decodes a signed Long object from exactly 1 or 9 bytes. If null is
returned, then 1 byte was read.
@param src source of encoded bytes
@param srcOffset offset into source array
@return signed Long object or null
"""
try {
int b = src[srcOffset];
if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) {
return null;
}
return decodeLong(src, srcOffset + 1);
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
} | java | public static Long decodeLongObj(byte[] src, int srcOffset)
throws CorruptEncodingException
{
try {
int b = src[srcOffset];
if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) {
return null;
}
return decodeLong(src, srcOffset + 1);
} catch (IndexOutOfBoundsException e) {
throw new CorruptEncodingException(null, e);
}
} | [
"public",
"static",
"Long",
"decodeLongObj",
"(",
"byte",
"[",
"]",
"src",
",",
"int",
"srcOffset",
")",
"throws",
"CorruptEncodingException",
"{",
"try",
"{",
"int",
"b",
"=",
"src",
"[",
"srcOffset",
"]",
";",
"if",
"(",
"b",
"==",
"NULL_BYTE_HIGH",
"|... | Decodes a signed Long object from exactly 1 or 9 bytes. If null is
returned, then 1 byte was read.
@param src source of encoded bytes
@param srcOffset offset into source array
@return signed Long object or null | [
"Decodes",
"a",
"signed",
"Long",
"object",
"from",
"exactly",
"1",
"or",
"9",
"bytes",
".",
"If",
"null",
"is",
"returned",
"then",
"1",
"byte",
"was",
"read",
"."
] | train | https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/DataDecoder.java#L114-L126 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/AbstractTagLibrary.java | AbstractTagLibrary.addComponent | protected final void addComponent(String name, String componentType, String rendererType,
Class<? extends TagHandler> handlerType) {
"""
Add a ComponentHandler with the specified componentType and rendererType, aliased by the tag name. The Facelet
will be compiled with the specified HandlerType (which must extend AbstractComponentHandler).
@see AbstractComponentHandler
@param name
name to use, "foo" would be <my:foo />
@param componentType
componentType to use
@param rendererType
rendererType to use
@param handlerType
a Class that extends AbstractComponentHandler
"""
_factories.put(name, new UserComponentHandlerFactory(componentType, rendererType, handlerType));
} | java | protected final void addComponent(String name, String componentType, String rendererType,
Class<? extends TagHandler> handlerType)
{
_factories.put(name, new UserComponentHandlerFactory(componentType, rendererType, handlerType));
} | [
"protected",
"final",
"void",
"addComponent",
"(",
"String",
"name",
",",
"String",
"componentType",
",",
"String",
"rendererType",
",",
"Class",
"<",
"?",
"extends",
"TagHandler",
">",
"handlerType",
")",
"{",
"_factories",
".",
"put",
"(",
"name",
",",
"ne... | Add a ComponentHandler with the specified componentType and rendererType, aliased by the tag name. The Facelet
will be compiled with the specified HandlerType (which must extend AbstractComponentHandler).
@see AbstractComponentHandler
@param name
name to use, "foo" would be <my:foo />
@param componentType
componentType to use
@param rendererType
rendererType to use
@param handlerType
a Class that extends AbstractComponentHandler | [
"Add",
"a",
"ComponentHandler",
"with",
"the",
"specified",
"componentType",
"and",
"rendererType",
"aliased",
"by",
"the",
"tag",
"name",
".",
"The",
"Facelet",
"will",
"be",
"compiled",
"with",
"the",
"specified",
"HandlerType",
"(",
"which",
"must",
"extend",... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/AbstractTagLibrary.java#L176-L180 |
apereo/cas | support/cas-server-support-rest-core/src/main/java/org/apereo/cas/support/rest/resources/TicketGrantingTicketResource.java | TicketGrantingTicketResource.createTicketGrantingTicket | @PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody(required=false) final MultiValueMap<String, String> requestBody,
final HttpServletRequest request) {
"""
Create new ticket granting ticket.
@param requestBody username and password application/x-www-form-urlencoded values
@param request raw HttpServletRequest used to call this method
@return ResponseEntity representing RESTful response
"""
try {
val tgtId = createTicketGrantingTicketForRequest(requestBody, request);
return createResponseEntityForTicket(request, tgtId);
} catch (final AuthenticationException e) {
return RestResourceUtils.createResponseEntityForAuthnFailure(e, request, applicationContext);
} catch (final BadRestRequestException e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
} | java | @PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody(required=false) final MultiValueMap<String, String> requestBody,
final HttpServletRequest request) {
try {
val tgtId = createTicketGrantingTicketForRequest(requestBody, request);
return createResponseEntityForTicket(request, tgtId);
} catch (final AuthenticationException e) {
return RestResourceUtils.createResponseEntityForAuthnFailure(e, request, applicationContext);
} catch (final BadRestRequestException e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
} | [
"@",
"PostMapping",
"(",
"value",
"=",
"\"/v1/tickets\"",
",",
"consumes",
"=",
"MediaType",
".",
"APPLICATION_FORM_URLENCODED_VALUE",
")",
"public",
"ResponseEntity",
"<",
"String",
">",
"createTicketGrantingTicket",
"(",
"@",
"RequestBody",
"(",
"required",
"=",
"... | Create new ticket granting ticket.
@param requestBody username and password application/x-www-form-urlencoded values
@param request raw HttpServletRequest used to call this method
@return ResponseEntity representing RESTful response | [
"Create",
"new",
"ticket",
"granting",
"ticket",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-rest-core/src/main/java/org/apereo/cas/support/rest/resources/TicketGrantingTicketResource.java#L62-L77 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ApplicationSecurityGroupsInner.java | ApplicationSecurityGroupsInner.createOrUpdateAsync | public Observable<ApplicationSecurityGroupInner> createOrUpdateAsync(String resourceGroupName, String applicationSecurityGroupName, ApplicationSecurityGroupInner parameters) {
"""
Creates or updates an application security group.
@param resourceGroupName The name of the resource group.
@param applicationSecurityGroupName The name of the application security group.
@param parameters Parameters supplied to the create or update ApplicationSecurityGroup operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, applicationSecurityGroupName, parameters).map(new Func1<ServiceResponse<ApplicationSecurityGroupInner>, ApplicationSecurityGroupInner>() {
@Override
public ApplicationSecurityGroupInner call(ServiceResponse<ApplicationSecurityGroupInner> response) {
return response.body();
}
});
} | java | public Observable<ApplicationSecurityGroupInner> createOrUpdateAsync(String resourceGroupName, String applicationSecurityGroupName, ApplicationSecurityGroupInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, applicationSecurityGroupName, parameters).map(new Func1<ServiceResponse<ApplicationSecurityGroupInner>, ApplicationSecurityGroupInner>() {
@Override
public ApplicationSecurityGroupInner call(ServiceResponse<ApplicationSecurityGroupInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ApplicationSecurityGroupInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"applicationSecurityGroupName",
",",
"ApplicationSecurityGroupInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseA... | Creates or updates an application security group.
@param resourceGroupName The name of the resource group.
@param applicationSecurityGroupName The name of the application security group.
@param parameters Parameters supplied to the create or update ApplicationSecurityGroup operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Creates",
"or",
"updates",
"an",
"application",
"security",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ApplicationSecurityGroupsInner.java#L378-L385 |
cdk/cdk | tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java | AtomPlacer3D.getBondLengthValue | public double getBondLengthValue(String id1, String id2) {
"""
Gets the distanceValue attribute of the parameter set.
@param id1 atom1 id
@param id2 atom2 id
@return The distanceValue value from the force field parameter set
"""
String dkey = "";
if (pSet.containsKey(("bond" + id1 + ";" + id2))) {
dkey = "bond" + id1 + ";" + id2;
} else if (pSet.containsKey(("bond" + id2 + ";" + id1))) {
dkey = "bond" + id2 + ";" + id1;
} else {
logger.warn("KEYError: Unknown distance key in pSet: " + id2 + ";" + id1
+ " take default bond length: " + DEFAULT_BOND_LENGTH);
return DEFAULT_BOND_LENGTH;
}
return ((Double) (pSet.get(dkey).get(0))).doubleValue();
} | java | public double getBondLengthValue(String id1, String id2) {
String dkey = "";
if (pSet.containsKey(("bond" + id1 + ";" + id2))) {
dkey = "bond" + id1 + ";" + id2;
} else if (pSet.containsKey(("bond" + id2 + ";" + id1))) {
dkey = "bond" + id2 + ";" + id1;
} else {
logger.warn("KEYError: Unknown distance key in pSet: " + id2 + ";" + id1
+ " take default bond length: " + DEFAULT_BOND_LENGTH);
return DEFAULT_BOND_LENGTH;
}
return ((Double) (pSet.get(dkey).get(0))).doubleValue();
} | [
"public",
"double",
"getBondLengthValue",
"(",
"String",
"id1",
",",
"String",
"id2",
")",
"{",
"String",
"dkey",
"=",
"\"\"",
";",
"if",
"(",
"pSet",
".",
"containsKey",
"(",
"(",
"\"bond\"",
"+",
"id1",
"+",
"\";\"",
"+",
"id2",
")",
")",
")",
"{",... | Gets the distanceValue attribute of the parameter set.
@param id1 atom1 id
@param id2 atom2 id
@return The distanceValue value from the force field parameter set | [
"Gets",
"the",
"distanceValue",
"attribute",
"of",
"the",
"parameter",
"set",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java#L327-L339 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLSubPropertyChainAxiomImpl_CustomFieldSerializer.java | OWLSubPropertyChainAxiomImpl_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLSubPropertyChainAxiomImpl instance) throws SerializationException {
"""
Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful
"""
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLSubPropertyChainAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLSubPropertyChainAxiomImpl",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"
] | Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{",
"@link",
"com",
".",
"google",
".",
"gwt",
".",
"user",
".",
"client",
".",
"rpc",
".",
"SerializationStreamReader",
"}",
"."
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLSubPropertyChainAxiomImpl_CustomFieldSerializer.java#L102-L105 |
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java | ObjectArrayList.binarySearchFromTo | public int binarySearchFromTo(Object key, int from, int to, java.util.Comparator comparator) {
"""
Searches the receiver for the specified value using
the binary search algorithm. The receiver must be sorted into ascending order
according to the specified comparator. All elements in the
range must be <i>mutually comparable</i> by the specified comparator
(that is, <tt>c.compare(e1, e2)</tt> must not throw a
<tt>ClassCastException</tt> for any elements <tt>e1</tt> and
<tt>e2</tt> in the range).<p>
If the receiver is not sorted, the results are undefined: in particular, the call
may enter an infinite loop. If the receiver contains multiple elements
equal to the specified object, there is no guarantee which instance
will be found.
@param key the value to be searched for.
@param from the leftmost search position, inclusive.
@param to the rightmost search position, inclusive.
@param comparator the comparator by which the receiver is sorted.
@throws ClassCastException if the receiver contains elements that are not
<i>mutually comparable</i> using the specified comparator.
@return index of the search key, if it is contained in the receiver;
otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The <i>insertion
point</i> is defined as the the point at which the value would
be inserted into the receiver: the index of the first
element greater than the key, or <tt>receiver.size()</tt>, if all
elements in the receiver are less than the specified key. Note
that this guarantees that the return value will be >= 0 if
and only if the key is found.
@see cern.colt.Sorting
@see java.util.Arrays
@see java.util.Comparator
"""
//return cern.colt.Sorting.binarySearchFromTo(this.elements,key,from,to,comparator);
return java.util.Arrays.binarySearch(this.elements,key);
} | java | public int binarySearchFromTo(Object key, int from, int to, java.util.Comparator comparator) {
//return cern.colt.Sorting.binarySearchFromTo(this.elements,key,from,to,comparator);
return java.util.Arrays.binarySearch(this.elements,key);
} | [
"public",
"int",
"binarySearchFromTo",
"(",
"Object",
"key",
",",
"int",
"from",
",",
"int",
"to",
",",
"java",
".",
"util",
".",
"Comparator",
"comparator",
")",
"{",
"//return cern.colt.Sorting.binarySearchFromTo(this.elements,key,from,to,comparator);\r",
"return",
"j... | Searches the receiver for the specified value using
the binary search algorithm. The receiver must be sorted into ascending order
according to the specified comparator. All elements in the
range must be <i>mutually comparable</i> by the specified comparator
(that is, <tt>c.compare(e1, e2)</tt> must not throw a
<tt>ClassCastException</tt> for any elements <tt>e1</tt> and
<tt>e2</tt> in the range).<p>
If the receiver is not sorted, the results are undefined: in particular, the call
may enter an infinite loop. If the receiver contains multiple elements
equal to the specified object, there is no guarantee which instance
will be found.
@param key the value to be searched for.
@param from the leftmost search position, inclusive.
@param to the rightmost search position, inclusive.
@param comparator the comparator by which the receiver is sorted.
@throws ClassCastException if the receiver contains elements that are not
<i>mutually comparable</i> using the specified comparator.
@return index of the search key, if it is contained in the receiver;
otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The <i>insertion
point</i> is defined as the the point at which the value would
be inserted into the receiver: the index of the first
element greater than the key, or <tt>receiver.size()</tt>, if all
elements in the receiver are less than the specified key. Note
that this guarantees that the return value will be >= 0 if
and only if the key is found.
@see cern.colt.Sorting
@see java.util.Arrays
@see java.util.Comparator | [
"Searches",
"the",
"receiver",
"for",
"the",
"specified",
"value",
"using",
"the",
"binary",
"search",
"algorithm",
".",
"The",
"receiver",
"must",
"be",
"sorted",
"into",
"ascending",
"order",
"according",
"to",
"the",
"specified",
"comparator",
".",
"All",
"... | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L226-L229 |
phoenixnap/springmvc-raml-plugin | src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/helpers/RamlTypeHelper.java | RamlTypeHelper.mapTypeToPojo | public static ApiBodyMetadata mapTypeToPojo(JCodeModel pojoCodeModel, RamlRoot document, TypeDeclaration type) {
"""
Maps a RAML Data Type to a JCodeModel using JSONSchema2Pojo and
encapsulates it along with some metadata into an {@link ApiBodyMetadata}
object.
@param pojoCodeModel
The code model containing the classes generated during
generation
@param document
The Raml document being parsed
@param type
The RAML type declaration
@return Object representing this Body
"""
RamlInterpretationResult interpret = RamlInterpreterFactory.getInterpreterForType(type).interpret(document, type, pojoCodeModel,
false);
// here we expect that a new object is created i guess... we'd need to
// see how primitive arrays fit in
JClass pojo = null;
if (interpret.getBuilder() != null) {
pojo = interpret.getBuilder().getPojo();
} else if (interpret.getResolvedClass() != null) {
pojo = interpret.getResolvedClass();
}
if (pojo == null) {
throw new IllegalStateException("No Pojo created or resolved for type " + type.getClass().getSimpleName() + ":" + type.name());
}
if (pojo.name().equals("Void")) {
return null;
}
boolean array = false;
String pojoName = pojo.name();
if (pojo.name().contains("List<") || pojo.name().contains("Set<")) {
array = true;
pojoName = pojo.getTypeParameters().get(0).name();
}
return new ApiBodyMetadata(pojoName, type, array, pojoCodeModel);
} | java | public static ApiBodyMetadata mapTypeToPojo(JCodeModel pojoCodeModel, RamlRoot document, TypeDeclaration type) {
RamlInterpretationResult interpret = RamlInterpreterFactory.getInterpreterForType(type).interpret(document, type, pojoCodeModel,
false);
// here we expect that a new object is created i guess... we'd need to
// see how primitive arrays fit in
JClass pojo = null;
if (interpret.getBuilder() != null) {
pojo = interpret.getBuilder().getPojo();
} else if (interpret.getResolvedClass() != null) {
pojo = interpret.getResolvedClass();
}
if (pojo == null) {
throw new IllegalStateException("No Pojo created or resolved for type " + type.getClass().getSimpleName() + ":" + type.name());
}
if (pojo.name().equals("Void")) {
return null;
}
boolean array = false;
String pojoName = pojo.name();
if (pojo.name().contains("List<") || pojo.name().contains("Set<")) {
array = true;
pojoName = pojo.getTypeParameters().get(0).name();
}
return new ApiBodyMetadata(pojoName, type, array, pojoCodeModel);
} | [
"public",
"static",
"ApiBodyMetadata",
"mapTypeToPojo",
"(",
"JCodeModel",
"pojoCodeModel",
",",
"RamlRoot",
"document",
",",
"TypeDeclaration",
"type",
")",
"{",
"RamlInterpretationResult",
"interpret",
"=",
"RamlInterpreterFactory",
".",
"getInterpreterForType",
"(",
"t... | Maps a RAML Data Type to a JCodeModel using JSONSchema2Pojo and
encapsulates it along with some metadata into an {@link ApiBodyMetadata}
object.
@param pojoCodeModel
The code model containing the classes generated during
generation
@param document
The Raml document being parsed
@param type
The RAML type declaration
@return Object representing this Body | [
"Maps",
"a",
"RAML",
"Data",
"Type",
"to",
"a",
"JCodeModel",
"using",
"JSONSchema2Pojo",
"and",
"encapsulates",
"it",
"along",
"with",
"some",
"metadata",
"into",
"an",
"{",
"@link",
"ApiBodyMetadata",
"}",
"object",
"."
] | train | https://github.com/phoenixnap/springmvc-raml-plugin/blob/6387072317cd771eb7d6f30943f556ac20dd3c84/src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/helpers/RamlTypeHelper.java#L99-L128 |
Javacord/Javacord | javacord-api/src/main/java/org/javacord/api/entity/server/ServerUpdater.java | ServerUpdater.setSplash | public ServerUpdater setSplash(BufferedImage splash, String fileType) {
"""
Queues the splash to be updated.
@param splash The new splash of the server.
@param fileType The type of the splash, e.g. "png" or "jpg".
@return The current instance in order to chain call methods.
"""
delegate.setSplash(splash, fileType);
return this;
} | java | public ServerUpdater setSplash(BufferedImage splash, String fileType) {
delegate.setSplash(splash, fileType);
return this;
} | [
"public",
"ServerUpdater",
"setSplash",
"(",
"BufferedImage",
"splash",
",",
"String",
"fileType",
")",
"{",
"delegate",
".",
"setSplash",
"(",
"splash",
",",
"fileType",
")",
";",
"return",
"this",
";",
"}"
] | Queues the splash to be updated.
@param splash The new splash of the server.
@param fileType The type of the splash, e.g. "png" or "jpg".
@return The current instance in order to chain call methods. | [
"Queues",
"the",
"splash",
"to",
"be",
"updated",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/server/ServerUpdater.java#L284-L287 |
sebastiangraf/treetank | interfacemodules/jax-rx/src/main/java/org/treetank/service/jaxrx/implementation/DatabaseRepresentation.java | DatabaseRepresentation.getLastRevision | public long getLastRevision(final String resourceName) throws JaxRxException, TTException {
"""
This method reads the existing database, and offers the last revision id
of the database
@param resourceName
The name of the existing database.
@return The {@link OutputStream} containing the result
@throws WebApplicationException
The Exception occurred.
@throws TTException
"""
long lastRevision;
if (mDatabase.existsResource(resourceName)) {
ISession session = null;
try {
session = mDatabase.getSession(new SessionConfiguration(resourceName, StandardSettings.KEY));
lastRevision = session.getMostRecentVersion();
} catch (final Exception globExcep) {
throw new JaxRxException(globExcep);
} finally {
session.close();
}
} else {
throw new JaxRxException(404, "Resource not found");
}
return lastRevision;
} | java | public long getLastRevision(final String resourceName) throws JaxRxException, TTException {
long lastRevision;
if (mDatabase.existsResource(resourceName)) {
ISession session = null;
try {
session = mDatabase.getSession(new SessionConfiguration(resourceName, StandardSettings.KEY));
lastRevision = session.getMostRecentVersion();
} catch (final Exception globExcep) {
throw new JaxRxException(globExcep);
} finally {
session.close();
}
} else {
throw new JaxRxException(404, "Resource not found");
}
return lastRevision;
} | [
"public",
"long",
"getLastRevision",
"(",
"final",
"String",
"resourceName",
")",
"throws",
"JaxRxException",
",",
"TTException",
"{",
"long",
"lastRevision",
";",
"if",
"(",
"mDatabase",
".",
"existsResource",
"(",
"resourceName",
")",
")",
"{",
"ISession",
"se... | This method reads the existing database, and offers the last revision id
of the database
@param resourceName
The name of the existing database.
@return The {@link OutputStream} containing the result
@throws WebApplicationException
The Exception occurred.
@throws TTException | [
"This",
"method",
"reads",
"the",
"existing",
"database",
"and",
"offers",
"the",
"last",
"revision",
"id",
"of",
"the",
"database"
] | train | https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/jax-rx/src/main/java/org/treetank/service/jaxrx/implementation/DatabaseRepresentation.java#L379-L397 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapTileCircuitModel.java | MapTileCircuitModel.getCircuitOverTransition | private Circuit getCircuitOverTransition(Circuit circuit, Tile neighbor) {
"""
Get the circuit, supporting over existing transition.
@param circuit The initial circuit.
@param neighbor The neighbor tile which can be a transition.
@return The new circuit or original one.
"""
final String group = getTransitiveGroup(circuit, neighbor);
final Circuit newCircuit;
if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getIn()))
{
newCircuit = new Circuit(circuit.getType(), group, circuit.getOut());
}
else if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getOut()))
{
newCircuit = new Circuit(circuit.getType(), circuit.getIn(), group);
}
else
{
newCircuit = circuit;
}
return newCircuit;
} | java | private Circuit getCircuitOverTransition(Circuit circuit, Tile neighbor)
{
final String group = getTransitiveGroup(circuit, neighbor);
final Circuit newCircuit;
if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getIn()))
{
newCircuit = new Circuit(circuit.getType(), group, circuit.getOut());
}
else if (TileGroupType.TRANSITION == mapGroup.getType(circuit.getOut()))
{
newCircuit = new Circuit(circuit.getType(), circuit.getIn(), group);
}
else
{
newCircuit = circuit;
}
return newCircuit;
} | [
"private",
"Circuit",
"getCircuitOverTransition",
"(",
"Circuit",
"circuit",
",",
"Tile",
"neighbor",
")",
"{",
"final",
"String",
"group",
"=",
"getTransitiveGroup",
"(",
"circuit",
",",
"neighbor",
")",
";",
"final",
"Circuit",
"newCircuit",
";",
"if",
"(",
... | Get the circuit, supporting over existing transition.
@param circuit The initial circuit.
@param neighbor The neighbor tile which can be a transition.
@return The new circuit or original one. | [
"Get",
"the",
"circuit",
"supporting",
"over",
"existing",
"transition",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapTileCircuitModel.java#L177-L194 |
EdwardRaff/JSAT | JSAT/src/jsat/math/DescriptiveStatistics.java | DescriptiveStatistics.sampleCorCoeff | public static double sampleCorCoeff(Vec xData, Vec yData) {
"""
Computes the sample correlation coefficient for two data sets X and Y. The lengths of X and Y must be the same, and each element in X should correspond to the element in Y.
@param yData the Y data set
@param xData the X data set
@return the sample correlation coefficient
"""
if(yData.length() != xData.length())
throw new ArithmeticException("X and Y data sets must have the same length");
double xMean = xData.mean();
double yMean = yData.mean();
double topSum = 0;
for(int i = 0; i < xData.length(); i++)
{
topSum += (xData.get(i)-xMean)*(yData.get(i)-yMean);
}
return topSum/((xData.length()-1)*xData.standardDeviation()*yData.standardDeviation());
} | java | public static double sampleCorCoeff(Vec xData, Vec yData)
{
if(yData.length() != xData.length())
throw new ArithmeticException("X and Y data sets must have the same length");
double xMean = xData.mean();
double yMean = yData.mean();
double topSum = 0;
for(int i = 0; i < xData.length(); i++)
{
topSum += (xData.get(i)-xMean)*(yData.get(i)-yMean);
}
return topSum/((xData.length()-1)*xData.standardDeviation()*yData.standardDeviation());
} | [
"public",
"static",
"double",
"sampleCorCoeff",
"(",
"Vec",
"xData",
",",
"Vec",
"yData",
")",
"{",
"if",
"(",
"yData",
".",
"length",
"(",
")",
"!=",
"xData",
".",
"length",
"(",
")",
")",
"throw",
"new",
"ArithmeticException",
"(",
"\"X and Y data sets m... | Computes the sample correlation coefficient for two data sets X and Y. The lengths of X and Y must be the same, and each element in X should correspond to the element in Y.
@param yData the Y data set
@param xData the X data set
@return the sample correlation coefficient | [
"Computes",
"the",
"sample",
"correlation",
"coefficient",
"for",
"two",
"data",
"sets",
"X",
"and",
"Y",
".",
"The",
"lengths",
"of",
"X",
"and",
"Y",
"must",
"be",
"the",
"same",
"and",
"each",
"element",
"in",
"X",
"should",
"correspond",
"to",
"the",... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/math/DescriptiveStatistics.java#L20-L37 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java | CommerceOrderPersistenceImpl.findAll | @Override
public List<CommerceOrder> findAll() {
"""
Returns all the commerce orders.
@return the commerce orders
"""
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceOrder> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceOrder",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the commerce orders.
@return the commerce orders | [
"Returns",
"all",
"the",
"commerce",
"orders",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java#L6962-L6965 |
Javacord/Javacord | javacord-api/src/main/java/org/javacord/api/entity/webhook/WebhookBuilder.java | WebhookBuilder.setAvatar | public WebhookBuilder setAvatar(InputStream avatar, String fileType) {
"""
Sets the avatar.
@param avatar The avatar to set.
@param fileType The type of the avatar, e.g. "png" or "jpg".
@return The current instance in order to chain call methods.
"""
delegate.setAvatar(avatar, fileType);
return this;
} | java | public WebhookBuilder setAvatar(InputStream avatar, String fileType) {
delegate.setAvatar(avatar, fileType);
return this;
} | [
"public",
"WebhookBuilder",
"setAvatar",
"(",
"InputStream",
"avatar",
",",
"String",
"fileType",
")",
"{",
"delegate",
".",
"setAvatar",
"(",
"avatar",
",",
"fileType",
")",
";",
"return",
"this",
";",
"}"
] | Sets the avatar.
@param avatar The avatar to set.
@param fileType The type of the avatar, e.g. "png" or "jpg".
@return The current instance in order to chain call methods. | [
"Sets",
"the",
"avatar",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/webhook/WebhookBuilder.java#L155-L158 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/workspace/LayerWorkspaceMgr.java | LayerWorkspaceMgr.setHelperWorkspace | public void setHelperWorkspace(@NonNull String key, Pointer value) {
"""
Set the pointer to the helper memory. Usually used for CuDNN workspace memory sharing.
NOTE: Don't use this method unless you are fully aware of how it is used to manage CuDNN memory!
Will (by design) throw a NPE if the underlying map (set from MultiLayerNetwork or ComputationGraph) is not set.
@param key Key for the helper workspace pointer
@param value Pointer
"""
if(helperWorkspacePointers == null){
helperWorkspacePointers = new HashMap<>();
}
helperWorkspacePointers.put(key, value);
} | java | public void setHelperWorkspace(@NonNull String key, Pointer value){
if(helperWorkspacePointers == null){
helperWorkspacePointers = new HashMap<>();
}
helperWorkspacePointers.put(key, value);
} | [
"public",
"void",
"setHelperWorkspace",
"(",
"@",
"NonNull",
"String",
"key",
",",
"Pointer",
"value",
")",
"{",
"if",
"(",
"helperWorkspacePointers",
"==",
"null",
")",
"{",
"helperWorkspacePointers",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"}",
"helper... | Set the pointer to the helper memory. Usually used for CuDNN workspace memory sharing.
NOTE: Don't use this method unless you are fully aware of how it is used to manage CuDNN memory!
Will (by design) throw a NPE if the underlying map (set from MultiLayerNetwork or ComputationGraph) is not set.
@param key Key for the helper workspace pointer
@param value Pointer | [
"Set",
"the",
"pointer",
"to",
"the",
"helper",
"memory",
".",
"Usually",
"used",
"for",
"CuDNN",
"workspace",
"memory",
"sharing",
".",
"NOTE",
":",
"Don",
"t",
"use",
"this",
"method",
"unless",
"you",
"are",
"fully",
"aware",
"of",
"how",
"it",
"is",
... | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/workspace/LayerWorkspaceMgr.java#L110-L115 |
groupon/monsoon | expr/src/main/java/com/groupon/lex/metrics/timeseries/expression/MinExpression.java | MinExpression.impl_ | private static Number impl_(Number x, Number y) {
"""
/* Calculate the sum of two numbers, preserving integral type if possible.
"""
return (x.doubleValue() > y.doubleValue() ? y : x);
} | java | private static Number impl_(Number x, Number y) {
return (x.doubleValue() > y.doubleValue() ? y : x);
} | [
"private",
"static",
"Number",
"impl_",
"(",
"Number",
"x",
",",
"Number",
"y",
")",
"{",
"return",
"(",
"x",
".",
"doubleValue",
"(",
")",
">",
"y",
".",
"doubleValue",
"(",
")",
"?",
"y",
":",
"x",
")",
";",
"}"
] | /* Calculate the sum of two numbers, preserving integral type if possible. | [
"/",
"*",
"Calculate",
"the",
"sum",
"of",
"two",
"numbers",
"preserving",
"integral",
"type",
"if",
"possible",
"."
] | train | https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/expr/src/main/java/com/groupon/lex/metrics/timeseries/expression/MinExpression.java#L25-L27 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.domain_changeDnsMXFilter_POST | public void domain_changeDnsMXFilter_POST(String domain, String customTarget, OvhDomainMXFilterEnum mxFilter, String subDomain) throws IOException {
"""
Change MX filter, so change MX DNS records
REST: POST /email/domain/{domain}/changeDnsMXFilter
@param subDomain [required] Sub domain
@param mxFilter [required] New MX filter
@param customTarget [required] Target server for custom MX
@param domain [required] Name of your domain name
"""
String qPath = "/email/domain/{domain}/changeDnsMXFilter";
StringBuilder sb = path(qPath, domain);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "customTarget", customTarget);
addBody(o, "mxFilter", mxFilter);
addBody(o, "subDomain", subDomain);
exec(qPath, "POST", sb.toString(), o);
} | java | public void domain_changeDnsMXFilter_POST(String domain, String customTarget, OvhDomainMXFilterEnum mxFilter, String subDomain) throws IOException {
String qPath = "/email/domain/{domain}/changeDnsMXFilter";
StringBuilder sb = path(qPath, domain);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "customTarget", customTarget);
addBody(o, "mxFilter", mxFilter);
addBody(o, "subDomain", subDomain);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"domain_changeDnsMXFilter_POST",
"(",
"String",
"domain",
",",
"String",
"customTarget",
",",
"OvhDomainMXFilterEnum",
"mxFilter",
",",
"String",
"subDomain",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/{domain}/changeDnsM... | Change MX filter, so change MX DNS records
REST: POST /email/domain/{domain}/changeDnsMXFilter
@param subDomain [required] Sub domain
@param mxFilter [required] New MX filter
@param customTarget [required] Target server for custom MX
@param domain [required] Name of your domain name | [
"Change",
"MX",
"filter",
"so",
"change",
"MX",
"DNS",
"records"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L1398-L1406 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/ProtoUtils.java | ProtoUtils.getForNumberMethod | private static MethodRef getForNumberMethod(EnumDescriptor descriptor) {
"""
Returns the {@link MethodRef} for the generated forNumber method.
"""
TypeInfo enumType = enumRuntimeType(descriptor);
return MethodRef.createStaticMethod(
enumType, new Method("forNumber", enumType.type(), ONE_INT_ARG))
// Note: Enum.forNumber() returns null if there is no corresponding enum. If a bad value is
// passed in (via unknown types), the generated bytecode will NPE.
.asNonNullable()
.asCheap();
} | java | private static MethodRef getForNumberMethod(EnumDescriptor descriptor) {
TypeInfo enumType = enumRuntimeType(descriptor);
return MethodRef.createStaticMethod(
enumType, new Method("forNumber", enumType.type(), ONE_INT_ARG))
// Note: Enum.forNumber() returns null if there is no corresponding enum. If a bad value is
// passed in (via unknown types), the generated bytecode will NPE.
.asNonNullable()
.asCheap();
} | [
"private",
"static",
"MethodRef",
"getForNumberMethod",
"(",
"EnumDescriptor",
"descriptor",
")",
"{",
"TypeInfo",
"enumType",
"=",
"enumRuntimeType",
"(",
"descriptor",
")",
";",
"return",
"MethodRef",
".",
"createStaticMethod",
"(",
"enumType",
",",
"new",
"Method... | Returns the {@link MethodRef} for the generated forNumber method. | [
"Returns",
"the",
"{"
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/ProtoUtils.java#L1298-L1306 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResultSets.java | ResultSets.forRows | public static ResultSet forRows(Type type, Iterable<Struct> rows) {
"""
Creates a pre-populated {@link com.google.cloud.spanner.ResultSet}
@param type row type of the rows in the returned {@link com.google.cloud.spanner.ResultSet}
@param rows the rows in the returned {@link com.google.cloud.spanner.ResultSet}.
"""
return new PrePopulatedResultSet(type, rows);
} | java | public static ResultSet forRows(Type type, Iterable<Struct> rows) {
return new PrePopulatedResultSet(type, rows);
} | [
"public",
"static",
"ResultSet",
"forRows",
"(",
"Type",
"type",
",",
"Iterable",
"<",
"Struct",
">",
"rows",
")",
"{",
"return",
"new",
"PrePopulatedResultSet",
"(",
"type",
",",
"rows",
")",
";",
"}"
] | Creates a pre-populated {@link com.google.cloud.spanner.ResultSet}
@param type row type of the rows in the returned {@link com.google.cloud.spanner.ResultSet}
@param rows the rows in the returned {@link com.google.cloud.spanner.ResultSet}. | [
"Creates",
"a",
"pre",
"-",
"populated",
"{",
"@link",
"com",
".",
"google",
".",
"cloud",
".",
"spanner",
".",
"ResultSet",
"}"
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResultSets.java#L40-L42 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_install_start_POST | public OvhTask serviceName_install_start_POST(String serviceName, OvhInstallCustom details, String partitionSchemeName, String templateName) throws IOException {
"""
Start an install
REST: POST /dedicated/server/{serviceName}/install/start
@param partitionSchemeName [required] Partition scheme name
@param details [required] parameters for default install
@param templateName [required] Template name
@param serviceName [required] The internal name of your dedicated server
"""
String qPath = "/dedicated/server/{serviceName}/install/start";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "details", details);
addBody(o, "partitionSchemeName", partitionSchemeName);
addBody(o, "templateName", templateName);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | java | public OvhTask serviceName_install_start_POST(String serviceName, OvhInstallCustom details, String partitionSchemeName, String templateName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/install/start";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "details", details);
addBody(o, "partitionSchemeName", partitionSchemeName);
addBody(o, "templateName", templateName);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} | [
"public",
"OvhTask",
"serviceName_install_start_POST",
"(",
"String",
"serviceName",
",",
"OvhInstallCustom",
"details",
",",
"String",
"partitionSchemeName",
",",
"String",
"templateName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{s... | Start an install
REST: POST /dedicated/server/{serviceName}/install/start
@param partitionSchemeName [required] Partition scheme name
@param details [required] parameters for default install
@param templateName [required] Template name
@param serviceName [required] The internal name of your dedicated server | [
"Start",
"an",
"install"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1641-L1650 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.config.1.2/src/com/ibm/ws/microprofile/config12/impl/Config12ConversionManager.java | Config12ConversionManager.implicitConverters | @Override
protected <T> ConversionStatus implicitConverters(String rawString, Class<T> type) {
"""
Attempt to apply a valueOf or T(String s) constructor
@param rawString
@param type
@return a converted T object
"""
ConversionStatus status = new ConversionStatus();
BuiltInConverter automaticConverter = getConverter(type);
//will be null if a suitable string constructor method could not be found
if (automaticConverter != null) {
try {
Object converted = automaticConverter.convert(rawString);
status.setConverted(converted);
} catch (IllegalArgumentException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, e);
}
throw e;
} catch (Throwable t) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, t);
}
throw new ConfigException(t);
}
}
return status;
} | java | @Override
protected <T> ConversionStatus implicitConverters(String rawString, Class<T> type) {
ConversionStatus status = new ConversionStatus();
BuiltInConverter automaticConverter = getConverter(type);
//will be null if a suitable string constructor method could not be found
if (automaticConverter != null) {
try {
Object converted = automaticConverter.convert(rawString);
status.setConverted(converted);
} catch (IllegalArgumentException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, e);
}
throw e;
} catch (Throwable t) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "implicitConverters: An automatic converter for type ''{0}'' and raw String ''{1}'' threw an exception: {2}.", type, rawString, t);
}
throw new ConfigException(t);
}
}
return status;
} | [
"@",
"Override",
"protected",
"<",
"T",
">",
"ConversionStatus",
"implicitConverters",
"(",
"String",
"rawString",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"ConversionStatus",
"status",
"=",
"new",
"ConversionStatus",
"(",
")",
";",
"BuiltInConverter",
"... | Attempt to apply a valueOf or T(String s) constructor
@param rawString
@param type
@return a converted T object | [
"Attempt",
"to",
"apply",
"a",
"valueOf",
"or",
"T",
"(",
"String",
"s",
")",
"constructor"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.config.1.2/src/com/ibm/ws/microprofile/config12/impl/Config12ConversionManager.java#L42-L66 |
threerings/narya | core/src/main/java/com/threerings/crowd/client/LocationDirector.java | LocationDirector.mayMoveTo | public boolean mayMoveTo (final int placeId, ResultListener<PlaceConfig> rl) {
"""
This can be called by cooperating directors that need to coopt the moving process to extend
it in some way or other. In such situations, they should call this method before moving to a
new location to check to be sure that all of the registered location observers are amenable
to a location change.
@param placeId the place oid of our tentative new location.
@return true if everyone is happy with the move, false if it was vetoed by one of the
location observers.
"""
final boolean[] vetoed = new boolean[1];
_observers.apply(new ObserverOp<LocationObserver>() {
public boolean apply (LocationObserver obs) {
vetoed[0] = (vetoed[0] || !obs.locationMayChange(placeId));
return true;
}
});
// if we're actually going somewhere, let the controller know that we might be leaving
mayLeavePlace();
// if we have a result listener, let it know if we failed or keep it for later if we're
// still going
if (rl != null) {
if (vetoed[0]) {
rl.requestFailed(new MoveVetoedException());
} else {
_moveListener = rl;
}
}
// and return the result
return !vetoed[0];
} | java | public boolean mayMoveTo (final int placeId, ResultListener<PlaceConfig> rl)
{
final boolean[] vetoed = new boolean[1];
_observers.apply(new ObserverOp<LocationObserver>() {
public boolean apply (LocationObserver obs) {
vetoed[0] = (vetoed[0] || !obs.locationMayChange(placeId));
return true;
}
});
// if we're actually going somewhere, let the controller know that we might be leaving
mayLeavePlace();
// if we have a result listener, let it know if we failed or keep it for later if we're
// still going
if (rl != null) {
if (vetoed[0]) {
rl.requestFailed(new MoveVetoedException());
} else {
_moveListener = rl;
}
}
// and return the result
return !vetoed[0];
} | [
"public",
"boolean",
"mayMoveTo",
"(",
"final",
"int",
"placeId",
",",
"ResultListener",
"<",
"PlaceConfig",
">",
"rl",
")",
"{",
"final",
"boolean",
"[",
"]",
"vetoed",
"=",
"new",
"boolean",
"[",
"1",
"]",
";",
"_observers",
".",
"apply",
"(",
"new",
... | This can be called by cooperating directors that need to coopt the moving process to extend
it in some way or other. In such situations, they should call this method before moving to a
new location to check to be sure that all of the registered location observers are amenable
to a location change.
@param placeId the place oid of our tentative new location.
@return true if everyone is happy with the move, false if it was vetoed by one of the
location observers. | [
"This",
"can",
"be",
"called",
"by",
"cooperating",
"directors",
"that",
"need",
"to",
"coopt",
"the",
"moving",
"process",
"to",
"extend",
"it",
"in",
"some",
"way",
"or",
"other",
".",
"In",
"such",
"situations",
"they",
"should",
"call",
"this",
"method... | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/client/LocationDirector.java#L233-L257 |
algolia/algoliasearch-client-java | src/main/java/com/algolia/search/saas/APIClient.java | APIClient.multipleQueries | public JSONObject multipleQueries(List<IndexQuery> queries) throws AlgoliaException {
"""
This method allows to query multiple indexes with one API call
"""
return multipleQueries(queries, "none", RequestOptions.empty);
} | java | public JSONObject multipleQueries(List<IndexQuery> queries) throws AlgoliaException {
return multipleQueries(queries, "none", RequestOptions.empty);
} | [
"public",
"JSONObject",
"multipleQueries",
"(",
"List",
"<",
"IndexQuery",
">",
"queries",
")",
"throws",
"AlgoliaException",
"{",
"return",
"multipleQueries",
"(",
"queries",
",",
"\"none\"",
",",
"RequestOptions",
".",
"empty",
")",
";",
"}"
] | This method allows to query multiple indexes with one API call | [
"This",
"method",
"allows",
"to",
"query",
"multiple",
"indexes",
"with",
"one",
"API",
"call"
] | train | https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/APIClient.java#L1255-L1257 |
aws/aws-sdk-java | aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/SearchProductsAsAdminRequest.java | SearchProductsAsAdminRequest.withFilters | public SearchProductsAsAdminRequest withFilters(java.util.Map<String, java.util.List<String>> filters) {
"""
<p>
The search filters. If no search filters are specified, the output includes all products to which the
administrator has access.
</p>
@param filters
The search filters. If no search filters are specified, the output includes all products to which the
administrator has access.
@return Returns a reference to this object so that method calls can be chained together.
"""
setFilters(filters);
return this;
} | java | public SearchProductsAsAdminRequest withFilters(java.util.Map<String, java.util.List<String>> filters) {
setFilters(filters);
return this;
} | [
"public",
"SearchProductsAsAdminRequest",
"withFilters",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"java",
".",
"util",
".",
"List",
"<",
"String",
">",
">",
"filters",
")",
"{",
"setFilters",
"(",
"filters",
")",
";",
"return",
"this",
"... | <p>
The search filters. If no search filters are specified, the output includes all products to which the
administrator has access.
</p>
@param filters
The search filters. If no search filters are specified, the output includes all products to which the
administrator has access.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"search",
"filters",
".",
"If",
"no",
"search",
"filters",
"are",
"specified",
"the",
"output",
"includes",
"all",
"products",
"to",
"which",
"the",
"administrator",
"has",
"access",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/SearchProductsAsAdminRequest.java#L315-L318 |
aws/aws-sdk-java | aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java | StepFunctionBuilder.gte | public static StringGreaterThanOrEqualCondition.Builder gte(String variable, String expectedValue) {
"""
Binary condition for String greater than or equal to comparison.
@param variable The JSONPath expression that determines which piece of the input document is used for the comparison.
@param expectedValue The expected value for this condition.
@see <a href="https://states-language.net/spec.html#choice-state">https://states-language.net/spec.html#choice-state</a>
@see com.amazonaws.services.stepfunctions.builder.states.Choice
"""
return StringGreaterThanOrEqualCondition.builder().variable(variable).expectedValue(expectedValue);
} | java | public static StringGreaterThanOrEqualCondition.Builder gte(String variable, String expectedValue) {
return StringGreaterThanOrEqualCondition.builder().variable(variable).expectedValue(expectedValue);
} | [
"public",
"static",
"StringGreaterThanOrEqualCondition",
".",
"Builder",
"gte",
"(",
"String",
"variable",
",",
"String",
"expectedValue",
")",
"{",
"return",
"StringGreaterThanOrEqualCondition",
".",
"builder",
"(",
")",
".",
"variable",
"(",
"variable",
")",
".",
... | Binary condition for String greater than or equal to comparison.
@param variable The JSONPath expression that determines which piece of the input document is used for the comparison.
@param expectedValue The expected value for this condition.
@see <a href="https://states-language.net/spec.html#choice-state">https://states-language.net/spec.html#choice-state</a>
@see com.amazonaws.services.stepfunctions.builder.states.Choice | [
"Binary",
"condition",
"for",
"String",
"greater",
"than",
"or",
"equal",
"to",
"comparison",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java#L320-L322 |
cdk/cdk | base/core/src/main/java/org/openscience/cdk/config/AtomTypeFactory.java | AtomTypeFactory.getInstance | public static AtomTypeFactory getInstance(InputStream ins, String format, IChemObjectBuilder builder) {
"""
Method to create a default AtomTypeFactory, using the given InputStream.
An AtomType of this kind is not cached.
@see #getInstance(String, IChemObjectBuilder)
@param ins InputStream containing the data
@param format String representing the possible formats ('xml' and 'txt')
@param builder IChemObjectBuilder used to make IChemObject instances
@return The AtomTypeFactory for the given data file
"""
return new AtomTypeFactory(ins, format, builder);
} | java | public static AtomTypeFactory getInstance(InputStream ins, String format, IChemObjectBuilder builder) {
return new AtomTypeFactory(ins, format, builder);
} | [
"public",
"static",
"AtomTypeFactory",
"getInstance",
"(",
"InputStream",
"ins",
",",
"String",
"format",
",",
"IChemObjectBuilder",
"builder",
")",
"{",
"return",
"new",
"AtomTypeFactory",
"(",
"ins",
",",
"format",
",",
"builder",
")",
";",
"}"
] | Method to create a default AtomTypeFactory, using the given InputStream.
An AtomType of this kind is not cached.
@see #getInstance(String, IChemObjectBuilder)
@param ins InputStream containing the data
@param format String representing the possible formats ('xml' and 'txt')
@param builder IChemObjectBuilder used to make IChemObject instances
@return The AtomTypeFactory for the given data file | [
"Method",
"to",
"create",
"a",
"default",
"AtomTypeFactory",
"using",
"the",
"given",
"InputStream",
".",
"An",
"AtomType",
"of",
"this",
"kind",
"is",
"not",
"cached",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/config/AtomTypeFactory.java#L129-L131 |
astrapi69/jaulp-wicket | jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/factory/ComponentFactory.java | ComponentFactory.newDateTimeField | public static DateTimeField newDateTimeField(final String id, final IModel<Date> model) {
"""
Factory method for create a new {@link DateTimeField}.
@param id
the id
@param model
the model
@return the {@link DateTimeField}.
"""
final DateTimeField dateTextField = new DateTimeField(id, model);
dateTextField.setOutputMarkupId(true);
return dateTextField;
} | java | public static DateTimeField newDateTimeField(final String id, final IModel<Date> model)
{
final DateTimeField dateTextField = new DateTimeField(id, model);
dateTextField.setOutputMarkupId(true);
return dateTextField;
} | [
"public",
"static",
"DateTimeField",
"newDateTimeField",
"(",
"final",
"String",
"id",
",",
"final",
"IModel",
"<",
"Date",
">",
"model",
")",
"{",
"final",
"DateTimeField",
"dateTextField",
"=",
"new",
"DateTimeField",
"(",
"id",
",",
"model",
")",
";",
"da... | Factory method for create a new {@link DateTimeField}.
@param id
the id
@param model
the model
@return the {@link DateTimeField}. | [
"Factory",
"method",
"for",
"create",
"a",
"new",
"{",
"@link",
"DateTimeField",
"}",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/factory/ComponentFactory.java#L159-L164 |
exoplatform/jcr | exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/command/PropPatchCommand.java | PropPatchCommand.setList | public List<HierarchicalProperty> setList(HierarchicalProperty request) {
"""
List of properties to set.
@param request request body
@return list of properties to set.
"""
HierarchicalProperty set = request.getChild(new QName("DAV:", "set"));
HierarchicalProperty prop = set.getChild(new QName("DAV:", "prop"));
List<HierarchicalProperty> setList = prop.getChildren();
return setList;
} | java | public List<HierarchicalProperty> setList(HierarchicalProperty request)
{
HierarchicalProperty set = request.getChild(new QName("DAV:", "set"));
HierarchicalProperty prop = set.getChild(new QName("DAV:", "prop"));
List<HierarchicalProperty> setList = prop.getChildren();
return setList;
} | [
"public",
"List",
"<",
"HierarchicalProperty",
">",
"setList",
"(",
"HierarchicalProperty",
"request",
")",
"{",
"HierarchicalProperty",
"set",
"=",
"request",
".",
"getChild",
"(",
"new",
"QName",
"(",
"\"DAV:\"",
",",
"\"set\"",
")",
")",
";",
"HierarchicalPro... | List of properties to set.
@param request request body
@return list of properties to set. | [
"List",
"of",
"properties",
"to",
"set",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/command/PropPatchCommand.java#L134-L140 |
PuyallupFoursquare/ccb-api-client-java | src/main/java/com/p4square/ccbapi/serializer/AbstractFormSerializer.java | AbstractFormSerializer.appendField | protected void appendField(final StringBuilder builder, final String key, final int value) {
"""
Append an integer field to the form.
@param builder The StringBuilder to use.
@param key The form key, which must be URLEncoded before calling this method.
@param value The value associated with the key.
"""
if (builder.length() > 0) {
builder.append("&");
}
builder.append(key).append("=").append(value);
} | java | protected void appendField(final StringBuilder builder, final String key, final int value) {
if (builder.length() > 0) {
builder.append("&");
}
builder.append(key).append("=").append(value);
} | [
"protected",
"void",
"appendField",
"(",
"final",
"StringBuilder",
"builder",
",",
"final",
"String",
"key",
",",
"final",
"int",
"value",
")",
"{",
"if",
"(",
"builder",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"builder",
".",
"append",
"(",
"\"&\... | Append an integer field to the form.
@param builder The StringBuilder to use.
@param key The form key, which must be URLEncoded before calling this method.
@param value The value associated with the key. | [
"Append",
"an",
"integer",
"field",
"to",
"the",
"form",
"."
] | train | https://github.com/PuyallupFoursquare/ccb-api-client-java/blob/54a7a3184dc565fe513aa520e1344b2303ea6834/src/main/java/com/p4square/ccbapi/serializer/AbstractFormSerializer.java#L67-L72 |
pravega/pravega | common/src/main/java/io/pravega/common/util/DelimitedStringParser.java | DelimitedStringParser.extractBoolean | public DelimitedStringParser extractBoolean(String key, Consumer<Boolean> consumer) {
"""
Associates the given consumer with the given key. This consumer will be invoked every time a Key-Value pair with
the given key is encountered (argument is the Value of the pair). Note that this may be invoked multiple times or
not at all, based on the given input.
@param key The key for which to invoke the consumer.
@param consumer The consumer to invoke.
@return This object instance.
"""
this.extractors.put(key, new Extractor<>(consumer,
value -> {
value = value.trim().toLowerCase();
return value.equals("true") || value.equals("yes") || value.equals("1");
}));
return this;
} | java | public DelimitedStringParser extractBoolean(String key, Consumer<Boolean> consumer) {
this.extractors.put(key, new Extractor<>(consumer,
value -> {
value = value.trim().toLowerCase();
return value.equals("true") || value.equals("yes") || value.equals("1");
}));
return this;
} | [
"public",
"DelimitedStringParser",
"extractBoolean",
"(",
"String",
"key",
",",
"Consumer",
"<",
"Boolean",
">",
"consumer",
")",
"{",
"this",
".",
"extractors",
".",
"put",
"(",
"key",
",",
"new",
"Extractor",
"<>",
"(",
"consumer",
",",
"value",
"->",
"{... | Associates the given consumer with the given key. This consumer will be invoked every time a Key-Value pair with
the given key is encountered (argument is the Value of the pair). Note that this may be invoked multiple times or
not at all, based on the given input.
@param key The key for which to invoke the consumer.
@param consumer The consumer to invoke.
@return This object instance. | [
"Associates",
"the",
"given",
"consumer",
"with",
"the",
"given",
"key",
".",
"This",
"consumer",
"will",
"be",
"invoked",
"every",
"time",
"a",
"Key",
"-",
"Value",
"pair",
"with",
"the",
"given",
"key",
"is",
"encountered",
"(",
"argument",
"is",
"the",
... | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/DelimitedStringParser.java#L129-L136 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java | KeyValueHandler.handleSnappyDecompression | private void handleSnappyDecompression(final ChannelHandlerContext ctx, final FullBinaryMemcacheResponse response) {
"""
Helper method which performs decompression for snappy compressed values.
"""
ByteBuf decompressed;
if (response.content().readableBytes() > 0) {
// we need to copy it on-heap...
byte[] compressed = Unpooled.copiedBuffer(response.content()).array();
try {
decompressed = Unpooled.wrappedBuffer(Snappy.uncompress(compressed, 0, compressed.length));
} catch (Exception ex) {
throw new RuntimeException("Could not decode snappy-compressed value.", ex);
}
} else {
decompressed = Unpooled.buffer(0);
}
response.content().release();
response.setContent(decompressed);
response.setTotalBodyLength(
response.getExtrasLength()
+ response.getKeyLength()
+ decompressed.readableBytes()
);
response.setDataType((byte) (response.getDataType() & ~DATATYPE_SNAPPY));
} | java | private void handleSnappyDecompression(final ChannelHandlerContext ctx, final FullBinaryMemcacheResponse response) {
ByteBuf decompressed;
if (response.content().readableBytes() > 0) {
// we need to copy it on-heap...
byte[] compressed = Unpooled.copiedBuffer(response.content()).array();
try {
decompressed = Unpooled.wrappedBuffer(Snappy.uncompress(compressed, 0, compressed.length));
} catch (Exception ex) {
throw new RuntimeException("Could not decode snappy-compressed value.", ex);
}
} else {
decompressed = Unpooled.buffer(0);
}
response.content().release();
response.setContent(decompressed);
response.setTotalBodyLength(
response.getExtrasLength()
+ response.getKeyLength()
+ decompressed.readableBytes()
);
response.setDataType((byte) (response.getDataType() & ~DATATYPE_SNAPPY));
} | [
"private",
"void",
"handleSnappyDecompression",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"FullBinaryMemcacheResponse",
"response",
")",
"{",
"ByteBuf",
"decompressed",
";",
"if",
"(",
"response",
".",
"content",
"(",
")",
".",
"readableBytes",
"("... | Helper method which performs decompression for snappy compressed values. | [
"Helper",
"method",
"which",
"performs",
"decompression",
"for",
"snappy",
"compressed",
"values",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueHandler.java#L389-L412 |
oasp/oasp4j | modules/logging/src/main/java/io/oasp/module/logging/common/impl/PerformanceLogFilter.java | PerformanceLogFilter.logPerformance | private void logPerformance(ServletResponse response, long startTime, String url, Throwable error) {
"""
Logs the request URL, execution time and {@link HttpStatus}. In case of an error also logs class name and error
message.
@param response - the {@link ServletResponse}
@param startTime - start time of the {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} function
@param url - requested URL
@param error - error thrown by the requested servlet, {@code null} if execution did not cause an error
"""
long endTime, duration;
int statusCode = ((HttpServletResponse) response).getStatus();
endTime = System.nanoTime();
duration = TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS);
String errorClass = "";
String errorMessage = "";
if (error != null) {
statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
errorClass = error.getClass().getName();
errorMessage = error.getMessage();
}
String message =
createMessage(url, Long.toString(duration), Integer.toString(statusCode), errorClass, errorMessage);
LOG.info(message);
} | java | private void logPerformance(ServletResponse response, long startTime, String url, Throwable error) {
long endTime, duration;
int statusCode = ((HttpServletResponse) response).getStatus();
endTime = System.nanoTime();
duration = TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS);
String errorClass = "";
String errorMessage = "";
if (error != null) {
statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
errorClass = error.getClass().getName();
errorMessage = error.getMessage();
}
String message =
createMessage(url, Long.toString(duration), Integer.toString(statusCode), errorClass, errorMessage);
LOG.info(message);
} | [
"private",
"void",
"logPerformance",
"(",
"ServletResponse",
"response",
",",
"long",
"startTime",
",",
"String",
"url",
",",
"Throwable",
"error",
")",
"{",
"long",
"endTime",
",",
"duration",
";",
"int",
"statusCode",
"=",
"(",
"(",
"HttpServletResponse",
")... | Logs the request URL, execution time and {@link HttpStatus}. In case of an error also logs class name and error
message.
@param response - the {@link ServletResponse}
@param startTime - start time of the {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} function
@param url - requested URL
@param error - error thrown by the requested servlet, {@code null} if execution did not cause an error | [
"Logs",
"the",
"request",
"URL",
"execution",
"time",
"and",
"{",
"@link",
"HttpStatus",
"}",
".",
"In",
"case",
"of",
"an",
"error",
"also",
"logs",
"class",
"name",
"and",
"error",
"message",
"."
] | train | https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/logging/src/main/java/io/oasp/module/logging/common/impl/PerformanceLogFilter.java#L78-L95 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java | CPOptionValuePersistenceImpl.removeByC_K | @Override
public CPOptionValue removeByC_K(long CPOptionId, String key)
throws NoSuchCPOptionValueException {
"""
Removes the cp option value where CPOptionId = ? and key = ? from the database.
@param CPOptionId the cp option ID
@param key the key
@return the cp option value that was removed
"""
CPOptionValue cpOptionValue = findByC_K(CPOptionId, key);
return remove(cpOptionValue);
} | java | @Override
public CPOptionValue removeByC_K(long CPOptionId, String key)
throws NoSuchCPOptionValueException {
CPOptionValue cpOptionValue = findByC_K(CPOptionId, key);
return remove(cpOptionValue);
} | [
"@",
"Override",
"public",
"CPOptionValue",
"removeByC_K",
"(",
"long",
"CPOptionId",
",",
"String",
"key",
")",
"throws",
"NoSuchCPOptionValueException",
"{",
"CPOptionValue",
"cpOptionValue",
"=",
"findByC_K",
"(",
"CPOptionId",
",",
"key",
")",
";",
"return",
"... | Removes the cp option value where CPOptionId = ? and key = ? from the database.
@param CPOptionId the cp option ID
@param key the key
@return the cp option value that was removed | [
"Removes",
"the",
"cp",
"option",
"value",
"where",
"CPOptionId",
"=",
"?",
";",
"and",
"key",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPOptionValuePersistenceImpl.java#L3171-L3177 |
micrometer-metrics/micrometer | micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java | MeterRegistry.gaugeCollectionSize | @Nullable
public <T extends Collection<?>> T gaugeCollectionSize(String name, Iterable<Tag> tags, T collection) {
"""
Register a gauge that reports the size of the {@link Collection}. The registration
will keep a weak reference to the collection so it will not prevent garbage collection.
The collection implementation used should be thread safe. Note that calling
{@link Collection#size()} can be expensive for some collection implementations
and should be considered before registering.
@param name Name of the gauge being registered.
@param tags Sequence of dimensions for breaking down the name.
@param collection Thread-safe implementation of {@link Collection} used to access the value.
@param <T> The type of the state object from which the gauge value is extracted.
@return The number that was passed in so the registration can be done as part of an assignment
statement.
"""
return gauge(name, tags, collection, Collection::size);
} | java | @Nullable
public <T extends Collection<?>> T gaugeCollectionSize(String name, Iterable<Tag> tags, T collection) {
return gauge(name, tags, collection, Collection::size);
} | [
"@",
"Nullable",
"public",
"<",
"T",
"extends",
"Collection",
"<",
"?",
">",
">",
"T",
"gaugeCollectionSize",
"(",
"String",
"name",
",",
"Iterable",
"<",
"Tag",
">",
"tags",
",",
"T",
"collection",
")",
"{",
"return",
"gauge",
"(",
"name",
",",
"tags"... | Register a gauge that reports the size of the {@link Collection}. The registration
will keep a weak reference to the collection so it will not prevent garbage collection.
The collection implementation used should be thread safe. Note that calling
{@link Collection#size()} can be expensive for some collection implementations
and should be considered before registering.
@param name Name of the gauge being registered.
@param tags Sequence of dimensions for breaking down the name.
@param collection Thread-safe implementation of {@link Collection} used to access the value.
@param <T> The type of the state object from which the gauge value is extracted.
@return The number that was passed in so the registration can be done as part of an assignment
statement. | [
"Register",
"a",
"gauge",
"that",
"reports",
"the",
"size",
"of",
"the",
"{",
"@link",
"Collection",
"}",
".",
"The",
"registration",
"will",
"keep",
"a",
"weak",
"reference",
"to",
"the",
"collection",
"so",
"it",
"will",
"not",
"prevent",
"garbage",
"col... | train | https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/MeterRegistry.java#L496-L499 |
hltcoe/annotated-nyt | src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java | NYTCorpusDocumentParser.getDOMObject | private Document getDOMObject(String filename, boolean validating)
throws SAXException, IOException, ParserConfigurationException {
"""
Parse a file containing an XML document, into a DOM object.
@param filename
A path to a valid file.
@param validating
True iff validating should be turned on.
@return A DOM Object containing a parsed XML document or a null value if
there is an error in parsing.
@throws ParserConfigurationException
@throws IOException
@throws SAXException
"""
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
if (!validating) {
factory.setValidating(validating);
factory.setSchema(null);
factory.setNamespaceAware(false);
}
DocumentBuilder builder = factory.newDocumentBuilder();
// Create the builder and parse the file
Document doc = builder.parse(new File(filename));
return doc;
} | java | private Document getDOMObject(String filename, boolean validating)
throws SAXException, IOException, ParserConfigurationException {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
if (!validating) {
factory.setValidating(validating);
factory.setSchema(null);
factory.setNamespaceAware(false);
}
DocumentBuilder builder = factory.newDocumentBuilder();
// Create the builder and parse the file
Document doc = builder.parse(new File(filename));
return doc;
} | [
"private",
"Document",
"getDOMObject",
"(",
"String",
"filename",
",",
"boolean",
"validating",
")",
"throws",
"SAXException",
",",
"IOException",
",",
"ParserConfigurationException",
"{",
"// Create a builder factory",
"DocumentBuilderFactory",
"factory",
"=",
"DocumentBui... | Parse a file containing an XML document, into a DOM object.
@param filename
A path to a valid file.
@param validating
True iff validating should be turned on.
@return A DOM Object containing a parsed XML document or a null value if
there is an error in parsing.
@throws ParserConfigurationException
@throws IOException
@throws SAXException | [
"Parse",
"a",
"file",
"containing",
"an",
"XML",
"document",
"into",
"a",
"DOM",
"object",
"."
] | train | https://github.com/hltcoe/annotated-nyt/blob/0a4daa97705591cefea9de61614770ae2665a48e/src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java#L942-L958 |
FedericoPecora/meta-csp-framework | src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java | TrajectoryEnvelope.getGroundEnvelopes | public TreeSet<TrajectoryEnvelope> getGroundEnvelopes() {
"""
Get the ground {@link TrajectoryEnvelope}s of this {@link TrajectoryEnvelope}, ordered
by increasing start time.
@return The ground {@link TrajectoryEnvelope}s of this {@link TrajectoryEnvelope}.
"""
TreeSet<TrajectoryEnvelope> ret = new TreeSet<TrajectoryEnvelope>(new Comparator<TrajectoryEnvelope>() {
@Override
public int compare(TrajectoryEnvelope o1, TrajectoryEnvelope o2) {
Bounds o1b = new Bounds(o1.getTemporalVariable().getEST(),o1.getTemporalVariable().getEET());
Bounds o2b = new Bounds(o2.getTemporalVariable().getEST(),o2.getTemporalVariable().getEET());
if (o2b.min-o1b.min > 0) return -1;
else if (o2b.min-o1b.min == 0) return 0;
return 1;
}
});
if (this.getSubEnvelopes() != null) {
for (TrajectoryEnvelope te : this.getSubEnvelopes()) {
ret.addAll(te.getGroundEnvelopes());
}
}
else ret.add(this);
return ret;
} | java | public TreeSet<TrajectoryEnvelope> getGroundEnvelopes() {
TreeSet<TrajectoryEnvelope> ret = new TreeSet<TrajectoryEnvelope>(new Comparator<TrajectoryEnvelope>() {
@Override
public int compare(TrajectoryEnvelope o1, TrajectoryEnvelope o2) {
Bounds o1b = new Bounds(o1.getTemporalVariable().getEST(),o1.getTemporalVariable().getEET());
Bounds o2b = new Bounds(o2.getTemporalVariable().getEST(),o2.getTemporalVariable().getEET());
if (o2b.min-o1b.min > 0) return -1;
else if (o2b.min-o1b.min == 0) return 0;
return 1;
}
});
if (this.getSubEnvelopes() != null) {
for (TrajectoryEnvelope te : this.getSubEnvelopes()) {
ret.addAll(te.getGroundEnvelopes());
}
}
else ret.add(this);
return ret;
} | [
"public",
"TreeSet",
"<",
"TrajectoryEnvelope",
">",
"getGroundEnvelopes",
"(",
")",
"{",
"TreeSet",
"<",
"TrajectoryEnvelope",
">",
"ret",
"=",
"new",
"TreeSet",
"<",
"TrajectoryEnvelope",
">",
"(",
"new",
"Comparator",
"<",
"TrajectoryEnvelope",
">",
"(",
")",... | Get the ground {@link TrajectoryEnvelope}s of this {@link TrajectoryEnvelope}, ordered
by increasing start time.
@return The ground {@link TrajectoryEnvelope}s of this {@link TrajectoryEnvelope}. | [
"Get",
"the",
"ground",
"{"
] | train | https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java#L263-L281 |
pryzach/midao | midao-jdbc-core/src/main/java/org/midao/jdbc/core/AbstractQueryRunner.java | AbstractQueryRunner.convertToQueryInputHandler | protected QueryInputHandler convertToQueryInputHandler(AbstractNamedInputHandler inputHandler, String catalog, String schema, boolean useCache) throws SQLException {
"""
Uses {@link MetadataHandler} to read Stored Procedure/Function parameters and creates new
{@link QueryInputHandler} instance with parameter values from @inputHandler
@param inputHandler {@link AbstractNamedInputHandler} which used as source for {@link QueryInputHandler}
parameter values
@param catalog Database Catalog
@param schema Database Schema
@param useCache specifies if {@link MetadataHandler} should use cache
@return new filled {@link QueryInputHandler} instance with values from @inputHandler
@throws SQLException if exception would be thrown by Driver/Database
"""
QueryInputHandler result = null;
String shortProcedureName = CallableUtils.getStoredProcedureShortNameFromSql(inputHandler.getEncodedQueryString());
boolean expectedReturn = CallableUtils.isFunctionCall(inputHandler.getEncodedQueryString());
Connection conn = this.transactionHandler.getConnection();
try {
//QueryParameters procedureParams = SimpleMetaDataFactory.getProcedureParameters(conn, catalog, schema, shortProcedureName, useCache);
QueryParameters procedureParams = this.metadataHandler.getProcedureParameters(conn, catalog, schema, shortProcedureName, useCache);
QueryParameters inputParams = inputHandler.getQueryParameters();
String encodedSql = inputHandler.getEncodedQueryString();
// trying to detect if user omitted return, but database returned it.
if (expectedReturn == false && (procedureParams.orderSize() == inputParams.orderSize() + 1)) {
for (String parameterName : procedureParams.keySet()) {
if (procedureParams.getDirection(parameterName) == QueryParameters.Direction.RETURN) {
procedureParams.remove(parameterName);
break;
}
}
}
if (procedureParams.orderSize() != inputParams.orderSize()) {
throw new MjdbcSQLException(String.format("Database reported %d parameters, but only %d were supplied.", procedureParams.orderSize(), inputParams.orderSize()));
}
inputParams = CallableUtils.updateDirections(inputParams, procedureParams);
inputParams = CallableUtils.updateTypes(inputParams, procedureParams);
result = new QueryInputHandler(encodedSql, inputParams);
} finally {
this.transactionHandler.closeConnection();
}
return result;
} | java | protected QueryInputHandler convertToQueryInputHandler(AbstractNamedInputHandler inputHandler, String catalog, String schema, boolean useCache) throws SQLException {
QueryInputHandler result = null;
String shortProcedureName = CallableUtils.getStoredProcedureShortNameFromSql(inputHandler.getEncodedQueryString());
boolean expectedReturn = CallableUtils.isFunctionCall(inputHandler.getEncodedQueryString());
Connection conn = this.transactionHandler.getConnection();
try {
//QueryParameters procedureParams = SimpleMetaDataFactory.getProcedureParameters(conn, catalog, schema, shortProcedureName, useCache);
QueryParameters procedureParams = this.metadataHandler.getProcedureParameters(conn, catalog, schema, shortProcedureName, useCache);
QueryParameters inputParams = inputHandler.getQueryParameters();
String encodedSql = inputHandler.getEncodedQueryString();
// trying to detect if user omitted return, but database returned it.
if (expectedReturn == false && (procedureParams.orderSize() == inputParams.orderSize() + 1)) {
for (String parameterName : procedureParams.keySet()) {
if (procedureParams.getDirection(parameterName) == QueryParameters.Direction.RETURN) {
procedureParams.remove(parameterName);
break;
}
}
}
if (procedureParams.orderSize() != inputParams.orderSize()) {
throw new MjdbcSQLException(String.format("Database reported %d parameters, but only %d were supplied.", procedureParams.orderSize(), inputParams.orderSize()));
}
inputParams = CallableUtils.updateDirections(inputParams, procedureParams);
inputParams = CallableUtils.updateTypes(inputParams, procedureParams);
result = new QueryInputHandler(encodedSql, inputParams);
} finally {
this.transactionHandler.closeConnection();
}
return result;
} | [
"protected",
"QueryInputHandler",
"convertToQueryInputHandler",
"(",
"AbstractNamedInputHandler",
"inputHandler",
",",
"String",
"catalog",
",",
"String",
"schema",
",",
"boolean",
"useCache",
")",
"throws",
"SQLException",
"{",
"QueryInputHandler",
"result",
"=",
"null",... | Uses {@link MetadataHandler} to read Stored Procedure/Function parameters and creates new
{@link QueryInputHandler} instance with parameter values from @inputHandler
@param inputHandler {@link AbstractNamedInputHandler} which used as source for {@link QueryInputHandler}
parameter values
@param catalog Database Catalog
@param schema Database Schema
@param useCache specifies if {@link MetadataHandler} should use cache
@return new filled {@link QueryInputHandler} instance with values from @inputHandler
@throws SQLException if exception would be thrown by Driver/Database | [
"Uses",
"{",
"@link",
"MetadataHandler",
"}",
"to",
"read",
"Stored",
"Procedure",
"/",
"Function",
"parameters",
"and",
"creates",
"new",
"{",
"@link",
"QueryInputHandler",
"}",
"instance",
"with",
"parameter",
"values",
"from",
"@inputHandler"
] | train | https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/AbstractQueryRunner.java#L1053-L1092 |
konvergeio/cofoja | src/main/java/com/google/java/contract/util/Predicates.java | Predicates.anyEntry | public static <K, V> Predicate<Map<K, V>> anyEntry(
Predicate<? super Map.Entry<K, V>> p) {
"""
Returns a predicate that applies {@code any(p)} to the entries of
its argument.
"""
return forEntries(Predicates.<Map.Entry<K, V>>any(p));
} | java | public static <K, V> Predicate<Map<K, V>> anyEntry(
Predicate<? super Map.Entry<K, V>> p) {
return forEntries(Predicates.<Map.Entry<K, V>>any(p));
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"Predicate",
"<",
"Map",
"<",
"K",
",",
"V",
">",
">",
"anyEntry",
"(",
"Predicate",
"<",
"?",
"super",
"Map",
".",
"Entry",
"<",
"K",
",",
"V",
">",
">",
"p",
")",
"{",
"return",
"forEntries",
"(",
... | Returns a predicate that applies {@code any(p)} to the entries of
its argument. | [
"Returns",
"a",
"predicate",
"that",
"applies",
"{"
] | train | https://github.com/konvergeio/cofoja/blob/6ded58fa05eb5bf85f16353c8dd4c70bee59121a/src/main/java/com/google/java/contract/util/Predicates.java#L282-L285 |
wuman/TwoLevelLruCache | src/main/java/com/wuman/twolevellrucache/TwoLevelLruCache.java | TwoLevelLruCache.put | public final V put(String key, V newValue) {
"""
Caches {@code newValue} for {@code key}.
@param key
@param newValue
@return oldValue
"""
V oldValue = mMemCache.put(key, newValue);
putToDiskQuietly(key, newValue);
return oldValue;
} | java | public final V put(String key, V newValue) {
V oldValue = mMemCache.put(key, newValue);
putToDiskQuietly(key, newValue);
return oldValue;
} | [
"public",
"final",
"V",
"put",
"(",
"String",
"key",
",",
"V",
"newValue",
")",
"{",
"V",
"oldValue",
"=",
"mMemCache",
".",
"put",
"(",
"key",
",",
"newValue",
")",
";",
"putToDiskQuietly",
"(",
"key",
",",
"newValue",
")",
";",
"return",
"oldValue",
... | Caches {@code newValue} for {@code key}.
@param key
@param newValue
@return oldValue | [
"Caches",
"{",
"@code",
"newValue",
"}",
"for",
"{",
"@code",
"key",
"}",
"."
] | train | https://github.com/wuman/TwoLevelLruCache/blob/3075004ab9be23310182d4dc22b9278f16caf063/src/main/java/com/wuman/twolevellrucache/TwoLevelLruCache.java#L185-L189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.