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 |
|---|---|---|---|---|---|---|---|---|---|---|
dustin/java-memcached-client | src/main/java/net/spy/memcached/tapmessage/RequestMessage.java | RequestMessage.setvBucketCheckpoints | public void setvBucketCheckpoints(Map<Short, Long> vbchkpnts) {
"""
Sets a map of vbucket checkpoints.
@param vbchkpnts - A map of vbucket checkpoint identifiers
"""
int oldSize = (vBucketCheckpoints.size()) * 10;
int newSize = (vbchkpnts.size()) * 10;
totalbody += newSize - oldSize;
vBucketCheckpoints = vbchkpnts;
} | java | public void setvBucketCheckpoints(Map<Short, Long> vbchkpnts) {
int oldSize = (vBucketCheckpoints.size()) * 10;
int newSize = (vbchkpnts.size()) * 10;
totalbody += newSize - oldSize;
vBucketCheckpoints = vbchkpnts;
} | [
"public",
"void",
"setvBucketCheckpoints",
"(",
"Map",
"<",
"Short",
",",
"Long",
">",
"vbchkpnts",
")",
"{",
"int",
"oldSize",
"=",
"(",
"vBucketCheckpoints",
".",
"size",
"(",
")",
")",
"*",
"10",
";",
"int",
"newSize",
"=",
"(",
"vbchkpnts",
".",
"s... | Sets a map of vbucket checkpoints.
@param vbchkpnts - A map of vbucket checkpoint identifiers | [
"Sets",
"a",
"map",
"of",
"vbucket",
"checkpoints",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/tapmessage/RequestMessage.java#L125-L130 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/octracker/ConnectionDataGroup.java | ConnectionDataGroup.connectOverNetwork | private NetworkConnection connectOverNetwork(JFapAddressHolder addressHolder, NetworkConnectionFactoryHolder factoryHolder) throws JFapConnectFailedException, FrameworkException {
"""
Create a new connection over the network
@param addressHolder The holder from which to obtain the jfap address (if any) over which to connect
@param factoryHolder The holder from which to get the a network connection factory (from which the virtual connection can be obtained)
@return NetworkConnection the network connection that was created
@throws FrameworkException if no network connection can be created
@throws JFapConnectFailedException if the connection fail
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "connectOverNetwork", new Object[] { addressHolder, factoryHolder });
NetworkConnectionFactory vcf = factoryHolder.getFactory();
NetworkConnection vc = vcf.createConnection();
Semaphore sem = new Semaphore();
ClientConnectionReadyCallback callback = new ClientConnectionReadyCallback(sem);
vc.connectAsynch(addressHolder.getAddress(), callback);
sem.waitOnIgnoringInterruptions();
if (!callback.connectionSucceeded())
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(this, tc, "Connect has failed due to ", callback.getException());
String failureKey;
Object[] failureInserts;
if (addressHolder.getAddress() != null)
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0063";
failureInserts = addressHolder.getErrorInserts();
}
else
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0080";
failureInserts = new Object[] {};
}
String message = nls.getFormattedMessage(failureKey, failureInserts, failureKey);
throw new JFapConnectFailedException(message, callback.getException());
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "connectOverNetwork", vc);
return vc;
} | java | private NetworkConnection connectOverNetwork(JFapAddressHolder addressHolder, NetworkConnectionFactoryHolder factoryHolder) throws JFapConnectFailedException, FrameworkException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "connectOverNetwork", new Object[] { addressHolder, factoryHolder });
NetworkConnectionFactory vcf = factoryHolder.getFactory();
NetworkConnection vc = vcf.createConnection();
Semaphore sem = new Semaphore();
ClientConnectionReadyCallback callback = new ClientConnectionReadyCallback(sem);
vc.connectAsynch(addressHolder.getAddress(), callback);
sem.waitOnIgnoringInterruptions();
if (!callback.connectionSucceeded())
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(this, tc, "Connect has failed due to ", callback.getException());
String failureKey;
Object[] failureInserts;
if (addressHolder.getAddress() != null)
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0063";
failureInserts = addressHolder.getErrorInserts();
}
else
{
failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0080";
failureInserts = new Object[] {};
}
String message = nls.getFormattedMessage(failureKey, failureInserts, failureKey);
throw new JFapConnectFailedException(message, callback.getException());
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "connectOverNetwork", vc);
return vc;
} | [
"private",
"NetworkConnection",
"connectOverNetwork",
"(",
"JFapAddressHolder",
"addressHolder",
",",
"NetworkConnectionFactoryHolder",
"factoryHolder",
")",
"throws",
"JFapConnectFailedException",
",",
"FrameworkException",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingE... | Create a new connection over the network
@param addressHolder The holder from which to obtain the jfap address (if any) over which to connect
@param factoryHolder The holder from which to get the a network connection factory (from which the virtual connection can be obtained)
@return NetworkConnection the network connection that was created
@throws FrameworkException if no network connection can be created
@throws JFapConnectFailedException if the connection fail | [
"Create",
"a",
"new",
"connection",
"over",
"the",
"network"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/octracker/ConnectionDataGroup.java#L752-L791 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java | FactoryKernel.random1D_I32 | public static Kernel1D_S32 random1D_I32(int width , int offset, int min, int max, Random rand) {
"""
Creates a random 1D kernel drawn from a uniform distribution.
@param width Kernel's width.
@param offset Offset for element zero in the kernel
@param min minimum value.
@param max maximum value.
@param rand Random number generator.
@return Randomized kernel.
"""
Kernel1D_S32 ret = new Kernel1D_S32(width,offset);
int range = max - min;
for (int i = 0; i < ret.data.length; i++) {
ret.data[i] = rand.nextInt(range) + min;
}
return ret;
} | java | public static Kernel1D_S32 random1D_I32(int width , int offset, int min, int max, Random rand) {
Kernel1D_S32 ret = new Kernel1D_S32(width,offset);
int range = max - min;
for (int i = 0; i < ret.data.length; i++) {
ret.data[i] = rand.nextInt(range) + min;
}
return ret;
} | [
"public",
"static",
"Kernel1D_S32",
"random1D_I32",
"(",
"int",
"width",
",",
"int",
"offset",
",",
"int",
"min",
",",
"int",
"max",
",",
"Random",
"rand",
")",
"{",
"Kernel1D_S32",
"ret",
"=",
"new",
"Kernel1D_S32",
"(",
"width",
",",
"offset",
")",
";"... | Creates a random 1D kernel drawn from a uniform distribution.
@param width Kernel's width.
@param offset Offset for element zero in the kernel
@param min minimum value.
@param max maximum value.
@param rand Random number generator.
@return Randomized kernel. | [
"Creates",
"a",
"random",
"1D",
"kernel",
"drawn",
"from",
"a",
"uniform",
"distribution",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/factory/filter/kernel/FactoryKernel.java#L223-L232 |
Frostman/dropbox4j | src/main/java/ru/frostman/dropbox/api/DropboxClient.java | DropboxClient.createFolder | public Entry createFolder(String path) {
"""
Create folder with specified path.
@param path to create
@return metadata of created folder
@see Entry
"""
OAuthRequest request = new OAuthRequest(Verb.GET, FILE_OPS_CREATE_FOLDER_URL);
request.addQuerystringParameter("root", "dropbox");
request.addQuerystringParameter("path", encode(path));
service.signRequest(accessToken, request);
String content = checkCreateFolder(request.send()).getBody();
return Json.parse(content, Entry.class);
} | java | public Entry createFolder(String path) {
OAuthRequest request = new OAuthRequest(Verb.GET, FILE_OPS_CREATE_FOLDER_URL);
request.addQuerystringParameter("root", "dropbox");
request.addQuerystringParameter("path", encode(path));
service.signRequest(accessToken, request);
String content = checkCreateFolder(request.send()).getBody();
return Json.parse(content, Entry.class);
} | [
"public",
"Entry",
"createFolder",
"(",
"String",
"path",
")",
"{",
"OAuthRequest",
"request",
"=",
"new",
"OAuthRequest",
"(",
"Verb",
".",
"GET",
",",
"FILE_OPS_CREATE_FOLDER_URL",
")",
";",
"request",
".",
"addQuerystringParameter",
"(",
"\"root\"",
",",
"\"d... | Create folder with specified path.
@param path to create
@return metadata of created folder
@see Entry | [
"Create",
"folder",
"with",
"specified",
"path",
"."
] | train | https://github.com/Frostman/dropbox4j/blob/774c817e5bf294d0139ecb5ac81399be50ada5e0/src/main/java/ru/frostman/dropbox/api/DropboxClient.java#L258-L267 |
motown-io/motown | operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/ChargingStationEventListener.java | ChargingStationEventListener.updateChargingStationAvailability | private void updateChargingStationAvailability(ChargingStationId chargingStationId, Availability availability) {
"""
Updates the charging station's availability.
@param chargingStationId the charging station's id.
@param availability the charging station's new availability.
"""
ChargingStation chargingStation = repository.findOne(chargingStationId.getId());
if (chargingStation != null) {
chargingStation.setAvailability(availability);
repository.createOrUpdate(chargingStation);
}
} | java | private void updateChargingStationAvailability(ChargingStationId chargingStationId, Availability availability) {
ChargingStation chargingStation = repository.findOne(chargingStationId.getId());
if (chargingStation != null) {
chargingStation.setAvailability(availability);
repository.createOrUpdate(chargingStation);
}
} | [
"private",
"void",
"updateChargingStationAvailability",
"(",
"ChargingStationId",
"chargingStationId",
",",
"Availability",
"availability",
")",
"{",
"ChargingStation",
"chargingStation",
"=",
"repository",
".",
"findOne",
"(",
"chargingStationId",
".",
"getId",
"(",
")",... | Updates the charging station's availability.
@param chargingStationId the charging station's id.
@param availability the charging station's new availability. | [
"Updates",
"the",
"charging",
"station",
"s",
"availability",
"."
] | train | https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/operator-api/view-model/src/main/java/io/motown/operatorapi/viewmodel/ChargingStationEventListener.java#L366-L373 |
threerings/narya | core/src/main/java/com/threerings/presents/peer/server/PeerManager.java | PeerManager.peerReleasingLock | protected void peerReleasingLock (PeerNode peer, NodeObject.Lock lock) {
"""
Called when a peer announces its intention to release a lock.
"""
// refuse to ratify if we don't believe they own the lock
String owner = queryLock(lock);
if (!peer.getNodeName().equals(owner)) {
log.warning("Refusing to ratify lock release.", "lock", lock,
"node", peer.getNodeName(), "owner", owner);
return;
}
// check for an existing handler
LockHandler handler = _locks.get(lock);
if (handler == null) {
createLockHandler(peer, lock, false);
} else {
log.warning("Received request to release resolving lock",
"node", peer.getNodeName(), "handler", handler);
}
} | java | protected void peerReleasingLock (PeerNode peer, NodeObject.Lock lock)
{
// refuse to ratify if we don't believe they own the lock
String owner = queryLock(lock);
if (!peer.getNodeName().equals(owner)) {
log.warning("Refusing to ratify lock release.", "lock", lock,
"node", peer.getNodeName(), "owner", owner);
return;
}
// check for an existing handler
LockHandler handler = _locks.get(lock);
if (handler == null) {
createLockHandler(peer, lock, false);
} else {
log.warning("Received request to release resolving lock",
"node", peer.getNodeName(), "handler", handler);
}
} | [
"protected",
"void",
"peerReleasingLock",
"(",
"PeerNode",
"peer",
",",
"NodeObject",
".",
"Lock",
"lock",
")",
"{",
"// refuse to ratify if we don't believe they own the lock",
"String",
"owner",
"=",
"queryLock",
"(",
"lock",
")",
";",
"if",
"(",
"!",
"peer",
".... | Called when a peer announces its intention to release a lock. | [
"Called",
"when",
"a",
"peer",
"announces",
"its",
"intention",
"to",
"release",
"a",
"lock",
"."
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/PeerManager.java#L1447-L1465 |
tvesalainen/util | util/src/main/java/org/vesalainen/util/AbstractProvisioner.java | AbstractProvisioner.setValue | public void setValue(String name, Object value) {
"""
Provides value for attached method
@param name From @Setting
@param value
"""
map.get(name).stream().forEach((im) ->
{
im.invoke(value);
} | java | public void setValue(String name, Object value)
{
map.get(name).stream().forEach((im) ->
{
im.invoke(value);
} | [
"public",
"void",
"setValue",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"map",
".",
"get",
"(",
"name",
")",
".",
"stream",
"(",
")",
".",
"forEach",
"(",
"(",
"im",
")",
"-",
">",
"{",
"im",
".",
"invoke",
"(",
"value",
")",
"",... | Provides value for attached method
@param name From @Setting
@param value | [
"Provides",
"value",
"for",
"attached",
"method"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/AbstractProvisioner.java#L153-L158 |
alipay/sofa-hessian | src/main/java/com/caucho/hessian/io/Hessian2Output.java | Hessian2Output.printString | public void printString(String v, int strOffset, int length)
throws IOException {
"""
Prints a string to the stream, encoded as UTF-8
@param v the string to print.
"""
int offset = _offset;
byte[] buffer = _buffer;
for (int i = 0; i < length; i++) {
if (SIZE <= offset + 16) {
_offset = offset;
flushBuffer();
offset = _offset;
}
char ch = v.charAt(i + strOffset);
if (ch < 0x80)
buffer[offset++] = (byte) (ch);
else if (ch < 0x800) {
buffer[offset++] = (byte) (0xc0 + ((ch >> 6) & 0x1f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
else {
buffer[offset++] = (byte) (0xe0 + ((ch >> 12) & 0xf));
buffer[offset++] = (byte) (0x80 + ((ch >> 6) & 0x3f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
}
_offset = offset;
} | java | public void printString(String v, int strOffset, int length)
throws IOException
{
int offset = _offset;
byte[] buffer = _buffer;
for (int i = 0; i < length; i++) {
if (SIZE <= offset + 16) {
_offset = offset;
flushBuffer();
offset = _offset;
}
char ch = v.charAt(i + strOffset);
if (ch < 0x80)
buffer[offset++] = (byte) (ch);
else if (ch < 0x800) {
buffer[offset++] = (byte) (0xc0 + ((ch >> 6) & 0x1f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
else {
buffer[offset++] = (byte) (0xe0 + ((ch >> 12) & 0xf));
buffer[offset++] = (byte) (0x80 + ((ch >> 6) & 0x3f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
}
_offset = offset;
} | [
"public",
"void",
"printString",
"(",
"String",
"v",
",",
"int",
"strOffset",
",",
"int",
"length",
")",
"throws",
"IOException",
"{",
"int",
"offset",
"=",
"_offset",
";",
"byte",
"[",
"]",
"buffer",
"=",
"_buffer",
";",
"for",
"(",
"int",
"i",
"=",
... | Prints a string to the stream, encoded as UTF-8
@param v the string to print. | [
"Prints",
"a",
"string",
"to",
"the",
"stream",
"encoded",
"as",
"UTF",
"-",
"8"
] | train | https://github.com/alipay/sofa-hessian/blob/89e4f5af28602101dab7b498995018871616357b/src/main/java/com/caucho/hessian/io/Hessian2Output.java#L1529-L1558 |
mcxiaoke/Android-Next | recycler/src/main/java/com/mcxiaoke/next/recycler/HeaderFooterRecyclerAdapter.java | HeaderFooterRecyclerAdapter.notifyFooterItemRangeInserted | public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {
"""
Notifies that multiple footer items are inserted.
@param positionStart the position.
@param itemCount the item count.
"""
int newHeaderItemCount = getHeaderItemCount();
int newContentItemCount = getContentItemCount();
int newFooterItemCount = getFooterItemCount();
if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {
throw new IndexOutOfBoundsException("The given range [" + positionStart + " - "
+ (positionStart + itemCount - 1) + "] is not within the position bounds for footer items [0 - "
+ (newFooterItemCount - 1) + "].");
}
notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);
} | java | public final void notifyFooterItemRangeInserted(int positionStart, int itemCount) {
int newHeaderItemCount = getHeaderItemCount();
int newContentItemCount = getContentItemCount();
int newFooterItemCount = getFooterItemCount();
if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newFooterItemCount) {
throw new IndexOutOfBoundsException("The given range [" + positionStart + " - "
+ (positionStart + itemCount - 1) + "] is not within the position bounds for footer items [0 - "
+ (newFooterItemCount - 1) + "].");
}
notifyItemRangeInserted(positionStart + newHeaderItemCount + newContentItemCount, itemCount);
} | [
"public",
"final",
"void",
"notifyFooterItemRangeInserted",
"(",
"int",
"positionStart",
",",
"int",
"itemCount",
")",
"{",
"int",
"newHeaderItemCount",
"=",
"getHeaderItemCount",
"(",
")",
";",
"int",
"newContentItemCount",
"=",
"getContentItemCount",
"(",
")",
";"... | Notifies that multiple footer items are inserted.
@param positionStart the position.
@param itemCount the item count. | [
"Notifies",
"that",
"multiple",
"footer",
"items",
"are",
"inserted",
"."
] | train | https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/recycler/src/main/java/com/mcxiaoke/next/recycler/HeaderFooterRecyclerAdapter.java#L329-L339 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMaterial.java | AiMaterial.getBlendFactor | public float getBlendFactor(AiTextureType type, int index) {
"""
Returns the blend factor of the texture.<p>
If missing, defaults to 1.0
@param type the texture type
@param index the index in the texture stack
@return the blend factor
"""
checkTexRange(type, index);
return getTyped(PropertyKey.TEX_BLEND, type, index, Float.class);
} | java | public float getBlendFactor(AiTextureType type, int index) {
checkTexRange(type, index);
return getTyped(PropertyKey.TEX_BLEND, type, index, Float.class);
} | [
"public",
"float",
"getBlendFactor",
"(",
"AiTextureType",
"type",
",",
"int",
"index",
")",
"{",
"checkTexRange",
"(",
"type",
",",
"index",
")",
";",
"return",
"getTyped",
"(",
"PropertyKey",
".",
"TEX_BLEND",
",",
"type",
",",
"index",
",",
"Float",
"."... | Returns the blend factor of the texture.<p>
If missing, defaults to 1.0
@param type the texture type
@param index the index in the texture stack
@return the blend factor | [
"Returns",
"the",
"blend",
"factor",
"of",
"the",
"texture",
".",
"<p",
">"
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/jassimp/AiMaterial.java#L939-L943 |
gallandarakhneorg/afc | advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/dfx/Segment3dfx.java | Segment3dfx.z2Property | @Pure
public DoubleProperty z2Property() {
"""
Replies the property that is the z coordinate of the second segment point.
@return the z2 property.
"""
if (this.p2.z == null) {
this.p2.z = new SimpleDoubleProperty(this, MathFXAttributeNames.Z2);
}
return this.p2.z;
} | java | @Pure
public DoubleProperty z2Property() {
if (this.p2.z == null) {
this.p2.z = new SimpleDoubleProperty(this, MathFXAttributeNames.Z2);
}
return this.p2.z;
} | [
"@",
"Pure",
"public",
"DoubleProperty",
"z2Property",
"(",
")",
"{",
"if",
"(",
"this",
".",
"p2",
".",
"z",
"==",
"null",
")",
"{",
"this",
".",
"p2",
".",
"z",
"=",
"new",
"SimpleDoubleProperty",
"(",
"this",
",",
"MathFXAttributeNames",
".",
"Z2",
... | Replies the property that is the z coordinate of the second segment point.
@return the z2 property. | [
"Replies",
"the",
"property",
"that",
"is",
"the",
"z",
"coordinate",
"of",
"the",
"second",
"segment",
"point",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/dfx/Segment3dfx.java#L295-L301 |
JodaOrg/joda-time | src/main/java/org/joda/time/field/FieldUtils.java | FieldUtils.safeSubtract | public static long safeSubtract(long val1, long val2) {
"""
Subtracts two values throwing an exception if overflow occurs.
@param val1 the first value, to be taken away from
@param val2 the second value, the amount to take away
@return the new total
@throws ArithmeticException if the value is too big or too small
"""
long diff = val1 - val2;
// If there is a sign change, but the two values have different signs...
if ((val1 ^ diff) < 0 && (val1 ^ val2) < 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " - " + val2);
}
return diff;
} | java | public static long safeSubtract(long val1, long val2) {
long diff = val1 - val2;
// If there is a sign change, but the two values have different signs...
if ((val1 ^ diff) < 0 && (val1 ^ val2) < 0) {
throw new ArithmeticException
("The calculation caused an overflow: " + val1 + " - " + val2);
}
return diff;
} | [
"public",
"static",
"long",
"safeSubtract",
"(",
"long",
"val1",
",",
"long",
"val2",
")",
"{",
"long",
"diff",
"=",
"val1",
"-",
"val2",
";",
"// If there is a sign change, but the two values have different signs...",
"if",
"(",
"(",
"val1",
"^",
"diff",
")",
"... | Subtracts two values throwing an exception if overflow occurs.
@param val1 the first value, to be taken away from
@param val2 the second value, the amount to take away
@return the new total
@throws ArithmeticException if the value is too big or too small | [
"Subtracts",
"two",
"values",
"throwing",
"an",
"exception",
"if",
"overflow",
"occurs",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/field/FieldUtils.java#L102-L110 |
threerings/narya | core/src/main/java/com/threerings/presents/peer/server/PeerManager.java | PeerManager.releaseLock | public void releaseLock (final NodeObject.Lock lock, final ResultListener<String> listener) {
"""
Releases a lock. This can be cancelled using {@link #reacquireLock}, in which case the
passed listener will receive this node's name as opposed to <code>null</code>, which
signifies that the lock has been successfully released.
"""
// wait until any pending resolution is complete
queryLock(lock, new ChainedResultListener<String, String>(listener) {
public void requestCompleted (String result) {
if (Objects.equal(_nodeName, result)) {
if (_suboids.isEmpty()) {
lockReleased(lock, listener);
} else {
_locks.put(lock, new LockHandler(lock, false, listener));
}
} else {
if (result != null) {
log.warning("Tried to release lock held by another peer", "lock", lock,
"owner", result);
}
listener.requestCompleted(result);
}
}
});
} | java | public void releaseLock (final NodeObject.Lock lock, final ResultListener<String> listener)
{
// wait until any pending resolution is complete
queryLock(lock, new ChainedResultListener<String, String>(listener) {
public void requestCompleted (String result) {
if (Objects.equal(_nodeName, result)) {
if (_suboids.isEmpty()) {
lockReleased(lock, listener);
} else {
_locks.put(lock, new LockHandler(lock, false, listener));
}
} else {
if (result != null) {
log.warning("Tried to release lock held by another peer", "lock", lock,
"owner", result);
}
listener.requestCompleted(result);
}
}
});
} | [
"public",
"void",
"releaseLock",
"(",
"final",
"NodeObject",
".",
"Lock",
"lock",
",",
"final",
"ResultListener",
"<",
"String",
">",
"listener",
")",
"{",
"// wait until any pending resolution is complete",
"queryLock",
"(",
"lock",
",",
"new",
"ChainedResultListener... | Releases a lock. This can be cancelled using {@link #reacquireLock}, in which case the
passed listener will receive this node's name as opposed to <code>null</code>, which
signifies that the lock has been successfully released. | [
"Releases",
"a",
"lock",
".",
"This",
"can",
"be",
"cancelled",
"using",
"{"
] | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/PeerManager.java#L822-L842 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderNotePersistenceImpl.java | CommerceOrderNotePersistenceImpl.findAll | @Override
public List<CommerceOrderNote> findAll(int start, int end) {
"""
Returns a range of all the commerce order notes.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderNoteModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce order notes
@param end the upper bound of the range of commerce order notes (not inclusive)
@return the range of commerce order notes
"""
return findAll(start, end, null);
} | java | @Override
public List<CommerceOrderNote> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceOrderNote",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce order notes.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderNoteModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce order notes
@param end the upper bound of the range of commerce order notes (not inclusive)
@return the range of commerce order notes | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"order",
"notes",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderNotePersistenceImpl.java#L2027-L2030 |
alkacon/opencms-core | src/org/opencms/importexport/CmsImportVersion7.java | CmsImportVersion7.addContentFile | public void addContentFile(String source, String resourceId) {
"""
Registers a file whose contents are contained in the zip file.<p>
@param source the path in the zip file
@param resourceId
"""
if ((source != null) && (resourceId != null)) {
try {
m_helper.getFileBytes(source);
m_contentFiles.add(new CmsUUID(resourceId));
} catch (CmsImportExportException e) {
LOG.info("File not found in import: " + source);
}
}
} | java | public void addContentFile(String source, String resourceId) {
if ((source != null) && (resourceId != null)) {
try {
m_helper.getFileBytes(source);
m_contentFiles.add(new CmsUUID(resourceId));
} catch (CmsImportExportException e) {
LOG.info("File not found in import: " + source);
}
}
} | [
"public",
"void",
"addContentFile",
"(",
"String",
"source",
",",
"String",
"resourceId",
")",
"{",
"if",
"(",
"(",
"source",
"!=",
"null",
")",
"&&",
"(",
"resourceId",
"!=",
"null",
")",
")",
"{",
"try",
"{",
"m_helper",
".",
"getFileBytes",
"(",
"so... | Registers a file whose contents are contained in the zip file.<p>
@param source the path in the zip file
@param resourceId | [
"Registers",
"a",
"file",
"whose",
"contents",
"are",
"contained",
"in",
"the",
"zip",
"file",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsImportVersion7.java#L533-L543 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/stat/cs/csvserver_stats.java | csvserver_stats.get | public static csvserver_stats get(nitro_service service, String name) throws Exception {
"""
Use this API to fetch statistics of csvserver_stats resource of given name .
"""
csvserver_stats obj = new csvserver_stats();
obj.set_name(name);
csvserver_stats response = (csvserver_stats) obj.stat_resource(service);
return response;
} | java | public static csvserver_stats get(nitro_service service, String name) throws Exception{
csvserver_stats obj = new csvserver_stats();
obj.set_name(name);
csvserver_stats response = (csvserver_stats) obj.stat_resource(service);
return response;
} | [
"public",
"static",
"csvserver_stats",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"csvserver_stats",
"obj",
"=",
"new",
"csvserver_stats",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
"csv... | Use this API to fetch statistics of csvserver_stats resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"statistics",
"of",
"csvserver_stats",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/cs/csvserver_stats.java#L419-L424 |
WiQuery/wiquery | wiquery-core/src/main/java/org/odlabs/wiquery/core/options/Options.java | Options.putShort | public Options putShort(String key, IModel<Short> value) {
"""
<p>
Puts an short value for the given option name.
</p>
@param key
the option name.
@param value
the short value.
"""
putOption(key, new ShortOption(value));
return this;
} | java | public Options putShort(String key, IModel<Short> value)
{
putOption(key, new ShortOption(value));
return this;
} | [
"public",
"Options",
"putShort",
"(",
"String",
"key",
",",
"IModel",
"<",
"Short",
">",
"value",
")",
"{",
"putOption",
"(",
"key",
",",
"new",
"ShortOption",
"(",
"value",
")",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Puts an short value for the given option name.
</p>
@param key
the option name.
@param value
the short value. | [
"<p",
">",
"Puts",
"an",
"short",
"value",
"for",
"the",
"given",
"option",
"name",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-core/src/main/java/org/odlabs/wiquery/core/options/Options.java#L532-L536 |
Jsondb/jsondb-core | src/main/java/io/jsondb/Util.java | Util.getIdForEntity | protected static Object getIdForEntity(Object document, Method getterMethodForId) {
"""
A utility method to extract the value of field marked by the @Id annotation using its
getter/accessor method.
@param document the actual Object representing the POJO we want the Id of.
@param getterMethodForId the Method that is the accessor for the attributed with @Id annotation
@return the actual Id or if none exists then a new random UUID
"""
Object id = null;
if (null != getterMethodForId) {
try {
id = getterMethodForId.invoke(document);
} catch (IllegalAccessException e) {
logger.error("Failed to invoke getter method for a idAnnotated field due to permissions", e);
throw new InvalidJsonDbApiUsageException("Failed to invoke getter method for a idAnnotated field due to permissions", e);
} catch (IllegalArgumentException e) {
logger.error("Failed to invoke getter method for a idAnnotated field due to wrong arguments", e);
throw new InvalidJsonDbApiUsageException("Failed to invoke getter method for a idAnnotated field due to wrong arguments", e);
} catch (InvocationTargetException e) {
logger.error("Failed to invoke getter method for a idAnnotated field, the method threw a exception", e);
throw new InvalidJsonDbApiUsageException("Failed to invoke getter method for a idAnnotated field, the method threw a exception", e);
}
}
return id;
} | java | protected static Object getIdForEntity(Object document, Method getterMethodForId) {
Object id = null;
if (null != getterMethodForId) {
try {
id = getterMethodForId.invoke(document);
} catch (IllegalAccessException e) {
logger.error("Failed to invoke getter method for a idAnnotated field due to permissions", e);
throw new InvalidJsonDbApiUsageException("Failed to invoke getter method for a idAnnotated field due to permissions", e);
} catch (IllegalArgumentException e) {
logger.error("Failed to invoke getter method for a idAnnotated field due to wrong arguments", e);
throw new InvalidJsonDbApiUsageException("Failed to invoke getter method for a idAnnotated field due to wrong arguments", e);
} catch (InvocationTargetException e) {
logger.error("Failed to invoke getter method for a idAnnotated field, the method threw a exception", e);
throw new InvalidJsonDbApiUsageException("Failed to invoke getter method for a idAnnotated field, the method threw a exception", e);
}
}
return id;
} | [
"protected",
"static",
"Object",
"getIdForEntity",
"(",
"Object",
"document",
",",
"Method",
"getterMethodForId",
")",
"{",
"Object",
"id",
"=",
"null",
";",
"if",
"(",
"null",
"!=",
"getterMethodForId",
")",
"{",
"try",
"{",
"id",
"=",
"getterMethodForId",
... | A utility method to extract the value of field marked by the @Id annotation using its
getter/accessor method.
@param document the actual Object representing the POJO we want the Id of.
@param getterMethodForId the Method that is the accessor for the attributed with @Id annotation
@return the actual Id or if none exists then a new random UUID | [
"A",
"utility",
"method",
"to",
"extract",
"the",
"value",
"of",
"field",
"marked",
"by",
"the"
] | train | https://github.com/Jsondb/jsondb-core/blob/c49654d1eee2ace4d5ca5be19730652a966ce7f4/src/main/java/io/jsondb/Util.java#L107-L124 |
alkacon/opencms-core | src/org/opencms/workplace/comparison/CmsXmlDocumentComparison.java | CmsXmlDocumentComparison.getElements | private List<CmsElementComparison> getElements(I_CmsXmlDocument xmlPage) {
"""
Returs a list of all element names of a xml page.<p>
@param xmlPage the xml page to read the element names from
@return a list of all element names of a xml page
"""
List<CmsElementComparison> elements = new ArrayList<CmsElementComparison>();
Iterator<Locale> locales = xmlPage.getLocales().iterator();
while (locales.hasNext()) {
Locale locale = locales.next();
Iterator<String> elementNames = xmlPage.getNames(locale).iterator();
while (elementNames.hasNext()) {
String elementName = elementNames.next();
elements.add(new CmsElementComparison(locale, elementName));
}
}
return elements;
} | java | private List<CmsElementComparison> getElements(I_CmsXmlDocument xmlPage) {
List<CmsElementComparison> elements = new ArrayList<CmsElementComparison>();
Iterator<Locale> locales = xmlPage.getLocales().iterator();
while (locales.hasNext()) {
Locale locale = locales.next();
Iterator<String> elementNames = xmlPage.getNames(locale).iterator();
while (elementNames.hasNext()) {
String elementName = elementNames.next();
elements.add(new CmsElementComparison(locale, elementName));
}
}
return elements;
} | [
"private",
"List",
"<",
"CmsElementComparison",
">",
"getElements",
"(",
"I_CmsXmlDocument",
"xmlPage",
")",
"{",
"List",
"<",
"CmsElementComparison",
">",
"elements",
"=",
"new",
"ArrayList",
"<",
"CmsElementComparison",
">",
"(",
")",
";",
"Iterator",
"<",
"Lo... | Returs a list of all element names of a xml page.<p>
@param xmlPage the xml page to read the element names from
@return a list of all element names of a xml page | [
"Returs",
"a",
"list",
"of",
"all",
"element",
"names",
"of",
"a",
"xml",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/comparison/CmsXmlDocumentComparison.java#L197-L210 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java | AppServiceEnvironmentsInner.listCapacitiesWithServiceResponseAsync | public Observable<ServiceResponse<Page<StampCapacityInner>>> listCapacitiesWithServiceResponseAsync(final String resourceGroupName, final String name) {
"""
Get the used, available, and total worker capacity an App Service Environment.
Get the used, available, and total worker capacity an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<StampCapacityInner> object
"""
return listCapacitiesSinglePageAsync(resourceGroupName, name)
.concatMap(new Func1<ServiceResponse<Page<StampCapacityInner>>, Observable<ServiceResponse<Page<StampCapacityInner>>>>() {
@Override
public Observable<ServiceResponse<Page<StampCapacityInner>>> call(ServiceResponse<Page<StampCapacityInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listCapacitiesNextWithServiceResponseAsync(nextPageLink));
}
});
} | java | public Observable<ServiceResponse<Page<StampCapacityInner>>> listCapacitiesWithServiceResponseAsync(final String resourceGroupName, final String name) {
return listCapacitiesSinglePageAsync(resourceGroupName, name)
.concatMap(new Func1<ServiceResponse<Page<StampCapacityInner>>, Observable<ServiceResponse<Page<StampCapacityInner>>>>() {
@Override
public Observable<ServiceResponse<Page<StampCapacityInner>>> call(ServiceResponse<Page<StampCapacityInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listCapacitiesNextWithServiceResponseAsync(nextPageLink));
}
});
} | [
"public",
"Observable",
"<",
"ServiceResponse",
"<",
"Page",
"<",
"StampCapacityInner",
">",
">",
">",
"listCapacitiesWithServiceResponseAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"name",
")",
"{",
"return",
"listCapacitiesSinglePageAsy... | Get the used, available, and total worker capacity an App Service Environment.
Get the used, available, and total worker capacity an App Service Environment.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param name Name of the App Service Environment.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<StampCapacityInner> object | [
"Get",
"the",
"used",
"available",
"and",
"total",
"worker",
"capacity",
"an",
"App",
"Service",
"Environment",
".",
"Get",
"the",
"used",
"available",
"and",
"total",
"worker",
"capacity",
"an",
"App",
"Service",
"Environment",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L1358-L1370 |
ludovicianul/selenium-on-steroids | src/main/java/com/insidecoding/sos/webdriver/WebDriverHelper.java | WebDriverHelper.isTextPresentInDropDown | public boolean isTextPresentInDropDown(final By by, final String text) {
"""
Checks if a text is displayed in the drop-down. This method considers the
actual display text. <br/>
For example if we have the following situation: <select id="test">
<option value="4">June</option> </select> we will call
the method as follows: isValuePresentInDropDown(By.id("test"), "June");
@param by
the method of identifying the drop-down
@param text
the text to search for
@return true if the text is present or false otherwise
"""
WebElement element = driver.findElement(by);
List<WebElement> options = element.findElements(By
.xpath(".//option[normalize-space(.) = " + escapeQuotes(text)
+ "]"));
return options != null && !options.isEmpty();
} | java | public boolean isTextPresentInDropDown(final By by, final String text) {
WebElement element = driver.findElement(by);
List<WebElement> options = element.findElements(By
.xpath(".//option[normalize-space(.) = " + escapeQuotes(text)
+ "]"));
return options != null && !options.isEmpty();
} | [
"public",
"boolean",
"isTextPresentInDropDown",
"(",
"final",
"By",
"by",
",",
"final",
"String",
"text",
")",
"{",
"WebElement",
"element",
"=",
"driver",
".",
"findElement",
"(",
"by",
")",
";",
"List",
"<",
"WebElement",
">",
"options",
"=",
"element",
... | Checks if a text is displayed in the drop-down. This method considers the
actual display text. <br/>
For example if we have the following situation: <select id="test">
<option value="4">June</option> </select> we will call
the method as follows: isValuePresentInDropDown(By.id("test"), "June");
@param by
the method of identifying the drop-down
@param text
the text to search for
@return true if the text is present or false otherwise | [
"Checks",
"if",
"a",
"text",
"is",
"displayed",
"in",
"the",
"drop",
"-",
"down",
".",
"This",
"method",
"considers",
"the",
"actual",
"display",
"text",
".",
"<br",
"/",
">",
"For",
"example",
"if",
"we",
"have",
"the",
"following",
"situation",
":",
... | train | https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/webdriver/WebDriverHelper.java#L562-L568 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/itemstreams/PubSubMessageItemStream.java | PubSubMessageItemStream.setWatermarks | @Override
protected void setWatermarks(long nextLowWatermark, long nextHighWatermark) {
"""
Include the referenceStreamCount when setting the watermarks (called by
BaseMessageItemStream.updateWaterMarks() (which has no concept of referenceStreams)
(510343)
@param nextLowWatermark
@param nextHighWatermark
@throws SevereMessageStoreException
"""
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "setWatermarks",
new Object[] { new Long(nextLowWatermark), new Long(nextHighWatermark), new Long(referenceStreamCount) });
super.setWatermarks(nextLowWatermark + referenceStreamCount, nextHighWatermark + referenceStreamCount);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "setWatermarks");
} | java | @Override
protected void setWatermarks(long nextLowWatermark, long nextHighWatermark)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "setWatermarks",
new Object[] { new Long(nextLowWatermark), new Long(nextHighWatermark), new Long(referenceStreamCount) });
super.setWatermarks(nextLowWatermark + referenceStreamCount, nextHighWatermark + referenceStreamCount);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "setWatermarks");
} | [
"@",
"Override",
"protected",
"void",
"setWatermarks",
"(",
"long",
"nextLowWatermark",
",",
"long",
"nextHighWatermark",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
".... | Include the referenceStreamCount when setting the watermarks (called by
BaseMessageItemStream.updateWaterMarks() (which has no concept of referenceStreams)
(510343)
@param nextLowWatermark
@param nextHighWatermark
@throws SevereMessageStoreException | [
"Include",
"the",
"referenceStreamCount",
"when",
"setting",
"the",
"watermarks",
"(",
"called",
"by",
"BaseMessageItemStream",
".",
"updateWaterMarks",
"()",
"(",
"which",
"has",
"no",
"concept",
"of",
"referenceStreams",
")"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/itemstreams/PubSubMessageItemStream.java#L922-L933 |
litsec/swedish-eid-shibboleth-base | shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java | AbstractExternalAuthenticationController.getPrincipalSelection | protected PrincipalSelection getPrincipalSelection(ProfileRequestContext<?, ?> context) {
"""
Utility method that may be used to obtain the {@link PrincipalSelection} extension that may be received in an
{@code AuthnRequest}.
@param context
the profile context
@return the {@code PrincipalSelection} extension, or {@code null} if none is found in the current
{@code AuthnRequest}
"""
final AuthnRequest authnRequest = this.getAuthnRequest(context);
if (authnRequest != null && authnRequest.getExtensions() != null) {
return authnRequest.getExtensions()
.getUnknownXMLObjects()
.stream()
.filter(PrincipalSelection.class::isInstance)
.map(PrincipalSelection.class::cast)
.findFirst()
.orElse(null);
}
return null;
} | java | protected PrincipalSelection getPrincipalSelection(ProfileRequestContext<?, ?> context) {
final AuthnRequest authnRequest = this.getAuthnRequest(context);
if (authnRequest != null && authnRequest.getExtensions() != null) {
return authnRequest.getExtensions()
.getUnknownXMLObjects()
.stream()
.filter(PrincipalSelection.class::isInstance)
.map(PrincipalSelection.class::cast)
.findFirst()
.orElse(null);
}
return null;
} | [
"protected",
"PrincipalSelection",
"getPrincipalSelection",
"(",
"ProfileRequestContext",
"<",
"?",
",",
"?",
">",
"context",
")",
"{",
"final",
"AuthnRequest",
"authnRequest",
"=",
"this",
".",
"getAuthnRequest",
"(",
"context",
")",
";",
"if",
"(",
"authnRequest... | Utility method that may be used to obtain the {@link PrincipalSelection} extension that may be received in an
{@code AuthnRequest}.
@param context
the profile context
@return the {@code PrincipalSelection} extension, or {@code null} if none is found in the current
{@code AuthnRequest} | [
"Utility",
"method",
"that",
"may",
"be",
"used",
"to",
"obtain",
"the",
"{",
"@link",
"PrincipalSelection",
"}",
"extension",
"that",
"may",
"be",
"received",
"in",
"an",
"{",
"@code",
"AuthnRequest",
"}",
"."
] | train | https://github.com/litsec/swedish-eid-shibboleth-base/blob/aaaa467ff61f07d7dfa31627fb36851a37da6804/shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/controller/AbstractExternalAuthenticationController.java#L555-L567 |
twitter/hraven | hraven-etl/src/main/java/com/twitter/hraven/mapreduce/JobFileTableMapper.java | JobFileTableMapper.getMegaByteMillisPut | private Put getMegaByteMillisPut(Long mbMillis, JobKey jobKey) {
"""
generates a put for the megabytemillis
@param mbMillis
@param jobKey
@return the put with megabytemillis
"""
Put pMb = new Put(jobKeyConv.toBytes(jobKey));
pMb.addColumn(Constants.INFO_FAM_BYTES, Constants.MEGABYTEMILLIS_BYTES,
Bytes.toBytes(mbMillis));
return pMb;
} | java | private Put getMegaByteMillisPut(Long mbMillis, JobKey jobKey) {
Put pMb = new Put(jobKeyConv.toBytes(jobKey));
pMb.addColumn(Constants.INFO_FAM_BYTES, Constants.MEGABYTEMILLIS_BYTES,
Bytes.toBytes(mbMillis));
return pMb;
} | [
"private",
"Put",
"getMegaByteMillisPut",
"(",
"Long",
"mbMillis",
",",
"JobKey",
"jobKey",
")",
"{",
"Put",
"pMb",
"=",
"new",
"Put",
"(",
"jobKeyConv",
".",
"toBytes",
"(",
"jobKey",
")",
")",
";",
"pMb",
".",
"addColumn",
"(",
"Constants",
".",
"INFO_... | generates a put for the megabytemillis
@param mbMillis
@param jobKey
@return the put with megabytemillis | [
"generates",
"a",
"put",
"for",
"the",
"megabytemillis"
] | train | https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-etl/src/main/java/com/twitter/hraven/mapreduce/JobFileTableMapper.java#L431-L436 |
square/otto | otto/src/main/java/com/squareup/otto/Bus.java | Bus.enqueueEvent | protected void enqueueEvent(Object event, EventHandler handler) {
"""
Queue the {@code event} for dispatch during {@link #dispatchQueuedEvents()}. Events are queued in-order of
occurrence so they can be dispatched in the same order.
"""
eventsToDispatch.get().offer(new EventWithHandler(event, handler));
} | java | protected void enqueueEvent(Object event, EventHandler handler) {
eventsToDispatch.get().offer(new EventWithHandler(event, handler));
} | [
"protected",
"void",
"enqueueEvent",
"(",
"Object",
"event",
",",
"EventHandler",
"handler",
")",
"{",
"eventsToDispatch",
".",
"get",
"(",
")",
".",
"offer",
"(",
"new",
"EventWithHandler",
"(",
"event",
",",
"handler",
")",
")",
";",
"}"
] | Queue the {@code event} for dispatch during {@link #dispatchQueuedEvents()}. Events are queued in-order of
occurrence so they can be dispatched in the same order. | [
"Queue",
"the",
"{"
] | train | https://github.com/square/otto/blob/2a67589abd91879cf23a8c96542b59349485ec3d/otto/src/main/java/com/squareup/otto/Bus.java#L344-L346 |
chrisjenx/Calligraphy | calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyFactory.java | CalligraphyFactory.resolveFontPath | private String resolveFontPath(Context context, AttributeSet attrs) {
"""
Resolving font path from xml attrs, style attrs or text appearance
"""
// Try view xml attributes
String textViewFont = CalligraphyUtils.pullFontPathFromView(context, attrs, mAttributeId);
// Try view style attributes
if (TextUtils.isEmpty(textViewFont)) {
textViewFont = CalligraphyUtils.pullFontPathFromStyle(context, attrs, mAttributeId);
}
// Try View TextAppearance
if (TextUtils.isEmpty(textViewFont)) {
textViewFont = CalligraphyUtils.pullFontPathFromTextAppearance(context, attrs, mAttributeId);
}
return textViewFont;
} | java | private String resolveFontPath(Context context, AttributeSet attrs) {
// Try view xml attributes
String textViewFont = CalligraphyUtils.pullFontPathFromView(context, attrs, mAttributeId);
// Try view style attributes
if (TextUtils.isEmpty(textViewFont)) {
textViewFont = CalligraphyUtils.pullFontPathFromStyle(context, attrs, mAttributeId);
}
// Try View TextAppearance
if (TextUtils.isEmpty(textViewFont)) {
textViewFont = CalligraphyUtils.pullFontPathFromTextAppearance(context, attrs, mAttributeId);
}
return textViewFont;
} | [
"private",
"String",
"resolveFontPath",
"(",
"Context",
"context",
",",
"AttributeSet",
"attrs",
")",
"{",
"// Try view xml attributes",
"String",
"textViewFont",
"=",
"CalligraphyUtils",
".",
"pullFontPathFromView",
"(",
"context",
",",
"attrs",
",",
"mAttributeId",
... | Resolving font path from xml attrs, style attrs or text appearance | [
"Resolving",
"font",
"path",
"from",
"xml",
"attrs",
"style",
"attrs",
"or",
"text",
"appearance"
] | train | https://github.com/chrisjenx/Calligraphy/blob/085e441954d787bd4ef31f245afe5f2f2a311ea5/calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyFactory.java#L181-L196 |
Impetus/Kundera | src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseClient.java | CouchbaseClient.validateQueryResults | private void validateQueryResults(String query, N1qlQueryResult result) {
"""
Validate query results.
@param query
the query
@param result
the result
"""
LOGGER.debug("Query output status: " + result.finalSuccess());
if (!result.finalSuccess())
{
StringBuilder errorBuilder = new StringBuilder();
for (JsonObject obj : result.errors())
{
errorBuilder.append(obj.toString());
errorBuilder.append("\n");
}
errorBuilder.deleteCharAt(errorBuilder.length() - 1);
String errors = errorBuilder.toString();
LOGGER.error(errors);
throw new KunderaException("Not able to execute query/statement:" + query + ". More details : " + errors);
}
} | java | private void validateQueryResults(String query, N1qlQueryResult result)
{
LOGGER.debug("Query output status: " + result.finalSuccess());
if (!result.finalSuccess())
{
StringBuilder errorBuilder = new StringBuilder();
for (JsonObject obj : result.errors())
{
errorBuilder.append(obj.toString());
errorBuilder.append("\n");
}
errorBuilder.deleteCharAt(errorBuilder.length() - 1);
String errors = errorBuilder.toString();
LOGGER.error(errors);
throw new KunderaException("Not able to execute query/statement:" + query + ". More details : " + errors);
}
} | [
"private",
"void",
"validateQueryResults",
"(",
"String",
"query",
",",
"N1qlQueryResult",
"result",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Query output status: \"",
"+",
"result",
".",
"finalSuccess",
"(",
")",
")",
";",
"if",
"(",
"!",
"result",
".",
"f... | Validate query results.
@param query
the query
@param result
the result | [
"Validate",
"query",
"results",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseClient.java#L376-L393 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/AvailabilitySetsInner.java | AvailabilitySetsInner.createOrUpdateAsync | public Observable<AvailabilitySetInner> createOrUpdateAsync(String resourceGroupName, String availabilitySetName, AvailabilitySetInner parameters) {
"""
Create or update an availability set.
@param resourceGroupName The name of the resource group.
@param availabilitySetName The name of the availability set.
@param parameters Parameters supplied to the Create Availability Set operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AvailabilitySetInner object
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, availabilitySetName, parameters).map(new Func1<ServiceResponse<AvailabilitySetInner>, AvailabilitySetInner>() {
@Override
public AvailabilitySetInner call(ServiceResponse<AvailabilitySetInner> response) {
return response.body();
}
});
} | java | public Observable<AvailabilitySetInner> createOrUpdateAsync(String resourceGroupName, String availabilitySetName, AvailabilitySetInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, availabilitySetName, parameters).map(new Func1<ServiceResponse<AvailabilitySetInner>, AvailabilitySetInner>() {
@Override
public AvailabilitySetInner call(ServiceResponse<AvailabilitySetInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"AvailabilitySetInner",
">",
"createOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"availabilitySetName",
",",
"AvailabilitySetInner",
"parameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGr... | Create or update an availability set.
@param resourceGroupName The name of the resource group.
@param availabilitySetName The name of the availability set.
@param parameters Parameters supplied to the Create Availability Set operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the AvailabilitySetInner object | [
"Create",
"or",
"update",
"an",
"availability",
"set",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/AvailabilitySetsInner.java#L123-L130 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/VaadinMessageSource.java | VaadinMessageSource.getMessage | public String getMessage(final Locale local, final String code, final Object... args) {
"""
Tries to resolve the message based on the provided Local. Returns message
code if fitting message could not be found.
@param local
to determinate the Language.
@param code
the code to lookup up.
@param args
Array of arguments that will be filled in for params within
the message.
@return the resolved message, or the message code if the lookup fails.
"""
try {
return source.getMessage(code, args, local);
} catch (final NoSuchMessageException ex) {
LOG.error("Failed to retrieve message!", ex);
return code;
}
} | java | public String getMessage(final Locale local, final String code, final Object... args) {
try {
return source.getMessage(code, args, local);
} catch (final NoSuchMessageException ex) {
LOG.error("Failed to retrieve message!", ex);
return code;
}
} | [
"public",
"String",
"getMessage",
"(",
"final",
"Locale",
"local",
",",
"final",
"String",
"code",
",",
"final",
"Object",
"...",
"args",
")",
"{",
"try",
"{",
"return",
"source",
".",
"getMessage",
"(",
"code",
",",
"args",
",",
"local",
")",
";",
"}"... | Tries to resolve the message based on the provided Local. Returns message
code if fitting message could not be found.
@param local
to determinate the Language.
@param code
the code to lookup up.
@param args
Array of arguments that will be filled in for params within
the message.
@return the resolved message, or the message code if the lookup fails. | [
"Tries",
"to",
"resolve",
"the",
"message",
"based",
"on",
"the",
"provided",
"Local",
".",
"Returns",
"message",
"code",
"if",
"fitting",
"message",
"could",
"not",
"be",
"found",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/VaadinMessageSource.java#L75-L82 |
ArcBees/gwtquery | gwtquery-core/src/main/java/com/google/gwt/query/client/css/LineHeightProperty.java | LineHeightProperty.with | public CssSetter with(Double value) {
"""
The used value of the property is this <code>value</code> multiplied by the
element's font size. Negative values are illegal.
"""
return new SimpleCssSetter(CSS_PROPERTY, value != null ? "" + value : null);
} | java | public CssSetter with(Double value) {
return new SimpleCssSetter(CSS_PROPERTY, value != null ? "" + value : null);
} | [
"public",
"CssSetter",
"with",
"(",
"Double",
"value",
")",
"{",
"return",
"new",
"SimpleCssSetter",
"(",
"CSS_PROPERTY",
",",
"value",
"!=",
"null",
"?",
"\"\"",
"+",
"value",
":",
"null",
")",
";",
"}"
] | The used value of the property is this <code>value</code> multiplied by the
element's font size. Negative values are illegal. | [
"The",
"used",
"value",
"of",
"the",
"property",
"is",
"this",
"<code",
">",
"value<",
"/",
"code",
">",
"multiplied",
"by",
"the",
"element",
"s",
"font",
"size",
".",
"Negative",
"values",
"are",
"illegal",
"."
] | train | https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/css/LineHeightProperty.java#L57-L59 |
CODAIT/stocator | src/main/java/com/ibm/stocator/fs/swift/SwiftAPIClient.java | SwiftAPIClient.createObject | @Override
public FSDataOutputStream createObject(String objName, String contentType,
Map<String, String> metadata, Statistics statistics) throws IOException {
"""
Direct HTTP PUT request without JOSS package
@param objName name of the object
@param contentType content type
@return HttpURLConnection
"""
final URL url = new URL(mJossAccount.getAccessURL() + "/" + getURLEncodedObjName(objName));
LOG.debug("PUT {}. Content-Type : {}", url.toString(), contentType);
// When overwriting an object, cached metadata will be outdated
String cachedName = getObjName(container + "/", objName);
objectCache.remove(cachedName);
try {
final OutputStream sos;
if (nonStreamingUpload) {
sos = new SwiftNoStreamingOutputStream(mJossAccount, url, contentType,
metadata, swiftConnectionManager, this);
} else {
sos = new SwiftOutputStream(mJossAccount, url, contentType,
metadata, swiftConnectionManager);
}
return new FSDataOutputStream(sos, statistics);
} catch (IOException e) {
LOG.error(e.getMessage());
throw e;
}
} | java | @Override
public FSDataOutputStream createObject(String objName, String contentType,
Map<String, String> metadata, Statistics statistics) throws IOException {
final URL url = new URL(mJossAccount.getAccessURL() + "/" + getURLEncodedObjName(objName));
LOG.debug("PUT {}. Content-Type : {}", url.toString(), contentType);
// When overwriting an object, cached metadata will be outdated
String cachedName = getObjName(container + "/", objName);
objectCache.remove(cachedName);
try {
final OutputStream sos;
if (nonStreamingUpload) {
sos = new SwiftNoStreamingOutputStream(mJossAccount, url, contentType,
metadata, swiftConnectionManager, this);
} else {
sos = new SwiftOutputStream(mJossAccount, url, contentType,
metadata, swiftConnectionManager);
}
return new FSDataOutputStream(sos, statistics);
} catch (IOException e) {
LOG.error(e.getMessage());
throw e;
}
} | [
"@",
"Override",
"public",
"FSDataOutputStream",
"createObject",
"(",
"String",
"objName",
",",
"String",
"contentType",
",",
"Map",
"<",
"String",
",",
"String",
">",
"metadata",
",",
"Statistics",
"statistics",
")",
"throws",
"IOException",
"{",
"final",
"URL"... | Direct HTTP PUT request without JOSS package
@param objName name of the object
@param contentType content type
@return HttpURLConnection | [
"Direct",
"HTTP",
"PUT",
"request",
"without",
"JOSS",
"package"
] | train | https://github.com/CODAIT/stocator/blob/35969cadd2e8faa6fdac45e8bec1799fdd3d8299/src/main/java/com/ibm/stocator/fs/swift/SwiftAPIClient.java#L641-L665 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java | JQLChecker.prepareParser | protected Pair<ParserRuleContext, CommonTokenStream> prepareParser(final JQLContext jqlContext, final String jql) {
"""
Prepare parser.
@param jqlContext
the jql context
@param jql
the jql
@return the pair
"""
JqlLexer lexer = new JqlLexer(CharStreams.fromString(jql));
CommonTokenStream tokens = new CommonTokenStream(lexer);
JqlParser parser = new JqlParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new JQLBaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
AssertKripton.assertTrue(false, jqlContext.getContextDescription() + ": unespected char at pos %s of SQL '%s'", charPositionInLine, jql);
}
});
ParserRuleContext context = parser.parse();
return new Pair<>(context, tokens);
} | java | protected Pair<ParserRuleContext, CommonTokenStream> prepareParser(final JQLContext jqlContext, final String jql) {
JqlLexer lexer = new JqlLexer(CharStreams.fromString(jql));
CommonTokenStream tokens = new CommonTokenStream(lexer);
JqlParser parser = new JqlParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new JQLBaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
AssertKripton.assertTrue(false, jqlContext.getContextDescription() + ": unespected char at pos %s of SQL '%s'", charPositionInLine, jql);
}
});
ParserRuleContext context = parser.parse();
return new Pair<>(context, tokens);
} | [
"protected",
"Pair",
"<",
"ParserRuleContext",
",",
"CommonTokenStream",
">",
"prepareParser",
"(",
"final",
"JQLContext",
"jqlContext",
",",
"final",
"String",
"jql",
")",
"{",
"JqlLexer",
"lexer",
"=",
"new",
"JqlLexer",
"(",
"CharStreams",
".",
"fromString",
... | Prepare parser.
@param jqlContext
the jql context
@param jql
the jql
@return the pair | [
"Prepare",
"parser",
"."
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java#L160-L175 |
rometools/rome | rome/src/main/java/com/rometools/rome/io/impl/NumberParser.java | NumberParser.parseLong | public static long parseLong(final String str, final long def) {
"""
Parses a long out of a string.
@param str string to parse for a long.
@param def default value to return if it is not possible to parse the the string.
@return the long represented by the given string, or the default.
"""
final Long ret = parseLong(str);
if (ret == null) {
return def;
} else {
return ret.longValue();
}
} | java | public static long parseLong(final String str, final long def) {
final Long ret = parseLong(str);
if (ret == null) {
return def;
} else {
return ret.longValue();
}
} | [
"public",
"static",
"long",
"parseLong",
"(",
"final",
"String",
"str",
",",
"final",
"long",
"def",
")",
"{",
"final",
"Long",
"ret",
"=",
"parseLong",
"(",
"str",
")",
";",
"if",
"(",
"ret",
"==",
"null",
")",
"{",
"return",
"def",
";",
"}",
"els... | Parses a long out of a string.
@param str string to parse for a long.
@param def default value to return if it is not possible to parse the the string.
@return the long represented by the given string, or the default. | [
"Parses",
"a",
"long",
"out",
"of",
"a",
"string",
"."
] | train | https://github.com/rometools/rome/blob/5fcf0b1a9a6cdedbe253a45ad9468c54a0f97010/rome/src/main/java/com/rometools/rome/io/impl/NumberParser.java#L111-L118 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.availabilities_raw_GET | public ArrayList<OvhAvailabilitiesRaw> availabilities_raw_GET() throws IOException {
"""
List the availability of dedicated server
REST: GET /dedicated/server/availabilities/raw
"""
String qPath = "/dedicated/server/availabilities/raw";
StringBuilder sb = path(qPath);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t16);
} | java | public ArrayList<OvhAvailabilitiesRaw> availabilities_raw_GET() throws IOException {
String qPath = "/dedicated/server/availabilities/raw";
StringBuilder sb = path(qPath);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t16);
} | [
"public",
"ArrayList",
"<",
"OvhAvailabilitiesRaw",
">",
"availabilities_raw_GET",
"(",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/availabilities/raw\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
")",
";",
"String",
... | List the availability of dedicated server
REST: GET /dedicated/server/availabilities/raw | [
"List",
"the",
"availability",
"of",
"dedicated",
"server"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L2360-L2365 |
wanglinsong/th-lipermi | src/main/java/net/sf/lipermi/handler/CallProxy.java | CallProxy.buildProxy | public static Object buildProxy(RemoteInstance remoteInstance, ConnectionHandler connectionHandler)
throws ClassNotFoundException {
"""
Build a proxy to a {
@see net.sf.lipermi.call.RemoteInstance RemoteInstance}
specifing how it could be reached (i.e., through a ConnectionHandler)
@param remoteInstance remote instance
@param connectionHandler handler
@return dymamic proxy for RemoteInstance
@throws ClassNotFoundException class not found
"""
Class<?> clazz = Class.forName(remoteInstance.getClassName());
return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new CallProxy(connectionHandler));
} | java | public static Object buildProxy(RemoteInstance remoteInstance, ConnectionHandler connectionHandler)
throws ClassNotFoundException {
Class<?> clazz = Class.forName(remoteInstance.getClassName());
return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new CallProxy(connectionHandler));
} | [
"public",
"static",
"Object",
"buildProxy",
"(",
"RemoteInstance",
"remoteInstance",
",",
"ConnectionHandler",
"connectionHandler",
")",
"throws",
"ClassNotFoundException",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"remoteInstance",
".... | Build a proxy to a {
@see net.sf.lipermi.call.RemoteInstance RemoteInstance}
specifing how it could be reached (i.e., through a ConnectionHandler)
@param remoteInstance remote instance
@param connectionHandler handler
@return dymamic proxy for RemoteInstance
@throws ClassNotFoundException class not found | [
"Build",
"a",
"proxy",
"to",
"a",
"{"
] | train | https://github.com/wanglinsong/th-lipermi/blob/5fa9ab1d7085b5133dc37ce3ba201d44a7bf25f0/src/main/java/net/sf/lipermi/handler/CallProxy.java#L76-L80 |
google/error-prone-javac | src/java.compiler/share/classes/javax/lang/model/util/ElementScanner7.java | ElementScanner7.visitVariable | @Override
public R visitVariable(VariableElement e, P p) {
"""
This implementation scans the enclosed elements.
@param e {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning
"""
return scan(e.getEnclosedElements(), p);
} | java | @Override
public R visitVariable(VariableElement e, P p) {
return scan(e.getEnclosedElements(), p);
} | [
"@",
"Override",
"public",
"R",
"visitVariable",
"(",
"VariableElement",
"e",
",",
"P",
"p",
")",
"{",
"return",
"scan",
"(",
"e",
".",
"getEnclosedElements",
"(",
")",
",",
"p",
")",
";",
"}"
] | This implementation scans the enclosed elements.
@param e {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"This",
"implementation",
"scans",
"the",
"enclosed",
"elements",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner7.java#L121-L124 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/BoardsApi.java | BoardsApi.deleteBoardList | public void deleteBoardList(Object projectIdOrPath, Integer boardId, Integer listId) throws GitLabApiException {
"""
Soft deletes an existing Issue Board list. Only for admins and project owners.
<pre><code>GitLab Endpoint: DELETE /projects/:id/boards/:board_id/lists/:list_id</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param boardId the ID of the board
@param listId the ID of the list
@throws GitLabApiException if any exception occurs
"""
delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists", listId);
} | java | public void deleteBoardList(Object projectIdOrPath, Integer boardId, Integer listId) throws GitLabApiException {
delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists", listId);
} | [
"public",
"void",
"deleteBoardList",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"boardId",
",",
"Integer",
"listId",
")",
"throws",
"GitLabApiException",
"{",
"delete",
"(",
"Response",
".",
"Status",
".",
"NO_CONTENT",
",",
"null",
",",
"\"projects\"",
"... | Soft deletes an existing Issue Board list. Only for admins and project owners.
<pre><code>GitLab Endpoint: DELETE /projects/:id/boards/:board_id/lists/:list_id</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param boardId the ID of the board
@param listId the ID of the list
@throws GitLabApiException if any exception occurs | [
"Soft",
"deletes",
"an",
"existing",
"Issue",
"Board",
"list",
".",
"Only",
"for",
"admins",
"and",
"project",
"owners",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/BoardsApi.java#L326-L328 |
aol/cyclops | cyclops/src/main/java/cyclops/companion/Streams.java | Streams.dropUntil | public static <U> Stream<U> dropUntil(final Stream<U> stream, final Predicate<? super U> predicate) {
"""
skip elements in Stream until Predicate holds true
<pre>
{@code Streams.dropUntil(Stream.of(4,3,6,7),i->i==6).collect(CyclopsCollectors.toList())
// [6,7]
}</pre>
@param stream Stream to skip elements from
@param predicate to applyHKT
@return Stream with elements skipped
"""
return dropWhile(stream, predicate.negate());
} | java | public static <U> Stream<U> dropUntil(final Stream<U> stream, final Predicate<? super U> predicate) {
return dropWhile(stream, predicate.negate());
} | [
"public",
"static",
"<",
"U",
">",
"Stream",
"<",
"U",
">",
"dropUntil",
"(",
"final",
"Stream",
"<",
"U",
">",
"stream",
",",
"final",
"Predicate",
"<",
"?",
"super",
"U",
">",
"predicate",
")",
"{",
"return",
"dropWhile",
"(",
"stream",
",",
"predi... | skip elements in Stream until Predicate holds true
<pre>
{@code Streams.dropUntil(Stream.of(4,3,6,7),i->i==6).collect(CyclopsCollectors.toList())
// [6,7]
}</pre>
@param stream Stream to skip elements from
@param predicate to applyHKT
@return Stream with elements skipped | [
"skip",
"elements",
"in",
"Stream",
"until",
"Predicate",
"holds",
"true",
"<pre",
">",
"{",
"@code",
"Streams",
".",
"dropUntil",
"(",
"Stream",
".",
"of",
"(",
"4",
"3",
"6",
"7",
")",
"i",
"-",
">",
"i",
"==",
"6",
")",
".",
"collect",
"(",
"C... | train | https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Streams.java#L1158-L1160 |
micronaut-projects/micronaut-core | inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java | AbstractBeanDefinition.getBeanProviderForMethodArgument | @SuppressWarnings("WeakerAccess")
@Internal
protected final Provider getBeanProviderForMethodArgument(BeanResolutionContext resolutionContext, BeanContext context, MethodInjectionPoint injectionPoint, Argument argument) {
"""
Obtains a bean provider for the method at the given index and the argument at the given index
<p>
Warning: this method is used by internal generated code and should not be called by user code.
@param resolutionContext The resolution context
@param context The context
@param injectionPoint The method injection point
@param argument The argument
@return The resolved bean
"""
return resolveBeanWithGenericsFromMethodArgument(resolutionContext, injectionPoint, argument, (beanType, qualifier) ->
((DefaultBeanContext) context).getBeanProvider(resolutionContext, beanType, qualifier)
);
} | java | @SuppressWarnings("WeakerAccess")
@Internal
protected final Provider getBeanProviderForMethodArgument(BeanResolutionContext resolutionContext, BeanContext context, MethodInjectionPoint injectionPoint, Argument argument) {
return resolveBeanWithGenericsFromMethodArgument(resolutionContext, injectionPoint, argument, (beanType, qualifier) ->
((DefaultBeanContext) context).getBeanProvider(resolutionContext, beanType, qualifier)
);
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"@",
"Internal",
"protected",
"final",
"Provider",
"getBeanProviderForMethodArgument",
"(",
"BeanResolutionContext",
"resolutionContext",
",",
"BeanContext",
"context",
",",
"MethodInjectionPoint",
"injectionPoint",
",",
... | Obtains a bean provider for the method at the given index and the argument at the given index
<p>
Warning: this method is used by internal generated code and should not be called by user code.
@param resolutionContext The resolution context
@param context The context
@param injectionPoint The method injection point
@param argument The argument
@return The resolved bean | [
"Obtains",
"a",
"bean",
"provider",
"for",
"the",
"method",
"at",
"the",
"given",
"index",
"and",
"the",
"argument",
"at",
"the",
"given",
"index",
"<p",
">",
"Warning",
":",
"this",
"method",
"is",
"used",
"by",
"internal",
"generated",
"code",
"and",
"... | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L889-L895 |
Azure/azure-sdk-for-java | labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/EnvironmentSettingsInner.java | EnvironmentSettingsInner.createOrUpdate | public EnvironmentSettingInner createOrUpdate(String resourceGroupName, String labAccountName, String labName, String environmentSettingName, EnvironmentSettingInner environmentSetting) {
"""
Create or replace an existing Environment Setting. This operation can take a while to complete.
@param resourceGroupName The name of the resource group.
@param labAccountName The name of the lab Account.
@param labName The name of the lab.
@param environmentSettingName The name of the environment Setting.
@param environmentSetting Represents settings of an environment, from which environment instances would be created
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the EnvironmentSettingInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, labAccountName, labName, environmentSettingName, environmentSetting).toBlocking().last().body();
} | java | public EnvironmentSettingInner createOrUpdate(String resourceGroupName, String labAccountName, String labName, String environmentSettingName, EnvironmentSettingInner environmentSetting) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, labAccountName, labName, environmentSettingName, environmentSetting).toBlocking().last().body();
} | [
"public",
"EnvironmentSettingInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"labAccountName",
",",
"String",
"labName",
",",
"String",
"environmentSettingName",
",",
"EnvironmentSettingInner",
"environmentSetting",
")",
"{",
"return",
"createOr... | Create or replace an existing Environment Setting. This operation can take a while to complete.
@param resourceGroupName The name of the resource group.
@param labAccountName The name of the lab Account.
@param labName The name of the lab.
@param environmentSettingName The name of the environment Setting.
@param environmentSetting Represents settings of an environment, from which environment instances would be created
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the EnvironmentSettingInner object if successful. | [
"Create",
"or",
"replace",
"an",
"existing",
"Environment",
"Setting",
".",
"This",
"operation",
"can",
"take",
"a",
"while",
"to",
"complete",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/EnvironmentSettingsInner.java#L616-L618 |
kotcrab/vis-ui | ui/src/main/java/com/kotcrab/vis/ui/util/form/SimpleFormValidator.java | SimpleFormValidator.valueLesserThan | public FormInputValidator valueLesserThan (VisValidatableTextField field, String errorMsg, float value) {
"""
Validates if entered text is lesser than entered number <p>
Can be used in combination with {@link #integerNumber(VisValidatableTextField, String)} to only allows integers.
"""
return valueLesserThan(field, errorMsg, value, false);
} | java | public FormInputValidator valueLesserThan (VisValidatableTextField field, String errorMsg, float value) {
return valueLesserThan(field, errorMsg, value, false);
} | [
"public",
"FormInputValidator",
"valueLesserThan",
"(",
"VisValidatableTextField",
"field",
",",
"String",
"errorMsg",
",",
"float",
"value",
")",
"{",
"return",
"valueLesserThan",
"(",
"field",
",",
"errorMsg",
",",
"value",
",",
"false",
")",
";",
"}"
] | Validates if entered text is lesser than entered number <p>
Can be used in combination with {@link #integerNumber(VisValidatableTextField, String)} to only allows integers. | [
"Validates",
"if",
"entered",
"text",
"is",
"lesser",
"than",
"entered",
"number",
"<p",
">",
"Can",
"be",
"used",
"in",
"combination",
"with",
"{"
] | train | https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/util/form/SimpleFormValidator.java#L133-L135 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java | KeyVaultClientCustomImpl.listSecretVersions | public PagedList<SecretItem> listSecretVersions(final String vaultBaseUrl, final String secretName) {
"""
List the versions of the specified secret.
@param vaultBaseUrl
The vault name, e.g. https://myvault.vault.azure.net
@param secretName
The name of the secret in the given vault
@return the PagedList<SecretItem> if successful.
"""
return getSecretVersions(vaultBaseUrl, secretName);
} | java | public PagedList<SecretItem> listSecretVersions(final String vaultBaseUrl, final String secretName) {
return getSecretVersions(vaultBaseUrl, secretName);
} | [
"public",
"PagedList",
"<",
"SecretItem",
">",
"listSecretVersions",
"(",
"final",
"String",
"vaultBaseUrl",
",",
"final",
"String",
"secretName",
")",
"{",
"return",
"getSecretVersions",
"(",
"vaultBaseUrl",
",",
"secretName",
")",
";",
"}"
] | List the versions of the specified secret.
@param vaultBaseUrl
The vault name, e.g. https://myvault.vault.azure.net
@param secretName
The name of the secret in the given vault
@return the PagedList<SecretItem> if successful. | [
"List",
"the",
"versions",
"of",
"the",
"specified",
"secret",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java#L1229-L1231 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgObject.java | DwgObject.readObjectHeaderV15 | public int readObjectHeaderV15(int[] data, int offset) throws Exception {
"""
Reads the header of an object in a DWG file Version 15
@param data Array of unsigned bytes obtained from the DWG binary file
@param offset The current bit offset where the value begins
@return int New offset
@throws Exception If an unexpected bit value is found in the DWG file. Occurs
when we are looking for LwPolylines.
"""
int bitPos = offset;
Integer mode = (Integer)DwgUtil.getBits(data, 2, bitPos);
bitPos = bitPos + 2;
setMode(mode.intValue());
Vector v = DwgUtil.getBitLong(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int rnum = ((Integer)v.get(1)).intValue();
setNumReactors(rnum);
v = DwgUtil.testBit(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
boolean nolinks = ((Boolean)v.get(1)).booleanValue();
setNoLinks(nolinks);
v = DwgUtil.getBitShort(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int color = ((Integer)v.get(1)).intValue();
setColor(color);
v = DwgUtil.getBitDouble(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
float ltscale = ((Double)v.get(1)).floatValue();
Integer ltflag = (Integer)DwgUtil.getBits(data, 2, bitPos);
bitPos = bitPos + 2;
Integer psflag = (Integer)DwgUtil.getBits(data, 2, bitPos);
bitPos = bitPos + 2;
v = DwgUtil.getBitShort(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int invis = ((Integer)v.get(1)).intValue();
v = DwgUtil.getRawChar(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int weight = ((Integer)v.get(1)).intValue();
return bitPos;
} | java | public int readObjectHeaderV15(int[] data, int offset) throws Exception {
int bitPos = offset;
Integer mode = (Integer)DwgUtil.getBits(data, 2, bitPos);
bitPos = bitPos + 2;
setMode(mode.intValue());
Vector v = DwgUtil.getBitLong(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int rnum = ((Integer)v.get(1)).intValue();
setNumReactors(rnum);
v = DwgUtil.testBit(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
boolean nolinks = ((Boolean)v.get(1)).booleanValue();
setNoLinks(nolinks);
v = DwgUtil.getBitShort(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int color = ((Integer)v.get(1)).intValue();
setColor(color);
v = DwgUtil.getBitDouble(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
float ltscale = ((Double)v.get(1)).floatValue();
Integer ltflag = (Integer)DwgUtil.getBits(data, 2, bitPos);
bitPos = bitPos + 2;
Integer psflag = (Integer)DwgUtil.getBits(data, 2, bitPos);
bitPos = bitPos + 2;
v = DwgUtil.getBitShort(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int invis = ((Integer)v.get(1)).intValue();
v = DwgUtil.getRawChar(data, bitPos);
bitPos = ((Integer)v.get(0)).intValue();
int weight = ((Integer)v.get(1)).intValue();
return bitPos;
} | [
"public",
"int",
"readObjectHeaderV15",
"(",
"int",
"[",
"]",
"data",
",",
"int",
"offset",
")",
"throws",
"Exception",
"{",
"int",
"bitPos",
"=",
"offset",
";",
"Integer",
"mode",
"=",
"(",
"Integer",
")",
"DwgUtil",
".",
"getBits",
"(",
"data",
",",
... | Reads the header of an object in a DWG file Version 15
@param data Array of unsigned bytes obtained from the DWG binary file
@param offset The current bit offset where the value begins
@return int New offset
@throws Exception If an unexpected bit value is found in the DWG file. Occurs
when we are looking for LwPolylines. | [
"Reads",
"the",
"header",
"of",
"an",
"object",
"in",
"a",
"DWG",
"file",
"Version",
"15"
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/DwgObject.java#L56-L87 |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/processor/map/SetTiledWmsProcessor.java | SetTiledWmsProcessor.adaptTileDimensions | private static Dimension adaptTileDimensions(
final Dimension pixels, final int maxWidth, final int maxHeight) {
"""
Adapt the size of the tiles so that we have the same amount of tiles as we would have had with maxWidth
and maxHeight, but with the smallest tiles as possible.
"""
return new Dimension(adaptTileDimension(pixels.width, maxWidth),
adaptTileDimension(pixels.height, maxHeight));
} | java | private static Dimension adaptTileDimensions(
final Dimension pixels, final int maxWidth, final int maxHeight) {
return new Dimension(adaptTileDimension(pixels.width, maxWidth),
adaptTileDimension(pixels.height, maxHeight));
} | [
"private",
"static",
"Dimension",
"adaptTileDimensions",
"(",
"final",
"Dimension",
"pixels",
",",
"final",
"int",
"maxWidth",
",",
"final",
"int",
"maxHeight",
")",
"{",
"return",
"new",
"Dimension",
"(",
"adaptTileDimension",
"(",
"pixels",
".",
"width",
",",
... | Adapt the size of the tiles so that we have the same amount of tiles as we would have had with maxWidth
and maxHeight, but with the smallest tiles as possible. | [
"Adapt",
"the",
"size",
"of",
"the",
"tiles",
"so",
"that",
"we",
"have",
"the",
"same",
"amount",
"of",
"tiles",
"as",
"we",
"would",
"have",
"had",
"with",
"maxWidth",
"and",
"maxHeight",
"but",
"with",
"the",
"smallest",
"tiles",
"as",
"possible",
"."... | train | https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/processor/map/SetTiledWmsProcessor.java#L67-L71 |
linkedin/dexmaker | dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/InvocationHandlerAdapter.java | InvocationHandlerAdapter.invoke | @Override
public Object invoke(final Object proxy, final Method method, final Object[] rawArgs) throws
Throwable {
"""
Intercept a method call. Called <u>before</u> a method is called by the proxied method.
<p>This does the same as {@link #interceptEntryHook(Object, Method, Object[], SuperMethod)}
but this handles proxied methods. We only proxy abstract methods.
@param proxy proxies object
@param method method that was called
@param rawArgs arguments to the method
@return mocked result
@throws Throwable An exception if thrown
"""
// args can be null if the method invoked has no arguments, but Mockito expects a non-null
Object[] args = rawArgs;
if (rawArgs == null) {
args = new Object[0];
}
if (isEqualsMethod(method)) {
return proxy == args[0];
} else if (isHashCodeMethod(method)) {
return System.identityHashCode(proxy);
}
return handler.handle(Mockito.framework().getInvocationFactory().createInvocation(proxy,
withSettings().build(proxy.getClass().getSuperclass()), method,
new RealMethodBehavior() {
@Override
public Object call() throws Throwable {
return ProxyBuilder.callSuper(proxy, method, rawArgs);
}
}, args));
} | java | @Override
public Object invoke(final Object proxy, final Method method, final Object[] rawArgs) throws
Throwable {
// args can be null if the method invoked has no arguments, but Mockito expects a non-null
Object[] args = rawArgs;
if (rawArgs == null) {
args = new Object[0];
}
if (isEqualsMethod(method)) {
return proxy == args[0];
} else if (isHashCodeMethod(method)) {
return System.identityHashCode(proxy);
}
return handler.handle(Mockito.framework().getInvocationFactory().createInvocation(proxy,
withSettings().build(proxy.getClass().getSuperclass()), method,
new RealMethodBehavior() {
@Override
public Object call() throws Throwable {
return ProxyBuilder.callSuper(proxy, method, rawArgs);
}
}, args));
} | [
"@",
"Override",
"public",
"Object",
"invoke",
"(",
"final",
"Object",
"proxy",
",",
"final",
"Method",
"method",
",",
"final",
"Object",
"[",
"]",
"rawArgs",
")",
"throws",
"Throwable",
"{",
"// args can be null if the method invoked has no arguments, but Mockito expec... | Intercept a method call. Called <u>before</u> a method is called by the proxied method.
<p>This does the same as {@link #interceptEntryHook(Object, Method, Object[], SuperMethod)}
but this handles proxied methods. We only proxy abstract methods.
@param proxy proxies object
@param method method that was called
@param rawArgs arguments to the method
@return mocked result
@throws Throwable An exception if thrown | [
"Intercept",
"a",
"method",
"call",
".",
"Called",
"<u",
">",
"before<",
"/",
"u",
">",
"a",
"method",
"is",
"called",
"by",
"the",
"proxied",
"method",
"."
] | train | https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/InvocationHandlerAdapter.java#L97-L120 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/odmg/ObjectEnvelopeOrdering.java | ObjectEnvelopeOrdering.containsObject | private static boolean containsObject(Object searchFor, Object[] searchIn) {
"""
Helper method that searches an object array for the occurence of a
specific object based on reference equality
@param searchFor the object to search for
@param searchIn the array to search in
@return true if the object is found, otherwise false
"""
for (int i = 0; i < searchIn.length; i++)
{
if (searchFor == searchIn[i])
{
return true;
}
}
return false;
} | java | private static boolean containsObject(Object searchFor, Object[] searchIn)
{
for (int i = 0; i < searchIn.length; i++)
{
if (searchFor == searchIn[i])
{
return true;
}
}
return false;
} | [
"private",
"static",
"boolean",
"containsObject",
"(",
"Object",
"searchFor",
",",
"Object",
"[",
"]",
"searchIn",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"searchIn",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"searchFor",... | Helper method that searches an object array for the occurence of a
specific object based on reference equality
@param searchFor the object to search for
@param searchIn the array to search in
@return true if the object is found, otherwise false | [
"Helper",
"method",
"that",
"searches",
"an",
"object",
"array",
"for",
"the",
"occurence",
"of",
"a",
"specific",
"object",
"based",
"on",
"reference",
"equality"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/odmg/ObjectEnvelopeOrdering.java#L389-L399 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java | GJGeometryReader.parsePoint | private Point parsePoint(JsonParser jp) throws IOException, SQLException {
"""
Parses one position
Syntax:
{ "type": "Point", "coordinates": [100.0, 0.0] }
@param jsParser
@throws IOException
@return Point
"""
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ to parse the coordinate
Point point = GF.createPoint(parseCoordinate(jp));
jp.nextToken();
return point;
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | java | private Point parsePoint(JsonParser jp) throws IOException, SQLException {
jp.nextToken(); // FIELD_NAME coordinates
String coordinatesField = jp.getText();
if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) {
jp.nextToken(); // START_ARRAY [ to parse the coordinate
Point point = GF.createPoint(parseCoordinate(jp));
jp.nextToken();
return point;
} else {
throw new SQLException("Malformed GeoJSON file. Expected 'coordinates', found '" + coordinatesField + "'");
}
} | [
"private",
"Point",
"parsePoint",
"(",
"JsonParser",
"jp",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"jp",
".",
"nextToken",
"(",
")",
";",
"// FIELD_NAME coordinates ",
"String",
"coordinatesField",
"=",
"jp",
".",
"getText",
"(",
")",
";",... | Parses one position
Syntax:
{ "type": "Point", "coordinates": [100.0, 0.0] }
@param jsParser
@throws IOException
@return Point | [
"Parses",
"one",
"position"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GJGeometryReader.java#L91-L102 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlSerialMethodWriter.java | HtmlSerialMethodWriter.addMemberTags | public void addMemberTags(ExecutableElement member, Content methodsContentTree) {
"""
Add the tag information for this member.
@param member the method to document.
@param methodsContentTree the tree to which the member tags info will be added
"""
Content tagContent = new ContentBuilder();
TagletManager tagletManager =
configuration.tagletManager;
TagletWriter.genTagOutput(tagletManager, member,
tagletManager.getSerializedFormTaglets(),
writer.getTagletWriterInstance(false), tagContent);
Content dlTags = new HtmlTree(HtmlTag.DL);
dlTags.addContent(tagContent);
methodsContentTree.addContent(dlTags);
if (name(member).compareTo("writeExternal") == 0
&& utils.getSerialDataTrees(member).isEmpty()) {
serialWarning(member, "doclet.MissingSerialDataTag",
utils.getFullyQualifiedName(member.getEnclosingElement()), name(member));
}
} | java | public void addMemberTags(ExecutableElement member, Content methodsContentTree) {
Content tagContent = new ContentBuilder();
TagletManager tagletManager =
configuration.tagletManager;
TagletWriter.genTagOutput(tagletManager, member,
tagletManager.getSerializedFormTaglets(),
writer.getTagletWriterInstance(false), tagContent);
Content dlTags = new HtmlTree(HtmlTag.DL);
dlTags.addContent(tagContent);
methodsContentTree.addContent(dlTags);
if (name(member).compareTo("writeExternal") == 0
&& utils.getSerialDataTrees(member).isEmpty()) {
serialWarning(member, "doclet.MissingSerialDataTag",
utils.getFullyQualifiedName(member.getEnclosingElement()), name(member));
}
} | [
"public",
"void",
"addMemberTags",
"(",
"ExecutableElement",
"member",
",",
"Content",
"methodsContentTree",
")",
"{",
"Content",
"tagContent",
"=",
"new",
"ContentBuilder",
"(",
")",
";",
"TagletManager",
"tagletManager",
"=",
"configuration",
".",
"tagletManager",
... | Add the tag information for this member.
@param member the method to document.
@param methodsContentTree the tree to which the member tags info will be added | [
"Add",
"the",
"tag",
"information",
"for",
"this",
"member",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlSerialMethodWriter.java#L153-L168 |
micronaut-projects/micronaut-core | cli/src/main/groovy/io/micronaut/cli/console/logging/MicronautConsole.java | MicronautConsole.indicateProgressPercentage | @SuppressWarnings("MagicNumber")
@Override
public void indicateProgressPercentage(long number, long total) {
"""
Indicates progress as a percentage for the given number and total.
@param number The number
@param total The total
"""
verifySystemOut();
progressIndicatorActive = true;
String currMsg = lastMessage;
try {
int percentage = Math.round(NumberMath.multiply(NumberMath.divide(number, total), 100).floatValue());
if (!isAnsiEnabled()) {
out.print("..");
out.print(percentage + '%');
} else {
updateStatus(currMsg + ' ' + percentage + '%');
}
} finally {
lastMessage = currMsg;
}
} | java | @SuppressWarnings("MagicNumber")
@Override
public void indicateProgressPercentage(long number, long total) {
verifySystemOut();
progressIndicatorActive = true;
String currMsg = lastMessage;
try {
int percentage = Math.round(NumberMath.multiply(NumberMath.divide(number, total), 100).floatValue());
if (!isAnsiEnabled()) {
out.print("..");
out.print(percentage + '%');
} else {
updateStatus(currMsg + ' ' + percentage + '%');
}
} finally {
lastMessage = currMsg;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"MagicNumber\"",
")",
"@",
"Override",
"public",
"void",
"indicateProgressPercentage",
"(",
"long",
"number",
",",
"long",
"total",
")",
"{",
"verifySystemOut",
"(",
")",
";",
"progressIndicatorActive",
"=",
"true",
";",
"String",
... | Indicates progress as a percentage for the given number and total.
@param number The number
@param total The total | [
"Indicates",
"progress",
"as",
"a",
"percentage",
"for",
"the",
"given",
"number",
"and",
"total",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/cli/src/main/groovy/io/micronaut/cli/console/logging/MicronautConsole.java#L658-L676 |
pippo-java/pippo | pippo-core/src/main/java/ro/pippo/core/PippoSettings.java | PippoSettings.loadOverrides | private Properties loadOverrides(File baseDir, Properties properties) throws IOException {
"""
Recursively read "override" properties files.
<p>
"Override" properties overwrite the provided properties.
</p>
@param baseDir
@param properties
@return the merged properties
@throws IOException
"""
return loadProperties(baseDir, properties, "override", true);
} | java | private Properties loadOverrides(File baseDir, Properties properties) throws IOException {
return loadProperties(baseDir, properties, "override", true);
} | [
"private",
"Properties",
"loadOverrides",
"(",
"File",
"baseDir",
",",
"Properties",
"properties",
")",
"throws",
"IOException",
"{",
"return",
"loadProperties",
"(",
"baseDir",
",",
"properties",
",",
"\"override\"",
",",
"true",
")",
";",
"}"
] | Recursively read "override" properties files.
<p>
"Override" properties overwrite the provided properties.
</p>
@param baseDir
@param properties
@return the merged properties
@throws IOException | [
"Recursively",
"read",
"override",
"properties",
"files",
".",
"<p",
">",
"Override",
"properties",
"overwrite",
"the",
"provided",
"properties",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/pippo-java/pippo/blob/cb5ccb453bffcc3cf386adc660674812d10b9726/pippo-core/src/main/java/ro/pippo/core/PippoSettings.java#L287-L289 |
baratine/baratine | framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java | XmlWriter.writeText | public void writeText(char[] buf, int offset, int length) {
"""
Close an open element (if any), then write with escaping as needed.
"""
closeElementIfNeeded(false);
writeIndentIfNewLine();
_strategy.writeText(this, buf, offset, length);
} | java | public void writeText(char[] buf, int offset, int length)
{
closeElementIfNeeded(false);
writeIndentIfNewLine();
_strategy.writeText(this, buf, offset, length);
} | [
"public",
"void",
"writeText",
"(",
"char",
"[",
"]",
"buf",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"closeElementIfNeeded",
"(",
"false",
")",
";",
"writeIndentIfNewLine",
"(",
")",
";",
"_strategy",
".",
"writeText",
"(",
"this",
",",
"bu... | Close an open element (if any), then write with escaping as needed. | [
"Close",
"an",
"open",
"element",
"(",
"if",
"any",
")",
"then",
"write",
"with",
"escaping",
"as",
"needed",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java#L355-L360 |
mlhartme/sushi | src/main/java/net/oneandone/sushi/util/IntBitRelation.java | IntBitRelation.composeRightLeft | public void composeRightLeft(IntBitRelation left, IntBitRelation right) {
"""
If (a,b) is element of left and (b,c) is element of right,
then (a,c) is added to this relation.
@param left left relation
@param right right relation.
"""
int i, ele;
IntBitSet li;
for (i = 0; i < left.line.length; i++) {
li = left.line[i];
if (li != null) {
for (ele = li.first(); ele != -1; ele = li.next(ele)) {
if (right.line[ele] != null) {
add(i, right.line[ele]);
}
}
}
}
} | java | public void composeRightLeft(IntBitRelation left, IntBitRelation right) {
int i, ele;
IntBitSet li;
for (i = 0; i < left.line.length; i++) {
li = left.line[i];
if (li != null) {
for (ele = li.first(); ele != -1; ele = li.next(ele)) {
if (right.line[ele] != null) {
add(i, right.line[ele]);
}
}
}
}
} | [
"public",
"void",
"composeRightLeft",
"(",
"IntBitRelation",
"left",
",",
"IntBitRelation",
"right",
")",
"{",
"int",
"i",
",",
"ele",
";",
"IntBitSet",
"li",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"left",
".",
"line",
".",
"length",
";",
"i"... | If (a,b) is element of left and (b,c) is element of right,
then (a,c) is added to this relation.
@param left left relation
@param right right relation. | [
"If",
"(",
"a",
"b",
")",
"is",
"element",
"of",
"left",
"and",
"(",
"b",
"c",
")",
"is",
"element",
"of",
"right",
"then",
"(",
"a",
"c",
")",
"is",
"added",
"to",
"this",
"relation",
"."
] | train | https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/util/IntBitRelation.java#L148-L162 |
jglobus/JGlobus | gridftp/src/main/java/org/globus/ftp/FTPClient.java | FTPClient.asynchPut | public TransferState asynchPut(String remoteFileName,
DataSource source,
MarkerListener mListener)
throws IOException, ServerException, ClientException {
"""
Stores file at the remote server.
@param remoteFileName remote file name
@param source data will be read from here
@param mListener restart marker listener (currently not used)
"""
return asynchPut(remoteFileName, source, mListener, false);
} | java | public TransferState asynchPut(String remoteFileName,
DataSource source,
MarkerListener mListener)
throws IOException, ServerException, ClientException {
return asynchPut(remoteFileName, source, mListener, false);
} | [
"public",
"TransferState",
"asynchPut",
"(",
"String",
"remoteFileName",
",",
"DataSource",
"source",
",",
"MarkerListener",
"mListener",
")",
"throws",
"IOException",
",",
"ServerException",
",",
"ClientException",
"{",
"return",
"asynchPut",
"(",
"remoteFileName",
"... | Stores file at the remote server.
@param remoteFileName remote file name
@param source data will be read from here
@param mListener restart marker listener (currently not used) | [
"Stores",
"file",
"at",
"the",
"remote",
"server",
"."
] | train | https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/FTPClient.java#L1319-L1324 |
Alluxio/alluxio | core/base/src/main/java/alluxio/util/SleepUtils.java | SleepUtils.sleepMs | public static void sleepMs(Logger logger, long timeMs) {
"""
Sleeps for the given number of milliseconds, reporting interruptions using the given logger.
Unlike Thread.sleep(), this method responds to interrupts by setting the thread interrupt
status. This means that callers must check the interrupt status if they need to handle
interrupts.
@param logger logger for reporting interruptions; no reporting is done if the logger is null
@param timeMs sleep duration in milliseconds
"""
try {
Thread.sleep(timeMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
if (logger != null) {
logger.warn(e.getMessage(), e);
}
}
} | java | public static void sleepMs(Logger logger, long timeMs) {
try {
Thread.sleep(timeMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
if (logger != null) {
logger.warn(e.getMessage(), e);
}
}
} | [
"public",
"static",
"void",
"sleepMs",
"(",
"Logger",
"logger",
",",
"long",
"timeMs",
")",
"{",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"timeMs",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"Thread",
".",
"currentThread",
"(",
... | Sleeps for the given number of milliseconds, reporting interruptions using the given logger.
Unlike Thread.sleep(), this method responds to interrupts by setting the thread interrupt
status. This means that callers must check the interrupt status if they need to handle
interrupts.
@param logger logger for reporting interruptions; no reporting is done if the logger is null
@param timeMs sleep duration in milliseconds | [
"Sleeps",
"for",
"the",
"given",
"number",
"of",
"milliseconds",
"reporting",
"interruptions",
"using",
"the",
"given",
"logger",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/base/src/main/java/alluxio/util/SleepUtils.java#L45-L54 |
liferay/com-liferay-commerce | commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleUserSegmentRelPersistenceImpl.java | CPRuleUserSegmentRelPersistenceImpl.findAll | @Override
public List<CPRuleUserSegmentRel> findAll(int start, int end) {
"""
Returns a range of all the cp rule user segment rels.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPRuleUserSegmentRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of cp rule user segment rels
@param end the upper bound of the range of cp rule user segment rels (not inclusive)
@return the range of cp rule user segment rels
"""
return findAll(start, end, null);
} | java | @Override
public List<CPRuleUserSegmentRel> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPRuleUserSegmentRel",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the cp rule user segment rels.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPRuleUserSegmentRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of cp rule user segment rels
@param end the upper bound of the range of cp rule user segment rels (not inclusive)
@return the range of cp rule user segment rels | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cp",
"rule",
"user",
"segment",
"rels",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPRuleUserSegmentRelPersistenceImpl.java#L1681-L1684 |
Azure/azure-sdk-for-java | labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java | GlobalUsersInner.listEnvironments | public ListEnvironmentsResponseInner listEnvironments(String userName, String labId) {
"""
List Environments for the user.
@param userName The name of the user.
@param labId The resource Id of the lab
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ListEnvironmentsResponseInner object if successful.
"""
return listEnvironmentsWithServiceResponseAsync(userName, labId).toBlocking().single().body();
} | java | public ListEnvironmentsResponseInner listEnvironments(String userName, String labId) {
return listEnvironmentsWithServiceResponseAsync(userName, labId).toBlocking().single().body();
} | [
"public",
"ListEnvironmentsResponseInner",
"listEnvironments",
"(",
"String",
"userName",
",",
"String",
"labId",
")",
"{",
"return",
"listEnvironmentsWithServiceResponseAsync",
"(",
"userName",
",",
"labId",
")",
".",
"toBlocking",
"(",
")",
".",
"single",
"(",
")"... | List Environments for the user.
@param userName The name of the user.
@param labId The resource Id of the lab
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ListEnvironmentsResponseInner object if successful. | [
"List",
"Environments",
"for",
"the",
"user",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/GlobalUsersInner.java#L623-L625 |
ZuInnoTe/hadoopcryptoledger | inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java | EthereumUtil.calculateChainId | public static Long calculateChainId(EthereumTransaction eTrans) {
"""
Calculates the chain Id
@param eTrans Ethereum Transaction of which the chain id should be calculated
@return chainId: 0, Ethereum testnet (aka Olympic); 1: Ethereum mainet (aka Frontier, Homestead, Metropolis) - also Classic (from fork) -also Expanse (alternative Ethereum implementation), 2 Morden (Ethereum testnet, now Ethereum classic testnet), 3 Ropsten public cross-client Ethereum testnet, 4: Rinkeby Geth Ethereum testnet, 42 Kovan, public Parity Ethereum testnet, 7762959 Musicoin, music blockchain
"""
Long result=null;
long rawResult=EthereumUtil.convertVarNumberToLong(new RLPElement(new byte[0],eTrans.getSig_v()));
if (!((rawResult == EthereumUtil.LOWER_REAL_V) || (rawResult== (LOWER_REAL_V+1)))) {
result = (rawResult-EthereumUtil.CHAIN_ID_INC)/2;
}
return result;
} | java | public static Long calculateChainId(EthereumTransaction eTrans) {
Long result=null;
long rawResult=EthereumUtil.convertVarNumberToLong(new RLPElement(new byte[0],eTrans.getSig_v()));
if (!((rawResult == EthereumUtil.LOWER_REAL_V) || (rawResult== (LOWER_REAL_V+1)))) {
result = (rawResult-EthereumUtil.CHAIN_ID_INC)/2;
}
return result;
} | [
"public",
"static",
"Long",
"calculateChainId",
"(",
"EthereumTransaction",
"eTrans",
")",
"{",
"Long",
"result",
"=",
"null",
";",
"long",
"rawResult",
"=",
"EthereumUtil",
".",
"convertVarNumberToLong",
"(",
"new",
"RLPElement",
"(",
"new",
"byte",
"[",
"0",
... | Calculates the chain Id
@param eTrans Ethereum Transaction of which the chain id should be calculated
@return chainId: 0, Ethereum testnet (aka Olympic); 1: Ethereum mainet (aka Frontier, Homestead, Metropolis) - also Classic (from fork) -also Expanse (alternative Ethereum implementation), 2 Morden (Ethereum testnet, now Ethereum classic testnet), 3 Ropsten public cross-client Ethereum testnet, 4: Rinkeby Geth Ethereum testnet, 42 Kovan, public Parity Ethereum testnet, 7762959 Musicoin, music blockchain | [
"Calculates",
"the",
"chain",
"Id"
] | train | https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L364-L371 |
GenesysPureEngage/provisioning-client-java | src/main/java/com/genesys/internal/provisioning/api/ObjectsApi.java | ObjectsApi.postPermissionsAsync | public com.squareup.okhttp.Call postPermissionsAsync(String objectType, PostPermissionsData body, final ApiCallback<Void> callback) throws ApiException {
"""
Post permissions for a list of objects. (asynchronously)
Post permissions from Configuration Server for objects identified by their type and DBIDs.
@param objectType (required)
@param body (optional)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object
"""
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = postPermissionsValidateBeforeCall(objectType, body, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
} | java | public com.squareup.okhttp.Call postPermissionsAsync(String objectType, PostPermissionsData body, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = postPermissionsValidateBeforeCall(objectType, body, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"postPermissionsAsync",
"(",
"String",
"objectType",
",",
"PostPermissionsData",
"body",
",",
"final",
"ApiCallback",
"<",
"Void",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"ProgressResponseB... | Post permissions for a list of objects. (asynchronously)
Post permissions from Configuration Server for objects identified by their type and DBIDs.
@param objectType (required)
@param body (optional)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Post",
"permissions",
"for",
"a",
"list",
"of",
"objects",
".",
"(",
"asynchronously",
")",
"Post",
"permissions",
"from",
"Configuration",
"Server",
"for",
"objects",
"identified",
"by",
"their",
"type",
"and",
"DBIDs",
"."
] | train | https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/ObjectsApi.java#L505-L529 |
mikepenz/FastAdapter | library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/DragDropUtil.java | DragDropUtil.bindDragHandle | public static void bindDragHandle(final RecyclerView.ViewHolder holder, final IExtendedDraggable item) {
"""
this functions binds the view's touch listener to start the drag via the touch helper...
@param holder the view holder
@param holder the item
"""
// if necessary, init the drag handle, which will start the drag when touched
if (item.getTouchHelper() != null && item.getDragView(holder) != null) {
item.getDragView(holder).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
if (item.isDraggable())
item.getTouchHelper().startDrag(holder);
}
return false;
}
});
}
} | java | public static void bindDragHandle(final RecyclerView.ViewHolder holder, final IExtendedDraggable item) {
// if necessary, init the drag handle, which will start the drag when touched
if (item.getTouchHelper() != null && item.getDragView(holder) != null) {
item.getDragView(holder).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
if (item.isDraggable())
item.getTouchHelper().startDrag(holder);
}
return false;
}
});
}
} | [
"public",
"static",
"void",
"bindDragHandle",
"(",
"final",
"RecyclerView",
".",
"ViewHolder",
"holder",
",",
"final",
"IExtendedDraggable",
"item",
")",
"{",
"// if necessary, init the drag handle, which will start the drag when touched",
"if",
"(",
"item",
".",
"getTouchH... | this functions binds the view's touch listener to start the drag via the touch helper...
@param holder the view holder
@param holder the item | [
"this",
"functions",
"binds",
"the",
"view",
"s",
"touch",
"listener",
"to",
"start",
"the",
"drag",
"via",
"the",
"touch",
"helper",
"..."
] | train | https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/utilities/DragDropUtil.java#L23-L37 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/GalleriesApi.java | GalleriesApi.editPhotos | public Response editPhotos(String galleryId, String primaryPhotoId, List<String> photoIds) throws JinxException {
"""
Modify the photos in a gallery. Use this method to add, remove and re-order photos.
<br>
This method requires authentication with 'write' permission.
@param galleryId Required. The id of the gallery to modify. The gallery must belong to the calling user.
@param primaryPhotoId Required. The id of the photo to use as the 'primary' photo for the gallery. This id must also be passed along in photo_ids list argument.
@param photoIds Required. A list of photo ids to include in the gallery. They will appear in the set in the order sent. This list must contain the primary photo id. This list of photos replaces the existing list.
@return object with response from Flickr indicating ok or fail.
@throws JinxException if required parameters are null or empty, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.galleries.editPhotos.html">flickr.galleries.editPhotos</a>
"""
JinxUtils.validateParams(galleryId, primaryPhotoId, photoIds);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.galleries.editPhotos");
params.put("gallery_id", galleryId);
params.put("primary_photo_id", primaryPhotoId);
params.put("photo_ids", JinxUtils.buildCommaDelimitedList(photoIds));
return jinx.flickrPost(params, Response.class);
} | java | public Response editPhotos(String galleryId, String primaryPhotoId, List<String> photoIds) throws JinxException {
JinxUtils.validateParams(galleryId, primaryPhotoId, photoIds);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.galleries.editPhotos");
params.put("gallery_id", galleryId);
params.put("primary_photo_id", primaryPhotoId);
params.put("photo_ids", JinxUtils.buildCommaDelimitedList(photoIds));
return jinx.flickrPost(params, Response.class);
} | [
"public",
"Response",
"editPhotos",
"(",
"String",
"galleryId",
",",
"String",
"primaryPhotoId",
",",
"List",
"<",
"String",
">",
"photoIds",
")",
"throws",
"JinxException",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"galleryId",
",",
"primaryPhotoId",
",",
"... | Modify the photos in a gallery. Use this method to add, remove and re-order photos.
<br>
This method requires authentication with 'write' permission.
@param galleryId Required. The id of the gallery to modify. The gallery must belong to the calling user.
@param primaryPhotoId Required. The id of the photo to use as the 'primary' photo for the gallery. This id must also be passed along in photo_ids list argument.
@param photoIds Required. A list of photo ids to include in the gallery. They will appear in the set in the order sent. This list must contain the primary photo id. This list of photos replaces the existing list.
@return object with response from Flickr indicating ok or fail.
@throws JinxException if required parameters are null or empty, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.galleries.editPhotos.html">flickr.galleries.editPhotos</a> | [
"Modify",
"the",
"photos",
"in",
"a",
"gallery",
".",
"Use",
"this",
"method",
"to",
"add",
"remove",
"and",
"re",
"-",
"order",
"photos",
".",
"<br",
">",
"This",
"method",
"requires",
"authentication",
"with",
"write",
"permission",
"."
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/GalleriesApi.java#L158-L166 |
jboss/jboss-jsf-api_spec | src/main/java/javax/faces/render/ResponseStateManager.java | ResponseStateManager.getState | public Object getState(FacesContext context, String viewId) {
"""
<p><span class="changed_modified_2_2">The</span> implementation must
inspect the current request and return
an Object representing the tree structure and component state
passed in to a previous invocation of {@link
#writeState(javax.faces.context.FacesContext,java.lang.Object)}.</p>
<p class="changed_added_2_2">If the state saving method for this
application is {@link
javax.faces.application.StateManager#STATE_SAVING_METHOD_CLIENT},
<code>writeState()</code> will have encrypted the state in a tamper
evident manner. If the state fails to decrypt, or decrypts but
indicates evidence of tampering, a
{@link javax.faces.application.ProtectedViewException} must be thrown.</p>
<p>For backwards compatability with existing
<code>ResponseStateManager</code> implementations, the default
implementation of this method calls {@link
#getTreeStructureToRestore} and {@link
#getComponentStateToRestore} and creates and returns a two
element <code>Object</code> array with element zero containing
the <code>structure</code> property and element one containing
the <code>state</code> property of the
<code>SerializedView</code>.</p>
@since 1.2
@param context The {@link FacesContext} instance for the current request
@param viewId View identifier of the view to be restored
@return the tree structure and component state Object passed in
to <code>writeState</code>. If this is an initial request, this
method returns <code>null</code>.
"""
Object stateArray[] = { getTreeStructureToRestore(context, viewId),
getComponentStateToRestore(context) };
return stateArray;
} | java | public Object getState(FacesContext context, String viewId) {
Object stateArray[] = { getTreeStructureToRestore(context, viewId),
getComponentStateToRestore(context) };
return stateArray;
} | [
"public",
"Object",
"getState",
"(",
"FacesContext",
"context",
",",
"String",
"viewId",
")",
"{",
"Object",
"stateArray",
"[",
"]",
"=",
"{",
"getTreeStructureToRestore",
"(",
"context",
",",
"viewId",
")",
",",
"getComponentStateToRestore",
"(",
"context",
")"... | <p><span class="changed_modified_2_2">The</span> implementation must
inspect the current request and return
an Object representing the tree structure and component state
passed in to a previous invocation of {@link
#writeState(javax.faces.context.FacesContext,java.lang.Object)}.</p>
<p class="changed_added_2_2">If the state saving method for this
application is {@link
javax.faces.application.StateManager#STATE_SAVING_METHOD_CLIENT},
<code>writeState()</code> will have encrypted the state in a tamper
evident manner. If the state fails to decrypt, or decrypts but
indicates evidence of tampering, a
{@link javax.faces.application.ProtectedViewException} must be thrown.</p>
<p>For backwards compatability with existing
<code>ResponseStateManager</code> implementations, the default
implementation of this method calls {@link
#getTreeStructureToRestore} and {@link
#getComponentStateToRestore} and creates and returns a two
element <code>Object</code> array with element zero containing
the <code>structure</code> property and element one containing
the <code>state</code> property of the
<code>SerializedView</code>.</p>
@since 1.2
@param context The {@link FacesContext} instance for the current request
@param viewId View identifier of the view to be restored
@return the tree structure and component state Object passed in
to <code>writeState</code>. If this is an initial request, this
method returns <code>null</code>. | [
"<p",
">",
"<span",
"class",
"=",
"changed_modified_2_2",
">",
"The<",
"/",
"span",
">",
"implementation",
"must",
"inspect",
"the",
"current",
"request",
"and",
"return",
"an",
"Object",
"representing",
"the",
"tree",
"structure",
"and",
"component",
"state",
... | train | https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/render/ResponseStateManager.java#L372-L376 |
btrplace/scheduler | btrpsl/src/main/java/org/btrplace/btrpsl/constraint/AmongBuilder.java | AmongBuilder.buildConstraint | @Override
public List<? extends SatConstraint> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
"""
Build a constraint.
@param t the current tree
@param args the argument. Must be a non-empty set of virtual machines and a multiset of nodes with
at least two non-empty sets. If the multi set contains only one set, a {@code Fence} constraint is created
@return the constraint
"""
if (checkConformance(t, args)) {
@SuppressWarnings("unchecked")
List<VM> vms = (List<VM>) params[0].transform(this, t, args.get(0));
@SuppressWarnings("unchecked")
Collection<Collection<Node>> nss = (Collection<Collection<Node>>) params[1].transform(this, t, args.get(1));
return vms != null && nss != null ? Collections.singletonList(new Among(vms, nss)) : Collections.emptyList();
}
return Collections.emptyList();
} | java | @Override
public List<? extends SatConstraint> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
if (checkConformance(t, args)) {
@SuppressWarnings("unchecked")
List<VM> vms = (List<VM>) params[0].transform(this, t, args.get(0));
@SuppressWarnings("unchecked")
Collection<Collection<Node>> nss = (Collection<Collection<Node>>) params[1].transform(this, t, args.get(1));
return vms != null && nss != null ? Collections.singletonList(new Among(vms, nss)) : Collections.emptyList();
}
return Collections.emptyList();
} | [
"@",
"Override",
"public",
"List",
"<",
"?",
"extends",
"SatConstraint",
">",
"buildConstraint",
"(",
"BtrPlaceTree",
"t",
",",
"List",
"<",
"BtrpOperand",
">",
"args",
")",
"{",
"if",
"(",
"checkConformance",
"(",
"t",
",",
"args",
")",
")",
"{",
"@",
... | Build a constraint.
@param t the current tree
@param args the argument. Must be a non-empty set of virtual machines and a multiset of nodes with
at least two non-empty sets. If the multi set contains only one set, a {@code Fence} constraint is created
@return the constraint | [
"Build",
"a",
"constraint",
"."
] | train | https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/constraint/AmongBuilder.java#L54-L64 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java | TaskOperations.updateTask | public void updateTask(String jobId, String taskId, TaskConstraints constraints)
throws BatchErrorException, IOException {
"""
Updates the specified task.
@param jobId
The ID of the job containing the task.
@param taskId
The ID of the task.
@param constraints
Constraints that apply to this task. If null, the task is given
the default constraints.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service.
"""
updateTask(jobId, taskId, constraints, null);
} | java | public void updateTask(String jobId, String taskId, TaskConstraints constraints)
throws BatchErrorException, IOException {
updateTask(jobId, taskId, constraints, null);
} | [
"public",
"void",
"updateTask",
"(",
"String",
"jobId",
",",
"String",
"taskId",
",",
"TaskConstraints",
"constraints",
")",
"throws",
"BatchErrorException",
",",
"IOException",
"{",
"updateTask",
"(",
"jobId",
",",
"taskId",
",",
"constraints",
",",
"null",
")"... | Updates the specified task.
@param jobId
The ID of the job containing the task.
@param taskId
The ID of the task.
@param constraints
Constraints that apply to this task. If null, the task is given
the default constraints.
@throws BatchErrorException
Exception thrown when an error response is received from the
Batch service.
@throws IOException
Exception thrown when there is an error in
serialization/deserialization of data sent to/received from the
Batch service. | [
"Updates",
"the",
"specified",
"task",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java#L679-L682 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/boosting/Bagging.java | Bagging.getWeightSampledDataSet | public static ClassificationDataSet getWeightSampledDataSet(ClassificationDataSet dataSet, int[] sampledCounts) {
"""
Creates a new data set from the given sample counts. Points sampled
multiple times will be added once to the data set with their weight
multiplied by the number of times it was sampled.
@param dataSet the data set that was sampled from
@param sampledCounts the sampling values obtained from
{@link #sampleWithReplacement(int[], int, java.util.Random) }
@return a new sampled classification data set
"""
ClassificationDataSet destination = new ClassificationDataSet(dataSet.getNumNumericalVars(), dataSet.getCategories(), dataSet.getPredicting());
for (int i = 0; i < sampledCounts.length; i++)
{
if(sampledCounts[i] <= 0)
continue;
DataPoint dp = dataSet.getDataPoint(i);
destination.addDataPoint(dp, dataSet.getDataPointCategory(i), dataSet.getWeight(i)*sampledCounts[i]);
}
return destination;
} | java | public static ClassificationDataSet getWeightSampledDataSet(ClassificationDataSet dataSet, int[] sampledCounts)
{
ClassificationDataSet destination = new ClassificationDataSet(dataSet.getNumNumericalVars(), dataSet.getCategories(), dataSet.getPredicting());
for (int i = 0; i < sampledCounts.length; i++)
{
if(sampledCounts[i] <= 0)
continue;
DataPoint dp = dataSet.getDataPoint(i);
destination.addDataPoint(dp, dataSet.getDataPointCategory(i), dataSet.getWeight(i)*sampledCounts[i]);
}
return destination;
} | [
"public",
"static",
"ClassificationDataSet",
"getWeightSampledDataSet",
"(",
"ClassificationDataSet",
"dataSet",
",",
"int",
"[",
"]",
"sampledCounts",
")",
"{",
"ClassificationDataSet",
"destination",
"=",
"new",
"ClassificationDataSet",
"(",
"dataSet",
".",
"getNumNumer... | Creates a new data set from the given sample counts. Points sampled
multiple times will be added once to the data set with their weight
multiplied by the number of times it was sampled.
@param dataSet the data set that was sampled from
@param sampledCounts the sampling values obtained from
{@link #sampleWithReplacement(int[], int, java.util.Random) }
@return a new sampled classification data set | [
"Creates",
"a",
"new",
"data",
"set",
"from",
"the",
"given",
"sample",
"counts",
".",
"Points",
"sampled",
"multiple",
"times",
"will",
"be",
"added",
"once",
"to",
"the",
"data",
"set",
"with",
"their",
"weight",
"multiplied",
"by",
"the",
"number",
"of"... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/boosting/Bagging.java#L301-L314 |
czyzby/gdx-lml | mvc/src/main/java/com/github/czyzby/autumn/mvc/component/ui/InterfaceService.java | InterfaceService.addPreferencesToParser | public void addPreferencesToParser(final String preferencesKey, final String preferencesPath) {
"""
Registers {@link com.badlogic.gdx.Preferences} object to the LML parser.
@param preferencesKey key of the preferences as it appears in LML views.
@param preferencesPath path to the preferences.
"""
parser.getData().addPreferences(preferencesKey, ApplicationPreferences.getPreferences(preferencesPath));
} | java | public void addPreferencesToParser(final String preferencesKey, final String preferencesPath) {
parser.getData().addPreferences(preferencesKey, ApplicationPreferences.getPreferences(preferencesPath));
} | [
"public",
"void",
"addPreferencesToParser",
"(",
"final",
"String",
"preferencesKey",
",",
"final",
"String",
"preferencesPath",
")",
"{",
"parser",
".",
"getData",
"(",
")",
".",
"addPreferences",
"(",
"preferencesKey",
",",
"ApplicationPreferences",
".",
"getPrefe... | Registers {@link com.badlogic.gdx.Preferences} object to the LML parser.
@param preferencesKey key of the preferences as it appears in LML views.
@param preferencesPath path to the preferences. | [
"Registers",
"{",
"@link",
"com",
".",
"badlogic",
".",
"gdx",
".",
"Preferences",
"}",
"object",
"to",
"the",
"LML",
"parser",
"."
] | train | https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/mvc/src/main/java/com/github/czyzby/autumn/mvc/component/ui/InterfaceService.java#L126-L128 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_easyHunting_serviceName_screenListConditions_PUT | public void billingAccount_easyHunting_serviceName_screenListConditions_PUT(String billingAccount, String serviceName, OvhEasyHuntingScreenListsConditionsSettings body) throws IOException {
"""
Alter this object properties
REST: PUT /telephony/{billingAccount}/easyHunting/{serviceName}/screenListConditions
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param serviceName [required]
"""
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/screenListConditions";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void billingAccount_easyHunting_serviceName_screenListConditions_PUT(String billingAccount, String serviceName, OvhEasyHuntingScreenListsConditionsSettings body) throws IOException {
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/screenListConditions";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"billingAccount_easyHunting_serviceName_screenListConditions_PUT",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"OvhEasyHuntingScreenListsConditionsSettings",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telepho... | Alter this object properties
REST: PUT /telephony/{billingAccount}/easyHunting/{serviceName}/screenListConditions
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param serviceName [required] | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3311-L3315 |
jbehave/jbehave-core | jbehave-guice/src/main/java/org/jbehave/core/configuration/guice/GuiceAnnotationBuilder.java | GuiceAnnotationBuilder.findBinding | private boolean findBinding(Injector injector, Class<?> type) {
"""
Finds binding for a type in the given injector and, if not found,
recurses to its parent
@param injector
the current Injector
@param type
the Class representing the type
@return A boolean flag, <code>true</code> if binding found
"""
boolean found = false;
for (Key<?> key : injector.getBindings().keySet()) {
if (key.getTypeLiteral().getRawType().equals(type)) {
found = true;
break;
}
}
if (!found && injector.getParent() != null) {
return findBinding(injector.getParent(), type);
}
return found;
} | java | private boolean findBinding(Injector injector, Class<?> type) {
boolean found = false;
for (Key<?> key : injector.getBindings().keySet()) {
if (key.getTypeLiteral().getRawType().equals(type)) {
found = true;
break;
}
}
if (!found && injector.getParent() != null) {
return findBinding(injector.getParent(), type);
}
return found;
} | [
"private",
"boolean",
"findBinding",
"(",
"Injector",
"injector",
",",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"boolean",
"found",
"=",
"false",
";",
"for",
"(",
"Key",
"<",
"?",
">",
"key",
":",
"injector",
".",
"getBindings",
"(",
")",
".",
"keyS... | Finds binding for a type in the given injector and, if not found,
recurses to its parent
@param injector
the current Injector
@param type
the Class representing the type
@return A boolean flag, <code>true</code> if binding found | [
"Finds",
"binding",
"for",
"a",
"type",
"in",
"the",
"given",
"injector",
"and",
"if",
"not",
"found",
"recurses",
"to",
"its",
"parent"
] | train | https://github.com/jbehave/jbehave-core/blob/bdd6a6199528df3c35087e72d4644870655b23e6/jbehave-guice/src/main/java/org/jbehave/core/configuration/guice/GuiceAnnotationBuilder.java#L165-L178 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/br/br_enable.java | br_enable.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception {
"""
<pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre>
"""
br_enable_responses result = (br_enable_responses) service.get_payload_formatter().string_to_resource(br_enable_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_enable_response_array);
}
br_enable[] result_br_enable = new br_enable[result.br_enable_response_array.length];
for(int i = 0; i < result.br_enable_response_array.length; i++)
{
result_br_enable[i] = result.br_enable_response_array[i].br_enable[0];
}
return result_br_enable;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
br_enable_responses result = (br_enable_responses) service.get_payload_formatter().string_to_resource(br_enable_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_enable_response_array);
}
br_enable[] result_br_enable = new br_enable[result.br_enable_response_array.length];
for(int i = 0; i < result.br_enable_response_array.length; i++)
{
result_br_enable[i] = result.br_enable_response_array[i].br_enable[0];
}
return result_br_enable;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"br_enable_responses",
"result",
"=",
"(",
"br_enable_responses",
")",
"service",
".",
"get_payload_formatter"... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_enable.java#L136-L153 |
vznet/mongo-jackson-mapper | src/main/java/net/vz/mongodb/jackson/DBUpdate.java | DBUpdate.pull | public static Builder pull(String field, Object value) {
"""
Remove all occurances of value from the array at field
@param field The field to remove the value from
@param value The value to remove. This may be another query.
@return this object
"""
return new Builder().pull(field, value);
} | java | public static Builder pull(String field, Object value) {
return new Builder().pull(field, value);
} | [
"public",
"static",
"Builder",
"pull",
"(",
"String",
"field",
",",
"Object",
"value",
")",
"{",
"return",
"new",
"Builder",
"(",
")",
".",
"pull",
"(",
"field",
",",
"value",
")",
";",
"}"
] | Remove all occurances of value from the array at field
@param field The field to remove the value from
@param value The value to remove. This may be another query.
@return this object | [
"Remove",
"all",
"occurances",
"of",
"value",
"from",
"the",
"array",
"at",
"field"
] | train | https://github.com/vznet/mongo-jackson-mapper/blob/ecd189aefa89636cddf70fb383f5d676be347976/src/main/java/net/vz/mongodb/jackson/DBUpdate.java#L176-L178 |
beanshell/beanshell | src/main/java/bsh/Reflect.java | Reflect.getClassInstanceThis | public static This getClassInstanceThis(Object instance, String className) {
"""
Get the instance bsh namespace field from the object instance.
@return the class instance This object or null if the object has not
been initialized.
"""
try {
Object o = getObjectFieldValue(instance, BSHTHIS + className);
return (This) Primitive.unwrap(o); // unwrap Primitive.Null to null
} catch (Exception e) {
throw new InterpreterError("Generated class: Error getting This" + e, e);
}
} | java | public static This getClassInstanceThis(Object instance, String className) {
try {
Object o = getObjectFieldValue(instance, BSHTHIS + className);
return (This) Primitive.unwrap(o); // unwrap Primitive.Null to null
} catch (Exception e) {
throw new InterpreterError("Generated class: Error getting This" + e, e);
}
} | [
"public",
"static",
"This",
"getClassInstanceThis",
"(",
"Object",
"instance",
",",
"String",
"className",
")",
"{",
"try",
"{",
"Object",
"o",
"=",
"getObjectFieldValue",
"(",
"instance",
",",
"BSHTHIS",
"+",
"className",
")",
";",
"return",
"(",
"This",
")... | Get the instance bsh namespace field from the object instance.
@return the class instance This object or null if the object has not
been initialized. | [
"Get",
"the",
"instance",
"bsh",
"namespace",
"field",
"from",
"the",
"object",
"instance",
"."
] | train | https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Reflect.java#L741-L748 |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/service/rest/Attributes.java | Attributes.put | @Override
@Path("/ {
"""
Update attributes owner type and id (does not delete existing ones).
"""ownerType}/{ownerId}")
@ApiOperation(value="Update attributes for an ownerType and ownerId", response=StatusMessage.class)
@ApiImplicitParams({
@ApiImplicitParam(name="Attributes", paramType="body", required=true, dataType="java.lang.Object")})
public JSONObject put(String path, JSONObject content, Map<String,String> headers)
throws ServiceException, JSONException {
String ownerType = getSegment(path, 1);
if (ownerType == null)
throw new ServiceException(ServiceException.BAD_REQUEST, "Missing pathSegment: ownerType");
String ownerId = getSegment(path, 2);
if (ownerId == null)
throw new ServiceException(ServiceException.BAD_REQUEST, "Missing pathSegment: ownerId");
try {
Map<String,String> attrs = JsonUtil.getMap(content);
ServiceLocator.getWorkflowServices().updateAttributes(ownerType, Long.parseLong(ownerId), attrs);
return null;
}
catch (NumberFormatException ex) {
throw new ServiceException(ServiceException.BAD_REQUEST, "Invalid ownerId: " + ownerId);
}
catch (JSONException ex) {
throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex);
}
} | java | @Override
@Path("/{ownerType}/{ownerId}")
@ApiOperation(value="Update attributes for an ownerType and ownerId", response=StatusMessage.class)
@ApiImplicitParams({
@ApiImplicitParam(name="Attributes", paramType="body", required=true, dataType="java.lang.Object")})
public JSONObject put(String path, JSONObject content, Map<String,String> headers)
throws ServiceException, JSONException {
String ownerType = getSegment(path, 1);
if (ownerType == null)
throw new ServiceException(ServiceException.BAD_REQUEST, "Missing pathSegment: ownerType");
String ownerId = getSegment(path, 2);
if (ownerId == null)
throw new ServiceException(ServiceException.BAD_REQUEST, "Missing pathSegment: ownerId");
try {
Map<String,String> attrs = JsonUtil.getMap(content);
ServiceLocator.getWorkflowServices().updateAttributes(ownerType, Long.parseLong(ownerId), attrs);
return null;
}
catch (NumberFormatException ex) {
throw new ServiceException(ServiceException.BAD_REQUEST, "Invalid ownerId: " + ownerId);
}
catch (JSONException ex) {
throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex);
}
} | [
"@",
"Override",
"@",
"Path",
"(",
"\"/{ownerType}/{ownerId}\"",
")",
"@",
"ApiOperation",
"(",
"value",
"=",
"\"Update attributes for an ownerType and ownerId\"",
",",
"response",
"=",
"StatusMessage",
".",
"class",
")",
"@",
"ApiImplicitParams",
"(",
"{",
"@",
"Ap... | Update attributes owner type and id (does not delete existing ones). | [
"Update",
"attributes",
"owner",
"type",
"and",
"id",
"(",
"does",
"not",
"delete",
"existing",
"ones",
")",
"."
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/rest/Attributes.java#L86-L111 |
kiswanij/jk-util | src/main/java/com/jk/util/model/table/JKDefaultTableModel.java | JKDefaultTableModel.setValueAt | @Override
public void setValueAt(final Object aValue, final int row, final int column) {
"""
Sets the object value for the cell at <code>column</code> and
<code>row</code>. <code>aValue</code> is the new value. This method will
generate a <code>tableChanged</code> notification.
@param aValue the new value; this can be null
@param row the row whose value is to be changed
@param column the column whose value is to be changed
@exception ArrayIndexOutOfBoundsException if an invalid row or column was
given
"""
final Vector rowVector = (Vector) this.dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
fireTableCellUpdated(row, column);
} | java | @Override
public void setValueAt(final Object aValue, final int row, final int column) {
final Vector rowVector = (Vector) this.dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
fireTableCellUpdated(row, column);
} | [
"@",
"Override",
"public",
"void",
"setValueAt",
"(",
"final",
"Object",
"aValue",
",",
"final",
"int",
"row",
",",
"final",
"int",
"column",
")",
"{",
"final",
"Vector",
"rowVector",
"=",
"(",
"Vector",
")",
"this",
".",
"dataVector",
".",
"elementAt",
... | Sets the object value for the cell at <code>column</code> and
<code>row</code>. <code>aValue</code> is the new value. This method will
generate a <code>tableChanged</code> notification.
@param aValue the new value; this can be null
@param row the row whose value is to be changed
@param column the column whose value is to be changed
@exception ArrayIndexOutOfBoundsException if an invalid row or column was
given | [
"Sets",
"the",
"object",
"value",
"for",
"the",
"cell",
"at",
"<code",
">",
"column<",
"/",
"code",
">",
"and",
"<code",
">",
"row<",
"/",
"code",
">",
".",
"<code",
">",
"aValue<",
"/",
"code",
">",
"is",
"the",
"new",
"value",
".",
"This",
"metho... | train | https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/model/table/JKDefaultTableModel.java#L726-L731 |
actorapp/actor-platform | actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java | MarkdownParser.isGoodAnchor | private boolean isGoodAnchor(String text, int index) {
"""
Test if symbol at index is space or out of string bounds
@param text text
@param index char to test
@return is good anchor
"""
// Check if there is space and punctuation mark after block
String punct = " .,:!?\t\n";
if (index >= 0 && index < text.length()) {
if (punct.indexOf(text.charAt(index)) == -1) {
return false;
}
}
return true;
} | java | private boolean isGoodAnchor(String text, int index) {
// Check if there is space and punctuation mark after block
String punct = " .,:!?\t\n";
if (index >= 0 && index < text.length()) {
if (punct.indexOf(text.charAt(index)) == -1) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"isGoodAnchor",
"(",
"String",
"text",
",",
"int",
"index",
")",
"{",
"// Check if there is space and punctuation mark after block",
"String",
"punct",
"=",
"\" .,:!?\\t\\n\"",
";",
"if",
"(",
"index",
">=",
"0",
"&&",
"index",
"<",
"text",
"... | Test if symbol at index is space or out of string bounds
@param text text
@param index char to test
@return is good anchor | [
"Test",
"if",
"symbol",
"at",
"index",
"is",
"space",
"or",
"out",
"of",
"string",
"bounds"
] | train | https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/runtime/runtime-shared/src/main/java/im/actor/runtime/markdown/MarkdownParser.java#L376-L386 |
pip-services3-java/pip-services3-components-java | src/org/pipservices3/components/count/CachedCounters.java | CachedCounters.stats | public void stats(String name, float value) {
"""
Calculates min/average/max statistics based on the current and previous
values.
@param name a counter name of Statistics type
@param value a value to update statistics
"""
Counter counter = get(name, CounterType.Statistics);
calculateStats(counter, value);
update();
} | java | public void stats(String name, float value) {
Counter counter = get(name, CounterType.Statistics);
calculateStats(counter, value);
update();
} | [
"public",
"void",
"stats",
"(",
"String",
"name",
",",
"float",
"value",
")",
"{",
"Counter",
"counter",
"=",
"get",
"(",
"name",
",",
"CounterType",
".",
"Statistics",
")",
";",
"calculateStats",
"(",
"counter",
",",
"value",
")",
";",
"update",
"(",
... | Calculates min/average/max statistics based on the current and previous
values.
@param name a counter name of Statistics type
@param value a value to update statistics | [
"Calculates",
"min",
"/",
"average",
"/",
"max",
"statistics",
"based",
"on",
"the",
"current",
"and",
"previous",
"values",
"."
] | train | https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/count/CachedCounters.java#L205-L209 |
Azure/azure-sdk-for-java | eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java | DomainsInner.listSharedAccessKeysAsync | public Observable<DomainSharedAccessKeysInner> listSharedAccessKeysAsync(String resourceGroupName, String domainName) {
"""
List keys for a domain.
List the two keys used to publish to a domain.
@param resourceGroupName The name of the resource group within the user's subscription.
@param domainName Name of the domain
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DomainSharedAccessKeysInner object
"""
return listSharedAccessKeysWithServiceResponseAsync(resourceGroupName, domainName).map(new Func1<ServiceResponse<DomainSharedAccessKeysInner>, DomainSharedAccessKeysInner>() {
@Override
public DomainSharedAccessKeysInner call(ServiceResponse<DomainSharedAccessKeysInner> response) {
return response.body();
}
});
} | java | public Observable<DomainSharedAccessKeysInner> listSharedAccessKeysAsync(String resourceGroupName, String domainName) {
return listSharedAccessKeysWithServiceResponseAsync(resourceGroupName, domainName).map(new Func1<ServiceResponse<DomainSharedAccessKeysInner>, DomainSharedAccessKeysInner>() {
@Override
public DomainSharedAccessKeysInner call(ServiceResponse<DomainSharedAccessKeysInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DomainSharedAccessKeysInner",
">",
"listSharedAccessKeysAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"domainName",
")",
"{",
"return",
"listSharedAccessKeysWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"domainName",
")",... | List keys for a domain.
List the two keys used to publish to a domain.
@param resourceGroupName The name of the resource group within the user's subscription.
@param domainName Name of the domain
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DomainSharedAccessKeysInner object | [
"List",
"keys",
"for",
"a",
"domain",
".",
"List",
"the",
"two",
"keys",
"used",
"to",
"publish",
"to",
"a",
"domain",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java#L1099-L1106 |
pravega/pravega | common/src/main/java/io/pravega/common/util/btree/UpdateablePageCollection.java | UpdateablePageCollection.collectPages | synchronized void collectPages(Collection<Long> offsets, Collection<PageWrapper> target) {
"""
Collects the PageWrappers with given offsets into the given Collection.
@param offsets A Collection of offsets to collect PageWrappers for.
@param target The Collection to collect into.
"""
offsets.forEach(offset -> {
PageWrapper p = this.pageByOffset.getOrDefault(offset, null);
if (p != null) {
target.add(p);
}
});
} | java | synchronized void collectPages(Collection<Long> offsets, Collection<PageWrapper> target) {
offsets.forEach(offset -> {
PageWrapper p = this.pageByOffset.getOrDefault(offset, null);
if (p != null) {
target.add(p);
}
});
} | [
"synchronized",
"void",
"collectPages",
"(",
"Collection",
"<",
"Long",
">",
"offsets",
",",
"Collection",
"<",
"PageWrapper",
">",
"target",
")",
"{",
"offsets",
".",
"forEach",
"(",
"offset",
"->",
"{",
"PageWrapper",
"p",
"=",
"this",
".",
"pageByOffset",... | Collects the PageWrappers with given offsets into the given Collection.
@param offsets A Collection of offsets to collect PageWrappers for.
@param target The Collection to collect into. | [
"Collects",
"the",
"PageWrappers",
"with",
"given",
"offsets",
"into",
"the",
"given",
"Collection",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/btree/UpdateablePageCollection.java#L131-L138 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java | JDBCResultSet.updateTime | public void updateTime(int columnIndex, Time x) throws SQLException {
"""
<!-- start generic documentation -->
Updates the designated column with a <code>java.sql.Time</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet)
"""
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, x);
} | java | public void updateTime(int columnIndex, Time x) throws SQLException {
startUpdate(columnIndex);
preparedStatement.setParameter(columnIndex, x);
} | [
"public",
"void",
"updateTime",
"(",
"int",
"columnIndex",
",",
"Time",
"x",
")",
"throws",
"SQLException",
"{",
"startUpdate",
"(",
"columnIndex",
")",
";",
"preparedStatement",
".",
"setParameter",
"(",
"columnIndex",
",",
"x",
")",
";",
"}"
] | <!-- start generic documentation -->
Updates the designated column with a <code>java.sql.Time</code> value.
The updater methods are used to update column values in the
current row or the insert row. The updater methods do not
update the underlying database; instead the <code>updateRow</code> or
<code>insertRow</code> methods are called to update the database.
<!-- end generic documentation -->
<!-- start release-specific documentation -->
<div class="ReleaseSpecificDocumentation">
<h3>HSQLDB-Specific Information:</h3> <p>
HSQLDB supports this feature. <p>
</div>
<!-- end release-specific documentation -->
@param columnIndex the first column is 1, the second is 2, ...
@param x the new column value
@exception SQLException if a database access error occurs,
the result set concurrency is <code>CONCUR_READ_ONLY</code>
or this method is called on a closed result set
@exception SQLFeatureNotSupportedException if the JDBC driver does not support
this method
@since JDK 1.2 (JDK 1.1.x developers: read the overview for
JDBCResultSet) | [
"<!",
"--",
"start",
"generic",
"documentation",
"--",
">",
"Updates",
"the",
"designated",
"column",
"with",
"a",
"<code",
">",
"java",
".",
"sql",
".",
"Time<",
"/",
"code",
">",
"value",
".",
"The",
"updater",
"methods",
"are",
"used",
"to",
"update",... | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/JDBCResultSet.java#L3013-L3016 |
j256/simplecsv | src/main/java/com/j256/simplecsv/processor/CsvProcessor.java | CsvProcessor.processHeader | public String[] processHeader(String line, ParseError parseError) throws ParseException {
"""
Process a header line and divide it up into a series of quoted columns.
@param line
Line to process looking for header.
@param parseError
If not null, this will be set with the first parse error and it will return null. If this is null then
a ParseException will be thrown instead.
@return Returns an array of processed header names entity or null if an error and parseError has been set. The
array will be the same length as the number of configured columns so some elements may be null.
@throws ParseException
Thrown on any parsing problems. If parseError is not null then the error will be added there and an
exception should not be thrown.
"""
checkEntityConfig();
try {
return processHeader(line, parseError, 1);
} catch (IOException e) {
// this won't happen because processRow won't do any IO
return null;
}
} | java | public String[] processHeader(String line, ParseError parseError) throws ParseException {
checkEntityConfig();
try {
return processHeader(line, parseError, 1);
} catch (IOException e) {
// this won't happen because processRow won't do any IO
return null;
}
} | [
"public",
"String",
"[",
"]",
"processHeader",
"(",
"String",
"line",
",",
"ParseError",
"parseError",
")",
"throws",
"ParseException",
"{",
"checkEntityConfig",
"(",
")",
";",
"try",
"{",
"return",
"processHeader",
"(",
"line",
",",
"parseError",
",",
"1",
... | Process a header line and divide it up into a series of quoted columns.
@param line
Line to process looking for header.
@param parseError
If not null, this will be set with the first parse error and it will return null. If this is null then
a ParseException will be thrown instead.
@return Returns an array of processed header names entity or null if an error and parseError has been set. The
array will be the same length as the number of configured columns so some elements may be null.
@throws ParseException
Thrown on any parsing problems. If parseError is not null then the error will be added there and an
exception should not be thrown. | [
"Process",
"a",
"header",
"line",
"and",
"divide",
"it",
"up",
"into",
"a",
"series",
"of",
"quoted",
"columns",
"."
] | train | https://github.com/j256/simplecsv/blob/964fe53073c43e2a311341e3f8fd2c94372f60cb/src/main/java/com/j256/simplecsv/processor/CsvProcessor.java#L365-L373 |
alibaba/vlayout | vlayout/src/main/java/com/alibaba/android/vlayout/DelegateAdapter.java | DelegateAdapter.simpleAdapter | public static Adapter<? extends RecyclerView.ViewHolder> simpleAdapter(@NonNull View view, @NonNull LayoutHelper layoutHelper) {
"""
Return an adapter that only contains on item and using given layoutHelper
@param view the only view, no binding is required
@param layoutHelper layoutHelper that adapter used
@return adapter
"""
return new SimpleViewAdapter(view, layoutHelper);
} | java | public static Adapter<? extends RecyclerView.ViewHolder> simpleAdapter(@NonNull View view, @NonNull LayoutHelper layoutHelper) {
return new SimpleViewAdapter(view, layoutHelper);
} | [
"public",
"static",
"Adapter",
"<",
"?",
"extends",
"RecyclerView",
".",
"ViewHolder",
">",
"simpleAdapter",
"(",
"@",
"NonNull",
"View",
"view",
",",
"@",
"NonNull",
"LayoutHelper",
"layoutHelper",
")",
"{",
"return",
"new",
"SimpleViewAdapter",
"(",
"view",
... | Return an adapter that only contains on item and using given layoutHelper
@param view the only view, no binding is required
@param layoutHelper layoutHelper that adapter used
@return adapter | [
"Return",
"an",
"adapter",
"that",
"only",
"contains",
"on",
"item",
"and",
"using",
"given",
"layoutHelper"
] | train | https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/DelegateAdapter.java#L610-L612 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/br/br_currentconfig.java | br_currentconfig.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception {
"""
<pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre>
"""
br_currentconfig_responses result = (br_currentconfig_responses) service.get_payload_formatter().string_to_resource(br_currentconfig_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_currentconfig_response_array);
}
br_currentconfig[] result_br_currentconfig = new br_currentconfig[result.br_currentconfig_response_array.length];
for(int i = 0; i < result.br_currentconfig_response_array.length; i++)
{
result_br_currentconfig[i] = result.br_currentconfig_response_array[i].br_currentconfig[0];
}
return result_br_currentconfig;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
br_currentconfig_responses result = (br_currentconfig_responses) service.get_payload_formatter().string_to_resource(br_currentconfig_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.br_currentconfig_response_array);
}
br_currentconfig[] result_br_currentconfig = new br_currentconfig[result.br_currentconfig_response_array.length];
for(int i = 0; i < result.br_currentconfig_response_array.length; i++)
{
result_br_currentconfig[i] = result.br_currentconfig_response_array[i].br_currentconfig[0];
}
return result_br_currentconfig;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"br_currentconfig_responses",
"result",
"=",
"(",
"br_currentconfig_responses",
")",
"service",
".",
"get_payl... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br/br_currentconfig.java#L202-L219 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/block/component/WallComponent.java | WallComponent.canMerge | @Override
public boolean canMerge(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos, EnumFacing side) {
"""
Checks whether the block can be merged into a corner.
@param itemStack the item stack
@param player the player
@param world the world
@param pos the pos
@param side the side
@return true, if successful
"""
IBlockState state = world.getBlockState(pos);
if (isCorner(state))
return false;
return EnumFacingUtils.getRealSide(state, side) != EnumFacing.NORTH;
} | java | @Override
public boolean canMerge(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos, EnumFacing side)
{
IBlockState state = world.getBlockState(pos);
if (isCorner(state))
return false;
return EnumFacingUtils.getRealSide(state, side) != EnumFacing.NORTH;
} | [
"@",
"Override",
"public",
"boolean",
"canMerge",
"(",
"ItemStack",
"itemStack",
",",
"EntityPlayer",
"player",
",",
"World",
"world",
",",
"BlockPos",
"pos",
",",
"EnumFacing",
"side",
")",
"{",
"IBlockState",
"state",
"=",
"world",
".",
"getBlockState",
"(",... | Checks whether the block can be merged into a corner.
@param itemStack the item stack
@param player the player
@param world the world
@param pos the pos
@param side the side
@return true, if successful | [
"Checks",
"whether",
"the",
"block",
"can",
"be",
"merged",
"into",
"a",
"corner",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/block/component/WallComponent.java#L107-L115 |
FedericoPecora/meta-csp-framework | src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java | TrajectoryEnvelope.getPartialEnvelopeGeometry | public Geometry getPartialEnvelopeGeometry(int indexFrom, int indexTo) {
"""
Get a {@link Geometry} representing the spatial envelope between two given indices.
@param indexFrom The starting index (inclusive).
@param indexTo The ending index (inclusive).
@return A {@link Geometry} representing the spatial envelope between two given indices.
"""
Geometry onePoly = null;
Geometry prevPoly = null;
if (indexFrom > indexTo || indexFrom < 0 || indexFrom > this.trajectory.getPoseSteering().length-1 || indexTo < 0 || indexTo >= this.trajectory.getPoseSteering().length) throw new Error("Indices incorrect!");
for (int i = indexFrom; i <= indexTo; i++) {
PoseSteering ps = this.trajectory.getPoseSteering()[i];
Geometry rect = makeFootprint(ps);
if (onePoly == null) {
onePoly = rect;
prevPoly = rect;
}
else {
Geometry auxPoly = prevPoly.union(rect);
onePoly = onePoly.union(auxPoly.convexHull());
prevPoly = rect;
}
}
return onePoly;
} | java | public Geometry getPartialEnvelopeGeometry(int indexFrom, int indexTo) {
Geometry onePoly = null;
Geometry prevPoly = null;
if (indexFrom > indexTo || indexFrom < 0 || indexFrom > this.trajectory.getPoseSteering().length-1 || indexTo < 0 || indexTo >= this.trajectory.getPoseSteering().length) throw new Error("Indices incorrect!");
for (int i = indexFrom; i <= indexTo; i++) {
PoseSteering ps = this.trajectory.getPoseSteering()[i];
Geometry rect = makeFootprint(ps);
if (onePoly == null) {
onePoly = rect;
prevPoly = rect;
}
else {
Geometry auxPoly = prevPoly.union(rect);
onePoly = onePoly.union(auxPoly.convexHull());
prevPoly = rect;
}
}
return onePoly;
} | [
"public",
"Geometry",
"getPartialEnvelopeGeometry",
"(",
"int",
"indexFrom",
",",
"int",
"indexTo",
")",
"{",
"Geometry",
"onePoly",
"=",
"null",
";",
"Geometry",
"prevPoly",
"=",
"null",
";",
"if",
"(",
"indexFrom",
">",
"indexTo",
"||",
"indexFrom",
"<",
"... | Get a {@link Geometry} representing the spatial envelope between two given indices.
@param indexFrom The starting index (inclusive).
@param indexTo The ending index (inclusive).
@return A {@link Geometry} representing the spatial envelope between two given indices. | [
"Get",
"a",
"{"
] | train | https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/spatioTemporal/paths/TrajectoryEnvelope.java#L695-L713 |
jamesagnew/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/IdDt.java | IdDt.withServerBase | @Override
public IdDt withServerBase(String theServerBase, String theResourceType) {
"""
Returns a view of this ID as a fully qualified URL, given a server base and resource name (which will only be used if the ID does not already contain those respective parts). Essentially,
because IdDt can contain either a complete URL or a partial one (or even jut a simple ID), this method may be used to translate into a complete URL.
@param theServerBase The server base (e.g. "http://example.com/fhir")
@param theResourceType The resource name (e.g. "Patient")
@return A fully qualified URL for this ID (e.g. "http://example.com/fhir/Patient/1")
"""
if (isLocal() || isUrn()) {
return new IdDt(getValueAsString());
}
return new IdDt(theServerBase, theResourceType, getIdPart(), getVersionIdPart());
} | java | @Override
public IdDt withServerBase(String theServerBase, String theResourceType) {
if (isLocal() || isUrn()) {
return new IdDt(getValueAsString());
}
return new IdDt(theServerBase, theResourceType, getIdPart(), getVersionIdPart());
} | [
"@",
"Override",
"public",
"IdDt",
"withServerBase",
"(",
"String",
"theServerBase",
",",
"String",
"theResourceType",
")",
"{",
"if",
"(",
"isLocal",
"(",
")",
"||",
"isUrn",
"(",
")",
")",
"{",
"return",
"new",
"IdDt",
"(",
"getValueAsString",
"(",
")",
... | Returns a view of this ID as a fully qualified URL, given a server base and resource name (which will only be used if the ID does not already contain those respective parts). Essentially,
because IdDt can contain either a complete URL or a partial one (or even jut a simple ID), this method may be used to translate into a complete URL.
@param theServerBase The server base (e.g. "http://example.com/fhir")
@param theResourceType The resource name (e.g. "Patient")
@return A fully qualified URL for this ID (e.g. "http://example.com/fhir/Patient/1") | [
"Returns",
"a",
"view",
"of",
"this",
"ID",
"as",
"a",
"fully",
"qualified",
"URL",
"given",
"a",
"server",
"base",
"and",
"resource",
"name",
"(",
"which",
"will",
"only",
"be",
"used",
"if",
"the",
"ID",
"does",
"not",
"already",
"contain",
"those",
... | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/IdDt.java#L611-L617 |
sai-pullabhotla/catatumbo | src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java | DefaultEntityManager.executeEntityListeners | public void executeEntityListeners(CallbackType callbackType, List<?> entities) {
"""
Executes the entity listeners associated with the given list of entities.
@param callbackType
the callback type
@param entities
the entities
"""
for (Object entity : entities) {
executeEntityListeners(callbackType, entity);
}
} | java | public void executeEntityListeners(CallbackType callbackType, List<?> entities) {
for (Object entity : entities) {
executeEntityListeners(callbackType, entity);
}
} | [
"public",
"void",
"executeEntityListeners",
"(",
"CallbackType",
"callbackType",
",",
"List",
"<",
"?",
">",
"entities",
")",
"{",
"for",
"(",
"Object",
"entity",
":",
"entities",
")",
"{",
"executeEntityListeners",
"(",
"callbackType",
",",
"entity",
")",
";"... | Executes the entity listeners associated with the given list of entities.
@param callbackType
the callback type
@param entities
the entities | [
"Executes",
"the",
"entity",
"listeners",
"associated",
"with",
"the",
"given",
"list",
"of",
"entities",
"."
] | train | https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L480-L484 |
spring-projects/spring-android | spring-android-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java | GenericConversionService.getDefaultConverter | protected GenericConverter getDefaultConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
"""
Return the default converter if no converter is found for the given sourceType/targetType pair.
Returns a NO_OP Converter if the sourceType is assignable to the targetType.
Returns {@code null} otherwise, indicating no suitable converter could be found.
Subclasses may override.
@param sourceType the source type to convert from
@param targetType the target type to convert to
@return the default generic converter that will perform the conversion
"""
return (sourceType.isAssignableTo(targetType) ? NO_OP_CONVERTER : null);
} | java | protected GenericConverter getDefaultConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
return (sourceType.isAssignableTo(targetType) ? NO_OP_CONVERTER : null);
} | [
"protected",
"GenericConverter",
"getDefaultConverter",
"(",
"TypeDescriptor",
"sourceType",
",",
"TypeDescriptor",
"targetType",
")",
"{",
"return",
"(",
"sourceType",
".",
"isAssignableTo",
"(",
"targetType",
")",
"?",
"NO_OP_CONVERTER",
":",
"null",
")",
";",
"}"... | Return the default converter if no converter is found for the given sourceType/targetType pair.
Returns a NO_OP Converter if the sourceType is assignable to the targetType.
Returns {@code null} otherwise, indicating no suitable converter could be found.
Subclasses may override.
@param sourceType the source type to convert from
@param targetType the target type to convert to
@return the default generic converter that will perform the conversion | [
"Return",
"the",
"default",
"converter",
"if",
"no",
"converter",
"is",
"found",
"for",
"the",
"given",
"sourceType",
"/",
"targetType",
"pair",
".",
"Returns",
"a",
"NO_OP",
"Converter",
"if",
"the",
"sourceType",
"is",
"assignable",
"to",
"the",
"targetType"... | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/core/convert/support/GenericConversionService.java#L252-L254 |
hector-client/hector | core/src/main/java/me/prettyprint/cassandra/service/template/AbstractColumnFamilyTemplate.java | AbstractColumnFamilyTemplate.deleteColumn | public void deleteColumn(Mutator<K> mutator, K key, N columnName) {
"""
Stage this column deletion into the pending mutator. Calls {@linkplain #executeIfNotBatched(Mutator)}
@param mutator
@param key
@param columnName
"""
mutator.addDeletion(key, columnFamily, columnName, topSerializer);
executeIfNotBatched(mutator);
} | java | public void deleteColumn(Mutator<K> mutator, K key, N columnName) {
mutator.addDeletion(key, columnFamily, columnName, topSerializer);
executeIfNotBatched(mutator);
} | [
"public",
"void",
"deleteColumn",
"(",
"Mutator",
"<",
"K",
">",
"mutator",
",",
"K",
"key",
",",
"N",
"columnName",
")",
"{",
"mutator",
".",
"addDeletion",
"(",
"key",
",",
"columnFamily",
",",
"columnName",
",",
"topSerializer",
")",
";",
"executeIfNotB... | Stage this column deletion into the pending mutator. Calls {@linkplain #executeIfNotBatched(Mutator)}
@param mutator
@param key
@param columnName | [
"Stage",
"this",
"column",
"deletion",
"into",
"the",
"pending",
"mutator",
".",
"Calls",
"{"
] | train | https://github.com/hector-client/hector/blob/a302e68ca8d91b45d332e8c9afd7d98030b54de1/core/src/main/java/me/prettyprint/cassandra/service/template/AbstractColumnFamilyTemplate.java#L201-L204 |
xdcrafts/flower | flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ClassApi.java | ClassApi.classDistance | private static int classDistance(Class<?> from, Class<?> to, int current) {
"""
Calculates distance between from and to classes, counting from current.
"""
return to.isAssignableFrom(from)
? to.equals(from) ? current : classDistance(findAssignableAncestor(from, to), to, current + 1)
: -1;
} | java | private static int classDistance(Class<?> from, Class<?> to, int current) {
return to.isAssignableFrom(from)
? to.equals(from) ? current : classDistance(findAssignableAncestor(from, to), to, current + 1)
: -1;
} | [
"private",
"static",
"int",
"classDistance",
"(",
"Class",
"<",
"?",
">",
"from",
",",
"Class",
"<",
"?",
">",
"to",
",",
"int",
"current",
")",
"{",
"return",
"to",
".",
"isAssignableFrom",
"(",
"from",
")",
"?",
"to",
".",
"equals",
"(",
"from",
... | Calculates distance between from and to classes, counting from current. | [
"Calculates",
"distance",
"between",
"from",
"and",
"to",
"classes",
"counting",
"from",
"current",
"."
] | train | https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ClassApi.java#L90-L94 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/tiles/user/TileDaoUtils.java | TileDaoUtils.getClosestZoomLevel | public static Long getClosestZoomLevel(double[] widths, double[] heights,
List<TileMatrix> tileMatrices, double width, double height) {
"""
Get the closest zoom level for the provided width and height in the
default units
@param widths
sorted widths
@param heights
sorted heights
@param tileMatrices
tile matrices
@param width
in default units
@param height
in default units
@return tile matrix zoom level
@since 1.2.1
"""
return getZoomLevel(widths, heights, tileMatrices, width, height, false);
} | java | public static Long getClosestZoomLevel(double[] widths, double[] heights,
List<TileMatrix> tileMatrices, double width, double height) {
return getZoomLevel(widths, heights, tileMatrices, width, height, false);
} | [
"public",
"static",
"Long",
"getClosestZoomLevel",
"(",
"double",
"[",
"]",
"widths",
",",
"double",
"[",
"]",
"heights",
",",
"List",
"<",
"TileMatrix",
">",
"tileMatrices",
",",
"double",
"width",
",",
"double",
"height",
")",
"{",
"return",
"getZoomLevel"... | Get the closest zoom level for the provided width and height in the
default units
@param widths
sorted widths
@param heights
sorted heights
@param tileMatrices
tile matrices
@param width
in default units
@param height
in default units
@return tile matrix zoom level
@since 1.2.1 | [
"Get",
"the",
"closest",
"zoom",
"level",
"for",
"the",
"provided",
"width",
"and",
"height",
"in",
"the",
"default",
"units"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/tiles/user/TileDaoUtils.java#L122-L125 |
nextreports/nextreports-engine | src/ro/nextreports/engine/exporter/util/XlsxUtil.java | XlsxUtil.copyCell | public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, CellStyle> styleMap) {
"""
Copy a cell to another cell
@param oldCell cell to be copied
@param newCell cell to be created
@param styleMap style map
"""
if (styleMap != null) {
if (oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()) {
newCell.setCellStyle(oldCell.getCellStyle());
} else {
int stHashCode = oldCell.getCellStyle().hashCode();
CellStyle newCellStyle = styleMap.get(stHashCode);
if (newCellStyle == null) {
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
}
switch (oldCell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case XSSFCell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case XSSFCell.CELL_TYPE_BLANK:
newCell.setCellType(XSSFCell.CELL_TYPE_BLANK);
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case XSSFCell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case XSSFCell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
} | java | public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, CellStyle> styleMap) {
if (styleMap != null) {
if (oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()) {
newCell.setCellStyle(oldCell.getCellStyle());
} else {
int stHashCode = oldCell.getCellStyle().hashCode();
CellStyle newCellStyle = styleMap.get(stHashCode);
if (newCellStyle == null) {
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
}
switch (oldCell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case XSSFCell.CELL_TYPE_NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case XSSFCell.CELL_TYPE_BLANK:
newCell.setCellType(XSSFCell.CELL_TYPE_BLANK);
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case XSSFCell.CELL_TYPE_ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case XSSFCell.CELL_TYPE_FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
} | [
"public",
"static",
"void",
"copyCell",
"(",
"XSSFCell",
"oldCell",
",",
"XSSFCell",
"newCell",
",",
"Map",
"<",
"Integer",
",",
"CellStyle",
">",
"styleMap",
")",
"{",
"if",
"(",
"styleMap",
"!=",
"null",
")",
"{",
"if",
"(",
"oldCell",
".",
"getSheet",... | Copy a cell to another cell
@param oldCell cell to be copied
@param newCell cell to be created
@param styleMap style map | [
"Copy",
"a",
"cell",
"to",
"another",
"cell"
] | train | https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/exporter/util/XlsxUtil.java#L123-L161 |
integration-technology/amazon-mws-orders | src/main/java/com/amazonservices/mws/client/MwsAQCall.java | MwsAQCall.addRequiredParametersToRequest | private void addRequiredParametersToRequest(HttpPost request) {
"""
Add authentication related and version parameter and set request body
with all of the parameters
@param request
"""
parameters.put("Action", operationName);
parameters.put("Version", serviceEndpoint.version);
parameters.put("Timestamp", MwsUtl.getFormattedTimestamp());
parameters.put("AWSAccessKeyId", connection.getAwsAccessKeyId());
String signature = MwsUtl.signParameters(serviceEndpoint.uri,
connection.getSignatureVersion(),
connection.getSignatureMethod(), parameters,
connection.getAwsSecretKeyId());
parameters.put("Signature", signature);
List<NameValuePair> parameterList = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : parameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (!(key == null || key.equals("") || value == null || value
.equals(""))) {
parameterList.add(new BasicNameValuePair(key, value));
}
}
try {
request.setEntity(new UrlEncodedFormEntity(parameterList, "UTF-8"));
} catch (Exception e) {
throw MwsUtl.wrap(e);
}
} | java | private void addRequiredParametersToRequest(HttpPost request) {
parameters.put("Action", operationName);
parameters.put("Version", serviceEndpoint.version);
parameters.put("Timestamp", MwsUtl.getFormattedTimestamp());
parameters.put("AWSAccessKeyId", connection.getAwsAccessKeyId());
String signature = MwsUtl.signParameters(serviceEndpoint.uri,
connection.getSignatureVersion(),
connection.getSignatureMethod(), parameters,
connection.getAwsSecretKeyId());
parameters.put("Signature", signature);
List<NameValuePair> parameterList = new ArrayList<NameValuePair>();
for (Entry<String, String> entry : parameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (!(key == null || key.equals("") || value == null || value
.equals(""))) {
parameterList.add(new BasicNameValuePair(key, value));
}
}
try {
request.setEntity(new UrlEncodedFormEntity(parameterList, "UTF-8"));
} catch (Exception e) {
throw MwsUtl.wrap(e);
}
} | [
"private",
"void",
"addRequiredParametersToRequest",
"(",
"HttpPost",
"request",
")",
"{",
"parameters",
".",
"put",
"(",
"\"Action\"",
",",
"operationName",
")",
";",
"parameters",
".",
"put",
"(",
"\"Version\"",
",",
"serviceEndpoint",
".",
"version",
")",
";"... | Add authentication related and version parameter and set request body
with all of the parameters
@param request | [
"Add",
"authentication",
"related",
"and",
"version",
"parameter",
"and",
"set",
"request",
"body",
"with",
"all",
"of",
"the",
"parameters"
] | train | https://github.com/integration-technology/amazon-mws-orders/blob/042e8cd5b10588a30150222bf9c91faf4f130b3c/src/main/java/com/amazonservices/mws/client/MwsAQCall.java#L70-L94 |
jpardogo/FlabbyListView | library/src/main/java/com/jpardogo/android/flabbylistview/lib/FlabbyListView.java | FlabbyListView.onScrollChanged | @Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
"""
Calculate the scroll distance comparing the distance with the top of the list of the current
child and the last one tracked
@param l - Current horizontal scroll origin.
@param t - Current vertical scroll origin.
@param oldl - Previous horizontal scroll origin.
@param oldt - Previous vertical scroll origin.
"""
super.onScrollChanged(l, t, oldl, oldt);
if (mTrackedChild == null) {
if (getChildCount() > 0) {
mTrackedChild = getChildInTheMiddle();
mTrackedChildPrevTop = mTrackedChild.getTop();
mTrackedChildPrevPosition = getPositionForView(mTrackedChild);
}
} else {
boolean childIsSafeToTrack = mTrackedChild.getParent() == this && getPositionForView(mTrackedChild) == mTrackedChildPrevPosition;
if (childIsSafeToTrack) {
int top = mTrackedChild.getTop();
float deltaY = top - mTrackedChildPrevTop;
if (deltaY == 0) {
//When we scroll so fast the list this value becomes 0 all the time
// so we don't want the other list stop, and we give it the last
//no 0 value we have
deltaY = OldDeltaY;
} else {
OldDeltaY = deltaY;
}
updateChildrenControlPoints(deltaY);
mTrackedChildPrevTop = top;
} else {
mTrackedChild = null;
}
}
} | java | @Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mTrackedChild == null) {
if (getChildCount() > 0) {
mTrackedChild = getChildInTheMiddle();
mTrackedChildPrevTop = mTrackedChild.getTop();
mTrackedChildPrevPosition = getPositionForView(mTrackedChild);
}
} else {
boolean childIsSafeToTrack = mTrackedChild.getParent() == this && getPositionForView(mTrackedChild) == mTrackedChildPrevPosition;
if (childIsSafeToTrack) {
int top = mTrackedChild.getTop();
float deltaY = top - mTrackedChildPrevTop;
if (deltaY == 0) {
//When we scroll so fast the list this value becomes 0 all the time
// so we don't want the other list stop, and we give it the last
//no 0 value we have
deltaY = OldDeltaY;
} else {
OldDeltaY = deltaY;
}
updateChildrenControlPoints(deltaY);
mTrackedChildPrevTop = top;
} else {
mTrackedChild = null;
}
}
} | [
"@",
"Override",
"protected",
"void",
"onScrollChanged",
"(",
"int",
"l",
",",
"int",
"t",
",",
"int",
"oldl",
",",
"int",
"oldt",
")",
"{",
"super",
".",
"onScrollChanged",
"(",
"l",
",",
"t",
",",
"oldl",
",",
"oldt",
")",
";",
"if",
"(",
"mTrack... | Calculate the scroll distance comparing the distance with the top of the list of the current
child and the last one tracked
@param l - Current horizontal scroll origin.
@param t - Current vertical scroll origin.
@param oldl - Previous horizontal scroll origin.
@param oldt - Previous vertical scroll origin. | [
"Calculate",
"the",
"scroll",
"distance",
"comparing",
"the",
"distance",
"with",
"the",
"top",
"of",
"the",
"list",
"of",
"the",
"current",
"child",
"and",
"the",
"last",
"one",
"tracked"
] | train | https://github.com/jpardogo/FlabbyListView/blob/2988f9182c98717a9c66326177c3ee1d7f42975f/library/src/main/java/com/jpardogo/android/flabbylistview/lib/FlabbyListView.java#L63-L97 |
baratine/baratine | framework/src/main/java/com/caucho/v5/ramp/hamp/InHamp.java | InHamp.readMessage | public boolean readMessage(InputStream is, OutboxAmp outbox)
throws IOException {
"""
Reads the next HMTP packet from the stream, returning false on
end of file.
"""
InH3 hIn = _hIn;
if (is.available() < 0) {
return false;
}
//hIn.initPacket(is);
try {
return readMessage(hIn, outbox);
} finally {
//outbox.setInbox(null);
}
} | java | public boolean readMessage(InputStream is, OutboxAmp outbox)
throws IOException
{
InH3 hIn = _hIn;
if (is.available() < 0) {
return false;
}
//hIn.initPacket(is);
try {
return readMessage(hIn, outbox);
} finally {
//outbox.setInbox(null);
}
} | [
"public",
"boolean",
"readMessage",
"(",
"InputStream",
"is",
",",
"OutboxAmp",
"outbox",
")",
"throws",
"IOException",
"{",
"InH3",
"hIn",
"=",
"_hIn",
";",
"if",
"(",
"is",
".",
"available",
"(",
")",
"<",
"0",
")",
"{",
"return",
"false",
";",
"}",
... | Reads the next HMTP packet from the stream, returning false on
end of file. | [
"Reads",
"the",
"next",
"HMTP",
"packet",
"from",
"the",
"stream",
"returning",
"false",
"on",
"end",
"of",
"file",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/ramp/hamp/InHamp.java#L235-L251 |
bekkopen/NoCommons | src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java | OrganisasjonsnummerValidator.isValid | public boolean isValid(String organisasjonsnummer, ConstraintValidatorContext context) {
"""
Validation method used by a JSR303 validator. Normally it is better to call the static methods directly.
@param organisasjonsnummer
The organisasjonsnummer to be validated
@param context
context sent in by a validator
@return boolean
whether or not the given organisasjonsnummer is valid
"""
if(organisasjonsnummer == null){
return true;
}
return isValid(organisasjonsnummer);
} | java | public boolean isValid(String organisasjonsnummer, ConstraintValidatorContext context) {
if(organisasjonsnummer == null){
return true;
}
return isValid(organisasjonsnummer);
} | [
"public",
"boolean",
"isValid",
"(",
"String",
"organisasjonsnummer",
",",
"ConstraintValidatorContext",
"context",
")",
"{",
"if",
"(",
"organisasjonsnummer",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"return",
"isValid",
"(",
"organisasjonsnummer",
")"... | Validation method used by a JSR303 validator. Normally it is better to call the static methods directly.
@param organisasjonsnummer
The organisasjonsnummer to be validated
@param context
context sent in by a validator
@return boolean
whether or not the given organisasjonsnummer is valid | [
"Validation",
"method",
"used",
"by",
"a",
"JSR303",
"validator",
".",
"Normally",
"it",
"is",
"better",
"to",
"call",
"the",
"static",
"methods",
"directly",
"."
] | train | https://github.com/bekkopen/NoCommons/blob/5a576696390cecaac111fa97fde581e0c1afb9b8/src/main/java/no/bekk/bekkopen/org/OrganisasjonsnummerValidator.java#L107-L113 |
lucee/Lucee | core/src/main/java/lucee/runtime/registry/RegistryQuery.java | RegistryQuery.setValue | public static void setValue(String branch, String entry, short type, String value) throws RegistryException, IOException, InterruptedException {
"""
writes a value to registry
@param branch
@param entry
@param type
@param value
@throws RegistryException
@throws IOException
@throws InterruptedException
"""
if (type == RegistryEntry.TYPE_KEY) {
String fullKey = ListUtil.trim(branch, "\\") + "\\" + ListUtil.trim(entry, "\\");
// String[] cmd = new String[]{"reg","add",cleanBrunch(fullKey),"/ve","/f"};
String[] cmd = new String[] { "reg", "add", cleanBrunch(fullKey), "/f" };
executeQuery(cmd);
}
else {
if (type == RegistryEntry.TYPE_DWORD) value = Caster.toString(Caster.toIntValue(value, 0));
String[] cmd = new String[] { "reg", "add", cleanBrunch(branch), "/v", entry, "/t", RegistryEntry.toStringType(type), "/d", value, "/f" };
executeQuery(cmd);
}
} | java | public static void setValue(String branch, String entry, short type, String value) throws RegistryException, IOException, InterruptedException {
if (type == RegistryEntry.TYPE_KEY) {
String fullKey = ListUtil.trim(branch, "\\") + "\\" + ListUtil.trim(entry, "\\");
// String[] cmd = new String[]{"reg","add",cleanBrunch(fullKey),"/ve","/f"};
String[] cmd = new String[] { "reg", "add", cleanBrunch(fullKey), "/f" };
executeQuery(cmd);
}
else {
if (type == RegistryEntry.TYPE_DWORD) value = Caster.toString(Caster.toIntValue(value, 0));
String[] cmd = new String[] { "reg", "add", cleanBrunch(branch), "/v", entry, "/t", RegistryEntry.toStringType(type), "/d", value, "/f" };
executeQuery(cmd);
}
} | [
"public",
"static",
"void",
"setValue",
"(",
"String",
"branch",
",",
"String",
"entry",
",",
"short",
"type",
",",
"String",
"value",
")",
"throws",
"RegistryException",
",",
"IOException",
",",
"InterruptedException",
"{",
"if",
"(",
"type",
"==",
"RegistryE... | writes a value to registry
@param branch
@param entry
@param type
@param value
@throws RegistryException
@throws IOException
@throws InterruptedException | [
"writes",
"a",
"value",
"to",
"registry"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/registry/RegistryQuery.java#L101-L114 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java | TypeEnter.handleDeprecatedAnnotations | private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) {
"""
If a list of annotations contains a reference to java.lang.Deprecated,
set the DEPRECATED flag.
If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL.
"""
for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
JCAnnotation a = al.head;
if (a.annotationType.type == syms.deprecatedType) {
sym.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION);
a.args.stream()
.filter(e -> e.hasTag(ASSIGN))
.map(e -> (JCAssign) e)
.filter(assign -> TreeInfo.name(assign.lhs) == names.forRemoval)
.findFirst()
.ifPresent(assign -> {
JCExpression rhs = TreeInfo.skipParens(assign.rhs);
if (rhs.hasTag(LITERAL)
&& Boolean.TRUE.equals(((JCLiteral) rhs).getValue())) {
sym.flags_field |= DEPRECATED_REMOVAL;
}
});
}
}
} | java | private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) {
for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
JCAnnotation a = al.head;
if (a.annotationType.type == syms.deprecatedType) {
sym.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION);
a.args.stream()
.filter(e -> e.hasTag(ASSIGN))
.map(e -> (JCAssign) e)
.filter(assign -> TreeInfo.name(assign.lhs) == names.forRemoval)
.findFirst()
.ifPresent(assign -> {
JCExpression rhs = TreeInfo.skipParens(assign.rhs);
if (rhs.hasTag(LITERAL)
&& Boolean.TRUE.equals(((JCLiteral) rhs).getValue())) {
sym.flags_field |= DEPRECATED_REMOVAL;
}
});
}
}
} | [
"private",
"void",
"handleDeprecatedAnnotations",
"(",
"List",
"<",
"JCAnnotation",
">",
"annotations",
",",
"Symbol",
"sym",
")",
"{",
"for",
"(",
"List",
"<",
"JCAnnotation",
">",
"al",
"=",
"annotations",
";",
"!",
"al",
".",
"isEmpty",
"(",
")",
";",
... | If a list of annotations contains a reference to java.lang.Deprecated,
set the DEPRECATED flag.
If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL. | [
"If",
"a",
"list",
"of",
"annotations",
"contains",
"a",
"reference",
"to",
"java",
".",
"lang",
".",
"Deprecated",
"set",
"the",
"DEPRECATED",
"flag",
".",
"If",
"the",
"annotation",
"is",
"marked",
"forRemoval",
"=",
"true",
"also",
"set",
"DEPRECATED_REMO... | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/TypeEnter.java#L1134-L1153 |
probedock/probedock-java | src/main/java/io/probedock/client/core/filters/FilterUtils.java | FilterUtils.isRunnable | @SuppressWarnings("unchecked")
public static boolean isRunnable(Class cl, String methodName, List<FilterDefinition> filters) {
"""
Define if a test is runnable or not based on a method name and class
@param cl Class
@param methodName The method name
@param filters The filters to apply
@return True if the test can be run
"""
try {
Method method = cl.getMethod(methodName);
return isRunnable(cl, method, filters);
} catch (NoSuchMethodException | SecurityException e) {
return true;
}
} | java | @SuppressWarnings("unchecked")
public static boolean isRunnable(Class cl, String methodName, List<FilterDefinition> filters) {
try {
Method method = cl.getMethod(methodName);
return isRunnable(cl, method, filters);
} catch (NoSuchMethodException | SecurityException e) {
return true;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"boolean",
"isRunnable",
"(",
"Class",
"cl",
",",
"String",
"methodName",
",",
"List",
"<",
"FilterDefinition",
">",
"filters",
")",
"{",
"try",
"{",
"Method",
"method",
"=",
"cl",
".",
... | Define if a test is runnable or not based on a method name and class
@param cl Class
@param methodName The method name
@param filters The filters to apply
@return True if the test can be run | [
"Define",
"if",
"a",
"test",
"is",
"runnable",
"or",
"not",
"based",
"on",
"a",
"method",
"name",
"and",
"class"
] | train | https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/core/filters/FilterUtils.java#L25-L34 |
carewebframework/carewebframework-core | org.carewebframework.messaging-parent/org.carewebframework.messaging.jms-parent/org.carewebframework.messaging.jms.core/src/main/java/org/carewebframework/messaging/jms/JMSUtil.java | JMSUtil.addRecipientSelector | private static void addRecipientSelector(String value, StringBuilder sb) {
"""
Add a recipient selector for the given value.
@param value Recipient value.
@param sb String builder to receive value.
"""
if (value != null) {
sb.append(" OR Recipients LIKE '%,").append(value).append(",%'");
}
} | java | private static void addRecipientSelector(String value, StringBuilder sb) {
if (value != null) {
sb.append(" OR Recipients LIKE '%,").append(value).append(",%'");
}
} | [
"private",
"static",
"void",
"addRecipientSelector",
"(",
"String",
"value",
",",
"StringBuilder",
"sb",
")",
"{",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"\" OR Recipients LIKE '%,\"",
")",
".",
"append",
"(",
"value",
")",
"... | Add a recipient selector for the given value.
@param value Recipient value.
@param sb String builder to receive value. | [
"Add",
"a",
"recipient",
"selector",
"for",
"the",
"given",
"value",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.messaging-parent/org.carewebframework.messaging.jms-parent/org.carewebframework.messaging.jms.core/src/main/java/org/carewebframework/messaging/jms/JMSUtil.java#L117-L121 |
brianwhu/xillium | core/src/main/java/org/xillium/core/PlatformControl.java | PlatformControl.bind | PlatformControl bind(ServicePlatform p, XmlWebApplicationContext c, ClassLoader l) {
"""
To be called by ServicePlatform when detected in the top-level application context.
"""
_platform = p;
_root = c;
_cloader = l;
return this;
} | java | PlatformControl bind(ServicePlatform p, XmlWebApplicationContext c, ClassLoader l) {
_platform = p;
_root = c;
_cloader = l;
return this;
} | [
"PlatformControl",
"bind",
"(",
"ServicePlatform",
"p",
",",
"XmlWebApplicationContext",
"c",
",",
"ClassLoader",
"l",
")",
"{",
"_platform",
"=",
"p",
";",
"_root",
"=",
"c",
";",
"_cloader",
"=",
"l",
";",
"return",
"this",
";",
"}"
] | To be called by ServicePlatform when detected in the top-level application context. | [
"To",
"be",
"called",
"by",
"ServicePlatform",
"when",
"detected",
"in",
"the",
"top",
"-",
"level",
"application",
"context",
"."
] | train | https://github.com/brianwhu/xillium/blob/e8dbf8cb6589fa1031a0bfcdcb58cb03d2ba7799/core/src/main/java/org/xillium/core/PlatformControl.java#L23-L28 |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java | ThriftCatalog.addDefaultCoercions | public void addDefaultCoercions(Class<?> coercionsClass) {
"""
Add the @ToThrift and @FromThrift coercions in the specified class to this catalog.
All coercions must be symmetrical, so every @ToThrift method must have a
corresponding @FromThrift method.
"""
Preconditions.checkNotNull(coercionsClass, "coercionsClass is null");
Map<ThriftType, Method> toThriftCoercions = new HashMap<>();
Map<ThriftType, Method> fromThriftCoercions = new HashMap<>();
for (Method method : coercionsClass.getDeclaredMethods()) {
if (method.isAnnotationPresent(ToThrift.class)) {
verifyCoercionMethod(method);
ThriftType thriftType = getThriftType(method.getGenericReturnType());
ThriftType coercedType = thriftType.coerceTo(method.getGenericParameterTypes()[0]);
Method oldValue = toThriftCoercions.put(coercedType, method);
Preconditions.checkArgument(
oldValue == null,
"Coercion class two @ToThrift methods (%s and %s) for type %s",
coercionsClass.getName(),
method,
oldValue,
coercedType);
}
else if (method.isAnnotationPresent(FromThrift.class)) {
verifyCoercionMethod(method);
ThriftType thriftType = getThriftType(method.getGenericParameterTypes()[0]);
ThriftType coercedType = thriftType.coerceTo(method.getGenericReturnType());
Method oldValue = fromThriftCoercions.put(coercedType, method);
Preconditions.checkArgument(
oldValue == null,
"Coercion class two @FromThrift methods (%s and %s) for type %s",
coercionsClass.getName(),
method,
oldValue,
coercedType);
}
}
// assure coercions are symmetric
Set<ThriftType> difference = Sets.symmetricDifference(toThriftCoercions.keySet(), fromThriftCoercions.keySet());
Preconditions.checkArgument(
difference.isEmpty(),
"Coercion class %s does not have matched @ToThrift and @FromThrift methods for types %s",
coercionsClass.getName(),
difference);
// add the coercions
Map<Type, TypeCoercion> coercions = new HashMap<>();
for (Map.Entry<ThriftType, Method> entry : toThriftCoercions.entrySet()) {
ThriftType type = entry.getKey();
Method toThriftMethod = entry.getValue();
Method fromThriftMethod = fromThriftCoercions.get(type);
// this should never happen due to the difference check above, but be careful
Preconditions.checkState(
fromThriftMethod != null,
"Coercion class %s does not have matched @ToThrift and @FromThrift methods for type %s",
coercionsClass.getName(),
type);
TypeCoercion coercion = new TypeCoercion(type, toThriftMethod, fromThriftMethod);
coercions.put(type.getJavaType(), coercion);
}
this.coercions.putAll(coercions);
} | java | public void addDefaultCoercions(Class<?> coercionsClass)
{
Preconditions.checkNotNull(coercionsClass, "coercionsClass is null");
Map<ThriftType, Method> toThriftCoercions = new HashMap<>();
Map<ThriftType, Method> fromThriftCoercions = new HashMap<>();
for (Method method : coercionsClass.getDeclaredMethods()) {
if (method.isAnnotationPresent(ToThrift.class)) {
verifyCoercionMethod(method);
ThriftType thriftType = getThriftType(method.getGenericReturnType());
ThriftType coercedType = thriftType.coerceTo(method.getGenericParameterTypes()[0]);
Method oldValue = toThriftCoercions.put(coercedType, method);
Preconditions.checkArgument(
oldValue == null,
"Coercion class two @ToThrift methods (%s and %s) for type %s",
coercionsClass.getName(),
method,
oldValue,
coercedType);
}
else if (method.isAnnotationPresent(FromThrift.class)) {
verifyCoercionMethod(method);
ThriftType thriftType = getThriftType(method.getGenericParameterTypes()[0]);
ThriftType coercedType = thriftType.coerceTo(method.getGenericReturnType());
Method oldValue = fromThriftCoercions.put(coercedType, method);
Preconditions.checkArgument(
oldValue == null,
"Coercion class two @FromThrift methods (%s and %s) for type %s",
coercionsClass.getName(),
method,
oldValue,
coercedType);
}
}
// assure coercions are symmetric
Set<ThriftType> difference = Sets.symmetricDifference(toThriftCoercions.keySet(), fromThriftCoercions.keySet());
Preconditions.checkArgument(
difference.isEmpty(),
"Coercion class %s does not have matched @ToThrift and @FromThrift methods for types %s",
coercionsClass.getName(),
difference);
// add the coercions
Map<Type, TypeCoercion> coercions = new HashMap<>();
for (Map.Entry<ThriftType, Method> entry : toThriftCoercions.entrySet()) {
ThriftType type = entry.getKey();
Method toThriftMethod = entry.getValue();
Method fromThriftMethod = fromThriftCoercions.get(type);
// this should never happen due to the difference check above, but be careful
Preconditions.checkState(
fromThriftMethod != null,
"Coercion class %s does not have matched @ToThrift and @FromThrift methods for type %s",
coercionsClass.getName(),
type);
TypeCoercion coercion = new TypeCoercion(type, toThriftMethod, fromThriftMethod);
coercions.put(type.getJavaType(), coercion);
}
this.coercions.putAll(coercions);
} | [
"public",
"void",
"addDefaultCoercions",
"(",
"Class",
"<",
"?",
">",
"coercionsClass",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"coercionsClass",
",",
"\"coercionsClass is null\"",
")",
";",
"Map",
"<",
"ThriftType",
",",
"Method",
">",
"toThriftCoerc... | Add the @ToThrift and @FromThrift coercions in the specified class to this catalog.
All coercions must be symmetrical, so every @ToThrift method must have a
corresponding @FromThrift method. | [
"Add",
"the"
] | train | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java#L145-L205 |
jmeetsma/Iglu-Util | src/main/java/org/ijsberg/iglu/util/formatting/PatternMatchingSupport.java | PatternMatchingSupport.valueMatchesWildcardExpression | public static boolean valueMatchesWildcardExpression(String val, String exp) {
"""
Matches DOS-type wildcardexpressions rather than regular expressions.
The function adds one little but handy feature of regular expressions:
The '|'-character is regarded as a boolean OR that separates multiple expressions.
@param val string value that may match the expression
@param exp expression that may contain wild cards
@return
"""
//replace [\^$.|?*+() to make regexp do wildcard match
String expCopy = StringSupport.replaceAll(
exp,
new String[]{"[", "\\", "^", "$", ".", "?", "*", "+", "(", ")"},
new String[]{"\\[", "\\\\", "\\^", "\\$", "\\.",".?", ".*", "\\+", "\\(", "\\)"});
return (valueMatchesRegularExpression(val, expCopy));
} | java | public static boolean valueMatchesWildcardExpression(String val, String exp) {
//replace [\^$.|?*+() to make regexp do wildcard match
String expCopy = StringSupport.replaceAll(
exp,
new String[]{"[", "\\", "^", "$", ".", "?", "*", "+", "(", ")"},
new String[]{"\\[", "\\\\", "\\^", "\\$", "\\.",".?", ".*", "\\+", "\\(", "\\)"});
return (valueMatchesRegularExpression(val, expCopy));
} | [
"public",
"static",
"boolean",
"valueMatchesWildcardExpression",
"(",
"String",
"val",
",",
"String",
"exp",
")",
"{",
"//replace [\\^$.|?*+() to make regexp do wildcard match",
"String",
"expCopy",
"=",
"StringSupport",
".",
"replaceAll",
"(",
"exp",
",",
"new",
"Strin... | Matches DOS-type wildcardexpressions rather than regular expressions.
The function adds one little but handy feature of regular expressions:
The '|'-character is regarded as a boolean OR that separates multiple expressions.
@param val string value that may match the expression
@param exp expression that may contain wild cards
@return | [
"Matches",
"DOS",
"-",
"type",
"wildcardexpressions",
"rather",
"than",
"regular",
"expressions",
".",
"The",
"function",
"adds",
"one",
"little",
"but",
"handy",
"feature",
"of",
"regular",
"expressions",
":",
"The",
"|",
"-",
"character",
"is",
"regarded",
"... | train | https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/formatting/PatternMatchingSupport.java#L105-L113 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.