repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
192
func_name
stringlengths
5
108
whole_func_string
stringlengths
75
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.91k
func_code_tokens
listlengths
21
629
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
111
306
scalecube/scalecube-services
services/src/main/java/io/scalecube/services/metrics/Metrics.java
Metrics.mark
public static void mark(Metrics metrics, Class component, String methodName, String eventType) { mark(metrics, component.getName(), methodName, eventType); }
java
public static void mark(Metrics metrics, Class component, String methodName, String eventType) { mark(metrics, component.getName(), methodName, eventType); }
[ "public", "static", "void", "mark", "(", "Metrics", "metrics", ",", "Class", "component", ",", "String", "methodName", ",", "String", "eventType", ")", "{", "mark", "(", "metrics", ",", "component", ".", "getName", "(", ")", ",", "methodName", ",", "eventT...
Reports an event to <code>meter</code> described by given parameters. @param metrics - {@link Metrics} instance with {@link MetricRegistry} initialized. @param component - part of metric description (calss name is used). @param methodName - part of metric description. @param eventType - part of metric description.
[ "Reports", "an", "event", "to", "<code", ">", "meter<", "/", "code", ">", "described", "by", "given", "parameters", "." ]
train
https://github.com/scalecube/scalecube-services/blob/76c8de6019e5480a1436d12b37acf163f70eea47/services/src/main/java/io/scalecube/services/metrics/Metrics.java#L132-L134
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShaderData.java
GVRShaderData.setInt
public void setInt(String key, int value) { checkKeyIsUniform(key); NativeShaderData.setInt(getNative(), key, value); }
java
public void setInt(String key, int value) { checkKeyIsUniform(key); NativeShaderData.setInt(getNative(), key, value); }
[ "public", "void", "setInt", "(", "String", "key", ",", "int", "value", ")", "{", "checkKeyIsUniform", "(", "key", ")", ";", "NativeShaderData", ".", "setInt", "(", "getNative", "(", ")", ",", "key", ",", "value", ")", ";", "}" ]
Bind an {@code int} to the shader uniform {@code key}. Throws an exception of the key does not exist. @param key Name of the shader uniform @param value New data
[ "Bind", "an", "{" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShaderData.java#L271-L275
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.billingAccount_offerTask_taskId_PUT
public void billingAccount_offerTask_taskId_PUT(String billingAccount, Long taskId, OvhOfferTask body) throws IOException { String qPath = "/telephony/{billingAccount}/offerTask/{taskId}"; StringBuilder sb = path(qPath, billingAccount, taskId); exec(qPath, "PUT", sb.toString(), body); }
java
public void billingAccount_offerTask_taskId_PUT(String billingAccount, Long taskId, OvhOfferTask body) throws IOException { String qPath = "/telephony/{billingAccount}/offerTask/{taskId}"; StringBuilder sb = path(qPath, billingAccount, taskId); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "billingAccount_offerTask_taskId_PUT", "(", "String", "billingAccount", ",", "Long", "taskId", ",", "OvhOfferTask", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/{billingAccount}/offerTask/{taskId}\"", ";", "StringBuilder...
Alter this object properties REST: PUT /telephony/{billingAccount}/offerTask/{taskId} @param body [required] New object properties @param billingAccount [required] The name of your billingAccount @param taskId [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#L8242-L8246
apache/groovy
src/main/groovy/groovy/util/FactoryBuilderSupport.java
FactoryBuilderSupport.restoreFromContinuationData
protected void restoreFromContinuationData(Map<String, Object> data) { //noinspection unchecked localProxyBuilder.set((FactoryBuilderSupport) data.get("proxyBuilder")); //noinspection unchecked contexts.set((LinkedList<Map<String, Object>>) data.get("contexts")); }
java
protected void restoreFromContinuationData(Map<String, Object> data) { //noinspection unchecked localProxyBuilder.set((FactoryBuilderSupport) data.get("proxyBuilder")); //noinspection unchecked contexts.set((LinkedList<Map<String, Object>>) data.get("contexts")); }
[ "protected", "void", "restoreFromContinuationData", "(", "Map", "<", "String", ",", "Object", ">", "data", ")", "{", "//noinspection unchecked", "localProxyBuilder", ".", "set", "(", "(", "FactoryBuilderSupport", ")", "data", ".", "get", "(", "\"proxyBuilder\"", "...
Restores the state of the current builder to the same state as an older build. Caution, this will destroy rather than merge the current build context if there is any, @param data the data retrieved from a compatible getContinuationData call
[ "Restores", "the", "state", "of", "the", "current", "builder", "to", "the", "same", "state", "as", "an", "older", "build", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/util/FactoryBuilderSupport.java#L1151-L1156
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/Popups.java
Popups.bindPopped
public static void bindPopped (final Value<Boolean> popped, final Thunk thunk) { Preconditions.checkNotNull(thunk, "thunk"); popped.addListenerAndTrigger(new Value.Listener<Boolean>() { public void valueChanged (Boolean visible) { if (visible) { popped.removeListener(this); bindPopped(popped, thunk.createPopup()); } } }); }
java
public static void bindPopped (final Value<Boolean> popped, final Thunk thunk) { Preconditions.checkNotNull(thunk, "thunk"); popped.addListenerAndTrigger(new Value.Listener<Boolean>() { public void valueChanged (Boolean visible) { if (visible) { popped.removeListener(this); bindPopped(popped, thunk.createPopup()); } } }); }
[ "public", "static", "void", "bindPopped", "(", "final", "Value", "<", "Boolean", ">", "popped", ",", "final", "Thunk", "thunk", ")", "{", "Preconditions", ".", "checkNotNull", "(", "thunk", ",", "\"thunk\"", ")", ";", "popped", ".", "addListenerAndTrigger", ...
Binds the popped up state of a popup to the supplied boolean value and vice versa (i.e. if the popup is popped down, the value will be updated to false). The popup is not created until the first time the value is true.
[ "Binds", "the", "popped", "up", "state", "of", "a", "popup", "to", "the", "supplied", "boolean", "value", "and", "vice", "versa", "(", "i", ".", "e", ".", "if", "the", "popup", "is", "popped", "down", "the", "value", "will", "be", "updated", "to", "f...
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/Popups.java#L307-L318
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/context/CounterContext.java
CounterContext.getClockAndCountOf
@VisibleForTesting public ClockAndCount getClockAndCountOf(ByteBuffer context, CounterId id) { int position = findPositionOf(context, id); if (position == -1) return ClockAndCount.BLANK; long clock = context.getLong(position + CounterId.LENGTH); long count = context.getLong(position + CounterId.LENGTH + CLOCK_LENGTH); return ClockAndCount.create(clock, count); }
java
@VisibleForTesting public ClockAndCount getClockAndCountOf(ByteBuffer context, CounterId id) { int position = findPositionOf(context, id); if (position == -1) return ClockAndCount.BLANK; long clock = context.getLong(position + CounterId.LENGTH); long count = context.getLong(position + CounterId.LENGTH + CLOCK_LENGTH); return ClockAndCount.create(clock, count); }
[ "@", "VisibleForTesting", "public", "ClockAndCount", "getClockAndCountOf", "(", "ByteBuffer", "context", ",", "CounterId", "id", ")", "{", "int", "position", "=", "findPositionOf", "(", "context", ",", "id", ")", ";", "if", "(", "position", "==", "-", "1", "...
Returns the clock and the count associated with the given counter id, or (0, 0) if no such shard is present.
[ "Returns", "the", "clock", "and", "the", "count", "associated", "with", "the", "given", "counter", "id", "or", "(", "0", "0", ")", "if", "no", "such", "shard", "is", "present", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/context/CounterContext.java#L674-L684
samskivert/pythagoras
src/main/java/pythagoras/f/Quaternion.java
Quaternion.fromAngleAxis
public Quaternion fromAngleAxis (float angle, IVector3 axis) { return fromAngleAxis(angle, axis.x(), axis.y(), axis.z()); }
java
public Quaternion fromAngleAxis (float angle, IVector3 axis) { return fromAngleAxis(angle, axis.x(), axis.y(), axis.z()); }
[ "public", "Quaternion", "fromAngleAxis", "(", "float", "angle", ",", "IVector3", "axis", ")", "{", "return", "fromAngleAxis", "(", "angle", ",", "axis", ".", "x", "(", ")", ",", "axis", ".", "y", "(", ")", ",", "axis", ".", "z", "(", ")", ")", ";",...
Sets this quaternion to the rotation described by the given angle and normalized axis. @return a reference to this quaternion, for chaining.
[ "Sets", "this", "quaternion", "to", "the", "rotation", "described", "by", "the", "given", "angle", "and", "normalized", "axis", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Quaternion.java#L155-L157
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.translationRotate
public Matrix4d translationRotate(double tx, double ty, double tz, double qx, double qy, double qz, double qw) { double w2 = qw * qw; double x2 = qx * qx; double y2 = qy * qy; double z2 = qz * qz; double zw = qz * qw; double xy = qx * qy; double xz = qx * qz; double yw = qy * qw; double yz = qy * qz; double xw = qx * qw; this.m00 = w2 + x2 - z2 - y2; this.m01 = xy + zw + zw + xy; this.m02 = xz - yw + xz - yw; this.m10 = -zw + xy - zw + xy; this.m11 = y2 - z2 + w2 - x2; this.m12 = yz + yz + xw + xw; this.m20 = yw + xz + xz + yw; this.m21 = yz + yz - xw - xw; this.m22 = z2 - y2 - x2 + w2; this.m30 = tx; this.m31 = ty; this.m32 = tz; this.m33 = 1.0; this.properties = PROPERTY_AFFINE | PROPERTY_ORTHONORMAL; return this; }
java
public Matrix4d translationRotate(double tx, double ty, double tz, double qx, double qy, double qz, double qw) { double w2 = qw * qw; double x2 = qx * qx; double y2 = qy * qy; double z2 = qz * qz; double zw = qz * qw; double xy = qx * qy; double xz = qx * qz; double yw = qy * qw; double yz = qy * qz; double xw = qx * qw; this.m00 = w2 + x2 - z2 - y2; this.m01 = xy + zw + zw + xy; this.m02 = xz - yw + xz - yw; this.m10 = -zw + xy - zw + xy; this.m11 = y2 - z2 + w2 - x2; this.m12 = yz + yz + xw + xw; this.m20 = yw + xz + xz + yw; this.m21 = yz + yz - xw - xw; this.m22 = z2 - y2 - x2 + w2; this.m30 = tx; this.m31 = ty; this.m32 = tz; this.m33 = 1.0; this.properties = PROPERTY_AFFINE | PROPERTY_ORTHONORMAL; return this; }
[ "public", "Matrix4d", "translationRotate", "(", "double", "tx", ",", "double", "ty", ",", "double", "tz", ",", "double", "qx", ",", "double", "qy", ",", "double", "qz", ",", "double", "qw", ")", "{", "double", "w2", "=", "qw", "*", "qw", ";", "double...
Set <code>this</code> matrix to <code>T * R</code>, where <code>T</code> is a translation by the given <code>(tx, ty, tz)</code> and <code>R</code> is a rotation - and possibly scaling - transformation specified by the quaternion <code>(qx, qy, qz, qw)</code>. <p> When transforming a vector by the resulting matrix the rotation - and possibly scaling - transformation will be applied first and then the translation. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> This method is equivalent to calling: <code>translation(tx, ty, tz).rotate(quat)</code> @see #translation(double, double, double) @see #rotate(Quaterniondc) @param tx the number of units by which to translate the x-component @param ty the number of units by which to translate the y-component @param tz the number of units by which to translate the z-component @param qx the x-coordinate of the vector part of the quaternion @param qy the y-coordinate of the vector part of the quaternion @param qz the z-coordinate of the vector part of the quaternion @param qw the scalar part of the quaternion @return this
[ "Set", "<code", ">", "this<", "/", "code", ">", "matrix", "to", "<code", ">", "T", "*", "R<", "/", "code", ">", "where", "<code", ">", "T<", "/", "code", ">", "is", "a", "translation", "by", "the", "given", "<code", ">", "(", "tx", "ty", "tz", ...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L7494-L7520
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/SystemJimfsFileSystemProvider.java
SystemJimfsFileSystemProvider.toPath
private static Path toPath(FileSystem fileSystem, URI uri) { // We have to invoke this method by reflection because while the file system should be // an instance of JimfsFileSystem, it may be loaded by a different class loader and as // such appear to be a totally different class. try { Method toPath = fileSystem.getClass().getDeclaredMethod("toPath", URI.class); return (Path) toPath.invoke(fileSystem, uri); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("invalid file system: " + fileSystem); } catch (InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } }
java
private static Path toPath(FileSystem fileSystem, URI uri) { // We have to invoke this method by reflection because while the file system should be // an instance of JimfsFileSystem, it may be loaded by a different class loader and as // such appear to be a totally different class. try { Method toPath = fileSystem.getClass().getDeclaredMethod("toPath", URI.class); return (Path) toPath.invoke(fileSystem, uri); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("invalid file system: " + fileSystem); } catch (InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } }
[ "private", "static", "Path", "toPath", "(", "FileSystem", "fileSystem", ",", "URI", "uri", ")", "{", "// We have to invoke this method by reflection because while the file system should be", "// an instance of JimfsFileSystem, it may be loaded by a different class loader and as", "// suc...
Invokes the {@code toPath(URI)} method on the given {@code FileSystem}.
[ "Invokes", "the", "{" ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/SystemJimfsFileSystemProvider.java#L168-L180
VoltDB/voltdb
third_party/java/src/org/HdrHistogram_voltpatches/DoubleRecorder.java
DoubleRecorder.recordValueWithExpectedInterval
public void recordValueWithExpectedInterval(final double value, final double expectedIntervalBetweenValueSamples) throws ArrayIndexOutOfBoundsException { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { activeHistogram.recordValueWithExpectedInterval(value, expectedIntervalBetweenValueSamples); } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } }
java
public void recordValueWithExpectedInterval(final double value, final double expectedIntervalBetweenValueSamples) throws ArrayIndexOutOfBoundsException { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { activeHistogram.recordValueWithExpectedInterval(value, expectedIntervalBetweenValueSamples); } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } }
[ "public", "void", "recordValueWithExpectedInterval", "(", "final", "double", "value", ",", "final", "double", "expectedIntervalBetweenValueSamples", ")", "throws", "ArrayIndexOutOfBoundsException", "{", "long", "criticalValueAtEnter", "=", "recordingPhaser", ".", "writerCriti...
Record a value <p> To compensate for the loss of sampled values when a recorded value is larger than the expected interval between value samples, Histogram will auto-generate an additional series of decreasingly-smaller (down to the expectedIntervalBetweenValueSamples) value records. <p> See related notes {@link org.HdrHistogram_voltpatches.DoubleHistogram#recordValueWithExpectedInterval(double, double)} for more explanations about coordinated omission and expected interval correction. * @param value The value to record @param expectedIntervalBetweenValueSamples If expectedIntervalBetweenValueSamples is larger than 0, add auto-generated value records as appropriate if value is larger than expectedIntervalBetweenValueSamples @throws ArrayIndexOutOfBoundsException (may throw) if value is exceeds highestTrackableValue
[ "Record", "a", "value", "<p", ">", "To", "compensate", "for", "the", "loss", "of", "sampled", "values", "when", "a", "recorded", "value", "is", "larger", "than", "the", "expected", "interval", "between", "value", "samples", "Histogram", "will", "auto", "-", ...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/HdrHistogram_voltpatches/DoubleRecorder.java#L115-L123
gallandarakhneorg/afc
core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d2/Transform2D.java
Transform2D.createInverse
@Pure public Transform2D createInverse() { final double det = this.m00 * this.m11 - this.m01 * this.m10; if (MathUtil.isEpsilonZero(det)) { throw new SingularMatrixException(Locale.getString("E1", det)); //$NON-NLS-1$ } return new Transform2D( this.m11 / det, -this.m01 / det, (this.m01 * this.m12 - this.m11 * this.m02) / det, -this.m10 / det, this.m00 / det, (this.m10 * this.m02 - this.m00 * this.m12) / det); }
java
@Pure public Transform2D createInverse() { final double det = this.m00 * this.m11 - this.m01 * this.m10; if (MathUtil.isEpsilonZero(det)) { throw new SingularMatrixException(Locale.getString("E1", det)); //$NON-NLS-1$ } return new Transform2D( this.m11 / det, -this.m01 / det, (this.m01 * this.m12 - this.m11 * this.m02) / det, -this.m10 / det, this.m00 / det, (this.m10 * this.m02 - this.m00 * this.m12) / det); }
[ "@", "Pure", "public", "Transform2D", "createInverse", "(", ")", "{", "final", "double", "det", "=", "this", ".", "m00", "*", "this", ".", "m11", "-", "this", ".", "m01", "*", "this", ".", "m10", ";", "if", "(", "MathUtil", ".", "isEpsilonZero", "(",...
Returns an <code>Transform2D</code> object representing the inverse transformation. The inverse transform Tx' of this transform Tx maps coordinates transformed by Tx back to their original coordinates. In other words, Tx'(Tx(p)) = p = Tx(Tx'(p)). <p>If this transform maps all coordinates onto a point or a line then it will not have an inverse, since coordinates that do not lie on the destination point or line will not have an inverse mapping. The <code>determinant</code> method can be used to determine if this transform has no inverse, in which case an exception will be thrown if the <code>createInverse</code> method is called. @return a new <code>Transform2D</code> object representing the inverse transformation. @see #determinant() @throws SingularMatrixException if the matrix cannot be inverted.
[ "Returns", "an", "<code", ">", "Transform2D<", "/", "code", ">", "object", "representing", "the", "inverse", "transformation", ".", "The", "inverse", "transform", "Tx", "of", "this", "transform", "Tx", "maps", "coordinates", "transformed", "by", "Tx", "back", ...
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d2/Transform2D.java#L711-L724
google/j2objc
jre_emul/android/platform/external/mockwebserver/src/main/java/com/google/mockwebserver/MockResponse.java
MockResponse.setChunkedBody
public MockResponse setChunkedBody(String body, int maxChunkSize) { try { return setChunkedBody(body.getBytes("UTF-8"), maxChunkSize); } catch (UnsupportedEncodingException e) { throw new AssertionError(); } }
java
public MockResponse setChunkedBody(String body, int maxChunkSize) { try { return setChunkedBody(body.getBytes("UTF-8"), maxChunkSize); } catch (UnsupportedEncodingException e) { throw new AssertionError(); } }
[ "public", "MockResponse", "setChunkedBody", "(", "String", "body", ",", "int", "maxChunkSize", ")", "{", "try", "{", "return", "setChunkedBody", "(", "body", ".", "getBytes", "(", "\"UTF-8\"", ")", ",", "maxChunkSize", ")", ";", "}", "catch", "(", "Unsupport...
Sets the response body to the UTF-8 encoded bytes of {@code body}, chunked every {@code maxChunkSize} bytes.
[ "Sets", "the", "response", "body", "to", "the", "UTF", "-", "8", "encoded", "bytes", "of", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/mockwebserver/src/main/java/com/google/mockwebserver/MockResponse.java#L214-L220
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java
PercentileDistributionSummary.get
public static PercentileDistributionSummary get(Registry registry, Id id) { return new PercentileDistributionSummary(registry, id, 0L, Long.MAX_VALUE); }
java
public static PercentileDistributionSummary get(Registry registry, Id id) { return new PercentileDistributionSummary(registry, id, 0L, Long.MAX_VALUE); }
[ "public", "static", "PercentileDistributionSummary", "get", "(", "Registry", "registry", ",", "Id", "id", ")", "{", "return", "new", "PercentileDistributionSummary", "(", "registry", ",", "id", ",", "0L", ",", "Long", ".", "MAX_VALUE", ")", ";", "}" ]
Creates a distribution summary object that can be used for estimating percentiles. <b>Percentile distribution summaries are expensive compared to basic distribution summaries from the registry.</b> Be diligent with ensuring that any additional dimensions have a small bounded cardinality. It is also highly recommended to explicitly set the threshold (see {@link Builder#withRange(long, long)}) whenever possible. @param registry Registry to use. @param id Identifier for the metric being registered. @return Distribution summary that keeps track of counts by buckets that can be used to estimate the percentiles for the distribution.
[ "Creates", "a", "distribution", "summary", "object", "that", "can", "be", "used", "for", "estimating", "percentiles", ".", "<b", ">", "Percentile", "distribution", "summaries", "are", "expensive", "compared", "to", "basic", "distribution", "summaries", "from", "th...
train
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java#L91-L93
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.queryBlockByTransactionID
public BlockInfo queryBlockByTransactionID(Peer peer, String txID) throws InvalidArgumentException, ProposalException { return queryBlockByTransactionID(Collections.singleton(peer), txID); }
java
public BlockInfo queryBlockByTransactionID(Peer peer, String txID) throws InvalidArgumentException, ProposalException { return queryBlockByTransactionID(Collections.singleton(peer), txID); }
[ "public", "BlockInfo", "queryBlockByTransactionID", "(", "Peer", "peer", ",", "String", "txID", ")", "throws", "InvalidArgumentException", ",", "ProposalException", "{", "return", "queryBlockByTransactionID", "(", "Collections", ".", "singleton", "(", "peer", ")", ","...
query a peer in this channel for a Block by a TransactionID contained in the block <STRONG>This method may not be thread safe if client context is changed!</STRONG> @param peer the peer to send the request to @param txID the transactionID to query on @return the {@link BlockInfo} for the Block containing the transaction @throws InvalidArgumentException @throws ProposalException
[ "query", "a", "peer", "in", "this", "channel", "for", "a", "Block", "by", "a", "TransactionID", "contained", "in", "the", "block" ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L2990-L2992
jspringbot/jspringbot
src/main/java/org/jspringbot/spring/KeywordUtils.java
KeywordUtils.getDescription
public static String getDescription(String keyword, ApplicationContext context, Map<String, String> beanMap) { KeywordInfo keywordInfo = getKeywordInfo(keyword, context, beanMap); if(keywordInfo == null) { return ""; } String desc = keywordInfo.description(); if(desc.startsWith("classpath:")) { try { ResourceEditor editor = new ResourceEditor(); editor.setAsText(desc); Resource r = (Resource) editor.getValue(); return IOUtils.toString(r.getInputStream()); } catch (Exception ignored) { } } return desc; }
java
public static String getDescription(String keyword, ApplicationContext context, Map<String, String> beanMap) { KeywordInfo keywordInfo = getKeywordInfo(keyword, context, beanMap); if(keywordInfo == null) { return ""; } String desc = keywordInfo.description(); if(desc.startsWith("classpath:")) { try { ResourceEditor editor = new ResourceEditor(); editor.setAsText(desc); Resource r = (Resource) editor.getValue(); return IOUtils.toString(r.getInputStream()); } catch (Exception ignored) { } } return desc; }
[ "public", "static", "String", "getDescription", "(", "String", "keyword", ",", "ApplicationContext", "context", ",", "Map", "<", "String", ",", "String", ">", "beanMap", ")", "{", "KeywordInfo", "keywordInfo", "=", "getKeywordInfo", "(", "keyword", ",", "context...
Retrieves the given keyword's description. @param keyword keyword name @param context Spring application context @param beanMap keyword name to bean name mapping @return the documentation string of the given keyword, or empty string if unavailable.
[ "Retrieves", "the", "given", "keyword", "s", "description", "." ]
train
https://github.com/jspringbot/jspringbot/blob/03285a7013492fb793cb0c38a4625a5f5c5750e0/src/main/java/org/jspringbot/spring/KeywordUtils.java#L90-L111
elki-project/elki
addons/uncertain/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/uncertain/RepresentativeUncertainClustering.java
RepresentativeUncertainClustering.computeConfidence
private double computeConfidence(int support, int samples) { final double z = NormalDistribution.standardNormalQuantile(alpha); final double eprob = support / (double) samples; return Math.max(0., eprob - z * FastMath.sqrt((eprob * (1 - eprob)) / samples)); }
java
private double computeConfidence(int support, int samples) { final double z = NormalDistribution.standardNormalQuantile(alpha); final double eprob = support / (double) samples; return Math.max(0., eprob - z * FastMath.sqrt((eprob * (1 - eprob)) / samples)); }
[ "private", "double", "computeConfidence", "(", "int", "support", ",", "int", "samples", ")", "{", "final", "double", "z", "=", "NormalDistribution", ".", "standardNormalQuantile", "(", "alpha", ")", ";", "final", "double", "eprob", "=", "support", "/", "(", ...
Estimate the confidence probability of a clustering. @param support Number of supporting samples @param samples Total samples @return Probability
[ "Estimate", "the", "confidence", "probability", "of", "a", "clustering", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/uncertain/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/uncertain/RepresentativeUncertainClustering.java#L294-L298
junit-team/junit4
src/main/java/org/junit/runners/ParentRunner.java
ParentRunner.runLeaf
protected final void runLeaf(Statement statement, Description description, RunNotifier notifier) { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestStarted(); try { statement.evaluate(); } catch (AssumptionViolatedException e) { eachNotifier.addFailedAssumption(e); } catch (Throwable e) { eachNotifier.addFailure(e); } finally { eachNotifier.fireTestFinished(); } }
java
protected final void runLeaf(Statement statement, Description description, RunNotifier notifier) { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestStarted(); try { statement.evaluate(); } catch (AssumptionViolatedException e) { eachNotifier.addFailedAssumption(e); } catch (Throwable e) { eachNotifier.addFailure(e); } finally { eachNotifier.fireTestFinished(); } }
[ "protected", "final", "void", "runLeaf", "(", "Statement", "statement", ",", "Description", "description", ",", "RunNotifier", "notifier", ")", "{", "EachTestNotifier", "eachNotifier", "=", "new", "EachTestNotifier", "(", "notifier", ",", "description", ")", ";", ...
Runs a {@link Statement} that represents a leaf (aka atomic) test.
[ "Runs", "a", "{" ]
train
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runners/ParentRunner.java#L360-L373
spring-projects/spring-security-oauth
spring-security-oauth/src/main/java/org/springframework/security/oauth/common/signature/PlainTextSignatureMethod.java
PlainTextSignatureMethod.verify
public void verify(String signatureBaseString, String signature) throws InvalidSignatureException { if (this.encoder != null) { if (!this.encoder.isPasswordValid(this.secret, signature, this.salt)) { throw new InvalidSignatureException("Invalid signature for signature method " + getName()); } } else if (!signature.equals(this.secret)) { throw new InvalidSignatureException("Invalid signature for signature method " + getName()); } }
java
public void verify(String signatureBaseString, String signature) throws InvalidSignatureException { if (this.encoder != null) { if (!this.encoder.isPasswordValid(this.secret, signature, this.salt)) { throw new InvalidSignatureException("Invalid signature for signature method " + getName()); } } else if (!signature.equals(this.secret)) { throw new InvalidSignatureException("Invalid signature for signature method " + getName()); } }
[ "public", "void", "verify", "(", "String", "signatureBaseString", ",", "String", "signature", ")", "throws", "InvalidSignatureException", "{", "if", "(", "this", ".", "encoder", "!=", "null", ")", "{", "if", "(", "!", "this", ".", "encoder", ".", "isPassword...
Validates that the signature is the same as the secret. @param signatureBaseString The signature base string (unimportant, ignored). @param signature The signature. @throws InvalidSignatureException If the signature is not the same as the secret.
[ "Validates", "that", "the", "signature", "is", "the", "same", "as", "the", "secret", "." ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth/src/main/java/org/springframework/security/oauth/common/signature/PlainTextSignatureMethod.java#L85-L94
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/list/AbstractLongList.java
AbstractLongList.addAllOfFromTo
public void addAllOfFromTo(AbstractLongList other, int from, int to) { beforeInsertAllOfFromTo(size,other,from,to); }
java
public void addAllOfFromTo(AbstractLongList other, int from, int to) { beforeInsertAllOfFromTo(size,other,from,to); }
[ "public", "void", "addAllOfFromTo", "(", "AbstractLongList", "other", ",", "int", "from", ",", "int", "to", ")", "{", "beforeInsertAllOfFromTo", "(", "size", ",", "other", ",", "from", ",", "to", ")", ";", "}" ]
Appends the part of the specified list between <code>from</code> (inclusive) and <code>to</code> (inclusive) to the receiver. @param other the list to be added to the receiver. @param from the index of the first element to be appended (inclusive). @param to the index of the last element to be appended (inclusive). @exception IndexOutOfBoundsException index is out of range (<tt>other.size()&gt;0 && (from&lt;0 || from&gt;to || to&gt;=other.size())</tt>).
[ "Appends", "the", "part", "of", "the", "specified", "list", "between", "<code", ">", "from<", "/", "code", ">", "(", "inclusive", ")", "and", "<code", ">", "to<", "/", "code", ">", "(", "inclusive", ")", "to", "the", "receiver", "." ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/AbstractLongList.java#L45-L47
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java
TrainingsImpl.getTaggedImagesAsync
public Observable<List<Image>> getTaggedImagesAsync(UUID projectId, GetTaggedImagesOptionalParameter getTaggedImagesOptionalParameter) { return getTaggedImagesWithServiceResponseAsync(projectId, getTaggedImagesOptionalParameter).map(new Func1<ServiceResponse<List<Image>>, List<Image>>() { @Override public List<Image> call(ServiceResponse<List<Image>> response) { return response.body(); } }); }
java
public Observable<List<Image>> getTaggedImagesAsync(UUID projectId, GetTaggedImagesOptionalParameter getTaggedImagesOptionalParameter) { return getTaggedImagesWithServiceResponseAsync(projectId, getTaggedImagesOptionalParameter).map(new Func1<ServiceResponse<List<Image>>, List<Image>>() { @Override public List<Image> call(ServiceResponse<List<Image>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "Image", ">", ">", "getTaggedImagesAsync", "(", "UUID", "projectId", ",", "GetTaggedImagesOptionalParameter", "getTaggedImagesOptionalParameter", ")", "{", "return", "getTaggedImagesWithServiceResponseAsync", "(", "projectId", ",", ...
Get tagged images for a given project iteration. This API supports batching and range selection. By default it will only return first 50 images matching images. Use the {take} and {skip} parameters to control how many images to return in a given batch. The filtering is on an and/or relationship. For example, if the provided tag ids are for the "Dog" and "Cat" tags, then only images tagged with Dog and/or Cat will be returned. @param projectId The project id @param getTaggedImagesOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;Image&gt; object
[ "Get", "tagged", "images", "for", "a", "given", "project", "iteration", ".", "This", "API", "supports", "batching", "and", "range", "selection", ".", "By", "default", "it", "will", "only", "return", "first", "50", "images", "matching", "images", ".", "Use", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java#L5007-L5014
Azure/azure-sdk-for-java
kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java
DatabasesInner.removePrincipals
public DatabasePrincipalListResultInner removePrincipals(String resourceGroupName, String clusterName, String databaseName, List<DatabasePrincipalInner> value) { return removePrincipalsWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, value).toBlocking().single().body(); }
java
public DatabasePrincipalListResultInner removePrincipals(String resourceGroupName, String clusterName, String databaseName, List<DatabasePrincipalInner> value) { return removePrincipalsWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, value).toBlocking().single().body(); }
[ "public", "DatabasePrincipalListResultInner", "removePrincipals", "(", "String", "resourceGroupName", ",", "String", "clusterName", ",", "String", "databaseName", ",", "List", "<", "DatabasePrincipalInner", ">", "value", ")", "{", "return", "removePrincipalsWithServiceRespo...
Remove Database principals permissions. @param resourceGroupName The name of the resource group containing the Kusto cluster. @param clusterName The name of the Kusto cluster. @param databaseName The name of the database in the Kusto cluster. @param value The list of Kusto database principals. @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 DatabasePrincipalListResultInner object if successful.
[ "Remove", "Database", "principals", "permissions", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java#L1324-L1326
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/normalization/KerasBatchNormalization.java
KerasBatchNormalization.getBatchNormMode
private int getBatchNormMode(Map<String, Object> layerConfig, boolean enforceTrainingConfig) throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf); int batchNormMode = 0; if (this.kerasMajorVersion == 1 & !innerConfig.containsKey(LAYER_FIELD_MODE)) throw new InvalidKerasConfigurationException( "Keras BatchNorm layer config missing " + LAYER_FIELD_MODE + " field"); if (this.kerasMajorVersion == 1) batchNormMode = (int) innerConfig.get(LAYER_FIELD_MODE); switch (batchNormMode) { case LAYER_BATCHNORM_MODE_1: throw new UnsupportedKerasConfigurationException("Keras BatchNormalization mode " + LAYER_BATCHNORM_MODE_1 + " (sample-wise) not supported"); case LAYER_BATCHNORM_MODE_2: throw new UnsupportedKerasConfigurationException( "Keras BatchNormalization (per-batch statistics during testing) " + LAYER_BATCHNORM_MODE_2 + " not supported"); } return batchNormMode; }
java
private int getBatchNormMode(Map<String, Object> layerConfig, boolean enforceTrainingConfig) throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf); int batchNormMode = 0; if (this.kerasMajorVersion == 1 & !innerConfig.containsKey(LAYER_FIELD_MODE)) throw new InvalidKerasConfigurationException( "Keras BatchNorm layer config missing " + LAYER_FIELD_MODE + " field"); if (this.kerasMajorVersion == 1) batchNormMode = (int) innerConfig.get(LAYER_FIELD_MODE); switch (batchNormMode) { case LAYER_BATCHNORM_MODE_1: throw new UnsupportedKerasConfigurationException("Keras BatchNormalization mode " + LAYER_BATCHNORM_MODE_1 + " (sample-wise) not supported"); case LAYER_BATCHNORM_MODE_2: throw new UnsupportedKerasConfigurationException( "Keras BatchNormalization (per-batch statistics during testing) " + LAYER_BATCHNORM_MODE_2 + " not supported"); } return batchNormMode; }
[ "private", "int", "getBatchNormMode", "(", "Map", "<", "String", ",", "Object", ">", "layerConfig", ",", "boolean", "enforceTrainingConfig", ")", "throws", "InvalidKerasConfigurationException", ",", "UnsupportedKerasConfigurationException", "{", "Map", "<", "String", ",...
Get BatchNormalization "mode" from Keras layer configuration. Most modes currently unsupported. @param layerConfig dictionary containing Keras layer configuration @return batchnormalization mode @throws InvalidKerasConfigurationException Invalid Keras config
[ "Get", "BatchNormalization", "mode", "from", "Keras", "layer", "configuration", ".", "Most", "modes", "currently", "unsupported", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/normalization/KerasBatchNormalization.java#L324-L343
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/media/MediaClient.java
MediaClient.createWaterMark
public CreateWaterMarkResponse createWaterMark(CreateWaterMarkRequest request) { checkStringNotEmpty(request.getBucket(), "The parameter bucket should NOT be null or empty string."); checkStringNotEmpty(request.getKey(), "The parameter key should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, WATER_MARK); return invokeHttpClient(internalRequest, CreateWaterMarkResponse.class); }
java
public CreateWaterMarkResponse createWaterMark(CreateWaterMarkRequest request) { checkStringNotEmpty(request.getBucket(), "The parameter bucket should NOT be null or empty string."); checkStringNotEmpty(request.getKey(), "The parameter key should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, WATER_MARK); return invokeHttpClient(internalRequest, CreateWaterMarkResponse.class); }
[ "public", "CreateWaterMarkResponse", "createWaterMark", "(", "CreateWaterMarkRequest", "request", ")", "{", "checkStringNotEmpty", "(", "request", ".", "getBucket", "(", ")", ",", "\"The parameter bucket should NOT be null or empty string.\"", ")", ";", "checkStringNotEmpty", ...
Creates a water mark and return water mark ID @param request The request object containing all options for creating new water mark. @return watermarkId the unique ID of the new water mark.
[ "Creates", "a", "water", "mark", "and", "return", "water", "mark", "ID" ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/media/MediaClient.java#L1100-L1106
lightblueseas/email-tails
src/main/java/de/alpharogroup/email/messages/EmailMessage.java
EmailMessage.setContent
@Override public void setContent(final Object content, final String type) throws MessagingException { charset = EmailExtensions.getCharsetFromContentType(type); super.setContent(content, type); }
java
@Override public void setContent(final Object content, final String type) throws MessagingException { charset = EmailExtensions.getCharsetFromContentType(type); super.setContent(content, type); }
[ "@", "Override", "public", "void", "setContent", "(", "final", "Object", "content", ",", "final", "String", "type", ")", "throws", "MessagingException", "{", "charset", "=", "EmailExtensions", ".", "getCharsetFromContentType", "(", "type", ")", ";", "super", "."...
Sets the content. @param content the content @param type the type @throws MessagingException is thrown if the underlying implementation does not support modification of existing values @see javax.mail.Part#setContent(java.lang.Object, java.lang.String)
[ "Sets", "the", "content", "." ]
train
https://github.com/lightblueseas/email-tails/blob/7be6fee3548e61e697cc8e64e90603cb1f505be2/src/main/java/de/alpharogroup/email/messages/EmailMessage.java#L307-L312
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementUI.java
ElementUI.setDesignContextMenu
protected void setDesignContextMenu(BaseUIComponent component, Menupopup contextMenu) { component.setAttribute(CONTEXT_MENU, contextMenu); if (contextMenu == null) { SavedState.restore(component); applyHint(); } else { new SavedState(component); component.setContext(contextMenu); component.setHint(getDefinition().getName()); } }
java
protected void setDesignContextMenu(BaseUIComponent component, Menupopup contextMenu) { component.setAttribute(CONTEXT_MENU, contextMenu); if (contextMenu == null) { SavedState.restore(component); applyHint(); } else { new SavedState(component); component.setContext(contextMenu); component.setHint(getDefinition().getName()); } }
[ "protected", "void", "setDesignContextMenu", "(", "BaseUIComponent", "component", ",", "Menupopup", "contextMenu", ")", "{", "component", ".", "setAttribute", "(", "CONTEXT_MENU", ",", "contextMenu", ")", ";", "if", "(", "contextMenu", "==", "null", ")", "{", "S...
Apply/remove the design context menu to/from the specified component. If applying the design context menu, any existing context menu is saved. When removing the context menu, any saved context menu is restored. @param component Component to which to apply/remove the design context menu. @param contextMenu The design menu if design mode is activated, or null if it is not.
[ "Apply", "/", "remove", "the", "design", "context", "menu", "to", "/", "from", "the", "specified", "component", ".", "If", "applying", "the", "design", "context", "menu", "any", "existing", "context", "menu", "is", "saved", ".", "When", "removing", "the", ...
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementUI.java#L226-L237
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ServerAutomaticTuningsInner.java
ServerAutomaticTuningsInner.getAsync
public Observable<ServerAutomaticTuningInner> getAsync(String resourceGroupName, String serverName) { return getWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<ServerAutomaticTuningInner>, ServerAutomaticTuningInner>() { @Override public ServerAutomaticTuningInner call(ServiceResponse<ServerAutomaticTuningInner> response) { return response.body(); } }); }
java
public Observable<ServerAutomaticTuningInner> getAsync(String resourceGroupName, String serverName) { return getWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<ServerAutomaticTuningInner>, ServerAutomaticTuningInner>() { @Override public ServerAutomaticTuningInner call(ServiceResponse<ServerAutomaticTuningInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ServerAutomaticTuningInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ")", ".", "map", "(", "new", ...
Retrieves server automatic tuning options. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerAutomaticTuningInner object
[ "Retrieves", "server", "automatic", "tuning", "options", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ServerAutomaticTuningsInner.java#L102-L109
JadiraOrg/jadira
cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java
UnsafeOperations.deepCopyObjectField
public final void deepCopyObjectField(Object source, Object copy, Field field, IdentityHashMap<Object, Object> referencesToReuse) { deepCopyObjectAtOffset(source, copy, field.getType(), getObjectFieldOffset(field), referencesToReuse); }
java
public final void deepCopyObjectField(Object source, Object copy, Field field, IdentityHashMap<Object, Object> referencesToReuse) { deepCopyObjectAtOffset(source, copy, field.getType(), getObjectFieldOffset(field), referencesToReuse); }
[ "public", "final", "void", "deepCopyObjectField", "(", "Object", "source", ",", "Object", "copy", ",", "Field", "field", ",", "IdentityHashMap", "<", "Object", ",", "Object", ">", "referencesToReuse", ")", "{", "deepCopyObjectAtOffset", "(", "source", ",", "copy...
Copies the object of the specified type from the given field in the source object to the same field in the copy, visiting the object during the copy so that its fields are also copied @param source The object to copy from @param copy The target object @param field Field to be copied @param referencesToReuse An identity map of references to reuse - this is further populated as the copy progresses. The key is the original object reference - the value is the copied instance for that original.
[ "Copies", "the", "object", "of", "the", "specified", "type", "from", "the", "given", "field", "in", "the", "source", "object", "to", "the", "same", "field", "in", "the", "copy", "visiting", "the", "object", "during", "the", "copy", "so", "that", "its", "...
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cloning/src/main/java/org/jadira/reflection/access/unsafe/UnsafeOperations.java#L429-L432
astrapi69/mystic-crypt
crypt-data/src/main/java/de/alpharogroup/crypto/key/reader/EncryptedPrivateKeyReader.java
EncryptedPrivateKeyReader.getKeyPair
public static KeyPair getKeyPair(final File encryptedPrivateKeyFile, final String password) throws FileNotFoundException, IOException, PEMException { PEMParser pemParser = new PEMParser(new FileReader(encryptedPrivateKeyFile)); Object pemObject = pemParser.readObject(); pemParser.close(); JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter() .setProvider(SecurityProvider.BC.name()); KeyPair keyPair; if (pemObject instanceof PEMEncryptedKeyPair) { PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder() .setProvider(SecurityProvider.BC.name()).build(password.toCharArray()); keyPair = keyConverter .getKeyPair(((PEMEncryptedKeyPair)pemObject).decryptKeyPair(decryptorProvider)); } else { keyPair = keyConverter.getKeyPair((PEMKeyPair)pemObject); } return keyPair; }
java
public static KeyPair getKeyPair(final File encryptedPrivateKeyFile, final String password) throws FileNotFoundException, IOException, PEMException { PEMParser pemParser = new PEMParser(new FileReader(encryptedPrivateKeyFile)); Object pemObject = pemParser.readObject(); pemParser.close(); JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter() .setProvider(SecurityProvider.BC.name()); KeyPair keyPair; if (pemObject instanceof PEMEncryptedKeyPair) { PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder() .setProvider(SecurityProvider.BC.name()).build(password.toCharArray()); keyPair = keyConverter .getKeyPair(((PEMEncryptedKeyPair)pemObject).decryptKeyPair(decryptorProvider)); } else { keyPair = keyConverter.getKeyPair((PEMKeyPair)pemObject); } return keyPair; }
[ "public", "static", "KeyPair", "getKeyPair", "(", "final", "File", "encryptedPrivateKeyFile", ",", "final", "String", "password", ")", "throws", "FileNotFoundException", ",", "IOException", ",", "PEMException", "{", "PEMParser", "pemParser", "=", "new", "PEMParser", ...
Reads from the given {@link File} that contains the password protected {@link KeyPair} and returns it @param encryptedPrivateKeyFile the file that contains the password protected {@link KeyPair} @param password the password @return the key pair @throws FileNotFoundException is thrown if the file did not found @throws IOException Signals that an I/O exception has occurred. @throws PEMException is thrown if an error occurs on read the pem file
[ "Reads", "from", "the", "given", "{", "@link", "File", "}", "that", "contains", "the", "password", "protected", "{", "@link", "KeyPair", "}", "and", "returns", "it" ]
train
https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/key/reader/EncryptedPrivateKeyReader.java#L177-L199
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/WarInfoCommand.java
WarInfoCommand.getDeployedWarInfo
public static WarInfo getDeployedWarInfo(String url, String warName, String token) throws Exception { HttpClient client = httpClient(); HttpGet get = new HttpGet(url + "/system/deployment/details/"+warName); addAuthHeader(token, get); HttpResponse resp = client.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { WarInfo info = new Gson().fromJson(EntityUtils.toString(resp.getEntity()), WarInfo.class); return info; } return null; }
java
public static WarInfo getDeployedWarInfo(String url, String warName, String token) throws Exception { HttpClient client = httpClient(); HttpGet get = new HttpGet(url + "/system/deployment/details/"+warName); addAuthHeader(token, get); HttpResponse resp = client.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { WarInfo info = new Gson().fromJson(EntityUtils.toString(resp.getEntity()), WarInfo.class); return info; } return null; }
[ "public", "static", "WarInfo", "getDeployedWarInfo", "(", "String", "url", ",", "String", "warName", ",", "String", "token", ")", "throws", "Exception", "{", "HttpClient", "client", "=", "httpClient", "(", ")", ";", "HttpGet", "get", "=", "new", "HttpGet", "...
Retrieves information about a deployed cadmium war. @param url The uri to a Cadmium deployer war. @param warName The name of a deployed war. @param token The Github API token used for authentication. @return @throws Exception
[ "Retrieves", "information", "about", "a", "deployed", "cadmium", "war", "." ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/WarInfoCommand.java#L102-L116
coursera/courier
generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java
FileFormatDataSchemaParser.parseFile
private void parseFile(File schemaSourceFile, CourierParseResult result) throws IOException { if (wasResolved(schemaSourceFile)) { return; } final List<DataSchema> schemas = parseSchema(schemaSourceFile, result); for (DataSchema schema : schemas) { validateSchemaWithFilePath(schemaSourceFile, schema); result.getSchemaAndLocations().put(schema, new FileDataSchemaLocation(schemaSourceFile)); result.getSourceFiles().add(schemaSourceFile); } }
java
private void parseFile(File schemaSourceFile, CourierParseResult result) throws IOException { if (wasResolved(schemaSourceFile)) { return; } final List<DataSchema> schemas = parseSchema(schemaSourceFile, result); for (DataSchema schema : schemas) { validateSchemaWithFilePath(schemaSourceFile, schema); result.getSchemaAndLocations().put(schema, new FileDataSchemaLocation(schemaSourceFile)); result.getSourceFiles().add(schemaSourceFile); } }
[ "private", "void", "parseFile", "(", "File", "schemaSourceFile", ",", "CourierParseResult", "result", ")", "throws", "IOException", "{", "if", "(", "wasResolved", "(", "schemaSourceFile", ")", ")", "{", "return", ";", "}", "final", "List", "<", "DataSchema", "...
Parse a source that specifies a file (not a fully qualified schema name). @param schemaSourceFile provides the source file. @param result {@link ParseResult} to update. @throws IOException if there is a file access error.
[ "Parse", "a", "source", "that", "specifies", "a", "file", "(", "not", "a", "fully", "qualified", "schema", "name", ")", "." ]
train
https://github.com/coursera/courier/blob/749674fa7ee33804ad11b6c8ecb560f455cb4c22/generator-api/src/main/java/org/coursera/courier/api/FileFormatDataSchemaParser.java#L174-L190
liferay/com-liferay-commerce
commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java
CommerceCurrencyPersistenceImpl.fetchByUUID_G
@Override public CommerceCurrency fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
java
@Override public CommerceCurrency fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
[ "@", "Override", "public", "CommerceCurrency", "fetchByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "{", "return", "fetchByUUID_G", "(", "uuid", ",", "groupId", ",", "true", ")", ";", "}" ]
Returns the commerce currency where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param uuid the uuid @param groupId the group ID @return the matching commerce currency, or <code>null</code> if a matching commerce currency could not be found
[ "Returns", "the", "commerce", "currency", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "returns", "<code", ">", "null<", "/", "code", ">", "if", "it", "could", "not", "be", "found", ".", "Uses", "the", "finder", "cache",...
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L701-L704
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.isAssignableFrom
@GwtIncompatible("incompatible method") public static void isAssignableFrom(final Class<?> superType, final Class<?> type) { // TODO when breaking BC, consider returning type if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, type == null ? "null" : type.getName(), superType.getName())); } }
java
@GwtIncompatible("incompatible method") public static void isAssignableFrom(final Class<?> superType, final Class<?> type) { // TODO when breaking BC, consider returning type if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(StringUtils.simpleFormat(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, type == null ? "null" : type.getName(), superType.getName())); } }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "void", "isAssignableFrom", "(", "final", "Class", "<", "?", ">", "superType", ",", "final", "Class", "<", "?", ">", "type", ")", "{", "// TODO when breaking BC, consider returning type...
Validates that the argument can be converted to the specified class, if not, throws an exception. <p>This method is useful when validating that there will be no casting errors.</p> <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre> <p>The message format of the exception is &quot;Cannot assign {type} to {superType}&quot;</p> @param superType the class the class must be validated against, not null @param type the class to check, not null @throws IllegalArgumentException if type argument is not assignable to the specified superType @see #isAssignableFrom(Class, Class, String, Object...) @since 3.0
[ "Validates", "that", "the", "argument", "can", "be", "converted", "to", "the", "specified", "class", "if", "not", "throws", "an", "exception", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1319-L1326
dadoonet/fscrawler
framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java
FsCrawlerUtil.isIncluded
public static boolean isIncluded(String filename, List<String> includes) { logger.debug("filename = [{}], includes = [{}]", filename, includes); // No rules ? Fine, we index everything if (includes == null || includes.isEmpty()) { logger.trace("no include rules"); return true; } for (String include : includes) { String regex = include.toLowerCase().replace("?", ".?").replace("*", ".*?"); logger.trace("regex is [{}]", regex); if (filename.toLowerCase().matches(regex)) { logger.trace("does match include regex"); return true; } } logger.trace("does not match any include pattern"); return false; }
java
public static boolean isIncluded(String filename, List<String> includes) { logger.debug("filename = [{}], includes = [{}]", filename, includes); // No rules ? Fine, we index everything if (includes == null || includes.isEmpty()) { logger.trace("no include rules"); return true; } for (String include : includes) { String regex = include.toLowerCase().replace("?", ".?").replace("*", ".*?"); logger.trace("regex is [{}]", regex); if (filename.toLowerCase().matches(regex)) { logger.trace("does match include regex"); return true; } } logger.trace("does not match any include pattern"); return false; }
[ "public", "static", "boolean", "isIncluded", "(", "String", "filename", ",", "List", "<", "String", ">", "includes", ")", "{", "logger", ".", "debug", "(", "\"filename = [{}], includes = [{}]\"", ",", "filename", ",", "includes", ")", ";", "// No rules ? Fine, we ...
We check if we can index the file or if we should ignore it @param filename The filename to scan @param includes include rules, may be empty not null
[ "We", "check", "if", "we", "can", "index", "the", "file", "or", "if", "we", "should", "ignore", "it" ]
train
https://github.com/dadoonet/fscrawler/blob/cca00a14e21ef9986aa30e19b160463aed6bf921/framework/src/main/java/fr/pilato/elasticsearch/crawler/fs/framework/FsCrawlerUtil.java#L229-L249
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java
CmsListItemWidget.concatIconTitles
String concatIconTitles(String main, String secondary) { if (main == null) { main = ""; } if (secondary == null) { secondary = ""; } if (secondary.length() == 0) { return main; } return main + " [" + secondary + "]"; }
java
String concatIconTitles(String main, String secondary) { if (main == null) { main = ""; } if (secondary == null) { secondary = ""; } if (secondary.length() == 0) { return main; } return main + " [" + secondary + "]"; }
[ "String", "concatIconTitles", "(", "String", "main", ",", "String", "secondary", ")", "{", "if", "(", "main", "==", "null", ")", "{", "main", "=", "\"\"", ";", "}", "if", "(", "secondary", "==", "null", ")", "{", "secondary", "=", "\"\"", ";", "}", ...
Combines the main icon title with the title for a status icon overlayed over the main icon.<p> @param main the main icon title @param secondary the secondary icon title @return the combined icon title for the secondary icon
[ "Combines", "the", "main", "icon", "title", "with", "the", "title", "for", "a", "status", "icon", "overlayed", "over", "the", "main", "icon", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java#L1185-L1199
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.getMarkerAnchor
public Content getMarkerAnchor(String anchorName, Content anchorContent) { if (anchorContent == null) anchorContent = new Comment(" "); Content markerAnchor = HtmlTree.A(configuration.htmlVersion, anchorName, anchorContent); return markerAnchor; }
java
public Content getMarkerAnchor(String anchorName, Content anchorContent) { if (anchorContent == null) anchorContent = new Comment(" "); Content markerAnchor = HtmlTree.A(configuration.htmlVersion, anchorName, anchorContent); return markerAnchor; }
[ "public", "Content", "getMarkerAnchor", "(", "String", "anchorName", ",", "Content", "anchorContent", ")", "{", "if", "(", "anchorContent", "==", "null", ")", "anchorContent", "=", "new", "Comment", "(", "\" \"", ")", ";", "Content", "markerAnchor", "=", "Html...
Get the marker anchor which will be added to the documentation tree. @param anchorName the anchor name or id attribute @param anchorContent the content that should be added to the anchor @return a content tree for the marker anchor
[ "Get", "the", "marker", "anchor", "which", "will", "be", "added", "to", "the", "documentation", "tree", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L839-L844
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java
SourceToHTMLConverter.convertClass
public void convertClass(TypeElement te, DocPath outputdir) throws DocFileIOException, SimpleDocletException { if (te == null) { return; } FileObject fo = utils.getFileObject(te); if (fo == null) return; try { Reader r = fo.openReader(true); int lineno = 1; String line; relativePath = DocPaths.SOURCE_OUTPUT .resolve(DocPath.forPackage(utils, te)) .invert(); Content body = getHeader(); Content pre = new HtmlTree(HtmlTag.PRE); try (LineNumberReader reader = new LineNumberReader(r)) { while ((line = reader.readLine()) != null) { addLineNo(pre, lineno); addLine(pre, line, lineno); lineno++; } } addBlankLines(pre); Content div = HtmlTree.DIV(HtmlStyle.sourceContainer, pre); body.addContent((configuration.allowTag(HtmlTag.MAIN)) ? HtmlTree.MAIN(div) : div); writeToFile(body, outputdir.resolve(DocPath.forClass(utils, te))); } catch (IOException e) { String message = configuration.resources.getText("doclet.exception.read.file", fo.getName()); throw new SimpleDocletException(message, e); } }
java
public void convertClass(TypeElement te, DocPath outputdir) throws DocFileIOException, SimpleDocletException { if (te == null) { return; } FileObject fo = utils.getFileObject(te); if (fo == null) return; try { Reader r = fo.openReader(true); int lineno = 1; String line; relativePath = DocPaths.SOURCE_OUTPUT .resolve(DocPath.forPackage(utils, te)) .invert(); Content body = getHeader(); Content pre = new HtmlTree(HtmlTag.PRE); try (LineNumberReader reader = new LineNumberReader(r)) { while ((line = reader.readLine()) != null) { addLineNo(pre, lineno); addLine(pre, line, lineno); lineno++; } } addBlankLines(pre); Content div = HtmlTree.DIV(HtmlStyle.sourceContainer, pre); body.addContent((configuration.allowTag(HtmlTag.MAIN)) ? HtmlTree.MAIN(div) : div); writeToFile(body, outputdir.resolve(DocPath.forClass(utils, te))); } catch (IOException e) { String message = configuration.resources.getText("doclet.exception.read.file", fo.getName()); throw new SimpleDocletException(message, e); } }
[ "public", "void", "convertClass", "(", "TypeElement", "te", ",", "DocPath", "outputdir", ")", "throws", "DocFileIOException", ",", "SimpleDocletException", "{", "if", "(", "te", "==", "null", ")", "{", "return", ";", "}", "FileObject", "fo", "=", "utils", "....
Convert the given Class to an HTML. @param te the class to convert. @param outputdir the name of the directory to output to @throws DocFileIOException if there is a problem generating the output file @throws SimpleDocletException if there is a problem reading the source file
[ "Convert", "the", "given", "Class", "to", "an", "HTML", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java#L165-L198
apptik/jus
benchmark/src/perf/java/com/android/volley/toolbox/DiskBasedCache.java
DiskBasedCache.putEntry
private void putEntry(String key, CacheHeader entry) { if (!mEntries.containsKey(key)) { mTotalSize += entry.size; } else { CacheHeader oldEntry = mEntries.get(key); mTotalSize += (entry.size - oldEntry.size); } mEntries.put(key, entry); }
java
private void putEntry(String key, CacheHeader entry) { if (!mEntries.containsKey(key)) { mTotalSize += entry.size; } else { CacheHeader oldEntry = mEntries.get(key); mTotalSize += (entry.size - oldEntry.size); } mEntries.put(key, entry); }
[ "private", "void", "putEntry", "(", "String", "key", ",", "CacheHeader", "entry", ")", "{", "if", "(", "!", "mEntries", ".", "containsKey", "(", "key", ")", ")", "{", "mTotalSize", "+=", "entry", ".", "size", ";", "}", "else", "{", "CacheHeader", "oldE...
Puts the entry with the specified key into the cache. @param key The key to identify the entry by. @param entry The entry to cache.
[ "Puts", "the", "entry", "with", "the", "specified", "key", "into", "the", "cache", "." ]
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/benchmark/src/perf/java/com/android/volley/toolbox/DiskBasedCache.java#L300-L308
protegeproject/sparql-dl-api
src/main/java/de/derivo/sparqldlapi/impl/QueryEngineImpl.java
QueryEngineImpl.combineResults
private QueryResultImpl combineResults(Queue<QueryResultImpl> results, boolean distinct) { while (results.size() > 1) { QueryResultImpl a = results.remove(); QueryResultImpl b = results.remove(); results.add(combineResults(a, b, distinct)); } return results.remove(); }
java
private QueryResultImpl combineResults(Queue<QueryResultImpl> results, boolean distinct) { while (results.size() > 1) { QueryResultImpl a = results.remove(); QueryResultImpl b = results.remove(); results.add(combineResults(a, b, distinct)); } return results.remove(); }
[ "private", "QueryResultImpl", "combineResults", "(", "Queue", "<", "QueryResultImpl", ">", "results", ",", "boolean", "distinct", ")", "{", "while", "(", "results", ".", "size", "(", ")", ">", "1", ")", "{", "QueryResultImpl", "a", "=", "results", ".", "re...
Combine the results of the individual components with the cartesian product. @return the combined result
[ "Combine", "the", "results", "of", "the", "individual", "components", "with", "the", "cartesian", "product", "." ]
train
https://github.com/protegeproject/sparql-dl-api/blob/80d430d439e17a691d0111819af2d3613e28d625/src/main/java/de/derivo/sparqldlapi/impl/QueryEngineImpl.java#L273-L281
openbase/jul
processing/default/src/main/java/org/openbase/jul/processing/StringProcessor.java
StringProcessor.fillWithSpaces
public static String fillWithSpaces(String input, int lenght, final Alignment textAlignment) { String spaces = ""; for (int i = lenght - input.length(); i > 0; i--) { spaces += " "; } switch (textAlignment) { case RIGHT: return spaces + input; case CENTER: final int half_spaces_size = (lenght - input.length()) / 2; return spaces.substring(0, half_spaces_size - 1) + input + spaces.substring(half_spaces_size); case LEFT: default: return input + spaces; } }
java
public static String fillWithSpaces(String input, int lenght, final Alignment textAlignment) { String spaces = ""; for (int i = lenght - input.length(); i > 0; i--) { spaces += " "; } switch (textAlignment) { case RIGHT: return spaces + input; case CENTER: final int half_spaces_size = (lenght - input.length()) / 2; return spaces.substring(0, half_spaces_size - 1) + input + spaces.substring(half_spaces_size); case LEFT: default: return input + spaces; } }
[ "public", "static", "String", "fillWithSpaces", "(", "String", "input", ",", "int", "lenght", ",", "final", "Alignment", "textAlignment", ")", "{", "String", "spaces", "=", "\"\"", ";", "for", "(", "int", "i", "=", "lenght", "-", "input", ".", "length", ...
Method fills the given input string with width-spaces until the given string length is reached. <p> Note: The origin input string will aligned to the left. @param input the original input string @param lenght the requested input string length. @param textAlignment the alignment of the origin input string. @return the extended input string
[ "Method", "fills", "the", "given", "input", "string", "with", "width", "-", "spaces", "until", "the", "given", "string", "length", "is", "reached", ".", "<p", ">", "Note", ":", "The", "origin", "input", "string", "will", "aligned", "to", "the", "left", "...
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/processing/default/src/main/java/org/openbase/jul/processing/StringProcessor.java#L142-L157
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java
QueueContainer.mapIterateAndRemove
public void mapIterateAndRemove(Map<Long, Data> map) { if (map.size() <= 0) { return; } if (store.isEnabled()) { try { store.deleteAll(map.keySet()); } catch (Exception e) { throw new HazelcastException(e); } } Iterator<QueueItem> iterator = getItemQueue().iterator(); while (iterator.hasNext()) { QueueItem item = iterator.next(); if (map.containsKey(item.getItemId())) { iterator.remove(); // for stats age(item, Clock.currentTimeMillis()); } } scheduleEvictionIfEmpty(); }
java
public void mapIterateAndRemove(Map<Long, Data> map) { if (map.size() <= 0) { return; } if (store.isEnabled()) { try { store.deleteAll(map.keySet()); } catch (Exception e) { throw new HazelcastException(e); } } Iterator<QueueItem> iterator = getItemQueue().iterator(); while (iterator.hasNext()) { QueueItem item = iterator.next(); if (map.containsKey(item.getItemId())) { iterator.remove(); // for stats age(item, Clock.currentTimeMillis()); } } scheduleEvictionIfEmpty(); }
[ "public", "void", "mapIterateAndRemove", "(", "Map", "<", "Long", ",", "Data", ">", "map", ")", "{", "if", "(", "map", ".", "size", "(", ")", "<=", "0", ")", "{", "return", ";", "}", "if", "(", "store", ".", "isEnabled", "(", ")", ")", "{", "tr...
Deletes items from the queue which have IDs contained in the key set of the given map. Also schedules the queue for destruction if it is empty or destroys it immediately if it is empty and {@link QueueConfig#getEmptyQueueTtl()} is 0. @param map the map of items which to be removed.
[ "Deletes", "items", "from", "the", "queue", "which", "have", "IDs", "contained", "in", "the", "key", "set", "of", "the", "given", "map", ".", "Also", "schedules", "the", "queue", "for", "destruction", "if", "it", "is", "empty", "or", "destroys", "it", "i...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/collection/impl/queue/QueueContainer.java#L801-L823
OpenLiberty/open-liberty
dev/wlp-bndPlugins/src/com/ibm/ws/build/bnd/plugins/ImportlessPackager.java
ImportlessPackager.collectClassDependencies
private void collectClassDependencies (Clazz classInstance, Analyzer analyzer) throws Exception { // retrieve the imports from the known class path Set<TypeRef> importedClasses = classInstance.parseClassFile(); for (TypeRef importedClass:importedClasses) { if (canBeSkipped(importedClass)) // validate the import continue; // find the class in the classpath Clazz classInstanceImported = analyzer.findClass(importedClass); if (classInstanceImported == null) error( "Referenced class " + importedClass.getFQN() + " not found for inclusion in jar. It is imported by " + classInstance.getAbsolutePath()); // update the imports map importedReferencedTypes.add(importedClass); allReferencedTypes.add(importedClass); // collect dependencies introduced by the imports collectClassDependencies(classInstanceImported, analyzer); } }
java
private void collectClassDependencies (Clazz classInstance, Analyzer analyzer) throws Exception { // retrieve the imports from the known class path Set<TypeRef> importedClasses = classInstance.parseClassFile(); for (TypeRef importedClass:importedClasses) { if (canBeSkipped(importedClass)) // validate the import continue; // find the class in the classpath Clazz classInstanceImported = analyzer.findClass(importedClass); if (classInstanceImported == null) error( "Referenced class " + importedClass.getFQN() + " not found for inclusion in jar. It is imported by " + classInstance.getAbsolutePath()); // update the imports map importedReferencedTypes.add(importedClass); allReferencedTypes.add(importedClass); // collect dependencies introduced by the imports collectClassDependencies(classInstanceImported, analyzer); } }
[ "private", "void", "collectClassDependencies", "(", "Clazz", "classInstance", ",", "Analyzer", "analyzer", ")", "throws", "Exception", "{", "// retrieve the imports from the known class path", "Set", "<", "TypeRef", ">", "importedClasses", "=", "classInstance", ".", "pars...
Collect the imports from a class and add the imported classes to the map of all known classes importedReferencedTypes is updated to contain newly added imports allReferencedTypes is updated to avoid the duplicated process @param classInstance @param analyzer @throws Exception
[ "Collect", "the", "imports", "from", "a", "class", "and", "add", "the", "imported", "classes", "to", "the", "map", "of", "all", "known", "classes", "importedReferencedTypes", "is", "updated", "to", "contain", "newly", "added", "imports", "allReferencedTypes", "i...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/wlp-bndPlugins/src/com/ibm/ws/build/bnd/plugins/ImportlessPackager.java#L239-L256
apache/incubator-heron
heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java
PackingUtils.computeTotalResourceChange
public static Resource computeTotalResourceChange(TopologyAPI.Topology topology, Map<String, Integer> componentChanges, Resource defaultInstanceResources, ScalingDirection scalingDirection) { double cpu = 0; ByteAmount ram = ByteAmount.ZERO; ByteAmount disk = ByteAmount.ZERO; Map<String, ByteAmount> ramMap = TopologyUtils.getComponentRamMapConfig(topology); Map<String, Integer> componentsToScale = PackingUtils.getComponentsToScale( componentChanges, scalingDirection); for (String component : componentsToScale.keySet()) { int parallelismChange = Math.abs(componentChanges.get(component)); cpu += parallelismChange * defaultInstanceResources.getCpu(); disk = disk.plus(defaultInstanceResources.getDisk().multiply(parallelismChange)); if (ramMap.containsKey(component)) { ram = ram.plus(ramMap.get(component).multiply(parallelismChange)); } else { ram = ram.plus(defaultInstanceResources.getRam().multiply(parallelismChange)); } } return new Resource(cpu, ram, disk); }
java
public static Resource computeTotalResourceChange(TopologyAPI.Topology topology, Map<String, Integer> componentChanges, Resource defaultInstanceResources, ScalingDirection scalingDirection) { double cpu = 0; ByteAmount ram = ByteAmount.ZERO; ByteAmount disk = ByteAmount.ZERO; Map<String, ByteAmount> ramMap = TopologyUtils.getComponentRamMapConfig(topology); Map<String, Integer> componentsToScale = PackingUtils.getComponentsToScale( componentChanges, scalingDirection); for (String component : componentsToScale.keySet()) { int parallelismChange = Math.abs(componentChanges.get(component)); cpu += parallelismChange * defaultInstanceResources.getCpu(); disk = disk.plus(defaultInstanceResources.getDisk().multiply(parallelismChange)); if (ramMap.containsKey(component)) { ram = ram.plus(ramMap.get(component).multiply(parallelismChange)); } else { ram = ram.plus(defaultInstanceResources.getRam().multiply(parallelismChange)); } } return new Resource(cpu, ram, disk); }
[ "public", "static", "Resource", "computeTotalResourceChange", "(", "TopologyAPI", ".", "Topology", "topology", ",", "Map", "<", "String", ",", "Integer", ">", "componentChanges", ",", "Resource", "defaultInstanceResources", ",", "ScalingDirection", "scalingDirection", "...
Identifies the resources reclaimed by the components that will be scaled down @return Total resources reclaimed
[ "Identifies", "the", "resources", "reclaimed", "by", "the", "components", "that", "will", "be", "scaled", "down" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/utils/PackingUtils.java#L128-L149
amzn/ion-java
src/com/amazon/ion/impl/BlockedBuffer.java
BlockedBuffer.insertInCurrOnly
private int insertInCurrOnly(Object caller, int version, bbBlock curr, int pos, int len) { assert mutation_in_progress(caller, version); // the space we need is available right in the block assert curr.unusedBlockCapacity() >= len; System.arraycopy(curr._buffer, curr.blockOffsetFromAbsolute(pos) ,curr._buffer, curr.blockOffsetFromAbsolute(pos) + len, curr.bytesAvailableToRead(pos)); curr._limit += len; this.adjustOffsets(curr._idx, len, 0); notifyInsert(pos, len); return len; }
java
private int insertInCurrOnly(Object caller, int version, bbBlock curr, int pos, int len) { assert mutation_in_progress(caller, version); // the space we need is available right in the block assert curr.unusedBlockCapacity() >= len; System.arraycopy(curr._buffer, curr.blockOffsetFromAbsolute(pos) ,curr._buffer, curr.blockOffsetFromAbsolute(pos) + len, curr.bytesAvailableToRead(pos)); curr._limit += len; this.adjustOffsets(curr._idx, len, 0); notifyInsert(pos, len); return len; }
[ "private", "int", "insertInCurrOnly", "(", "Object", "caller", ",", "int", "version", ",", "bbBlock", "curr", ",", "int", "pos", ",", "int", "len", ")", "{", "assert", "mutation_in_progress", "(", "caller", ",", "version", ")", ";", "// the space we need is av...
this handles insert when there's enough room in the current block
[ "this", "handles", "insert", "when", "there", "s", "enough", "room", "in", "the", "current", "block" ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/BlockedBuffer.java#L564-L575
google/closure-templates
java/src/com/google/template/soy/shared/internal/Sanitizers.java
Sanitizers.escapeJsValue
public static String escapeJsValue(SoyValue value) { // We surround values with spaces so that they can't be interpolated into identifiers // by accident. We could use parentheses but those might be interpreted as a function call. if (NullData.INSTANCE == value || value == null) { // The JS counterpart of this code in soyutils.js emits " null " for both null and the special // JS value undefined. return " null "; } else if (value instanceof NumberData) { // This will emit references to NaN and Infinity. Client code should not redefine those // to store sensitive data. return " " + value.numberValue() + " "; } else if (value instanceof BooleanData) { return " " + value.booleanValue() + " "; } else if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.JS)) { String jsCode = value.coerceToString(); // This value may not be embeddable if it contains the substring "</script". // TODO(msamuel): Fixup. We need to be careful because mucking with '<' can // break code like // while (i</foo/.exec(str).length) // and mucking with / can break // return untrustedHTML.replace(/</g, '&lt;'); return jsCode; } else { return escapeJsValue(value.coerceToString()); } }
java
public static String escapeJsValue(SoyValue value) { // We surround values with spaces so that they can't be interpolated into identifiers // by accident. We could use parentheses but those might be interpreted as a function call. if (NullData.INSTANCE == value || value == null) { // The JS counterpart of this code in soyutils.js emits " null " for both null and the special // JS value undefined. return " null "; } else if (value instanceof NumberData) { // This will emit references to NaN and Infinity. Client code should not redefine those // to store sensitive data. return " " + value.numberValue() + " "; } else if (value instanceof BooleanData) { return " " + value.booleanValue() + " "; } else if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.JS)) { String jsCode = value.coerceToString(); // This value may not be embeddable if it contains the substring "</script". // TODO(msamuel): Fixup. We need to be careful because mucking with '<' can // break code like // while (i</foo/.exec(str).length) // and mucking with / can break // return untrustedHTML.replace(/</g, '&lt;'); return jsCode; } else { return escapeJsValue(value.coerceToString()); } }
[ "public", "static", "String", "escapeJsValue", "(", "SoyValue", "value", ")", "{", "// We surround values with spaces so that they can't be interpolated into identifiers", "// by accident. We could use parentheses but those might be interpreted as a function call.", "if", "(", "NullData",...
Converts the input to a JavaScript expression. The resulting expression can be a boolean, number, string literal, or {@code null}.
[ "Converts", "the", "input", "to", "a", "JavaScript", "expression", ".", "The", "resulting", "expression", "can", "be", "a", "boolean", "number", "string", "literal", "or", "{" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/shared/internal/Sanitizers.java#L406-L431
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/util/CompareUtil.java
CompareUtil.elementIsContainedInArray
public static <T> boolean elementIsContainedInArray(T element, T... values) { if (element != null && values != null) { return elementIsContainedInList(element, Arrays.asList(values)); } else { return false; } }
java
public static <T> boolean elementIsContainedInArray(T element, T... values) { if (element != null && values != null) { return elementIsContainedInList(element, Arrays.asList(values)); } else { return false; } }
[ "public", "static", "<", "T", ">", "boolean", "elementIsContainedInArray", "(", "T", "element", ",", "T", "...", "values", ")", "{", "if", "(", "element", "!=", "null", "&&", "values", "!=", "null", ")", "{", "return", "elementIsContainedInList", "(", "ele...
Checks if the element is contained within the list of values. @param element to check @param values to check in @param <T> the type of the element @return {@code true} if the element and values are not {@code null} and the values contain the element, {@code false} otherwise
[ "Checks", "if", "the", "element", "is", "contained", "within", "the", "list", "of", "values", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/util/CompareUtil.java#L139-L146
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/DataSet.java
DataSet.squishToRange
@Override public void squishToRange(double min, double max) { for (int i = 0; i < getFeatures().length(); i++) { double curr = (double) getFeatures().getScalar(i).element(); if (curr < min) getFeatures().put(i, Nd4j.scalar(min)); else if (curr > max) getFeatures().put(i, Nd4j.scalar(max)); } }
java
@Override public void squishToRange(double min, double max) { for (int i = 0; i < getFeatures().length(); i++) { double curr = (double) getFeatures().getScalar(i).element(); if (curr < min) getFeatures().put(i, Nd4j.scalar(min)); else if (curr > max) getFeatures().put(i, Nd4j.scalar(max)); } }
[ "@", "Override", "public", "void", "squishToRange", "(", "double", "min", ",", "double", "max", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "getFeatures", "(", ")", ".", "length", "(", ")", ";", "i", "++", ")", "{", "double", "curr...
Squeezes input data to a max and a min @param min the min value to occur in the dataset @param max the max value to ccur in the dataset
[ "Squeezes", "input", "data", "to", "a", "max", "and", "a", "min" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/DataSet.java#L486-L495
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java
ValueEnforcer.notEmpty
public static <T extends CharSequence> T notEmpty (final T aValue, final String sName) { if (isEnabled ()) return notEmpty (aValue, () -> sName); return aValue; }
java
public static <T extends CharSequence> T notEmpty (final T aValue, final String sName) { if (isEnabled ()) return notEmpty (aValue, () -> sName); return aValue; }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "notEmpty", "(", "final", "T", "aValue", ",", "final", "String", "sName", ")", "{", "if", "(", "isEnabled", "(", ")", ")", "return", "notEmpty", "(", "aValue", ",", "(", ")", "->", "s...
Check that the passed String is neither <code>null</code> nor empty. @param <T> Type to be checked and returned @param aValue The String to check. @param sName The name of the value (e.g. the parameter name) @return The passed value. @throws IllegalArgumentException if the passed value is empty
[ "Check", "that", "the", "passed", "String", "is", "neither", "<code", ">", "null<", "/", "code", ">", "nor", "empty", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L348-L353
ben-manes/caffeine
simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/linked/FrequentlyUsedPolicy.java
FrequentlyUsedPolicy.policies
public static Set<Policy> policies(Config config, EvictionPolicy policy) { BasicSettings settings = new BasicSettings(config); return settings.admission().stream().map(admission -> new FrequentlyUsedPolicy(admission, policy, config) ).collect(toSet()); }
java
public static Set<Policy> policies(Config config, EvictionPolicy policy) { BasicSettings settings = new BasicSettings(config); return settings.admission().stream().map(admission -> new FrequentlyUsedPolicy(admission, policy, config) ).collect(toSet()); }
[ "public", "static", "Set", "<", "Policy", ">", "policies", "(", "Config", "config", ",", "EvictionPolicy", "policy", ")", "{", "BasicSettings", "settings", "=", "new", "BasicSettings", "(", "config", ")", ";", "return", "settings", ".", "admission", "(", ")"...
Returns all variations of this policy based on the configuration parameters.
[ "Returns", "all", "variations", "of", "this", "policy", "based", "on", "the", "configuration", "parameters", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/linked/FrequentlyUsedPolicy.java#L62-L67
liferay/com-liferay-commerce
commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java
CommerceCurrencyPersistenceImpl.findByG_P
@Override public List<CommerceCurrency> findByG_P(long groupId, boolean primary, int start, int end) { return findByG_P(groupId, primary, start, end, null); }
java
@Override public List<CommerceCurrency> findByG_P(long groupId, boolean primary, int start, int end) { return findByG_P(groupId, primary, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceCurrency", ">", "findByG_P", "(", "long", "groupId", ",", "boolean", "primary", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByG_P", "(", "groupId", ",", "primary", ",", "start", ",", "...
Returns a range of all the commerce currencies where groupId = &#63; and primary = &#63;. <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 CommerceCurrencyModelImpl}. 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 groupId the group ID @param primary the primary @param start the lower bound of the range of commerce currencies @param end the upper bound of the range of commerce currencies (not inclusive) @return the range of matching commerce currencies
[ "Returns", "a", "range", "of", "all", "the", "commerce", "currencies", "where", "groupId", "=", "&#63", ";", "and", "primary", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L2288-L2292
blackfizz/EazeGraph
EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/PieChart.java
PieChart.onSizeChanged
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mGraph.setPivot(mGraphBounds.centerX(), mGraphBounds.centerY()); onDataChanged(); }
java
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mGraph.setPivot(mGraphBounds.centerX(), mGraphBounds.centerY()); onDataChanged(); }
[ "@", "Override", "protected", "void", "onSizeChanged", "(", "int", "w", ",", "int", "h", ",", "int", "oldw", ",", "int", "oldh", ")", "{", "super", ".", "onSizeChanged", "(", "w", ",", "h", ",", "oldw", ",", "oldh", ")", ";", "mGraph", ".", "setPiv...
This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0. @param w Current width of this view. @param h Current height of this view. @param oldw Old width of this view. @param oldh Old height of this view.
[ "This", "is", "called", "during", "layout", "when", "the", "size", "of", "this", "view", "has", "changed", ".", "If", "you", "were", "just", "added", "to", "the", "view", "hierarchy", "you", "re", "called", "with", "the", "old", "values", "of", "0", "....
train
https://github.com/blackfizz/EazeGraph/blob/ce5e68ecc70e154f83bbb2fcce1a970db125c1e6/EazeGraphLibrary/src/main/java/org/eazegraph/lib/charts/PieChart.java#L588-L595
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java
SparkComputationGraph.evaluateRegression
public <T extends RegressionEvaluation> T evaluateRegression(JavaRDD<DataSet> data) { return evaluateRegression(data, DEFAULT_EVAL_SCORE_BATCH_SIZE); }
java
public <T extends RegressionEvaluation> T evaluateRegression(JavaRDD<DataSet> data) { return evaluateRegression(data, DEFAULT_EVAL_SCORE_BATCH_SIZE); }
[ "public", "<", "T", "extends", "RegressionEvaluation", ">", "T", "evaluateRegression", "(", "JavaRDD", "<", "DataSet", ">", "data", ")", "{", "return", "evaluateRegression", "(", "data", ",", "DEFAULT_EVAL_SCORE_BATCH_SIZE", ")", ";", "}" ]
Evaluate the network (regression performance) in a distributed manner on the provided data @param data Data to evaluate @return {@link RegressionEvaluation} instance with regression performance
[ "Evaluate", "the", "network", "(", "regression", "performance", ")", "in", "a", "distributed", "manner", "on", "the", "provided", "data" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java#L628-L630
osglworks/java-tool
src/main/java/org/osgl/Lang.java
F4.orElse
public F4<P1, P2, P3, P4, R> orElse( final Func4<? super P1, ? super P2, ? super P3, ? super P4, ? extends R> fallback ) { final F4<P1, P2, P3, P4, R> me = this; return new F4<P1, P2, P3, P4, R>() { @Override public R apply(P1 p1, P2 p2, P3 p3, P4 p4) { try { return me.apply(p1, p2, p3, p4); } catch (RuntimeException e) { return fallback.apply(p1, p2, p3, p4); } } }; }
java
public F4<P1, P2, P3, P4, R> orElse( final Func4<? super P1, ? super P2, ? super P3, ? super P4, ? extends R> fallback ) { final F4<P1, P2, P3, P4, R> me = this; return new F4<P1, P2, P3, P4, R>() { @Override public R apply(P1 p1, P2 p2, P3 p3, P4 p4) { try { return me.apply(p1, p2, p3, p4); } catch (RuntimeException e) { return fallback.apply(p1, p2, p3, p4); } } }; }
[ "public", "F4", "<", "P1", ",", "P2", ",", "P3", ",", "P4", ",", "R", ">", "orElse", "(", "final", "Func4", "<", "?", "super", "P1", ",", "?", "super", "P2", ",", "?", "super", "P3", ",", "?", "super", "P4", ",", "?", "extends", "R", ">", "...
Returns a composed function that when applied, try to apply this function first, in case a {@link NotAppliedException} is captured apply to the fallback function specified. This method helps to implement partial function @param fallback the function to applied if this function doesn't apply to the parameter(s) @return the composed function
[ "Returns", "a", "composed", "function", "that", "when", "applied", "try", "to", "apply", "this", "function", "first", "in", "case", "a", "{", "@link", "NotAppliedException", "}", "is", "captured", "apply", "to", "the", "fallback", "function", "specified", ".",...
train
https://github.com/osglworks/java-tool/blob/8b6eee2bccb067eb32e6a7bc4a4dfef7a7d9008b/src/main/java/org/osgl/Lang.java#L1603-L1617
vorburger/ch.vorburger.exec
src/main/java/ch/vorburger/exec/ManagedProcessBuilder.java
ManagedProcessBuilder.getCommandLine
CommandLine getCommandLine() { if (getWorkingDirectory() == null) { if (commonsExecCommandLine.isFile()) { File exec = new File(commonsExecCommandLine.getExecutable()); File dir = exec.getParentFile(); if (dir == null) { throw new IllegalStateException( "directory MUST be set (and could not be auto-determined from executable, although it was a File)"); } this.setWorkingDirectory(dir); // DO NOT } else { // throw new // IllegalStateException("directory MUST be set (and could not be auto-determined from executable)"); } } return commonsExecCommandLine; }
java
CommandLine getCommandLine() { if (getWorkingDirectory() == null) { if (commonsExecCommandLine.isFile()) { File exec = new File(commonsExecCommandLine.getExecutable()); File dir = exec.getParentFile(); if (dir == null) { throw new IllegalStateException( "directory MUST be set (and could not be auto-determined from executable, although it was a File)"); } this.setWorkingDirectory(dir); // DO NOT } else { // throw new // IllegalStateException("directory MUST be set (and could not be auto-determined from executable)"); } } return commonsExecCommandLine; }
[ "CommandLine", "getCommandLine", "(", ")", "{", "if", "(", "getWorkingDirectory", "(", ")", "==", "null", ")", "{", "if", "(", "commonsExecCommandLine", ".", "isFile", "(", ")", ")", "{", "File", "exec", "=", "new", "File", "(", "commonsExecCommandLine", "...
/* package-local... let's keep ch.vorburger.exec's API separate from Apache Commons Exec, so it COULD be replaced
[ "/", "*", "package", "-", "local", "...", "let", "s", "keep", "ch", ".", "vorburger", ".", "exec", "s", "API", "separate", "from", "Apache", "Commons", "Exec", "so", "it", "COULD", "be", "replaced" ]
train
https://github.com/vorburger/ch.vorburger.exec/blob/98853c55c8dfb3a6185019b8928df2a091baa471/src/main/java/ch/vorburger/exec/ManagedProcessBuilder.java#L241-L257
lucee/Lucee
core/src/main/java/lucee/runtime/interpreter/CFMLExpressionInterpreter.java
CFMLExpressionInterpreter.interpretPart
protected Object interpretPart(PageContext pc, ParserString cfml) throws PageException { this.cfml = cfml; init(pc); cfml.removeSpace(); return assignOp().getValue(pc); }
java
protected Object interpretPart(PageContext pc, ParserString cfml) throws PageException { this.cfml = cfml; init(pc); cfml.removeSpace(); return assignOp().getValue(pc); }
[ "protected", "Object", "interpretPart", "(", "PageContext", "pc", ",", "ParserString", "cfml", ")", "throws", "PageException", "{", "this", ".", "cfml", "=", "cfml", ";", "init", "(", "pc", ")", ";", "cfml", ".", "removeSpace", "(", ")", ";", "return", "...
/* private FunctionLibFunction getFLF(String name) { FunctionLibFunction flf=null; for (int i = 0; i < flds.length; i++) { flf = flds[i].getFunction(name); if (flf != null) break; } return flf; }
[ "/", "*", "private", "FunctionLibFunction", "getFLF", "(", "String", "name", ")", "{", "FunctionLibFunction", "flf", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "flds", ".", "length", ";", "i", "++", ")", "{", "flf", "=", "fl...
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/interpreter/CFMLExpressionInterpreter.java#L243-L249
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsPreferences.java
CmsPreferences.getOptionsForLanguageStatic
public static SelectOptions getOptionsForLanguageStatic(Locale setLocale, Locale prevLocale) { // get available locales from the workplace manager List<Locale> locales = OpenCms.getWorkplaceManager().getLocales(); List<String> options = new ArrayList<String>(locales.size()); List<String> values = new ArrayList<String>(locales.size()); int checkedIndex = 0; int counter = 0; Iterator<Locale> i = locales.iterator(); while (i.hasNext()) { Locale currentLocale = i.next(); // add all locales to the select box String language = currentLocale.getDisplayLanguage(setLocale); if (CmsStringUtil.isNotEmpty(currentLocale.getCountry())) { language = language + " (" + currentLocale.getDisplayCountry(setLocale) + ")"; } if (CmsStringUtil.isNotEmpty(currentLocale.getVariant())) { language = language + " (" + currentLocale.getDisplayVariant(setLocale) + ")"; } options.add(language); values.add(currentLocale.toString()); if (prevLocale.toString().equals(currentLocale.toString())) { // mark the currently active locale checkedIndex = counter; } counter++; } SelectOptions selectOptions = new SelectOptions(options, values, checkedIndex); return selectOptions; }
java
public static SelectOptions getOptionsForLanguageStatic(Locale setLocale, Locale prevLocale) { // get available locales from the workplace manager List<Locale> locales = OpenCms.getWorkplaceManager().getLocales(); List<String> options = new ArrayList<String>(locales.size()); List<String> values = new ArrayList<String>(locales.size()); int checkedIndex = 0; int counter = 0; Iterator<Locale> i = locales.iterator(); while (i.hasNext()) { Locale currentLocale = i.next(); // add all locales to the select box String language = currentLocale.getDisplayLanguage(setLocale); if (CmsStringUtil.isNotEmpty(currentLocale.getCountry())) { language = language + " (" + currentLocale.getDisplayCountry(setLocale) + ")"; } if (CmsStringUtil.isNotEmpty(currentLocale.getVariant())) { language = language + " (" + currentLocale.getDisplayVariant(setLocale) + ")"; } options.add(language); values.add(currentLocale.toString()); if (prevLocale.toString().equals(currentLocale.toString())) { // mark the currently active locale checkedIndex = counter; } counter++; } SelectOptions selectOptions = new SelectOptions(options, values, checkedIndex); return selectOptions; }
[ "public", "static", "SelectOptions", "getOptionsForLanguageStatic", "(", "Locale", "setLocale", ",", "Locale", "prevLocale", ")", "{", "// get available locales from the workplace manager", "List", "<", "Locale", ">", "locales", "=", "OpenCms", ".", "getWorkplaceManager", ...
Gets the options for the language selector.<p> @param setLocale the locale for the select options @param prevLocale the locale currently set @return the options for the language selector
[ "Gets", "the", "options", "for", "the", "language", "selector", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsPreferences.java#L290-L319
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Cipher.java
Cipher.updateAAD
public final void updateAAD(byte[] src, int offset, int len) { checkCipherState(); // Input sanity check if ((src == null) || (offset < 0) || (len < 0) || ((len + offset) > src.length)) { throw new IllegalArgumentException("Bad arguments"); } updateProviderIfNeeded(); if (len == 0) { return; } spi.engineUpdateAAD(src, offset, len); }
java
public final void updateAAD(byte[] src, int offset, int len) { checkCipherState(); // Input sanity check if ((src == null) || (offset < 0) || (len < 0) || ((len + offset) > src.length)) { throw new IllegalArgumentException("Bad arguments"); } updateProviderIfNeeded(); if (len == 0) { return; } spi.engineUpdateAAD(src, offset, len); }
[ "public", "final", "void", "updateAAD", "(", "byte", "[", "]", "src", ",", "int", "offset", ",", "int", "len", ")", "{", "checkCipherState", "(", ")", ";", "// Input sanity check", "if", "(", "(", "src", "==", "null", ")", "||", "(", "offset", "<", "...
Continues a multi-part update of the Additional Authentication Data (AAD), using a subset of the provided buffer. <p> Calls to this method provide AAD to the cipher when operating in modes such as AEAD (GCM/CCM). If this cipher is operating in either GCM or CCM mode, all AAD must be supplied before beginning operations on the ciphertext (via the {@code update} and {@code doFinal} methods). @param src the buffer containing the AAD @param offset the offset in {@code src} where the AAD input starts @param len the number of AAD bytes @throws IllegalArgumentException if the {@code src} byte array is null, or the {@code offset} or {@code length} is less than 0, or the sum of the {@code offset} and {@code len} is greater than the length of the {@code src} byte array @throws IllegalStateException if this cipher is in a wrong state (e.g., has not been initialized), does not accept AAD, or if operating in either GCM or CCM mode and one of the {@code update} methods has already been called for the active encryption/decryption operation @throws UnsupportedOperationException if the corresponding method in the {@code CipherSpi} has not been overridden by an implementation @since 1.7
[ "Continues", "a", "multi", "-", "part", "update", "of", "the", "Additional", "Authentication", "Data", "(", "AAD", ")", "using", "a", "subset", "of", "the", "provided", "buffer", ".", "<p", ">", "Calls", "to", "this", "method", "provide", "AAD", "to", "t...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Cipher.java#L2604-L2618
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/store/JCRStoreResource.java
JCRStoreResource.getBinary
protected Binary getBinary(final InputStream _in) throws EFapsException { Binary ret = null; try { ret = SerialValueFactory.getInstance().createBinary(_in); } catch (final RepositoryException e) { throw new EFapsException("RepositoryException", e); } return ret; }
java
protected Binary getBinary(final InputStream _in) throws EFapsException { Binary ret = null; try { ret = SerialValueFactory.getInstance().createBinary(_in); } catch (final RepositoryException e) { throw new EFapsException("RepositoryException", e); } return ret; }
[ "protected", "Binary", "getBinary", "(", "final", "InputStream", "_in", ")", "throws", "EFapsException", "{", "Binary", "ret", "=", "null", ";", "try", "{", "ret", "=", "SerialValueFactory", ".", "getInstance", "(", ")", ".", "createBinary", "(", "_in", ")",...
Gets the binary. @param _in the in @return the binary @throws EFapsException on error
[ "Gets", "the", "binary", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/store/JCRStoreResource.java#L308-L318
sdl/Testy
src/main/java/com/sdl/selenium/extjs3/grid/GridPanel.java
GridPanel.isCellPresent
public boolean isCellPresent(String searchElement, int columnId, SearchType... searchTypes) { ready(); GridCell cell = new GridCell(columnId, searchElement, searchTypes).setContainer(this); boolean selected; do { selected = cell.isElementPresent(); } while (!selected && scrollPageDown()); return selected; }
java
public boolean isCellPresent(String searchElement, int columnId, SearchType... searchTypes) { ready(); GridCell cell = new GridCell(columnId, searchElement, searchTypes).setContainer(this); boolean selected; do { selected = cell.isElementPresent(); } while (!selected && scrollPageDown()); return selected; }
[ "public", "boolean", "isCellPresent", "(", "String", "searchElement", ",", "int", "columnId", ",", "SearchType", "...", "searchTypes", ")", "{", "ready", "(", ")", ";", "GridCell", "cell", "=", "new", "GridCell", "(", "columnId", ",", "searchElement", ",", "...
Scroll Page Down to find the cell. If you found it return true, if not return false. @param searchElement searchElement @param columnId columnId @param searchTypes SearchType.EQUALS @return true or false
[ "Scroll", "Page", "Down", "to", "find", "the", "cell", ".", "If", "you", "found", "it", "return", "true", "if", "not", "return", "false", "." ]
train
https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/extjs3/grid/GridPanel.java#L267-L275
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/CommsLightTrace.java
CommsLightTrace.traceMessageIds
public static void traceMessageIds(TraceComponent callersTrace, String action, SIMessageHandle[] messageHandles) { if ((light_tc.isDebugEnabled() || callersTrace.isDebugEnabled()) && messageHandles != null) { // Build our trace string StringBuffer trcBuffer = new StringBuffer(); trcBuffer.append(action + ": ["); for (int i = 0; i < messageHandles.length; i++) { if (i != 0) trcBuffer.append(","); if (messageHandles[i] != null) { trcBuffer.append(messageHandles[i].getSystemMessageId()); } } trcBuffer.append("]"); // Trace using the correct trace group if (light_tc.isDebugEnabled()) { SibTr.debug(light_tc, trcBuffer.toString()); } else { SibTr.debug(callersTrace, trcBuffer.toString()); } } }
java
public static void traceMessageIds(TraceComponent callersTrace, String action, SIMessageHandle[] messageHandles) { if ((light_tc.isDebugEnabled() || callersTrace.isDebugEnabled()) && messageHandles != null) { // Build our trace string StringBuffer trcBuffer = new StringBuffer(); trcBuffer.append(action + ": ["); for (int i = 0; i < messageHandles.length; i++) { if (i != 0) trcBuffer.append(","); if (messageHandles[i] != null) { trcBuffer.append(messageHandles[i].getSystemMessageId()); } } trcBuffer.append("]"); // Trace using the correct trace group if (light_tc.isDebugEnabled()) { SibTr.debug(light_tc, trcBuffer.toString()); } else { SibTr.debug(callersTrace, trcBuffer.toString()); } } }
[ "public", "static", "void", "traceMessageIds", "(", "TraceComponent", "callersTrace", ",", "String", "action", ",", "SIMessageHandle", "[", "]", "messageHandles", ")", "{", "if", "(", "(", "light_tc", ".", "isDebugEnabled", "(", ")", "||", "callersTrace", ".", ...
Allow tracing of messages and transaction when deleting @param callersTrace The trace component of the caller @param action A string (no spaces) provided by the caller to prefix the keyword included in the trace line @param messageHandles The messages handles to trace
[ "Allow", "tracing", "of", "messages", "and", "transaction", "when", "deleting" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/CommsLightTrace.java#L100-L124
guardtime/ksi-java-sdk
ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java
HAConfUtil.isBigger
static boolean isBigger(Long a, Long b) { return a == null || (b != null && b > a); }
java
static boolean isBigger(Long a, Long b) { return a == null || (b != null && b > a); }
[ "static", "boolean", "isBigger", "(", "Long", "a", ",", "Long", "b", ")", "{", "return", "a", "==", "null", "||", "(", "b", "!=", "null", "&&", "b", ">", "a", ")", ";", "}" ]
Is value of b bigger than value of a. @return True, if b is bigger than a. Always true, if value of a is null.
[ "Is", "value", "of", "b", "bigger", "than", "value", "of", "a", "." ]
train
https://github.com/guardtime/ksi-java-sdk/blob/b2cd877050f0f392657c724452318d10a1002171/ksi-service-ha/src/main/java/com/guardtime/ksi/service/ha/HAConfUtil.java#L34-L36
amilcar-sr/JustifiedTextView
library/src/main/java/com/codesgood/views/JustifiedTextView.java
JustifiedTextView.fitsInSentence
private boolean fitsInSentence(String word, List<String> sentence, boolean addSpaces) { String stringSentence = getSentenceFromList(sentence, addSpaces); stringSentence += word; float sentenceWidth = getPaint().measureText(stringSentence); return sentenceWidth < viewWidth; }
java
private boolean fitsInSentence(String word, List<String> sentence, boolean addSpaces) { String stringSentence = getSentenceFromList(sentence, addSpaces); stringSentence += word; float sentenceWidth = getPaint().measureText(stringSentence); return sentenceWidth < viewWidth; }
[ "private", "boolean", "fitsInSentence", "(", "String", "word", ",", "List", "<", "String", ">", "sentence", ",", "boolean", "addSpaces", ")", "{", "String", "stringSentence", "=", "getSentenceFromList", "(", "sentence", ",", "addSpaces", ")", ";", "stringSentenc...
Verifies if word to be added will fit into the sentence @param word Word to be added @param sentence Sentence that will receive the new word @param addSpaces Specifies weather we should add spaces to validation or not @return True if word fits, false otherwise.
[ "Verifies", "if", "word", "to", "be", "added", "will", "fit", "into", "the", "sentence" ]
train
https://github.com/amilcar-sr/JustifiedTextView/blob/8fd91b4cfb225f973096519eae8295c3d7e8d49f/library/src/main/java/com/codesgood/views/JustifiedTextView.java#L224-L231
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java
ExtensionRegistry.getExtensionContext
public ExtensionContext getExtensionContext(final String moduleName, ManagementResourceRegistration rootRegistration, ExtensionRegistryType extensionRegistryType) { // Can't use processType.isServer() to determine where to look for profile reg because a lot of test infrastructure // doesn't add the profile mrr even in HC-based tests ManagementResourceRegistration profileRegistration = rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(PROFILE))); if (profileRegistration == null) { profileRegistration = rootRegistration; } ManagementResourceRegistration deploymentsRegistration = processType.isServer() ? rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT))) : null; // Hack to restrict extra data to specified extension(s) boolean allowSupplement = legallySupplemented.contains(moduleName); ManagedAuditLogger al = allowSupplement ? auditLogger : null; return new ExtensionContextImpl(moduleName, profileRegistration, deploymentsRegistration, pathManager, extensionRegistryType, al); }
java
public ExtensionContext getExtensionContext(final String moduleName, ManagementResourceRegistration rootRegistration, ExtensionRegistryType extensionRegistryType) { // Can't use processType.isServer() to determine where to look for profile reg because a lot of test infrastructure // doesn't add the profile mrr even in HC-based tests ManagementResourceRegistration profileRegistration = rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(PROFILE))); if (profileRegistration == null) { profileRegistration = rootRegistration; } ManagementResourceRegistration deploymentsRegistration = processType.isServer() ? rootRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT))) : null; // Hack to restrict extra data to specified extension(s) boolean allowSupplement = legallySupplemented.contains(moduleName); ManagedAuditLogger al = allowSupplement ? auditLogger : null; return new ExtensionContextImpl(moduleName, profileRegistration, deploymentsRegistration, pathManager, extensionRegistryType, al); }
[ "public", "ExtensionContext", "getExtensionContext", "(", "final", "String", "moduleName", ",", "ManagementResourceRegistration", "rootRegistration", ",", "ExtensionRegistryType", "extensionRegistryType", ")", "{", "// Can't use processType.isServer() to determine where to look for pro...
Gets an {@link ExtensionContext} for use when handling an {@code add} operation for a resource representing an {@link org.jboss.as.controller.Extension}. @param moduleName the name of the extension's module. Cannot be {@code null} @param rootRegistration the root management resource registration @param extensionRegistryType the type of registry we are working on, which has an effect on things like whether extensions get registered etc. @return the {@link ExtensionContext}. Will not return {@code null}
[ "Gets", "an", "{", "@link", "ExtensionContext", "}", "for", "use", "when", "handling", "an", "{", "@code", "add", "}", "operation", "for", "a", "resource", "representing", "an", "{", "@link", "org", ".", "jboss", ".", "as", ".", "controller", ".", "Exten...
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java#L280-L293
microfocus-idol/java-content-parameter-api
src/main/java/com/hp/autonomy/aci/content/fieldtext/FieldTextBuilder.java
FieldTextBuilder.binaryOp
private FieldTextBuilder binaryOp(final String operator, final FieldTextBuilder fieldText) { // Special case when we're empty if(componentCount == 0) { // Just copy the argument fieldTextString.append(fieldText.fieldTextString); lastOperator = fieldText.lastOperator; not = fieldText.not; componentCount = fieldText.componentCount; } else { // Add the NOTs, parentheses and operator addOperator(operator); if(fieldText.lastOperator == null || fieldText.lastOperator.equals(operator) || fieldText.not) { fieldTextString.append(fieldText.toString()); } else { fieldTextString.append('(').append(fieldText.toString()).append(')'); } componentCount += fieldText.size(); not = false; } return this; }
java
private FieldTextBuilder binaryOp(final String operator, final FieldTextBuilder fieldText) { // Special case when we're empty if(componentCount == 0) { // Just copy the argument fieldTextString.append(fieldText.fieldTextString); lastOperator = fieldText.lastOperator; not = fieldText.not; componentCount = fieldText.componentCount; } else { // Add the NOTs, parentheses and operator addOperator(operator); if(fieldText.lastOperator == null || fieldText.lastOperator.equals(operator) || fieldText.not) { fieldTextString.append(fieldText.toString()); } else { fieldTextString.append('(').append(fieldText.toString()).append(')'); } componentCount += fieldText.size(); not = false; } return this; }
[ "private", "FieldTextBuilder", "binaryOp", "(", "final", "String", "operator", ",", "final", "FieldTextBuilder", "fieldText", ")", "{", "// Special case when we're empty", "if", "(", "componentCount", "==", "0", ")", "{", "// Just copy the argument", "fieldTextString", ...
Does the work for the OR, AND and XOR methods in the optimized case where fieldText is a FieldTextBuilder. @param operator @param fieldText @return
[ "Does", "the", "work", "for", "the", "OR", "AND", "and", "XOR", "methods", "in", "the", "optimized", "case", "where", "fieldText", "is", "a", "FieldTextBuilder", "." ]
train
https://github.com/microfocus-idol/java-content-parameter-api/blob/8d33dc633f8df2a470a571ac7694e423e7004ad0/src/main/java/com/hp/autonomy/aci/content/fieldtext/FieldTextBuilder.java#L340-L363
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/IntegralImageOps.java
IntegralImageOps.convolveSparse
public static double convolveSparse(GrayF64 integral , IntegralKernel kernel , int x , int y ) { return ImplIntegralImageOps.convolveSparse(integral,kernel,x,y); }
java
public static double convolveSparse(GrayF64 integral , IntegralKernel kernel , int x , int y ) { return ImplIntegralImageOps.convolveSparse(integral,kernel,x,y); }
[ "public", "static", "double", "convolveSparse", "(", "GrayF64", "integral", ",", "IntegralKernel", "kernel", ",", "int", "x", ",", "int", "y", ")", "{", "return", "ImplIntegralImageOps", ".", "convolveSparse", "(", "integral", ",", "kernel", ",", "x", ",", "...
Convolves a kernel around a single point in the integral image. @param integral Input integral image. Not modified. @param kernel Convolution kernel. @param x Pixel the convolution is performed at. @param y Pixel the convolution is performed at. @return Value of the convolution
[ "Convolves", "a", "kernel", "around", "a", "single", "point", "in", "the", "integral", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/IntegralImageOps.java#L326-L329
opengeospatial/teamengine
teamengine-web/src/main/java/com/occamlab/te/web/XMLUtils.java
XMLUtils.getFirstNode
public static Node getFirstNode(Document doc, String xPathExpression) { try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr; expr = xpath.compile(xPathExpression); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); return nl.item(0); } catch (XPathExpressionException e) { e.printStackTrace(); } return null; }
java
public static Node getFirstNode(Document doc, String xPathExpression) { try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr; expr = xpath.compile(xPathExpression); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); return nl.item(0); } catch (XPathExpressionException e) { e.printStackTrace(); } return null; }
[ "public", "static", "Node", "getFirstNode", "(", "Document", "doc", ",", "String", "xPathExpression", ")", "{", "try", "{", "XPathFactory", "xPathfactory", "=", "XPathFactory", ".", "newInstance", "(", ")", ";", "XPath", "xpath", "=", "xPathfactory", ".", "new...
Get first node on a Document doc, give a xpath Expression @param doc @param xPathExpression @return a Node or null if not found
[ "Get", "first", "node", "on", "a", "Document", "doc", "give", "a", "xpath", "Expression" ]
train
https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/XMLUtils.java#L29-L44
sculptor/sculptor
sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaHelper.java
JpaHelper.getValue
public static Object getValue(Object instance, String name) { assert instance != null; assert name != null; try { Class<?> clazz = instance.getClass(); Object value = null; Method property = findProperty(clazz, name); if (property != null) { value = property.invoke(instance); } else { Field field = findField(clazz, name); if (field != null) { value = field.get(instance); } } log.debug("Value for field/property '{}' is: '{}'", name, value); return value; } catch (Exception e) { log.error("Could not get a value for field/property '" + name + "'", e); return null; } }
java
public static Object getValue(Object instance, String name) { assert instance != null; assert name != null; try { Class<?> clazz = instance.getClass(); Object value = null; Method property = findProperty(clazz, name); if (property != null) { value = property.invoke(instance); } else { Field field = findField(clazz, name); if (field != null) { value = field.get(instance); } } log.debug("Value for field/property '{}' is: '{}'", name, value); return value; } catch (Exception e) { log.error("Could not get a value for field/property '" + name + "'", e); return null; } }
[ "public", "static", "Object", "getValue", "(", "Object", "instance", ",", "String", "name", ")", "{", "assert", "instance", "!=", "null", ";", "assert", "name", "!=", "null", ";", "try", "{", "Class", "<", "?", ">", "clazz", "=", "instance", ".", "getC...
tries to get the value from a field or a getter property for a given object instance @param instance the object instance @param name name of the property or field @return @throws IllegalArgumentException @throws IllegalAccessException @throws InvocationTargetException
[ "tries", "to", "get", "the", "value", "from", "a", "field", "or", "a", "getter", "property", "for", "a", "given", "object", "instance" ]
train
https://github.com/sculptor/sculptor/blob/38df06ceb7e40f5f52dbd53b1cd1d07ee11aade5/sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaHelper.java#L162-L185
percolate/caffeine
caffeine/src/main/java/com/percolate/caffeine/IntentUtils.java
IntentUtils.launchWebBrowserOnClick
public static OnClickListener launchWebBrowserOnClick(final Context context, final String url){ return new OnClickListener() { @Override public void onClick(View v) { launchWebBrowser(context, url); } }; }
java
public static OnClickListener launchWebBrowserOnClick(final Context context, final String url){ return new OnClickListener() { @Override public void onClick(View v) { launchWebBrowser(context, url); } }; }
[ "public", "static", "OnClickListener", "launchWebBrowserOnClick", "(", "final", "Context", "context", ",", "final", "String", "url", ")", "{", "return", "new", "OnClickListener", "(", ")", "{", "@", "Override", "public", "void", "onClick", "(", "View", "v", ")...
Return an OnClickListener that will open a web browser for the given <code>url</code>.
[ "Return", "an", "OnClickListener", "that", "will", "open", "a", "web", "browser", "for", "the", "given", "<code", ">", "url<", "/", "code", ">", "." ]
train
https://github.com/percolate/caffeine/blob/e2265cab474a6397f4d75b1ed928c356a7b9672e/caffeine/src/main/java/com/percolate/caffeine/IntentUtils.java#L25-L32
citrusframework/citrus
modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/ZooActionBuilder.java
ZooActionBuilder.validate
public ZooActionBuilder validate(String jsonPath, String expectedValue) { JsonPathMessageValidationContext validationContext = action.getJsonPathMessageValidationContext(); if (validationContext == null) { validationContext = new JsonPathMessageValidationContext(); action.setJsonPathMessageValidationContext(validationContext); } validationContext.getJsonPathExpressions().put(jsonPath, expectedValue); return this; }
java
public ZooActionBuilder validate(String jsonPath, String expectedValue) { JsonPathMessageValidationContext validationContext = action.getJsonPathMessageValidationContext(); if (validationContext == null) { validationContext = new JsonPathMessageValidationContext(); action.setJsonPathMessageValidationContext(validationContext); } validationContext.getJsonPathExpressions().put(jsonPath, expectedValue); return this; }
[ "public", "ZooActionBuilder", "validate", "(", "String", "jsonPath", ",", "String", "expectedValue", ")", "{", "JsonPathMessageValidationContext", "validationContext", "=", "action", ".", "getJsonPathMessageValidationContext", "(", ")", ";", "if", "(", "validationContext"...
Adds variable extractor for extracting variable from command response. @param jsonPath the json path to reference the value to be extracted @param expectedValue the expected value (or variable to retrieve the expected value from) @return
[ "Adds", "variable", "extractor", "for", "extracting", "variable", "from", "command", "response", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/ZooActionBuilder.java#L176-L184
liferay/com-liferay-commerce
commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java
CPSpecificationOptionWrapper.setDescription
@Override public void setDescription(String description, java.util.Locale locale) { _cpSpecificationOption.setDescription(description, locale); }
java
@Override public void setDescription(String description, java.util.Locale locale) { _cpSpecificationOption.setDescription(description, locale); }
[ "@", "Override", "public", "void", "setDescription", "(", "String", "description", ",", "java", ".", "util", ".", "Locale", "locale", ")", "{", "_cpSpecificationOption", ".", "setDescription", "(", "description", ",", "locale", ")", ";", "}" ]
Sets the localized description of this cp specification option in the language. @param description the localized description of this cp specification option @param locale the locale of the language
[ "Sets", "the", "localized", "description", "of", "this", "cp", "specification", "option", "in", "the", "language", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-api/src/main/java/com/liferay/commerce/product/model/CPSpecificationOptionWrapper.java#L607-L610
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/disk/HadoopStoreWriter.java
HadoopStoreWriter.initFileStreams
@NotThreadsafe private void initFileStreams(int chunkId) { /** * {@link Set#add(Object)} returns false if the element already existed in the set. * This ensures we initialize the resources for each chunk only once. */ if (chunksHandled.add(chunkId)) { try { this.indexFileSizeInBytes[chunkId] = 0L; this.valueFileSizeInBytes[chunkId] = 0L; this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType); this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType); this.position[chunkId] = 0; this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + INDEX_FILE_EXTENSION + fileExtension); this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + DATA_FILE_EXTENSION + fileExtension); if(this.fs == null) this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf); if(isValidCompressionEnabled) { this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]), DEFAULT_BUFFER_SIZE))); this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]), DEFAULT_BUFFER_SIZE))); } else { this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]); this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]); } fs.setPermission(this.taskIndexFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskIndexFileName[chunkId]); fs.setPermission(this.taskValueFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskValueFileName[chunkId]); logger.info("Opening " + this.taskIndexFileName[chunkId] + " and " + this.taskValueFileName[chunkId] + " for writing."); } catch(IOException e) { throw new RuntimeException("Failed to open Input/OutputStream", e); } } }
java
@NotThreadsafe private void initFileStreams(int chunkId) { /** * {@link Set#add(Object)} returns false if the element already existed in the set. * This ensures we initialize the resources for each chunk only once. */ if (chunksHandled.add(chunkId)) { try { this.indexFileSizeInBytes[chunkId] = 0L; this.valueFileSizeInBytes[chunkId] = 0L; this.checkSumDigestIndex[chunkId] = CheckSum.getInstance(checkSumType); this.checkSumDigestValue[chunkId] = CheckSum.getInstance(checkSumType); this.position[chunkId] = 0; this.taskIndexFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + INDEX_FILE_EXTENSION + fileExtension); this.taskValueFileName[chunkId] = new Path(FileOutputFormat.getOutputPath(conf), getStoreName() + "." + Integer.toString(chunkId) + "_" + this.taskId + DATA_FILE_EXTENSION + fileExtension); if(this.fs == null) this.fs = this.taskIndexFileName[chunkId].getFileSystem(conf); if(isValidCompressionEnabled) { this.indexFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskIndexFileName[chunkId]), DEFAULT_BUFFER_SIZE))); this.valueFileStream[chunkId] = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(fs.create(this.taskValueFileName[chunkId]), DEFAULT_BUFFER_SIZE))); } else { this.indexFileStream[chunkId] = fs.create(this.taskIndexFileName[chunkId]); this.valueFileStream[chunkId] = fs.create(this.taskValueFileName[chunkId]); } fs.setPermission(this.taskIndexFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskIndexFileName[chunkId]); fs.setPermission(this.taskValueFileName[chunkId], new FsPermission(HadoopStoreBuilder.HADOOP_FILE_PERMISSION)); logger.info("Setting permission to 755 for " + this.taskValueFileName[chunkId]); logger.info("Opening " + this.taskIndexFileName[chunkId] + " and " + this.taskValueFileName[chunkId] + " for writing."); } catch(IOException e) { throw new RuntimeException("Failed to open Input/OutputStream", e); } } }
[ "@", "NotThreadsafe", "private", "void", "initFileStreams", "(", "int", "chunkId", ")", "{", "/**\n * {@link Set#add(Object)} returns false if the element already existed in the set.\n * This ensures we initialize the resources for each chunk only once.\n */", "if", "...
The MapReduce framework should operate sequentially, so thread safety shouldn't be a problem.
[ "The", "MapReduce", "framework", "should", "operate", "sequentially", "so", "thread", "safety", "shouldn", "t", "be", "a", "problem", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/disk/HadoopStoreWriter.java#L155-L204
aws/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StepExecution.java
StepExecution.setOutputs
public void setOutputs(java.util.Map<String, java.util.List<String>> outputs) { this.outputs = outputs; }
java
public void setOutputs(java.util.Map<String, java.util.List<String>> outputs) { this.outputs = outputs; }
[ "public", "void", "setOutputs", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "java", ".", "util", ".", "List", "<", "String", ">", ">", "outputs", ")", "{", "this", ".", "outputs", "=", "outputs", ";", "}" ]
<p> Returned values from the execution of the step. </p> @param outputs Returned values from the execution of the step.
[ "<p", ">", "Returned", "values", "from", "the", "execution", "of", "the", "step", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StepExecution.java#L666-L668
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/LineStringSerializer.java
LineStringSerializer.writeShapeSpecificSerialization
@Override public void writeShapeSpecificSerialization(LineString value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeFieldName("type"); jgen.writeString("LineString"); jgen.writeArrayFieldStart("coordinates"); // set beanproperty to null since we are not serializing a real property JsonSerializer<Object> ser = provider.findValueSerializer(Double.class, null); for (int j = 0; j < value.getNumPoints(); j++) { Point coordinate = value.getPointN(j); jgen.writeStartArray(); ser.serialize(coordinate.getX(), jgen, provider); ser.serialize(coordinate.getY(), jgen, provider); jgen.writeEndArray(); } jgen.writeEndArray(); }
java
@Override public void writeShapeSpecificSerialization(LineString value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeFieldName("type"); jgen.writeString("LineString"); jgen.writeArrayFieldStart("coordinates"); // set beanproperty to null since we are not serializing a real property JsonSerializer<Object> ser = provider.findValueSerializer(Double.class, null); for (int j = 0; j < value.getNumPoints(); j++) { Point coordinate = value.getPointN(j); jgen.writeStartArray(); ser.serialize(coordinate.getX(), jgen, provider); ser.serialize(coordinate.getY(), jgen, provider); jgen.writeEndArray(); } jgen.writeEndArray(); }
[ "@", "Override", "public", "void", "writeShapeSpecificSerialization", "(", "LineString", "value", ",", "JsonGenerator", "jgen", ",", "SerializerProvider", "provider", ")", "throws", "IOException", "{", "jgen", ".", "writeFieldName", "(", "\"type\"", ")", ";", "jgen"...
Method that can be called to ask implementation to serialize values of type this serializer handles. @param value Value to serialize; can not be null. @param jgen Generator used to output resulting Json content @param provider Provider that can be used to get serializers for serializing Objects value contains, if any. @throws java.io.IOException If serialization failed.
[ "Method", "that", "can", "be", "called", "to", "ask", "implementation", "to", "serialize", "values", "of", "type", "this", "serializer", "handles", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/LineStringSerializer.java#L60-L76
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/util/mem/Memory.java
Memory.getBytes
public void getBytes(long memoryOffset, byte[] buffer, int bufferOffset, int count) { if (buffer == null) throw new NullPointerException(); else if (bufferOffset < 0 || count < 0 || count > buffer.length - bufferOffset) throw new IndexOutOfBoundsException(); else if (count == 0) return; checkPosition(memoryOffset); long end = memoryOffset + count; checkPosition(end - 1); while (memoryOffset < end) { buffer[bufferOffset++] = unsafe.getByte(peer + memoryOffset); memoryOffset++; } }
java
public void getBytes(long memoryOffset, byte[] buffer, int bufferOffset, int count) { if (buffer == null) throw new NullPointerException(); else if (bufferOffset < 0 || count < 0 || count > buffer.length - bufferOffset) throw new IndexOutOfBoundsException(); else if (count == 0) return; checkPosition(memoryOffset); long end = memoryOffset + count; checkPosition(end - 1); while (memoryOffset < end) { buffer[bufferOffset++] = unsafe.getByte(peer + memoryOffset); memoryOffset++; } }
[ "public", "void", "getBytes", "(", "long", "memoryOffset", ",", "byte", "[", "]", "buffer", ",", "int", "bufferOffset", ",", "int", "count", ")", "{", "if", "(", "buffer", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "else", ...
Transfers count bytes from Memory starting at memoryOffset to buffer starting at bufferOffset @param memoryOffset start offset in the memory @param buffer the data buffer @param bufferOffset start offset of the buffer @param count number of bytes to transfer
[ "Transfers", "count", "bytes", "from", "Memory", "starting", "at", "memoryOffset", "to", "buffer", "starting", "at", "bufferOffset" ]
train
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/util/mem/Memory.java#L187-L204
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/cloud/storage/AzureObjectMetadata.java
AzureObjectMetadata.addUserMetadata
@Override public void addUserMetadata(String key, String value) { userDefinedMetadata.put(key, value); }
java
@Override public void addUserMetadata(String key, String value) { userDefinedMetadata.put(key, value); }
[ "@", "Override", "public", "void", "addUserMetadata", "(", "String", "key", ",", "String", "value", ")", "{", "userDefinedMetadata", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
Adds the key value pair of custom user-metadata for the associated object.
[ "Adds", "the", "key", "value", "pair", "of", "custom", "user", "-", "metadata", "for", "the", "associated", "object", "." ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/AzureObjectMetadata.java#L71-L75
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/FieldReSelectHandler.java
FieldReSelectHandler.fieldChanged
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { if (m_gridScreen != null) m_gridScreen.reSelectRecords(); if (m_sPopupBox != null) m_sPopupBox.reSelectRecords(); return DBConstants.NORMAL_RETURN; }
java
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { if (m_gridScreen != null) m_gridScreen.reSelectRecords(); if (m_sPopupBox != null) m_sPopupBox.reSelectRecords(); return DBConstants.NORMAL_RETURN; }
[ "public", "int", "fieldChanged", "(", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "if", "(", "m_gridScreen", "!=", "null", ")", "m_gridScreen", ".", "reSelectRecords", "(", ")", ";", "if", "(", "m_sPopupBox", "!=", "null", ")", "m_sPopupB...
The Field has Changed. Reselect the grid screen. @param bDisplayOption If true, display the change. @param iMoveMode The type of move being done (init/read/screen). @return The error code (or NORMAL_RETURN if okay). Reselect the records.
[ "The", "Field", "has", "Changed", ".", "Reselect", "the", "grid", "screen", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/FieldReSelectHandler.java#L103-L110
samskivert/samskivert
src/main/java/com/samskivert/swing/util/SwingUtil.java
SwingUtil.positionRect
public static boolean positionRect ( Rectangle r, Rectangle bounds, Collection<? extends Shape> avoidShapes) { Point origPos = r.getLocation(); Comparator<Point> comp = createPointComparator(origPos); SortableArrayList<Point> possibles = new SortableArrayList<Point>(); // start things off with the passed-in point (adjusted to be inside the bounds, if needed) possibles.add(fitRectInRect(r, bounds)); // keep track of area that doesn't generate new possibles Area dead = new Area(); CHECKPOSSIBLES: while (!possibles.isEmpty()) { r.setLocation(possibles.remove(0)); // make sure the rectangle is in the view and not over a dead area if ((!bounds.contains(r)) || dead.intersects(r)) { continue; } // see if it hits any shapes we're trying to avoid for (Iterator<? extends Shape> iter = avoidShapes.iterator(); iter.hasNext(); ) { Shape shape = iter.next(); if (shape.intersects(r)) { // remove that shape from our avoid list iter.remove(); // but add it to our dead area dead.add(new Area(shape)); // add 4 new possible points, each pushed in one direction Rectangle pusher = shape.getBounds(); possibles.add(new Point(pusher.x - r.width, r.y)); possibles.add(new Point(r.x, pusher.y - r.height)); possibles.add(new Point(pusher.x + pusher.width, r.y)); possibles.add(new Point(r.x, pusher.y + pusher.height)); // re-sort the list possibles.sort(comp); continue CHECKPOSSIBLES; } } // hey! if we got here, then it worked! return true; } // we never found a match, move the rectangle back r.setLocation(origPos); return false; }
java
public static boolean positionRect ( Rectangle r, Rectangle bounds, Collection<? extends Shape> avoidShapes) { Point origPos = r.getLocation(); Comparator<Point> comp = createPointComparator(origPos); SortableArrayList<Point> possibles = new SortableArrayList<Point>(); // start things off with the passed-in point (adjusted to be inside the bounds, if needed) possibles.add(fitRectInRect(r, bounds)); // keep track of area that doesn't generate new possibles Area dead = new Area(); CHECKPOSSIBLES: while (!possibles.isEmpty()) { r.setLocation(possibles.remove(0)); // make sure the rectangle is in the view and not over a dead area if ((!bounds.contains(r)) || dead.intersects(r)) { continue; } // see if it hits any shapes we're trying to avoid for (Iterator<? extends Shape> iter = avoidShapes.iterator(); iter.hasNext(); ) { Shape shape = iter.next(); if (shape.intersects(r)) { // remove that shape from our avoid list iter.remove(); // but add it to our dead area dead.add(new Area(shape)); // add 4 new possible points, each pushed in one direction Rectangle pusher = shape.getBounds(); possibles.add(new Point(pusher.x - r.width, r.y)); possibles.add(new Point(r.x, pusher.y - r.height)); possibles.add(new Point(pusher.x + pusher.width, r.y)); possibles.add(new Point(r.x, pusher.y + pusher.height)); // re-sort the list possibles.sort(comp); continue CHECKPOSSIBLES; } } // hey! if we got here, then it worked! return true; } // we never found a match, move the rectangle back r.setLocation(origPos); return false; }
[ "public", "static", "boolean", "positionRect", "(", "Rectangle", "r", ",", "Rectangle", "bounds", ",", "Collection", "<", "?", "extends", "Shape", ">", "avoidShapes", ")", "{", "Point", "origPos", "=", "r", ".", "getLocation", "(", ")", ";", "Comparator", ...
Position the specified rectangle as closely as possible to its current position, but make sure it is within the specified bounds and that it does not overlap any of the Shapes contained in the avoid list. @param r the rectangle to attempt to position. @param bounds the bounding box within which the rectangle must be positioned. @param avoidShapes a collection of Shapes that must not be overlapped. The collection will be destructively modified. @return true if the rectangle was successfully placed, given the constraints, or false if the positioning failed (the rectangle will be left at it's original location.
[ "Position", "the", "specified", "rectangle", "as", "closely", "as", "possible", "to", "its", "current", "position", "but", "make", "sure", "it", "is", "within", "the", "specified", "bounds", "and", "that", "it", "does", "not", "overlap", "any", "of", "the", ...
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/util/SwingUtil.java#L172-L222
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.backupCertificateAsync
public Observable<BackupCertificateResult> backupCertificateAsync(String vaultBaseUrl, String certificateName) { return backupCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<BackupCertificateResult>, BackupCertificateResult>() { @Override public BackupCertificateResult call(ServiceResponse<BackupCertificateResult> response) { return response.body(); } }); }
java
public Observable<BackupCertificateResult> backupCertificateAsync(String vaultBaseUrl, String certificateName) { return backupCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<BackupCertificateResult>, BackupCertificateResult>() { @Override public BackupCertificateResult call(ServiceResponse<BackupCertificateResult> response) { return response.body(); } }); }
[ "public", "Observable", "<", "BackupCertificateResult", ">", "backupCertificateAsync", "(", "String", "vaultBaseUrl", ",", "String", "certificateName", ")", "{", "return", "backupCertificateWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "certificateName", ")", ".", ...
Backs up the specified certificate. Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate will be downloaded. This operation requires the certificates/backup permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param certificateName The name of the certificate. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BackupCertificateResult object
[ "Backs", "up", "the", "specified", "certificate", ".", "Requests", "that", "a", "backup", "of", "the", "specified", "certificate", "be", "downloaded", "to", "the", "client", ".", "All", "versions", "of", "the", "certificate", "will", "be", "downloaded", ".", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L8142-L8149
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/FileListUtils.java
FileListUtils.listMostNestedPathRecursively
public static List<FileStatus> listMostNestedPathRecursively(FileSystem fs, Path path) throws IOException { return listMostNestedPathRecursively(fs, path, NO_OP_PATH_FILTER); }
java
public static List<FileStatus> listMostNestedPathRecursively(FileSystem fs, Path path) throws IOException { return listMostNestedPathRecursively(fs, path, NO_OP_PATH_FILTER); }
[ "public", "static", "List", "<", "FileStatus", ">", "listMostNestedPathRecursively", "(", "FileSystem", "fs", ",", "Path", "path", ")", "throws", "IOException", "{", "return", "listMostNestedPathRecursively", "(", "fs", ",", "path", ",", "NO_OP_PATH_FILTER", ")", ...
Method to list out all files, or directory if no file exists, under a specified path.
[ "Method", "to", "list", "out", "all", "files", "or", "directory", "if", "no", "file", "exists", "under", "a", "specified", "path", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/FileListUtils.java#L166-L169
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java
MetadataFinder.updateMetadata
private void updateMetadata(CdjStatus update, TrackMetadata data) { hotCache.put(DeckReference.getDeckReference(update.getDeviceNumber(), 0), data); // Main deck if (data.getCueList() != null) { // Update the cache with any hot cues in this track as well for (CueList.Entry entry : data.getCueList().entries) { if (entry.hotCueNumber != 0) { hotCache.put(DeckReference.getDeckReference(update.getDeviceNumber(), entry.hotCueNumber), data); } } } deliverTrackMetadataUpdate(update.getDeviceNumber(), data); }
java
private void updateMetadata(CdjStatus update, TrackMetadata data) { hotCache.put(DeckReference.getDeckReference(update.getDeviceNumber(), 0), data); // Main deck if (data.getCueList() != null) { // Update the cache with any hot cues in this track as well for (CueList.Entry entry : data.getCueList().entries) { if (entry.hotCueNumber != 0) { hotCache.put(DeckReference.getDeckReference(update.getDeviceNumber(), entry.hotCueNumber), data); } } } deliverTrackMetadataUpdate(update.getDeviceNumber(), data); }
[ "private", "void", "updateMetadata", "(", "CdjStatus", "update", ",", "TrackMetadata", "data", ")", "{", "hotCache", ".", "put", "(", "DeckReference", ".", "getDeckReference", "(", "update", ".", "getDeviceNumber", "(", ")", ",", "0", ")", ",", "data", ")", ...
We have obtained metadata for a device, so store it and alert any listeners. @param update the update which caused us to retrieve this metadata @param data the metadata which we received
[ "We", "have", "obtained", "metadata", "for", "a", "device", "so", "store", "it", "and", "alert", "any", "listeners", "." ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java#L462-L472
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/File.java
File.setWritable
public boolean setWritable(boolean writable, boolean ownerOnly) { return doChmod(ownerOnly ? S_IWUSR : (S_IWUSR | S_IWGRP | S_IWOTH), writable); }
java
public boolean setWritable(boolean writable, boolean ownerOnly) { return doChmod(ownerOnly ? S_IWUSR : (S_IWUSR | S_IWGRP | S_IWOTH), writable); }
[ "public", "boolean", "setWritable", "(", "boolean", "writable", ",", "boolean", "ownerOnly", ")", "{", "return", "doChmod", "(", "ownerOnly", "?", "S_IWUSR", ":", "(", "S_IWUSR", "|", "S_IWGRP", "|", "S_IWOTH", ")", ",", "writable", ")", ";", "}" ]
Manipulates the write permissions for the abstract path designated by this file. @param writable To allow write permission if true, otherwise disallow @param ownerOnly To manipulate write permission only for owner if true, otherwise for everyone. The manipulation will apply to everyone regardless of this value if the underlying system does not distinguish owner and other users. @return true if and only if the operation succeeded. If the user does not have permission to change the access permissions of this abstract pathname the operation will fail. @since 1.6
[ "Manipulates", "the", "write", "permissions", "for", "the", "abstract", "path", "designated", "by", "this", "file", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/File.java#L755-L757
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/storage/types/DigitalObjectUtil.java
DigitalObjectUtil.updateLegacyDatastreams
@SuppressWarnings("deprecation") public static void updateLegacyDatastreams(DigitalObject obj) { final String xml = "text/xml"; final String rdf = "application/rdf+xml"; updateLegacyDatastream(obj, "DC", xml, OAI_DC2_0.uri); updateLegacyDatastream(obj, "RELS-EXT", rdf, RELS_EXT1_0.uri); updateLegacyDatastream(obj, "RELS-INT", rdf, RELS_INT1_0.uri); updateLegacyDatastream(obj, "POLICY", xml, XACML_POLICY1_0.uri); String fType = obj.getExtProperty(RDF.TYPE.uri); if (MODEL.BDEF_OBJECT.looselyMatches(fType, false)) { updateLegacyDatastream(obj, "METHODMAP", xml, SDEF_METHOD_MAP1_0.uri); } else if (MODEL.BMECH_OBJECT.looselyMatches(fType, false)) { updateLegacyDatastream(obj, "METHODMAP", xml, SDEP_METHOD_MAP1_1.uri); updateLegacyDatastream(obj, "DSINPUTSPEC", xml, DS_INPUT_SPEC1_1.uri); updateLegacyDatastream(obj, "WSDL", xml, WSDL.uri); } }
java
@SuppressWarnings("deprecation") public static void updateLegacyDatastreams(DigitalObject obj) { final String xml = "text/xml"; final String rdf = "application/rdf+xml"; updateLegacyDatastream(obj, "DC", xml, OAI_DC2_0.uri); updateLegacyDatastream(obj, "RELS-EXT", rdf, RELS_EXT1_0.uri); updateLegacyDatastream(obj, "RELS-INT", rdf, RELS_INT1_0.uri); updateLegacyDatastream(obj, "POLICY", xml, XACML_POLICY1_0.uri); String fType = obj.getExtProperty(RDF.TYPE.uri); if (MODEL.BDEF_OBJECT.looselyMatches(fType, false)) { updateLegacyDatastream(obj, "METHODMAP", xml, SDEF_METHOD_MAP1_0.uri); } else if (MODEL.BMECH_OBJECT.looselyMatches(fType, false)) { updateLegacyDatastream(obj, "METHODMAP", xml, SDEP_METHOD_MAP1_1.uri); updateLegacyDatastream(obj, "DSINPUTSPEC", xml, DS_INPUT_SPEC1_1.uri); updateLegacyDatastream(obj, "WSDL", xml, WSDL.uri); } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "static", "void", "updateLegacyDatastreams", "(", "DigitalObject", "obj", ")", "{", "final", "String", "xml", "=", "\"text/xml\"", ";", "final", "String", "rdf", "=", "\"application/rdf+xml\"", ";", "...
Upgrades a legacy (pre-Fedora-3.0) object by setting the correct MIME type and Format URI for all "reserved" datastreams. @param obj the object to update.
[ "Upgrades", "a", "legacy", "(", "pre", "-", "Fedora", "-", "3", ".", "0", ")", "object", "by", "setting", "the", "correct", "MIME", "type", "and", "Format", "URI", "for", "all", "reserved", "datastreams", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/storage/types/DigitalObjectUtil.java#L23-L51
apache/flink
flink-connectors/flink-orc/src/main/java/org/apache/flink/orc/OrcBatchReader.java
OrcBatchReader.fillColumnWithRepeatingValue
private static void fillColumnWithRepeatingValue(Object[] vals, int fieldIdx, Object repeatingValue, int childCount) { if (fieldIdx == -1) { // set value as an object Arrays.fill(vals, 0, childCount, repeatingValue); } else { // set value as a field of Row Row[] rows = (Row[]) vals; for (int i = 0; i < childCount; i++) { rows[i].setField(fieldIdx, repeatingValue); } } }
java
private static void fillColumnWithRepeatingValue(Object[] vals, int fieldIdx, Object repeatingValue, int childCount) { if (fieldIdx == -1) { // set value as an object Arrays.fill(vals, 0, childCount, repeatingValue); } else { // set value as a field of Row Row[] rows = (Row[]) vals; for (int i = 0; i < childCount; i++) { rows[i].setField(fieldIdx, repeatingValue); } } }
[ "private", "static", "void", "fillColumnWithRepeatingValue", "(", "Object", "[", "]", "vals", ",", "int", "fieldIdx", ",", "Object", "repeatingValue", ",", "int", "childCount", ")", "{", "if", "(", "fieldIdx", "==", "-", "1", ")", "{", "// set value as an obje...
Sets a repeating value to all objects or row fields of the passed vals array. @param vals The array of objects or Rows. @param fieldIdx If the objs array is an array of Row, the index of the field that needs to be filled. Otherwise a -1 must be passed and the data is directly filled into the array. @param repeatingValue The value that is set. @param childCount The number of times the value is set.
[ "Sets", "a", "repeating", "value", "to", "all", "objects", "or", "row", "fields", "of", "the", "passed", "vals", "array", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-orc/src/main/java/org/apache/flink/orc/OrcBatchReader.java#L1122-L1134
jeremylong/DependencyCheck
utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java
Settings.getFloat
public float getFloat(@NotNull final String key, float defaultValue) { float retValue = defaultValue; try { retValue = Float.parseFloat(getString(key)); } catch (Throwable ignore) { LOGGER.trace("ignore", ignore); } return retValue; }
java
public float getFloat(@NotNull final String key, float defaultValue) { float retValue = defaultValue; try { retValue = Float.parseFloat(getString(key)); } catch (Throwable ignore) { LOGGER.trace("ignore", ignore); } return retValue; }
[ "public", "float", "getFloat", "(", "@", "NotNull", "final", "String", "key", ",", "float", "defaultValue", ")", "{", "float", "retValue", "=", "defaultValue", ";", "try", "{", "retValue", "=", "Float", ".", "parseFloat", "(", "getString", "(", "key", ")",...
Returns a float value from the properties file. If the value was specified as a system property or passed in via the <code>-Dprop=value</code> argument this method will return the value from the system properties before the values in the contained configuration file. @param key the key to lookup within the properties file @param defaultValue the default value to return if the setting does not exist @return the property from the properties file
[ "Returns", "a", "float", "value", "from", "the", "properties", "file", ".", "If", "the", "value", "was", "specified", "as", "a", "system", "property", "or", "passed", "in", "via", "the", "<code", ">", "-", "Dprop", "=", "value<", "/", "code", ">", "arg...
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java#L1072-L1080
groundupworks/wings
wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java
FacebookEndpoint.finishSettingsRequest
private FacebookSettings finishSettingsRequest(int requestCode, int resultCode, Intent data) { FacebookSettings settings = null; if (requestCode == SETTINGS_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) { // Construct settings from the extras bundle. settings = FacebookSettings.newInstance(data.getExtras()); } return settings; }
java
private FacebookSettings finishSettingsRequest(int requestCode, int resultCode, Intent data) { FacebookSettings settings = null; if (requestCode == SETTINGS_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) { // Construct settings from the extras bundle. settings = FacebookSettings.newInstance(data.getExtras()); } return settings; }
[ "private", "FacebookSettings", "finishSettingsRequest", "(", "int", "requestCode", ",", "int", "resultCode", ",", "Intent", "data", ")", "{", "FacebookSettings", "settings", "=", "null", ";", "if", "(", "requestCode", "==", "SETTINGS_REQUEST_CODE", "&&", "resultCode...
Finishes a {@link com.groundupworks.wings.facebook.FacebookEndpoint#startSettingsRequest(android.app.Activity, android.support.v4.app.Fragment)}. @param requestCode the integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from. @param resultCode the integer result code returned by the child activity through its setResult(). @param data an Intent, which can return result data to the caller (various data can be attached to Intent "extras"). @return the settings; or null if failed.
[ "Finishes", "a", "{", "@link", "com", ".", "groundupworks", ".", "wings", ".", "facebook", ".", "FacebookEndpoint#startSettingsRequest", "(", "android", ".", "app", ".", "Activity", "android", ".", "support", ".", "v4", ".", "app", ".", "Fragment", ")", "}",...
train
https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java#L481-L489
VueGWT/vue-gwt
processors/src/main/java/com/axellience/vuegwt/processors/component/ComponentInjectedDependenciesBuilder.java
ComponentInjectedDependenciesBuilder.addInjectedVariable
private void addInjectedVariable(VariableElement element, String fieldName) { TypeName typeName = resolveVariableTypeName(element, messager); // Create field FieldSpec.Builder fieldBuilder = FieldSpec.builder(typeName, fieldName, Modifier.PUBLIC); // Copy field annotations element .getAnnotationMirrors() .stream() .map(AnnotationSpec::get) .forEach(fieldBuilder::addAnnotation); // If the variable element is a method parameter, it might not have the Inject annotation if (!hasInjectAnnotation(element)) { fieldBuilder.addAnnotation(Inject.class); } // And add field builder.addField(fieldBuilder.build()); }
java
private void addInjectedVariable(VariableElement element, String fieldName) { TypeName typeName = resolveVariableTypeName(element, messager); // Create field FieldSpec.Builder fieldBuilder = FieldSpec.builder(typeName, fieldName, Modifier.PUBLIC); // Copy field annotations element .getAnnotationMirrors() .stream() .map(AnnotationSpec::get) .forEach(fieldBuilder::addAnnotation); // If the variable element is a method parameter, it might not have the Inject annotation if (!hasInjectAnnotation(element)) { fieldBuilder.addAnnotation(Inject.class); } // And add field builder.addField(fieldBuilder.build()); }
[ "private", "void", "addInjectedVariable", "(", "VariableElement", "element", ",", "String", "fieldName", ")", "{", "TypeName", "typeName", "=", "resolveVariableTypeName", "(", "element", ",", "messager", ")", ";", "// Create field", "FieldSpec", ".", "Builder", "fie...
Add an injected variable to our component @param element The {@link VariableElement} that was injected @param fieldName The name of the field
[ "Add", "an", "injected", "variable", "to", "our", "component" ]
train
https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/ComponentInjectedDependenciesBuilder.java#L176-L196
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/SmartGrid.java
SmartGrid.setWidget
public void setWidget (int row, int column, Widget widget, String style) { setWidget(row, column, widget); if (style != null) { getCellFormatter().setStyleName(row, column, style); } }
java
public void setWidget (int row, int column, Widget widget, String style) { setWidget(row, column, widget); if (style != null) { getCellFormatter().setStyleName(row, column, style); } }
[ "public", "void", "setWidget", "(", "int", "row", ",", "int", "column", ",", "Widget", "widget", ",", "String", "style", ")", "{", "setWidget", "(", "row", ",", "column", ",", "widget", ")", ";", "if", "(", "style", "!=", "null", ")", "{", "getCellFo...
Sets the widget in the specified cell, with the specified style and column span.
[ "Sets", "the", "widget", "in", "the", "specified", "cell", "with", "the", "specified", "style", "and", "column", "span", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/SmartGrid.java#L68-L74
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java
StringIterate.allSatisfy
@Deprecated public static boolean allSatisfy(String string, CharPredicate predicate) { return StringIterate.allSatisfyChar(string, predicate); }
java
@Deprecated public static boolean allSatisfy(String string, CharPredicate predicate) { return StringIterate.allSatisfyChar(string, predicate); }
[ "@", "Deprecated", "public", "static", "boolean", "allSatisfy", "(", "String", "string", ",", "CharPredicate", "predicate", ")", "{", "return", "StringIterate", ".", "allSatisfyChar", "(", "string", ",", "predicate", ")", ";", "}" ]
@return true if all of the characters in the {@code string} answer true for the specified {@code predicate}. @deprecated since 7.0. Use {@link #allSatisfyChar(String, CharPredicate)} instead.
[ "@return", "true", "if", "all", "of", "the", "characters", "in", "the", "{", "@code", "string", "}", "answer", "true", "for", "the", "specified", "{", "@code", "predicate", "}", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java#L850-L854
VoltDB/voltdb
src/frontend/org/voltdb/sysprocs/AdHocBase.java
AdHocBase.adHocSQLStringFromPlannedStatement
public static String adHocSQLStringFromPlannedStatement(AdHocPlannedStatement statement, Object[] userparams) { final int MAX_PARAM_LINE_CHARS = 120; StringBuilder sb = new StringBuilder(); String sql = new String(statement.sql, Charsets.UTF_8); sb.append(sql); Object[] params = paramsForStatement(statement, userparams); // convert params to strings of a certain max length for (int i = 0; i < params.length; i++) { Object param = params[i]; String paramLineStr = String.format(" Param %d: %s", i, param.toString()); // trim param line if it's silly long if (paramLineStr.length() > MAX_PARAM_LINE_CHARS) { paramLineStr = paramLineStr.substring(0, MAX_PARAM_LINE_CHARS - 3); paramLineStr += "..."; } sb.append('\n').append(paramLineStr); } return sb.toString(); }
java
public static String adHocSQLStringFromPlannedStatement(AdHocPlannedStatement statement, Object[] userparams) { final int MAX_PARAM_LINE_CHARS = 120; StringBuilder sb = new StringBuilder(); String sql = new String(statement.sql, Charsets.UTF_8); sb.append(sql); Object[] params = paramsForStatement(statement, userparams); // convert params to strings of a certain max length for (int i = 0; i < params.length; i++) { Object param = params[i]; String paramLineStr = String.format(" Param %d: %s", i, param.toString()); // trim param line if it's silly long if (paramLineStr.length() > MAX_PARAM_LINE_CHARS) { paramLineStr = paramLineStr.substring(0, MAX_PARAM_LINE_CHARS - 3); paramLineStr += "..."; } sb.append('\n').append(paramLineStr); } return sb.toString(); }
[ "public", "static", "String", "adHocSQLStringFromPlannedStatement", "(", "AdHocPlannedStatement", "statement", ",", "Object", "[", "]", "userparams", ")", "{", "final", "int", "MAX_PARAM_LINE_CHARS", "=", "120", ";", "StringBuilder", "sb", "=", "new", "StringBuilder",...
Get a string containing a SQL statement and any parameters for a given AdHocPlannedStatement. Used for debugging and logging.
[ "Get", "a", "string", "containing", "a", "SQL", "statement", "and", "any", "parameters", "for", "a", "given", "AdHocPlannedStatement", ".", "Used", "for", "debugging", "and", "logging", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/sysprocs/AdHocBase.java#L104-L127
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/edge/HysteresisEdgeTracePoints.java
HysteresisEdgeTracePoints.process
public void process(GrayF32 intensity , GrayS8 direction , float lower , float upper ) { if( lower < 0 ) throw new IllegalArgumentException("Lower must be >= 0!"); InputSanityCheck.checkSameShape(intensity, direction); // set up internal data structures this.intensity = intensity; this.direction = direction; this.lower = lower; queuePoints.reset(); contours.clear(); // step through each pixel in the image for( int y = 0; y < intensity.height; y++ ) { int indexInten = intensity.startIndex + y*intensity.stride; for( int x = 0; x < intensity.width; x++ , indexInten++ ) { // start a search if a pixel is found that's above the threshold if( intensity.data[indexInten] >= upper ) { trace( x,y,indexInten); } } } }
java
public void process(GrayF32 intensity , GrayS8 direction , float lower , float upper ) { if( lower < 0 ) throw new IllegalArgumentException("Lower must be >= 0!"); InputSanityCheck.checkSameShape(intensity, direction); // set up internal data structures this.intensity = intensity; this.direction = direction; this.lower = lower; queuePoints.reset(); contours.clear(); // step through each pixel in the image for( int y = 0; y < intensity.height; y++ ) { int indexInten = intensity.startIndex + y*intensity.stride; for( int x = 0; x < intensity.width; x++ , indexInten++ ) { // start a search if a pixel is found that's above the threshold if( intensity.data[indexInten] >= upper ) { trace( x,y,indexInten); } } } }
[ "public", "void", "process", "(", "GrayF32", "intensity", ",", "GrayS8", "direction", ",", "float", "lower", ",", "float", "upper", ")", "{", "if", "(", "lower", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Lower must be >= 0!\"", ")", ...
Performs hysteresis thresholding using the provided lower and upper thresholds. @param intensity Intensity image after edge non-maximum suppression has been applied. Modified. @param direction 4-direction image. Not modified. @param lower Lower threshold. @param upper Upper threshold.
[ "Performs", "hysteresis", "thresholding", "using", "the", "provided", "lower", "and", "upper", "thresholds", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/edge/HysteresisEdgeTracePoints.java#L76-L99
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/ProbabilityWeightedMoments.java
ProbabilityWeightedMoments.normalizeLMR
private static void normalizeLMR(double[] sum, int nmom) { for(int k = nmom - 1; k >= 1; --k) { double p = ((k & 1) == 0) ? +1 : -1; double temp = p * sum[0]; for(int i = 0; i < k; i++) { double ai = i + 1.; p *= -(k + ai) * (k - i) / (ai * ai); temp += p * sum[i + 1]; } sum[k] = temp; } }
java
private static void normalizeLMR(double[] sum, int nmom) { for(int k = nmom - 1; k >= 1; --k) { double p = ((k & 1) == 0) ? +1 : -1; double temp = p * sum[0]; for(int i = 0; i < k; i++) { double ai = i + 1.; p *= -(k + ai) * (k - i) / (ai * ai); temp += p * sum[i + 1]; } sum[k] = temp; } }
[ "private", "static", "void", "normalizeLMR", "(", "double", "[", "]", "sum", ",", "int", "nmom", ")", "{", "for", "(", "int", "k", "=", "nmom", "-", "1", ";", "k", ">=", "1", ";", "--", "k", ")", "{", "double", "p", "=", "(", "(", "k", "&", ...
Normalize the moments @param sum Sums @param nmom Number of moments
[ "Normalize", "the", "moments" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/ProbabilityWeightedMoments.java#L191-L202
netty/netty
common/src/main/java/io/netty/util/Signal.java
Signal.valueOf
public static Signal valueOf(Class<?> firstNameComponent, String secondNameComponent) { return pool.valueOf(firstNameComponent, secondNameComponent); }
java
public static Signal valueOf(Class<?> firstNameComponent, String secondNameComponent) { return pool.valueOf(firstNameComponent, secondNameComponent); }
[ "public", "static", "Signal", "valueOf", "(", "Class", "<", "?", ">", "firstNameComponent", ",", "String", "secondNameComponent", ")", "{", "return", "pool", ".", "valueOf", "(", "firstNameComponent", ",", "secondNameComponent", ")", ";", "}" ]
Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}.
[ "Shortcut", "of", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/Signal.java#L44-L46
alkacon/opencms-core
src-modules/org/opencms/workplace/explorer/CmsExplorer.java
CmsExplorer.resourceExists
private boolean resourceExists(CmsObject cms, String resource) { try { cms.readResource(resource, CmsResourceFilter.ALL); return true; } catch (CmsException e) { return false; } }
java
private boolean resourceExists(CmsObject cms, String resource) { try { cms.readResource(resource, CmsResourceFilter.ALL); return true; } catch (CmsException e) { return false; } }
[ "private", "boolean", "resourceExists", "(", "CmsObject", "cms", ",", "String", "resource", ")", "{", "try", "{", "cms", ".", "readResource", "(", "resource", ",", "CmsResourceFilter", ".", "ALL", ")", ";", "return", "true", ";", "}", "catch", "(", "CmsExc...
Checks if a resource with a given name exits in the VFS.<p> @param cms the current cms context @param resource the resource to check for @return true if the resource exists in the VFS
[ "Checks", "if", "a", "resource", "with", "a", "given", "name", "exits", "in", "the", "VFS", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/explorer/CmsExplorer.java#L884-L892
opencb/java-common-libs
commons-datastore/commons-datastore-solr/src/main/java/org/opencb/commons/datastore/solr/SolrManager.java
SolrManager.removeCollection
public void removeCollection(String collectionName) throws SolrException { try { CollectionAdminRequest request = CollectionAdminRequest.deleteCollection(collectionName); request.process(solrClient); } catch (SolrServerException | IOException e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e.getMessage(), e); } }
java
public void removeCollection(String collectionName) throws SolrException { try { CollectionAdminRequest request = CollectionAdminRequest.deleteCollection(collectionName); request.process(solrClient); } catch (SolrServerException | IOException e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e.getMessage(), e); } }
[ "public", "void", "removeCollection", "(", "String", "collectionName", ")", "throws", "SolrException", "{", "try", "{", "CollectionAdminRequest", "request", "=", "CollectionAdminRequest", ".", "deleteCollection", "(", "collectionName", ")", ";", "request", ".", "proce...
Remove a collection. @param collectionName Collection name @throws SolrException SolrException
[ "Remove", "a", "collection", "." ]
train
https://github.com/opencb/java-common-libs/blob/5c97682530d0be55828e1e4e374ff01fceb5f198/commons-datastore/commons-datastore-solr/src/main/java/org/opencb/commons/datastore/solr/SolrManager.java#L238-L245
cdk/cdk
display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardGenerator.java
StandardGenerator.embedText
public static IRenderingElement embedText(Font font, String text, Color color, double scale) { final String[] lines = text.split("\n"); ElementGroup group = new ElementGroup(); double yOffset = 0; double lineHeight = 1.4d; for (String line : lines) { TextOutline outline = new TextOutline(line, font).resize(scale, -scale); Point2D center = outline.getCenter(); outline = outline.translate(-center.getX(), -(center.getY() + yOffset)); yOffset += lineHeight * outline.getBounds().getHeight(); group.add(GeneralPath.shapeOf(outline.getOutline(), color)); Rectangle2D logicalBounds = outline.getLogicalBounds(); group.add(new Bounds(logicalBounds.getMinX(), logicalBounds.getMinY(), logicalBounds.getMaxX(), logicalBounds.getMaxY())); } return group; }
java
public static IRenderingElement embedText(Font font, String text, Color color, double scale) { final String[] lines = text.split("\n"); ElementGroup group = new ElementGroup(); double yOffset = 0; double lineHeight = 1.4d; for (String line : lines) { TextOutline outline = new TextOutline(line, font).resize(scale, -scale); Point2D center = outline.getCenter(); outline = outline.translate(-center.getX(), -(center.getY() + yOffset)); yOffset += lineHeight * outline.getBounds().getHeight(); group.add(GeneralPath.shapeOf(outline.getOutline(), color)); Rectangle2D logicalBounds = outline.getLogicalBounds(); group.add(new Bounds(logicalBounds.getMinX(), logicalBounds.getMinY(), logicalBounds.getMaxX(), logicalBounds.getMaxY())); } return group; }
[ "public", "static", "IRenderingElement", "embedText", "(", "Font", "font", ",", "String", "text", ",", "Color", "color", ",", "double", "scale", ")", "{", "final", "String", "[", "]", "lines", "=", "text", ".", "split", "(", "\"\\n\"", ")", ";", "Element...
Make an embedded text label for display in a CDK renderer. If a piece of text contains newlines they are centred aligned below each other with a line height of 1.4. @param font the font to embedded @param text the text label @param color the color @param scale the resize, should include the model scale @return pre-rendered element
[ "Make", "an", "embedded", "text", "label", "for", "display", "in", "a", "CDK", "renderer", ".", "If", "a", "piece", "of", "text", "contains", "newlines", "they", "are", "centred", "aligned", "below", "each", "other", "with", "a", "line", "height", "of", ...
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardGenerator.java#L573-L596
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetVMsInner.java
VirtualMachineScaleSetVMsInner.beginReimage
public OperationStatusResponseInner beginReimage(String resourceGroupName, String vmScaleSetName, String instanceId) { return beginReimageWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceId).toBlocking().single().body(); }
java
public OperationStatusResponseInner beginReimage(String resourceGroupName, String vmScaleSetName, String instanceId) { return beginReimageWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceId).toBlocking().single().body(); }
[ "public", "OperationStatusResponseInner", "beginReimage", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ",", "String", "instanceId", ")", "{", "return", "beginReimageWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetName", ",", "ins...
Reimages (upgrade the operating system) a specific virtual machine in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @param instanceId The instance ID of the virtual machine. @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 OperationStatusResponseInner object if successful.
[ "Reimages", "(", "upgrade", "the", "operating", "system", ")", "a", "specific", "virtual", "machine", "in", "a", "VM", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetVMsInner.java#L250-L252
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/db/SQLUtils.java
SQLUtils.closeResultSetStatement
public static void closeResultSetStatement(ResultSet resultSet, String sql) { if (resultSet != null) { try { resultSet.getStatement().close(); } catch (SQLException e) { log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql, e); } } }
java
public static void closeResultSetStatement(ResultSet resultSet, String sql) { if (resultSet != null) { try { resultSet.getStatement().close(); } catch (SQLException e) { log.log(Level.WARNING, "Failed to close SQL ResultSet: " + sql, e); } } }
[ "public", "static", "void", "closeResultSetStatement", "(", "ResultSet", "resultSet", ",", "String", "sql", ")", "{", "if", "(", "resultSet", "!=", "null", ")", "{", "try", "{", "resultSet", ".", "getStatement", "(", ")", ".", "close", "(", ")", ";", "}"...
Close the ResultSet Statement from which it was created, which closes all ResultSets as well @param resultSet result set @param sql sql statement
[ "Close", "the", "ResultSet", "Statement", "from", "which", "it", "was", "created", "which", "closes", "all", "ResultSets", "as", "well" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/db/SQLUtils.java#L573-L582
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsConfigurationReader.java
CmsConfigurationReader.parseSitemapConfiguration
public CmsADEConfigDataInternal parseSitemapConfiguration(String basePath, CmsResource configRes) throws CmsException { LOG.info("Parsing configuration " + configRes.getRootPath()); CmsFile configFile = m_cms.readFile(configRes); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, configFile); return parseConfiguration(basePath, content); }
java
public CmsADEConfigDataInternal parseSitemapConfiguration(String basePath, CmsResource configRes) throws CmsException { LOG.info("Parsing configuration " + configRes.getRootPath()); CmsFile configFile = m_cms.readFile(configRes); CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, configFile); return parseConfiguration(basePath, content); }
[ "public", "CmsADEConfigDataInternal", "parseSitemapConfiguration", "(", "String", "basePath", ",", "CmsResource", "configRes", ")", "throws", "CmsException", "{", "LOG", ".", "info", "(", "\"Parsing configuration \"", "+", "configRes", ".", "getRootPath", "(", ")", ")...
Parses the sitemap configuration given the configuration file and base path.<p> @param basePath the base path @param configRes the configuration file resource @return the parsed configuration data @throws CmsException if something goes wrong
[ "Parses", "the", "sitemap", "configuration", "given", "the", "configuration", "file", "and", "base", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsConfigurationReader.java#L736-L743
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/TreePath.java
TreePath.getPath
public static TreePath getPath(CompilationUnitTree unit, Tree target) { return getPath(new TreePath(unit), target); }
java
public static TreePath getPath(CompilationUnitTree unit, Tree target) { return getPath(new TreePath(unit), target); }
[ "public", "static", "TreePath", "getPath", "(", "CompilationUnitTree", "unit", ",", "Tree", "target", ")", "{", "return", "getPath", "(", "new", "TreePath", "(", "unit", ")", ",", "target", ")", ";", "}" ]
Returns a tree path for a tree node within a compilation unit, or {@code null} if the node is not found. @param unit the compilation unit to search @param target the node to locate @return the tree path
[ "Returns", "a", "tree", "path", "for", "a", "tree", "node", "within", "a", "compilation", "unit", "or", "{" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreePath.java#L48-L50
molgenis/molgenis
molgenis-ontology-core/src/main/java/org/molgenis/ontology/core/importer/repository/OntologyRepositoryCollection.java
OntologyRepositoryCollection.constructNodePath
private String constructNodePath(String parentNodePath, int currentPosition) { StringBuilder nodePathStringBuilder = new StringBuilder(); if (!StringUtils.isEmpty(parentNodePath)) nodePathStringBuilder.append(parentNodePath).append('.'); nodePathStringBuilder .append(currentPosition) .append('[') .append(nodePathStringBuilder.toString().split("\\.").length - 1) .append(']'); return nodePathStringBuilder.toString(); }
java
private String constructNodePath(String parentNodePath, int currentPosition) { StringBuilder nodePathStringBuilder = new StringBuilder(); if (!StringUtils.isEmpty(parentNodePath)) nodePathStringBuilder.append(parentNodePath).append('.'); nodePathStringBuilder .append(currentPosition) .append('[') .append(nodePathStringBuilder.toString().split("\\.").length - 1) .append(']'); return nodePathStringBuilder.toString(); }
[ "private", "String", "constructNodePath", "(", "String", "parentNodePath", ",", "int", "currentPosition", ")", "{", "StringBuilder", "nodePathStringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "!", "StringUtils", ".", "isEmpty", "(", "parentNod...
Constructs the node path string for a child node @param parentNodePath node path string of the node's parent @param currentPosition position of the node in the parent's child list @return node path string
[ "Constructs", "the", "node", "path", "string", "for", "a", "child", "node" ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-ontology-core/src/main/java/org/molgenis/ontology/core/importer/repository/OntologyRepositoryCollection.java#L294-L304
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/factory/BaseNDArrayFactory.java
BaseNDArrayFactory.randn
@Override public INDArray randn(long rows, long columns) { return randn(new long[] {rows, columns}, System.currentTimeMillis()); }
java
@Override public INDArray randn(long rows, long columns) { return randn(new long[] {rows, columns}, System.currentTimeMillis()); }
[ "@", "Override", "public", "INDArray", "randn", "(", "long", "rows", ",", "long", "columns", ")", "{", "return", "randn", "(", "new", "long", "[", "]", "{", "rows", ",", "columns", "}", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "}"...
Random normal using the current time stamp as the seed @param rows the number of rows in the matrix @param columns the number of columns in the matrix @return
[ "Random", "normal", "using", "the", "current", "time", "stamp", "as", "the", "seed" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/factory/BaseNDArrayFactory.java#L511-L514