repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
looly/hutool
hutool-core/src/main/java/cn/hutool/core/exceptions/ExceptionUtil.java
ExceptionUtil.isFromOrSuppressedThrowable
public static boolean isFromOrSuppressedThrowable(Throwable throwable, Class<? extends Throwable> exceptionClass) { return convertFromOrSuppressedThrowable(throwable, exceptionClass, true) != null; }
java
public static boolean isFromOrSuppressedThrowable(Throwable throwable, Class<? extends Throwable> exceptionClass) { return convertFromOrSuppressedThrowable(throwable, exceptionClass, true) != null; }
[ "public", "static", "boolean", "isFromOrSuppressedThrowable", "(", "Throwable", "throwable", ",", "Class", "<", "?", "extends", "Throwable", ">", "exceptionClass", ")", "{", "return", "convertFromOrSuppressedThrowable", "(", "throwable", ",", "exceptionClass", ",", "t...
判断指定异常是否来自或者包含指定异常 @param throwable 异常 @param exceptionClass 定义的引起异常的类 @return true 来自或者包含 @since 4.3.2
[ "判断指定异常是否来自或者包含指定异常" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/exceptions/ExceptionUtil.java#L256-L258
ben-manes/caffeine
caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java
BoundedLocalCache.expireAfterWriteOrder
@SuppressWarnings("GuardedByChecker") Map<K, V> expireAfterWriteOrder(int limit, Function<V, V> transformer, boolean oldest) { Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> oldest ? writeOrderDeque().iterator() : writeOrderDeque().descendingIterator(); return fixedSnapshot(iteratorSupplier, limit, transformer); }
java
@SuppressWarnings("GuardedByChecker") Map<K, V> expireAfterWriteOrder(int limit, Function<V, V> transformer, boolean oldest) { Supplier<Iterator<Node<K, V>>> iteratorSupplier = () -> oldest ? writeOrderDeque().iterator() : writeOrderDeque().descendingIterator(); return fixedSnapshot(iteratorSupplier, limit, transformer); }
[ "@", "SuppressWarnings", "(", "\"GuardedByChecker\"", ")", "Map", "<", "K", ",", "V", ">", "expireAfterWriteOrder", "(", "int", "limit", ",", "Function", "<", "V", ",", "V", ">", "transformer", ",", "boolean", "oldest", ")", "{", "Supplier", "<", "Iterator...
Returns an unmodifiable snapshot map ordered in write expiration order, either ascending or descending. Beware that obtaining the mappings is <em>NOT</em> a constant-time operation. @param limit the maximum number of entries @param transformer a function that unwraps the value @param oldest the iteration order @return an unmodifiable snapshot in a specified order
[ "Returns", "an", "unmodifiable", "snapshot", "map", "ordered", "in", "write", "expiration", "order", "either", "ascending", "or", "descending", ".", "Beware", "that", "obtaining", "the", "mappings", "is", "<em", ">", "NOT<", "/", "em", ">", "a", "constant", ...
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java#L2687-L2693
jbundle/jbundle
base/remote/src/main/java/org/jbundle/base/remote/lock/ClientLockManager.java
ClientLockManager.unlockThisRecord
public boolean unlockThisRecord(Task objSession, String strDatabaseName, String strRecordName, Object bookmark) throws DBException { SessionInfo sessionInfo = this.getLockSessionInfo(objSession, null); try { boolean bSuccess = this.getRemoteLockSession(sessionInfo).unlockThisRecord(strDatabaseName, strRecordName, bookmark, sessionInfo); //? if (bookmark == null) //? this.removeLockSessionInfo(objSession); // For close all, remove the session return bSuccess; } catch (RemoteException ex) { throw DatabaseException.toDatabaseException(ex); } }
java
public boolean unlockThisRecord(Task objSession, String strDatabaseName, String strRecordName, Object bookmark) throws DBException { SessionInfo sessionInfo = this.getLockSessionInfo(objSession, null); try { boolean bSuccess = this.getRemoteLockSession(sessionInfo).unlockThisRecord(strDatabaseName, strRecordName, bookmark, sessionInfo); //? if (bookmark == null) //? this.removeLockSessionInfo(objSession); // For close all, remove the session return bSuccess; } catch (RemoteException ex) { throw DatabaseException.toDatabaseException(ex); } }
[ "public", "boolean", "unlockThisRecord", "(", "Task", "objSession", ",", "String", "strDatabaseName", ",", "String", "strRecordName", ",", "Object", "bookmark", ")", "throws", "DBException", "{", "SessionInfo", "sessionInfo", "=", "this", ".", "getLockSessionInfo", ...
Unlock this bookmark in this record for this session. @param strRecordName The record to unlock in. @param bookmark The bookmark to unlock (or null to unlock all for this session). @param objSession The session that wants to unlock. @param iLockType The type of lock (wait or error lock). @return True if successful.
[ "Unlock", "this", "bookmark", "in", "this", "record", "for", "this", "session", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/lock/ClientLockManager.java#L91-L103
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java
Convolution.col2im
public static INDArray col2im(INDArray col, int sH, int sW, int ph, int pW, int kH, int kW) { if (col.rank() != 6) throw new IllegalArgumentException("col2im input array must be rank 6"); INDArray output = Nd4j.create(col.dataType(), new long[]{col.size(0), col.size(1), kH, kW}); val cfg = Conv2DConfig.builder() .sH(sH) .sW(sW) .dH(1) .dW(1) .kH(kH) .kW(kW) .pH(ph) .pW(pW) .build(); Col2Im col2Im = Col2Im.builder() .inputArrays(new INDArray[]{col}) .outputs(new INDArray[]{output}) .conv2DConfig(cfg) .build(); Nd4j.getExecutioner().execAndReturn(col2Im); return col2Im.outputArguments()[0]; }
java
public static INDArray col2im(INDArray col, int sH, int sW, int ph, int pW, int kH, int kW) { if (col.rank() != 6) throw new IllegalArgumentException("col2im input array must be rank 6"); INDArray output = Nd4j.create(col.dataType(), new long[]{col.size(0), col.size(1), kH, kW}); val cfg = Conv2DConfig.builder() .sH(sH) .sW(sW) .dH(1) .dW(1) .kH(kH) .kW(kW) .pH(ph) .pW(pW) .build(); Col2Im col2Im = Col2Im.builder() .inputArrays(new INDArray[]{col}) .outputs(new INDArray[]{output}) .conv2DConfig(cfg) .build(); Nd4j.getExecutioner().execAndReturn(col2Im); return col2Im.outputArguments()[0]; }
[ "public", "static", "INDArray", "col2im", "(", "INDArray", "col", ",", "int", "sH", ",", "int", "sW", ",", "int", "ph", ",", "int", "pW", ",", "int", "kH", ",", "int", "kW", ")", "{", "if", "(", "col", ".", "rank", "(", ")", "!=", "6", ")", "...
Rearrange matrix columns into blocks @param col the column transposed image to convert @param sH stride height @param sW stride width @param ph padding height @param pW padding width @param kH height @param kW width @return
[ "Rearrange", "matrix", "columns", "into", "blocks" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java#L77-L102
BoltsFramework/Bolts-Android
bolts-tasks/src/main/java/bolts/Task.java
Task.onSuccess
public <TContinuationResult> Task<TContinuationResult> onSuccess( final Continuation<TResult, TContinuationResult> continuation) { return onSuccess(continuation, IMMEDIATE_EXECUTOR, null); }
java
public <TContinuationResult> Task<TContinuationResult> onSuccess( final Continuation<TResult, TContinuationResult> continuation) { return onSuccess(continuation, IMMEDIATE_EXECUTOR, null); }
[ "public", "<", "TContinuationResult", ">", "Task", "<", "TContinuationResult", ">", "onSuccess", "(", "final", "Continuation", "<", "TResult", ",", "TContinuationResult", ">", "continuation", ")", "{", "return", "onSuccess", "(", "continuation", ",", "IMMEDIATE_EXEC...
Runs a continuation when a task completes successfully, forwarding along {@link java.lang.Exception}s or cancellation.
[ "Runs", "a", "continuation", "when", "a", "task", "completes", "successfully", "forwarding", "along", "{" ]
train
https://github.com/BoltsFramework/Bolts-Android/blob/54e9cb8bdd4950aa4d418dcbc0ea65414762aef5/bolts-tasks/src/main/java/bolts/Task.java#L773-L776
apache/incubator-gobblin
gobblin-yarn/src/main/java/org/apache/gobblin/yarn/GobblinApplicationMaster.java
GobblinApplicationMaster.buildYarnContainerSecurityManager
private YarnContainerSecurityManager buildYarnContainerSecurityManager(Config config, FileSystem fs) { return new YarnContainerSecurityManager(config, fs, this.eventBus); }
java
private YarnContainerSecurityManager buildYarnContainerSecurityManager(Config config, FileSystem fs) { return new YarnContainerSecurityManager(config, fs, this.eventBus); }
[ "private", "YarnContainerSecurityManager", "buildYarnContainerSecurityManager", "(", "Config", "config", ",", "FileSystem", "fs", ")", "{", "return", "new", "YarnContainerSecurityManager", "(", "config", ",", "fs", ",", "this", ".", "eventBus", ")", ";", "}" ]
Build the {@link YarnContainerSecurityManager} for the Application Master.
[ "Build", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-yarn/src/main/java/org/apache/gobblin/yarn/GobblinApplicationMaster.java#L106-L108
azkaban/azkaban
az-core/src/main/java/azkaban/utils/Utils.java
Utils.croak
public static void croak(final String message, final int exitCode) { System.err.println(message); System.exit(exitCode); }
java
public static void croak(final String message, final int exitCode) { System.err.println(message); System.exit(exitCode); }
[ "public", "static", "void", "croak", "(", "final", "String", "message", ",", "final", "int", "exitCode", ")", "{", "System", ".", "err", ".", "println", "(", "message", ")", ";", "System", ".", "exit", "(", "exitCode", ")", ";", "}" ]
Print the message and then exit with the given exit code @param message The message to print @param exitCode The exit code
[ "Print", "the", "message", "and", "then", "exit", "with", "the", "given", "exit", "code" ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-core/src/main/java/azkaban/utils/Utils.java#L120-L123
alkacon/opencms-core
src/org/opencms/main/CmsShell.java
CmsShell.initShell
public void initShell(I_CmsShellCommands additionalShellCommands, PrintStream out, PrintStream err) { // set the output streams m_out = out; m_err = err; // initialize the settings of the user m_settings = initSettings(); // initialize shell command object m_shellCommands = new CmsShellCommands(); m_shellCommands.initShellCmsObject(m_cms, this); // initialize additional shell command object if (additionalShellCommands != null) { m_additionalShellCommands = additionalShellCommands; m_additionalShellCommands.initShellCmsObject(m_cms, this); m_additionalShellCommands.shellStart(); } else { m_shellCommands.shellStart(); } m_commandObjects = new ArrayList<CmsCommandObject>(); if (m_additionalShellCommands != null) { // get all shell callable methods from the additional shell command object m_commandObjects.add(new CmsCommandObject(m_additionalShellCommands)); } // get all shell callable methods from the CmsShellCommands m_commandObjects.add(new CmsCommandObject(m_shellCommands)); // get all shell callable methods from the CmsRequestContext m_commandObjects.add(new CmsCommandObject(m_cms.getRequestContext())); // get all shell callable methods from the CmsObject m_commandObjects.add(new CmsCommandObject(m_cms)); }
java
public void initShell(I_CmsShellCommands additionalShellCommands, PrintStream out, PrintStream err) { // set the output streams m_out = out; m_err = err; // initialize the settings of the user m_settings = initSettings(); // initialize shell command object m_shellCommands = new CmsShellCommands(); m_shellCommands.initShellCmsObject(m_cms, this); // initialize additional shell command object if (additionalShellCommands != null) { m_additionalShellCommands = additionalShellCommands; m_additionalShellCommands.initShellCmsObject(m_cms, this); m_additionalShellCommands.shellStart(); } else { m_shellCommands.shellStart(); } m_commandObjects = new ArrayList<CmsCommandObject>(); if (m_additionalShellCommands != null) { // get all shell callable methods from the additional shell command object m_commandObjects.add(new CmsCommandObject(m_additionalShellCommands)); } // get all shell callable methods from the CmsShellCommands m_commandObjects.add(new CmsCommandObject(m_shellCommands)); // get all shell callable methods from the CmsRequestContext m_commandObjects.add(new CmsCommandObject(m_cms.getRequestContext())); // get all shell callable methods from the CmsObject m_commandObjects.add(new CmsCommandObject(m_cms)); }
[ "public", "void", "initShell", "(", "I_CmsShellCommands", "additionalShellCommands", ",", "PrintStream", "out", ",", "PrintStream", "err", ")", "{", "// set the output streams", "m_out", "=", "out", ";", "m_err", "=", "err", ";", "// initialize the settings of the user"...
Initializes the CmsShell.<p> @param additionalShellCommands optional object for additional shell commands, or null @param out stream to write the regular output messages to @param err stream to write the error messages output to
[ "Initializes", "the", "CmsShell", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShell.java#L1037-L1070
apache/flink
flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/clustering/undirected/TriangleListing.java
TriangleListing.runInternal
@Override public DataSet<Result<K>> runInternal(Graph<K, VV, EV> input) throws Exception { // u, v where u < v DataSet<Tuple2<K, K>> filteredByID = input .getEdges() .flatMap(new FilterByID<>()) .setParallelism(parallelism) .name("Filter by ID"); // u, v, (edge value, deg(u), deg(v)) DataSet<Edge<K, Tuple3<EV, LongValue, LongValue>>> pairDegree = input .run(new EdgeDegreePair<K, VV, EV>() .setParallelism(parallelism)); // u, v where deg(u) < deg(v) or (deg(u) == deg(v) and u < v) DataSet<Tuple2<K, K>> filteredByDegree = pairDegree .flatMap(new FilterByDegree<>()) .setParallelism(parallelism) .name("Filter by degree"); // u, v, w where (u, v) and (u, w) are edges in graph, v < w DataSet<Tuple3<K, K, K>> triplets = filteredByDegree .groupBy(0) .sortGroup(1, Order.ASCENDING) .reduceGroup(new GenerateTriplets<>()) .name("Generate triplets"); // u, v, w where (u, v), (u, w), and (v, w) are edges in graph, v < w DataSet<Result<K>> triangles = triplets .join(filteredByID, JoinOperatorBase.JoinHint.REPARTITION_HASH_SECOND) .where(1, 2) .equalTo(0, 1) .with(new ProjectTriangles<>()) .name("Triangle listing"); if (permuteResults) { triangles = triangles .flatMap(new PermuteResult<>()) .name("Permute triangle vertices"); } else if (sortTriangleVertices.get()) { triangles = triangles .map(new SortTriangleVertices<>()) .name("Sort triangle vertices"); } return triangles; }
java
@Override public DataSet<Result<K>> runInternal(Graph<K, VV, EV> input) throws Exception { // u, v where u < v DataSet<Tuple2<K, K>> filteredByID = input .getEdges() .flatMap(new FilterByID<>()) .setParallelism(parallelism) .name("Filter by ID"); // u, v, (edge value, deg(u), deg(v)) DataSet<Edge<K, Tuple3<EV, LongValue, LongValue>>> pairDegree = input .run(new EdgeDegreePair<K, VV, EV>() .setParallelism(parallelism)); // u, v where deg(u) < deg(v) or (deg(u) == deg(v) and u < v) DataSet<Tuple2<K, K>> filteredByDegree = pairDegree .flatMap(new FilterByDegree<>()) .setParallelism(parallelism) .name("Filter by degree"); // u, v, w where (u, v) and (u, w) are edges in graph, v < w DataSet<Tuple3<K, K, K>> triplets = filteredByDegree .groupBy(0) .sortGroup(1, Order.ASCENDING) .reduceGroup(new GenerateTriplets<>()) .name("Generate triplets"); // u, v, w where (u, v), (u, w), and (v, w) are edges in graph, v < w DataSet<Result<K>> triangles = triplets .join(filteredByID, JoinOperatorBase.JoinHint.REPARTITION_HASH_SECOND) .where(1, 2) .equalTo(0, 1) .with(new ProjectTriangles<>()) .name("Triangle listing"); if (permuteResults) { triangles = triangles .flatMap(new PermuteResult<>()) .name("Permute triangle vertices"); } else if (sortTriangleVertices.get()) { triangles = triangles .map(new SortTriangleVertices<>()) .name("Sort triangle vertices"); } return triangles; }
[ "@", "Override", "public", "DataSet", "<", "Result", "<", "K", ">", ">", "runInternal", "(", "Graph", "<", "K", ",", "VV", ",", "EV", ">", "input", ")", "throws", "Exception", "{", "// u, v where u < v", "DataSet", "<", "Tuple2", "<", "K", ",", "K", ...
/* Implementation notes: The requirement that "K extends CopyableValue<K>" can be removed when Flink has a self-join and GenerateTriplets is implemented as such. ProjectTriangles should eventually be replaced by ".projectFirst("*")" when projections use code generation.
[ "/", "*", "Implementation", "notes", ":" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/library/clustering/undirected/TriangleListing.java#L80-L127
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/JMessageClient.java
JMessageClient.deleteFriends
public ResponseWrapper deleteFriends(String username, String...users) throws APIConnectionException, APIRequestException { return _userClient.deleteFriends(username, users); }
java
public ResponseWrapper deleteFriends(String username, String...users) throws APIConnectionException, APIRequestException { return _userClient.deleteFriends(username, users); }
[ "public", "ResponseWrapper", "deleteFriends", "(", "String", "username", ",", "String", "...", "users", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "return", "_userClient", ".", "deleteFriends", "(", "username", ",", "users", ")", ";", ...
Delete friends @param username Friends you want to delete to @param users username to be delete @return No content @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Delete", "friends" ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/JMessageClient.java#L303-L306
apache/incubator-gobblin
gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/source/extractor/extract/google/GoogleCommon.java
GoogleCommon.newTransport
public static HttpTransport newTransport(String proxyUrl, String portStr) throws NumberFormatException, GeneralSecurityException, IOException { if (!StringUtils.isEmpty(proxyUrl) && !StringUtils.isEmpty(portStr)) { return new NetHttpTransport.Builder() .trustCertificates(GoogleUtils.getCertificateTrustStore()) .setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, Integer.parseInt(portStr)))) .build(); } return GoogleNetHttpTransport.newTrustedTransport(); }
java
public static HttpTransport newTransport(String proxyUrl, String portStr) throws NumberFormatException, GeneralSecurityException, IOException { if (!StringUtils.isEmpty(proxyUrl) && !StringUtils.isEmpty(portStr)) { return new NetHttpTransport.Builder() .trustCertificates(GoogleUtils.getCertificateTrustStore()) .setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, Integer.parseInt(portStr)))) .build(); } return GoogleNetHttpTransport.newTrustedTransport(); }
[ "public", "static", "HttpTransport", "newTransport", "(", "String", "proxyUrl", ",", "String", "portStr", ")", "throws", "NumberFormatException", ",", "GeneralSecurityException", ",", "IOException", "{", "if", "(", "!", "StringUtils", ".", "isEmpty", "(", "proxyUrl"...
Provides HttpTransport. If both proxyUrl and postStr is defined, it provides transport with Proxy. @param proxyUrl Optional. @param portStr Optional. String type for port so that user can easily pass null. (e.g: state.getProp(key)) @return @throws NumberFormatException @throws GeneralSecurityException @throws IOException
[ "Provides", "HttpTransport", ".", "If", "both", "proxyUrl", "and", "postStr", "is", "defined", "it", "provides", "transport", "with", "Proxy", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/source/extractor/extract/google/GoogleCommon.java#L218-L226
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyClient.java
RecurlyClient.getCouponRedemptionsBySubscription
public Redemptions getCouponRedemptionsBySubscription(final String subscriptionUuid, final QueryParams params) { return doGET(Subscription.SUBSCRIPTION_RESOURCE + "/" + subscriptionUuid + Redemptions.REDEMPTIONS_RESOURCE, Redemptions.class, params); }
java
public Redemptions getCouponRedemptionsBySubscription(final String subscriptionUuid, final QueryParams params) { return doGET(Subscription.SUBSCRIPTION_RESOURCE + "/" + subscriptionUuid + Redemptions.REDEMPTIONS_RESOURCE, Redemptions.class, params); }
[ "public", "Redemptions", "getCouponRedemptionsBySubscription", "(", "final", "String", "subscriptionUuid", ",", "final", "QueryParams", "params", ")", "{", "return", "doGET", "(", "Subscription", ".", "SUBSCRIPTION_RESOURCE", "+", "\"/\"", "+", "subscriptionUuid", "+", ...
Lookup all coupon redemptions on a subscription given query params. @param subscriptionUuid String subscription uuid @param params {@link QueryParams} @return the coupon redemptions for this subscription on success, null otherwise
[ "Lookup", "all", "coupon", "redemptions", "on", "a", "subscription", "given", "query", "params", "." ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L1701-L1704
Pkmmte/CircularImageView
circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java
CircularImageView.updateBitmapShader
public void updateBitmapShader() { if (image == null) return; shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) image.getWidth(); matrix.setScale(scale, scale); shader.setLocalMatrix(matrix); } }
java
public void updateBitmapShader() { if (image == null) return; shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) image.getWidth(); matrix.setScale(scale, scale); shader.setLocalMatrix(matrix); } }
[ "public", "void", "updateBitmapShader", "(", ")", "{", "if", "(", "image", "==", "null", ")", "return", ";", "shader", "=", "new", "BitmapShader", "(", "image", ",", "Shader", ".", "TileMode", ".", "CLAMP", ",", "Shader", ".", "TileMode", ".", "CLAMP", ...
Re-initializes the shader texture used to fill in the Circle upon drawing.
[ "Re", "-", "initializes", "the", "shader", "texture", "used", "to", "fill", "in", "the", "Circle", "upon", "drawing", "." ]
train
https://github.com/Pkmmte/CircularImageView/blob/aca59f32d9267c943eb6c930bdaed59c417a4d16/circularimageview/src/main/java/com/pkmmte/view/CircularImageView.java#L428-L440
Erudika/para
para-client/src/main/java/com/erudika/para/client/ParaClient.java
ParaClient.countLinks
@SuppressWarnings("unchecked") public Long countLinks(ParaObject obj, String type2) { if (obj == null || obj.getId() == null || type2 == null) { return 0L; } MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("count", "true"); Pager pager = new Pager(); String url = Utils.formatMessage("{0}/links/{1}", obj.getObjectURI(), type2); getItems((Map<String, Object>) getEntity(invokeGet(url, params), Map.class), pager); return pager.getCount(); }
java
@SuppressWarnings("unchecked") public Long countLinks(ParaObject obj, String type2) { if (obj == null || obj.getId() == null || type2 == null) { return 0L; } MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("count", "true"); Pager pager = new Pager(); String url = Utils.formatMessage("{0}/links/{1}", obj.getObjectURI(), type2); getItems((Map<String, Object>) getEntity(invokeGet(url, params), Map.class), pager); return pager.getCount(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "Long", "countLinks", "(", "ParaObject", "obj", ",", "String", "type2", ")", "{", "if", "(", "obj", "==", "null", "||", "obj", ".", "getId", "(", ")", "==", "null", "||", "type2", "==", "nul...
Count the total number of links between this object and another type of object. @param type2 the other type of object @param obj the object to execute this method on @return the number of links for the given object
[ "Count", "the", "total", "number", "of", "links", "between", "this", "object", "and", "another", "type", "of", "object", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L937-L948
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geodesy/SphereUtil.java
SphereUtil.cosineFormulaRad
public static double cosineFormulaRad(double lat1, double lon1, double lat2, double lon2) { if(lat1 == lat2 && lon1 == lon2) { return 0.; } final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine final double slat1 = sinAndCos(lat1, tmp), clat1 = tmp.value; final double slat2 = sinAndCos(lat2, tmp), clat2 = tmp.value; final double a = slat1 * slat2 + clat1 * clat2 * cos(lon2 - lon1); return a < .9999_9999_9999_999 ? acos(a) : 0; }
java
public static double cosineFormulaRad(double lat1, double lon1, double lat2, double lon2) { if(lat1 == lat2 && lon1 == lon2) { return 0.; } final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine final double slat1 = sinAndCos(lat1, tmp), clat1 = tmp.value; final double slat2 = sinAndCos(lat2, tmp), clat2 = tmp.value; final double a = slat1 * slat2 + clat1 * clat2 * cos(lon2 - lon1); return a < .9999_9999_9999_999 ? acos(a) : 0; }
[ "public", "static", "double", "cosineFormulaRad", "(", "double", "lat1", ",", "double", "lon1", ",", "double", "lat2", ",", "double", "lon2", ")", "{", "if", "(", "lat1", "==", "lat2", "&&", "lon1", "==", "lon2", ")", "{", "return", "0.", ";", "}", "...
Compute the approximate great-circle distance of two points using the Spherical law of cosines. <p> Complexity: 6 trigonometric functions. Note that acos is rather expensive apparently - roughly atan + sqrt. <p> Reference: <p> R. W. Sinnott,<br> Virtues of the Haversine<br> Sky and Telescope 68(2) @param lat1 Latitude of first point in degree @param lon1 Longitude of first point in degree @param lat2 Latitude of second point in degree @param lon2 Longitude of second point in degree @return Distance on unit sphere
[ "Compute", "the", "approximate", "great", "-", "circle", "distance", "of", "two", "points", "using", "the", "Spherical", "law", "of", "cosines", ".", "<p", ">", "Complexity", ":", "6", "trigonometric", "functions", ".", "Note", "that", "acos", "is", "rather"...
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geodesy/SphereUtil.java#L123-L132
javagl/ND
nd-distance/src/main/java/de/javagl/nd/distance/tuples/i/IntTupleDistanceFunctions.java
IntTupleDistanceFunctions.byDistanceComparator
public static Comparator<IntTuple> byDistanceComparator( IntTuple reference, final ToDoubleBiFunction<? super IntTuple, ? super IntTuple> distanceFunction) { final IntTuple fReference = IntTuples.copy(reference); return new Comparator<IntTuple>() { @Override public int compare(IntTuple t0, IntTuple t1) { double d0 = distanceFunction.applyAsDouble(fReference, t0); double d1 = distanceFunction.applyAsDouble(fReference, t1); return Double.compare(d0, d1); } }; }
java
public static Comparator<IntTuple> byDistanceComparator( IntTuple reference, final ToDoubleBiFunction<? super IntTuple, ? super IntTuple> distanceFunction) { final IntTuple fReference = IntTuples.copy(reference); return new Comparator<IntTuple>() { @Override public int compare(IntTuple t0, IntTuple t1) { double d0 = distanceFunction.applyAsDouble(fReference, t0); double d1 = distanceFunction.applyAsDouble(fReference, t1); return Double.compare(d0, d1); } }; }
[ "public", "static", "Comparator", "<", "IntTuple", ">", "byDistanceComparator", "(", "IntTuple", "reference", ",", "final", "ToDoubleBiFunction", "<", "?", "super", "IntTuple", ",", "?", "super", "IntTuple", ">", "distanceFunction", ")", "{", "final", "IntTuple", ...
Returns a new comparator that compares {@link IntTuple} instances by their distance to the given reference, according to the given distance function. A copy of the given reference point will be stored, so that changes in the given point will not affect the returned comparator. @param reference The reference point @param distanceFunction The distance function @return The comparator
[ "Returns", "a", "new", "comparator", "that", "compares", "{", "@link", "IntTuple", "}", "instances", "by", "their", "distance", "to", "the", "given", "reference", "according", "to", "the", "given", "distance", "function", ".", "A", "copy", "of", "the", "give...
train
https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-distance/src/main/java/de/javagl/nd/distance/tuples/i/IntTupleDistanceFunctions.java#L54-L70
cdk/cdk
display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java
StandardAtomGenerator.accessPseudoLabel
static String accessPseudoLabel(IPseudoAtom atom, String defaultLabel) { String label = atom.getLabel(); if (label != null && !label.isEmpty()) return label; return defaultLabel; }
java
static String accessPseudoLabel(IPseudoAtom atom, String defaultLabel) { String label = atom.getLabel(); if (label != null && !label.isEmpty()) return label; return defaultLabel; }
[ "static", "String", "accessPseudoLabel", "(", "IPseudoAtom", "atom", ",", "String", "defaultLabel", ")", "{", "String", "label", "=", "atom", ".", "getLabel", "(", ")", ";", "if", "(", "label", "!=", "null", "&&", "!", "label", ".", "isEmpty", "(", ")", ...
Safely access the label of a pseudo atom. If the label is null or empty, the default label is returned. @param atom the pseudo @return pseudo label
[ "Safely", "access", "the", "label", "of", "a", "pseudo", "atom", ".", "If", "the", "label", "is", "null", "or", "empty", "the", "default", "label", "is", "returned", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java#L614-L618
Whiley/WhileyCompiler
src/main/java/wyc/io/WhileyFileParser.java
WhileyFileParser.parseLogicalNotExpression
private Expr parseLogicalNotExpression(EnclosingScope scope, boolean terminated) { int start = index; match(Shreak); // Note: cannot parse unit expression here, because that messes up the // precedence. For example, !result ==> other should be parsed as // (!result) ==> other, not !(result ==> other). Expr expression = parseConditionExpression(scope, terminated); return annotateSourceLocation(new Expr.LogicalNot(expression), start); }
java
private Expr parseLogicalNotExpression(EnclosingScope scope, boolean terminated) { int start = index; match(Shreak); // Note: cannot parse unit expression here, because that messes up the // precedence. For example, !result ==> other should be parsed as // (!result) ==> other, not !(result ==> other). Expr expression = parseConditionExpression(scope, terminated); return annotateSourceLocation(new Expr.LogicalNot(expression), start); }
[ "private", "Expr", "parseLogicalNotExpression", "(", "EnclosingScope", "scope", ",", "boolean", "terminated", ")", "{", "int", "start", "=", "index", ";", "match", "(", "Shreak", ")", ";", "// Note: cannot parse unit expression here, because that messes up the", "// prece...
Parse a logical not expression, which has the form: <pre> TermExpr::= ... | '!' Expr </pre> @param scope The enclosing scope for this statement, which determines the set of visible (i.e. declared) variables and also the current indentation level. @param terminated This indicates that the expression is known to be terminated (or not). An expression that's known to be terminated is one which is guaranteed to be followed by something. This is important because it means that we can ignore any newline characters encountered in parsing this expression, and that we'll never overrun the end of the expression (i.e. because there's guaranteed to be something which terminates this expression). A classic situation where terminated is true is when parsing an expression surrounded in braces. In such case, we know the right-brace will always terminate this expression. @return
[ "Parse", "a", "logical", "not", "expression", "which", "has", "the", "form", ":" ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L3067-L3075
JodaOrg/joda-money
src/main/java/org/joda/money/BigMoney.java
BigMoney.convertedTo
public BigMoney convertedTo(CurrencyUnit currency, BigDecimal conversionMultipler) { MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); MoneyUtils.checkNotNull(conversionMultipler, "Multiplier must not be null"); if (this.currency == currency) { if (conversionMultipler.compareTo(BigDecimal.ONE) == 0) { return this; } throw new IllegalArgumentException("Cannot convert to the same currency"); } if (conversionMultipler.compareTo(BigDecimal.ZERO) < 0) { throw new IllegalArgumentException("Cannot convert using a negative conversion multiplier"); } BigDecimal newAmount = amount.multiply(conversionMultipler); return BigMoney.of(currency, newAmount); }
java
public BigMoney convertedTo(CurrencyUnit currency, BigDecimal conversionMultipler) { MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); MoneyUtils.checkNotNull(conversionMultipler, "Multiplier must not be null"); if (this.currency == currency) { if (conversionMultipler.compareTo(BigDecimal.ONE) == 0) { return this; } throw new IllegalArgumentException("Cannot convert to the same currency"); } if (conversionMultipler.compareTo(BigDecimal.ZERO) < 0) { throw new IllegalArgumentException("Cannot convert using a negative conversion multiplier"); } BigDecimal newAmount = amount.multiply(conversionMultipler); return BigMoney.of(currency, newAmount); }
[ "public", "BigMoney", "convertedTo", "(", "CurrencyUnit", "currency", ",", "BigDecimal", "conversionMultipler", ")", "{", "MoneyUtils", ".", "checkNotNull", "(", "currency", ",", "\"CurrencyUnit must not be null\"", ")", ";", "MoneyUtils", ".", "checkNotNull", "(", "c...
Returns a copy of this monetary value converted into another currency using the specified conversion rate. <p> The scale of the result will be the sum of the scale of this money and the scale of the multiplier. If desired, the scale of the result can be adjusted to the scale of the new currency using {@link #withCurrencyScale()}. <p> This instance is immutable and unaffected by this method. @param currency the new currency, not null @param conversionMultipler the conversion factor between the currencies, not null @return the new multiplied instance, never null @throws IllegalArgumentException if the currency is the same as this currency and the conversion is not one; or if the conversion multiplier is negative
[ "Returns", "a", "copy", "of", "this", "monetary", "value", "converted", "into", "another", "currency", "using", "the", "specified", "conversion", "rate", ".", "<p", ">", "The", "scale", "of", "the", "result", "will", "be", "the", "sum", "of", "the", "scale...
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L1511-L1525
aws/aws-sdk-java
aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateSimulationApplicationResult.java
CreateSimulationApplicationResult.withTags
public CreateSimulationApplicationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public CreateSimulationApplicationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "CreateSimulationApplicationResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> The list of all tags added to the simulation application. </p> @param tags The list of all tags added to the simulation application. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "list", "of", "all", "tags", "added", "to", "the", "simulation", "application", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateSimulationApplicationResult.java#L512-L515
joniles/mpxj
src/main/java/net/sf/mpxj/Duration.java
Duration.getInstance
public static Duration getInstance(double duration, TimeUnit type) { Duration result; if (duration == 0) { result = ZERO_DURATIONS[type.getValue()]; } else { result = new Duration(duration, type); } return (result); }
java
public static Duration getInstance(double duration, TimeUnit type) { Duration result; if (duration == 0) { result = ZERO_DURATIONS[type.getValue()]; } else { result = new Duration(duration, type); } return (result); }
[ "public", "static", "Duration", "getInstance", "(", "double", "duration", ",", "TimeUnit", "type", ")", "{", "Duration", "result", ";", "if", "(", "duration", "==", "0", ")", "{", "result", "=", "ZERO_DURATIONS", "[", "type", ".", "getValue", "(", ")", "...
Retrieve an Duration instance. Use shared objects to represent common values for memory efficiency. @param duration duration value @param type duration type @return Duration instance
[ "Retrieve", "an", "Duration", "instance", ".", "Use", "shared", "objects", "to", "represent", "common", "values", "for", "memory", "efficiency", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Duration.java#L298-L310
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/protocols/payments/PaymentSession.java
PaymentSession.createFromBitcoinUri
public static ListenableFuture<PaymentSession> createFromBitcoinUri(final BitcoinURI uri) throws PaymentProtocolException { return createFromBitcoinUri(uri, true, null); }
java
public static ListenableFuture<PaymentSession> createFromBitcoinUri(final BitcoinURI uri) throws PaymentProtocolException { return createFromBitcoinUri(uri, true, null); }
[ "public", "static", "ListenableFuture", "<", "PaymentSession", ">", "createFromBitcoinUri", "(", "final", "BitcoinURI", "uri", ")", "throws", "PaymentProtocolException", "{", "return", "createFromBitcoinUri", "(", "uri", ",", "true", ",", "null", ")", ";", "}" ]
<p>Returns a future that will be notified with a PaymentSession object after it is fetched using the provided uri. uri is a BIP-72-style BitcoinURI object that specifies where the {@link Protos.PaymentRequest} object may be fetched in the r= parameter.</p> <p>If the payment request object specifies a PKI method, then the system trust store will be used to verify the signature provided by the payment request. An exception is thrown by the future if the signature cannot be verified.</p>
[ "<p", ">", "Returns", "a", "future", "that", "will", "be", "notified", "with", "a", "PaymentSession", "object", "after", "it", "is", "fetched", "using", "the", "provided", "uri", ".", "uri", "is", "a", "BIP", "-", "72", "-", "style", "BitcoinURI", "objec...
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentSession.java#L93-L95
atomix/atomix
core/src/main/java/io/atomix/core/impl/CoreTransactionService.java
CoreTransactionService.completePreparingTransaction
private void completePreparingTransaction(TransactionId transactionId) { // Change ownership of the transaction to the local node and set its state to ROLLING_BACK and then roll it back. completeTransaction( transactionId, TransactionState.PREPARING, info -> new TransactionInfo(localMemberId, TransactionState.ROLLING_BACK, info.participants), info -> info.state == TransactionState.ROLLING_BACK, (id, transactional) -> transactional.rollback(id)) .whenComplete((result, error) -> { if (error != null) { error = Throwables.getRootCause(error); if (error instanceof TransactionException) { LOGGER.warn("Failed to complete transaction", error); } else { LOGGER.warn("Failed to roll back transaction " + transactionId); } } }); }
java
private void completePreparingTransaction(TransactionId transactionId) { // Change ownership of the transaction to the local node and set its state to ROLLING_BACK and then roll it back. completeTransaction( transactionId, TransactionState.PREPARING, info -> new TransactionInfo(localMemberId, TransactionState.ROLLING_BACK, info.participants), info -> info.state == TransactionState.ROLLING_BACK, (id, transactional) -> transactional.rollback(id)) .whenComplete((result, error) -> { if (error != null) { error = Throwables.getRootCause(error); if (error instanceof TransactionException) { LOGGER.warn("Failed to complete transaction", error); } else { LOGGER.warn("Failed to roll back transaction " + transactionId); } } }); }
[ "private", "void", "completePreparingTransaction", "(", "TransactionId", "transactionId", ")", "{", "// Change ownership of the transaction to the local node and set its state to ROLLING_BACK and then roll it back.", "completeTransaction", "(", "transactionId", ",", "TransactionState", "...
Completes a transaction in the {@link TransactionState#PREPARING} state. @param transactionId the transaction identifier for the transaction to complete
[ "Completes", "a", "transaction", "in", "the", "{", "@link", "TransactionState#PREPARING", "}", "state", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/core/src/main/java/io/atomix/core/impl/CoreTransactionService.java#L233-L251
apereo/cas
support/cas-server-support-memcached-core/src/main/java/org/apereo/cas/memcached/kryo/serial/RegisteredServiceSerializer.java
RegisteredServiceSerializer.readObjectByReflection
@SneakyThrows private static <T> T readObjectByReflection(final Kryo kryo, final Input input, final Class<T> clazz) { val className = kryo.readObject(input, String.class); val foundClass = (Class<T>) Class.forName(className); val result = kryo.readObject(input, foundClass); if (!clazz.isAssignableFrom(result.getClass())) { throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz); } return result; }
java
@SneakyThrows private static <T> T readObjectByReflection(final Kryo kryo, final Input input, final Class<T> clazz) { val className = kryo.readObject(input, String.class); val foundClass = (Class<T>) Class.forName(className); val result = kryo.readObject(input, foundClass); if (!clazz.isAssignableFrom(result.getClass())) { throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz); } return result; }
[ "@", "SneakyThrows", "private", "static", "<", "T", ">", "T", "readObjectByReflection", "(", "final", "Kryo", "kryo", ",", "final", "Input", "input", ",", "final", "Class", "<", "T", ">", "clazz", ")", "{", "val", "className", "=", "kryo", ".", "readObje...
Read object by reflection. @param <T> the type parameter @param kryo the kryo @param input the input @param clazz the clazz @return the t
[ "Read", "object", "by", "reflection", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-memcached-core/src/main/java/org/apereo/cas/memcached/kryo/serial/RegisteredServiceSerializer.java#L75-L87
aaschmid/gradle-cpd-plugin
src/main/java/de/aaschmid/gradle/plugins/cpd/internal/CpdReporter.java
CpdReporter.setTrimLeadingWhitespacesByReflection
private void setTrimLeadingWhitespacesByReflection(Renderer result, boolean trimLeadingCommonSourceWhitespaces) { String fieldName = "trimLeadingWhitespace"; if (logger.isDebugEnabled()) { logger.debug("Try setting '{}' field to '{}' for '{}' by reflection.", fieldName, trimLeadingCommonSourceWhitespaces, result); } try { Field field = SimpleRenderer.class.getDeclaredField(fieldName); field.setAccessible(true); field.set(result, trimLeadingCommonSourceWhitespaces); } catch (Exception e) { if (logger.isWarnEnabled()) { // TODO test if it is really logged? logger.warn(String.format("Could not set field '%s' on created SimpleRenderer by reflection due to:", fieldName), e); } } }
java
private void setTrimLeadingWhitespacesByReflection(Renderer result, boolean trimLeadingCommonSourceWhitespaces) { String fieldName = "trimLeadingWhitespace"; if (logger.isDebugEnabled()) { logger.debug("Try setting '{}' field to '{}' for '{}' by reflection.", fieldName, trimLeadingCommonSourceWhitespaces, result); } try { Field field = SimpleRenderer.class.getDeclaredField(fieldName); field.setAccessible(true); field.set(result, trimLeadingCommonSourceWhitespaces); } catch (Exception e) { if (logger.isWarnEnabled()) { // TODO test if it is really logged? logger.warn(String.format("Could not set field '%s' on created SimpleRenderer by reflection due to:", fieldName), e); } } }
[ "private", "void", "setTrimLeadingWhitespacesByReflection", "(", "Renderer", "result", ",", "boolean", "trimLeadingCommonSourceWhitespaces", ")", "{", "String", "fieldName", "=", "\"trimLeadingWhitespace\"", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")"...
Also set second field to trim leading whitespaces. <p/> <i>Information:</i> Use reflection because neither proper constructor for setting both fields nor setter are available.
[ "Also", "set", "second", "field", "to", "trim", "leading", "whitespaces", ".", "<p", "/", ">", "<i", ">", "Information", ":", "<", "/", "i", ">", "Use", "reflection", "because", "neither", "proper", "constructor", "for", "setting", "both", "fields", "nor",...
train
https://github.com/aaschmid/gradle-cpd-plugin/blob/1cf1b79e0f7fa6eddd5d135a359c90e37b5e90fe/src/main/java/de/aaschmid/gradle/plugins/cpd/internal/CpdReporter.java#L112-L127
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/ReturnValue.java
ReturnValue.withPerformanceData
public ReturnValue withPerformanceData(final Metric metric, IThreshold threshold) { performanceDataList.add(new PerformanceData(metric, threshold.getPrefix(), threshold.getUnitString(), threshold.getRangesAsString(Status.WARNING), threshold.getRangesAsString(Status.CRITICAL))); return this; }
java
public ReturnValue withPerformanceData(final Metric metric, IThreshold threshold) { performanceDataList.add(new PerformanceData(metric, threshold.getPrefix(), threshold.getUnitString(), threshold.getRangesAsString(Status.WARNING), threshold.getRangesAsString(Status.CRITICAL))); return this; }
[ "public", "ReturnValue", "withPerformanceData", "(", "final", "Metric", "metric", ",", "IThreshold", "threshold", ")", "{", "performanceDataList", ".", "add", "(", "new", "PerformanceData", "(", "metric", ",", "threshold", ".", "getPrefix", "(", ")", ",", "thres...
Adds performance data to the plugin result. Thos data will be added to the output formatted as specified in Nagios specifications (http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN201) @param metric The metric relative to this result @param threshold The treshold to be evaluated @return this
[ "Adds", "performance", "data", "to", "the", "plugin", "result", ".", "Thos", "data", "will", "be", "added", "to", "the", "output", "formatted", "as", "specified", "in", "Nagios", "specifications", "(", "http", ":", "//", "nagiosplug", ".", "sourceforge", "."...
train
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/ReturnValue.java#L254-L258
fernandospr/javapns-jdk16
src/main/java/javapns/communication/ProxyManager.java
ProxyManager.setProxy
public static void setProxy(String host, String port) { System.setProperty(LOCAL_PROXY_HOST_PROPERTY, host); System.setProperty(LOCAL_PROXY_PORT_PROPERTY, port); }
java
public static void setProxy(String host, String port) { System.setProperty(LOCAL_PROXY_HOST_PROPERTY, host); System.setProperty(LOCAL_PROXY_PORT_PROPERTY, port); }
[ "public", "static", "void", "setProxy", "(", "String", "host", ",", "String", "port", ")", "{", "System", ".", "setProperty", "(", "LOCAL_PROXY_HOST_PROPERTY", ",", "host", ")", ";", "System", ".", "setProperty", "(", "LOCAL_PROXY_PORT_PROPERTY", ",", "port", ...
Configure a proxy to use for HTTPS connections created by JavaPNS. @param host the proxyHost @param port the proxyPort
[ "Configure", "a", "proxy", "to", "use", "for", "HTTPS", "connections", "created", "by", "JavaPNS", "." ]
train
https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/communication/ProxyManager.java#L27-L30
realexpayments/rxp-hpp-java
src/main/java/com/realexpayments/hpp/sdk/utils/JsonUtils.java
JsonUtils.fromJsonHppRequest
public static HppRequest fromJsonHppRequest(String json) { try { return hppRequestReader.readValue(json); } catch (Exception ex) { LOGGER.error("Error creating HppRequest from JSON.", ex); throw new RealexException("Error creating HppRequest from JSON.", ex); } }
java
public static HppRequest fromJsonHppRequest(String json) { try { return hppRequestReader.readValue(json); } catch (Exception ex) { LOGGER.error("Error creating HppRequest from JSON.", ex); throw new RealexException("Error creating HppRequest from JSON.", ex); } }
[ "public", "static", "HppRequest", "fromJsonHppRequest", "(", "String", "json", ")", "{", "try", "{", "return", "hppRequestReader", ".", "readValue", "(", "json", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOGGER", ".", "error", "(", "\"Erro...
Method deserialises JSON to <code>HppRequest</code>. @param json @return HppRequest
[ "Method", "deserialises", "JSON", "to", "<code", ">", "HppRequest<", "/", "code", ">", "." ]
train
https://github.com/realexpayments/rxp-hpp-java/blob/29cc5df036af09a6d8ea16ccd7e02e856f72620f/src/main/java/com/realexpayments/hpp/sdk/utils/JsonUtils.java#L93-L100
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java
Configuration.getBoolean
public boolean getBoolean(String key, boolean defaultValue) { String val = getStringInternal(key); if (val == null) { return defaultValue; } else { return Boolean.parseBoolean(val); } }
java
public boolean getBoolean(String key, boolean defaultValue) { String val = getStringInternal(key); if (val == null) { return defaultValue; } else { return Boolean.parseBoolean(val); } }
[ "public", "boolean", "getBoolean", "(", "String", "key", ",", "boolean", "defaultValue", ")", "{", "String", "val", "=", "getStringInternal", "(", "key", ")", ";", "if", "(", "val", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "else", "{",...
Returns the value associated with the given key as a boolean. @param key the key pointing to the associated value @param defaultValue the default value which is returned in case there is no value associated with the given key @return the (default) value associated with the given key
[ "Returns", "the", "value", "associated", "with", "the", "given", "key", "as", "a", "boolean", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java#L242-L249
indeedeng/util
io/src/main/java/com/indeed/util/io/Files.java
Files.writeObjectIfChangedOrDie
public static boolean writeObjectIfChangedOrDie(@Nonnull final Object obj, @Nonnull final String file, @Nonnull final Logger log) throws IOException { Preconditions.checkNotNull(log, "log argument is required!"); Preconditions.checkNotNull(file, "file argument is required!"); Preconditions.checkArgument(!file.isEmpty(), "file argument is required!"); // todo: should 'obj' be required? do we ever WANT to write 'null' to an artifact? Preconditions.checkNotNull(obj, "cannot write a 'null' object to file %s", file); // first serialize the object into a byte array, this should almost never fail final IndexableByteArrayOutputStream baos = new IndexableByteArrayOutputStream(524288); { final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(obj); out.close(); baos.close(); } if (isChanged(baos.unsafeByteArrayView(), baos.size(), file)) { // compute the checksum of what we intend on writing to disk final Checksum checksum = new CRC32(); checksum.update(baos.unsafeByteArrayView(), 0, baos.size()); final long checksumForWrittenData = checksum.getValue(); final File targetFile = new File(file); // write object to temporary file that is flushed, fsynced, and closed by the time it returns final File tmpFile = writeDataToTempFileOrDie(new OutputStreamCallback(){ @Override public void writeAndFlushData(@Nonnull OutputStream outputStream) throws IOException { // write the data baos.writeTo(outputStream); // flush it, so that the fsync() has everything it needs outputStream.flush(); } }, targetFile, log); // verify that what we WROTE to the disk is then immediately READABLE before allowing the rename to happen checksum.reset(); final long checksumFound = computeFileChecksum(tmpFile, new CRC32()); if (checksumForWrittenData != checksumFound) { throw new IOException("Data written to file is not what we expected, " + checksumFound + " != " + checksumForWrittenData + ": " + tmpFile); } if (!tmpFile.renameTo(targetFile)) { // failed to atomically rename from temp file to target file, so throw an exception, leaving the filesystem in // a sane state at all times throw new IOException("Could not rename '" + tmpFile + "' to '" + targetFile + "'."); } return true; } else { return false; } }
java
public static boolean writeObjectIfChangedOrDie(@Nonnull final Object obj, @Nonnull final String file, @Nonnull final Logger log) throws IOException { Preconditions.checkNotNull(log, "log argument is required!"); Preconditions.checkNotNull(file, "file argument is required!"); Preconditions.checkArgument(!file.isEmpty(), "file argument is required!"); // todo: should 'obj' be required? do we ever WANT to write 'null' to an artifact? Preconditions.checkNotNull(obj, "cannot write a 'null' object to file %s", file); // first serialize the object into a byte array, this should almost never fail final IndexableByteArrayOutputStream baos = new IndexableByteArrayOutputStream(524288); { final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(obj); out.close(); baos.close(); } if (isChanged(baos.unsafeByteArrayView(), baos.size(), file)) { // compute the checksum of what we intend on writing to disk final Checksum checksum = new CRC32(); checksum.update(baos.unsafeByteArrayView(), 0, baos.size()); final long checksumForWrittenData = checksum.getValue(); final File targetFile = new File(file); // write object to temporary file that is flushed, fsynced, and closed by the time it returns final File tmpFile = writeDataToTempFileOrDie(new OutputStreamCallback(){ @Override public void writeAndFlushData(@Nonnull OutputStream outputStream) throws IOException { // write the data baos.writeTo(outputStream); // flush it, so that the fsync() has everything it needs outputStream.flush(); } }, targetFile, log); // verify that what we WROTE to the disk is then immediately READABLE before allowing the rename to happen checksum.reset(); final long checksumFound = computeFileChecksum(tmpFile, new CRC32()); if (checksumForWrittenData != checksumFound) { throw new IOException("Data written to file is not what we expected, " + checksumFound + " != " + checksumForWrittenData + ": " + tmpFile); } if (!tmpFile.renameTo(targetFile)) { // failed to atomically rename from temp file to target file, so throw an exception, leaving the filesystem in // a sane state at all times throw new IOException("Could not rename '" + tmpFile + "' to '" + targetFile + "'."); } return true; } else { return false; } }
[ "public", "static", "boolean", "writeObjectIfChangedOrDie", "(", "@", "Nonnull", "final", "Object", "obj", ",", "@", "Nonnull", "final", "String", "file", ",", "@", "Nonnull", "final", "Logger", "log", ")", "throws", "IOException", "{", "Preconditions", ".", "...
Writes an object to a file only if it is different from the current contents of the file, or if the file does not exist. Note that you must have enough heap to contain the entire contents of the object graph. @param obj object to write to a file @param file path to save the object to @param log logger to use @return true if the file was actually written, false if the file was unchanged @throws java.io.IOException if the existing file could not be read for comparison, if the existing file could not be erased, or if the new file could not be written, flushed, synced, or closed
[ "Writes", "an", "object", "to", "a", "file", "only", "if", "it", "is", "different", "from", "the", "current", "contents", "of", "the", "file", "or", "if", "the", "file", "does", "not", "exist", ".", "Note", "that", "you", "must", "have", "enough", "hea...
train
https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/io/src/main/java/com/indeed/util/io/Files.java#L269-L323
biojava/biojava
biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java
SequenceScalePanel.drawSequence
protected int drawSequence(Graphics2D g2D, int y){ //g2D.drawString(panelName,10,10); g2D.setColor(SEQUENCE_COLOR); int aminosize = Math.round(1*scale); if ( aminosize < 1) aminosize = 1; // only draw within the ranges of the Clip Rectangle drawHere = g2D.getClipBounds(); int startpos = coordManager.getSeqPos(drawHere.x); //int endpos = coordManager.getSeqPos(drawHere.x+drawHere.width-2); Composite oldComp = g2D.getComposite(); g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.8f)); //logger.info("paint l " + l + " length " + length ); if ( startpos < 0) startpos = 999; if ( scale > SEQUENCE_SHOW){ g2D.setColor(Color.black); //g2D.setColor(SCALE_COLOR); int i = startpos; // display the actual sequence!; for ( int gap = startpos ; gap < apos.size() ;gap++){ int xpos = coordManager.getPanelPos(gap) ; AlignedPosition m = apos.get(gap); if (m.getPos(position) == -1){ // a gap position g2D.drawString("-",xpos+1,y+2+DEFAULT_Y_STEP); continue; } i = m.getPos(position); // TODO: // color amino acids by hydrophobicity g2D.drawString(seqArr[i].toString(),xpos+1,y+2+DEFAULT_Y_STEP); } // in full sequence mode we need abit more space to look nice y+=2; } g2D.setComposite(oldComp); y+= DEFAULT_Y_STEP + 2; return y; }
java
protected int drawSequence(Graphics2D g2D, int y){ //g2D.drawString(panelName,10,10); g2D.setColor(SEQUENCE_COLOR); int aminosize = Math.round(1*scale); if ( aminosize < 1) aminosize = 1; // only draw within the ranges of the Clip Rectangle drawHere = g2D.getClipBounds(); int startpos = coordManager.getSeqPos(drawHere.x); //int endpos = coordManager.getSeqPos(drawHere.x+drawHere.width-2); Composite oldComp = g2D.getComposite(); g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.8f)); //logger.info("paint l " + l + " length " + length ); if ( startpos < 0) startpos = 999; if ( scale > SEQUENCE_SHOW){ g2D.setColor(Color.black); //g2D.setColor(SCALE_COLOR); int i = startpos; // display the actual sequence!; for ( int gap = startpos ; gap < apos.size() ;gap++){ int xpos = coordManager.getPanelPos(gap) ; AlignedPosition m = apos.get(gap); if (m.getPos(position) == -1){ // a gap position g2D.drawString("-",xpos+1,y+2+DEFAULT_Y_STEP); continue; } i = m.getPos(position); // TODO: // color amino acids by hydrophobicity g2D.drawString(seqArr[i].toString(),xpos+1,y+2+DEFAULT_Y_STEP); } // in full sequence mode we need abit more space to look nice y+=2; } g2D.setComposite(oldComp); y+= DEFAULT_Y_STEP + 2; return y; }
[ "protected", "int", "drawSequence", "(", "Graphics2D", "g2D", ",", "int", "y", ")", "{", "//g2D.drawString(panelName,10,10);", "g2D", ".", "setColor", "(", "SEQUENCE_COLOR", ")", ";", "int", "aminosize", "=", "Math", ".", "round", "(", "1", "*", "scale", ")"...
draw the Amino acid sequence @param g2D @param y .. height of line to draw the sequence onto @return the new y value
[ "draw", "the", "Amino", "acid", "sequence" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java#L422-L477
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.postConstructQuietly
public static void postConstructQuietly(Object obj, Logger log) { try { postConstruct(obj, log); } catch( Throwable t ) { log.warn("Could not @PostConstruct object", t); } }
java
public static void postConstructQuietly(Object obj, Logger log) { try { postConstruct(obj, log); } catch( Throwable t ) { log.warn("Could not @PostConstruct object", t); } }
[ "public", "static", "void", "postConstructQuietly", "(", "Object", "obj", ",", "Logger", "log", ")", "{", "try", "{", "postConstruct", "(", "obj", ",", "log", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "log", ".", "warn", "(", "\"Could no...
Calls postConstruct with the same arguments, logging any exceptions that are thrown at the level warn.
[ "Calls", "postConstruct", "with", "the", "same", "arguments", "logging", "any", "exceptions", "that", "are", "thrown", "at", "the", "level", "warn", "." ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L70-L77
kuali/ojb-1.0.4
src/xdoclet/java/src/xdoclet/modules/ojb/constraints/FieldDescriptorConstraints.java
FieldDescriptorConstraints.checkId
private void checkId(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } String id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID); if ((id != null) && (id.length() > 0)) { try { Integer.parseInt(id); } catch (NumberFormatException ex) { throw new ConstraintException("The id attribute of field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" is not a valid number"); } } }
java
private void checkId(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } String id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID); if ((id != null) && (id.length() > 0)) { try { Integer.parseInt(id); } catch (NumberFormatException ex) { throw new ConstraintException("The id attribute of field "+fieldDef.getName()+" in class "+fieldDef.getOwner().getName()+" is not a valid number"); } } }
[ "private", "void", "checkId", "(", "FieldDescriptorDef", "fieldDef", ",", "String", "checkLevel", ")", "throws", "ConstraintException", "{", "if", "(", "CHECKLEVEL_NONE", ".", "equals", "(", "checkLevel", ")", ")", "{", "return", ";", "}", "String", "id", "=",...
Checks the id value. @param fieldDef The field descriptor @param checkLevel The current check level (this constraint is checked in basic and strict) @exception ConstraintException If the constraint has been violated
[ "Checks", "the", "id", "value", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/constraints/FieldDescriptorConstraints.java#L365-L385
finmath/finmath-lib
src/main/java/net/finmath/marketdata/model/bond/Bond.java
Bond.getYield
public double getYield(double bondPrice, AnalyticModel model) { GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0); while(search.getAccuracy() > 1E-11 && !search.isDone()) { double x = search.getNextPoint(); double fx=getValueWithGivenYield(0.0,x,model); double y = (bondPrice-fx)*(bondPrice-fx); search.setValue(y); } return search.getBestPoint(); }
java
public double getYield(double bondPrice, AnalyticModel model) { GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0); while(search.getAccuracy() > 1E-11 && !search.isDone()) { double x = search.getNextPoint(); double fx=getValueWithGivenYield(0.0,x,model); double y = (bondPrice-fx)*(bondPrice-fx); search.setValue(y); } return search.getBestPoint(); }
[ "public", "double", "getYield", "(", "double", "bondPrice", ",", "AnalyticModel", "model", ")", "{", "GoldenSectionSearch", "search", "=", "new", "GoldenSectionSearch", "(", "-", "2.0", ",", "2.0", ")", ";", "while", "(", "search", ".", "getAccuracy", "(", "...
Returns the yield value such that the sum of cash flows of the bond discounted with the yield curve coincides with a given price. @param bondPrice The target price as double. @param model The model under which the product is valued. @return The optimal yield value.
[ "Returns", "the", "yield", "value", "such", "that", "the", "sum", "of", "cash", "flows", "of", "the", "bond", "discounted", "with", "the", "yield", "curve", "coincides", "with", "a", "given", "price", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/bond/Bond.java#L290-L300
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/WaveformFinder.java
WaveformFinder.updatePreview
private void updatePreview(TrackMetadataUpdate update, WaveformPreview preview) { previewHotCache.put(DeckReference.getDeckReference(update.player, 0), preview); // Main deck if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well for (CueList.Entry entry : update.metadata.getCueList().entries) { if (entry.hotCueNumber != 0) { previewHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), preview); } } } deliverWaveformPreviewUpdate(update.player, preview); }
java
private void updatePreview(TrackMetadataUpdate update, WaveformPreview preview) { previewHotCache.put(DeckReference.getDeckReference(update.player, 0), preview); // Main deck if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well for (CueList.Entry entry : update.metadata.getCueList().entries) { if (entry.hotCueNumber != 0) { previewHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), preview); } } } deliverWaveformPreviewUpdate(update.player, preview); }
[ "private", "void", "updatePreview", "(", "TrackMetadataUpdate", "update", ",", "WaveformPreview", "preview", ")", "{", "previewHotCache", ".", "put", "(", "DeckReference", ".", "getDeckReference", "(", "update", ".", "player", ",", "0", ")", ",", "preview", ")",...
We have obtained a waveform preview for a device, so store it and alert any listeners. @param update the update which caused us to retrieve this waveform preview @param preview the waveform preview which we retrieved
[ "We", "have", "obtained", "a", "waveform", "preview", "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/WaveformFinder.java#L283-L293
cvut/JCOP
src/main/java/cz/cvut/felk/cig/jcop/result/render/JFreeChartRender.java
JFreeChartRender.setRangeAxis
public JFreeChartRender setRangeAxis(double lowerBound, double upperBound) { ValueAxis valueAxis = getPlot().getRangeAxis(); valueAxis.setUpperBound(upperBound); valueAxis.setLowerBound(lowerBound); return this; }
java
public JFreeChartRender setRangeAxis(double lowerBound, double upperBound) { ValueAxis valueAxis = getPlot().getRangeAxis(); valueAxis.setUpperBound(upperBound); valueAxis.setLowerBound(lowerBound); return this; }
[ "public", "JFreeChartRender", "setRangeAxis", "(", "double", "lowerBound", ",", "double", "upperBound", ")", "{", "ValueAxis", "valueAxis", "=", "getPlot", "(", ")", ".", "getRangeAxis", "(", ")", ";", "valueAxis", ".", "setUpperBound", "(", "upperBound", ")", ...
Sets bounds for range axis. @param lowerBound lower range bound @param upperBound upper range bound @return itself (fluent interface)
[ "Sets", "bounds", "for", "range", "axis", "." ]
train
https://github.com/cvut/JCOP/blob/2ec18315a9a452e5f4e3d07cccfde0310adc465a/src/main/java/cz/cvut/felk/cig/jcop/result/render/JFreeChartRender.java#L273-L278
trellis-ldp/trellis
components/app/src/main/java/org/trellisldp/app/AbstractTrellisApplication.java
AbstractTrellisApplication.getLdpComponent
protected Object getLdpComponent(final T config, final boolean initialize) { final TrellisHttpResource ldpResource = new TrellisHttpResource(getServiceBundler(), config.getBaseUrl()); if (initialize) { ldpResource.initialize(); } return ldpResource; }
java
protected Object getLdpComponent(final T config, final boolean initialize) { final TrellisHttpResource ldpResource = new TrellisHttpResource(getServiceBundler(), config.getBaseUrl()); if (initialize) { ldpResource.initialize(); } return ldpResource; }
[ "protected", "Object", "getLdpComponent", "(", "final", "T", "config", ",", "final", "boolean", "initialize", ")", "{", "final", "TrellisHttpResource", "ldpResource", "=", "new", "TrellisHttpResource", "(", "getServiceBundler", "(", ")", ",", "config", ".", "getBa...
Get the TrellisHttpResource matcher. @param config the configuration @param initialize true if the TrellisHttpResource object should be initialized; false otherwise @return the LDP resource matcher
[ "Get", "the", "TrellisHttpResource", "matcher", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/app/src/main/java/org/trellisldp/app/AbstractTrellisApplication.java#L84-L90
alkacon/opencms-core
src/org/opencms/staticexport/CmsStaticExportManager.java
CmsStaticExportManager.addRfsRule
public void addRfsRule( String name, String description, String source, String rfsPrefix, String exportPath, String exportWorkPath, String exportBackups, String useRelativeLinks) { if ((m_staticExportPathConfigured != null) && exportPath.equals(m_staticExportPathConfigured)) { m_useTempDirs = false; } Iterator<CmsStaticExportRfsRule> itRules = m_rfsRules.iterator(); while (m_useTempDirs && itRules.hasNext()) { CmsStaticExportRfsRule rule = itRules.next(); if (exportPath.equals(rule.getExportPathConfigured())) { m_useTempDirs = false; } } Boolean relativeLinks = (useRelativeLinks == null ? null : Boolean.valueOf(useRelativeLinks)); Integer backups = (exportBackups == null ? null : Integer.valueOf(exportBackups)); m_rfsRules.add( new CmsStaticExportRfsRule( name, description, source, rfsPrefix, exportPath, exportWorkPath, backups, relativeLinks, m_rfsTmpRule.getRelatedSystemResources())); m_rfsTmpRule = new CmsStaticExportRfsRule("", "", "", "", "", "", null, null); }
java
public void addRfsRule( String name, String description, String source, String rfsPrefix, String exportPath, String exportWorkPath, String exportBackups, String useRelativeLinks) { if ((m_staticExportPathConfigured != null) && exportPath.equals(m_staticExportPathConfigured)) { m_useTempDirs = false; } Iterator<CmsStaticExportRfsRule> itRules = m_rfsRules.iterator(); while (m_useTempDirs && itRules.hasNext()) { CmsStaticExportRfsRule rule = itRules.next(); if (exportPath.equals(rule.getExportPathConfigured())) { m_useTempDirs = false; } } Boolean relativeLinks = (useRelativeLinks == null ? null : Boolean.valueOf(useRelativeLinks)); Integer backups = (exportBackups == null ? null : Integer.valueOf(exportBackups)); m_rfsRules.add( new CmsStaticExportRfsRule( name, description, source, rfsPrefix, exportPath, exportWorkPath, backups, relativeLinks, m_rfsTmpRule.getRelatedSystemResources())); m_rfsTmpRule = new CmsStaticExportRfsRule("", "", "", "", "", "", null, null); }
[ "public", "void", "addRfsRule", "(", "String", "name", ",", "String", "description", ",", "String", "source", ",", "String", "rfsPrefix", ",", "String", "exportPath", ",", "String", "exportWorkPath", ",", "String", "exportBackups", ",", "String", "useRelativeLinks...
Adds a new rfs rule to the configuration.<p> @param name the name of the rule @param description the description for the rule @param source the source regex @param rfsPrefix the url prefix @param exportPath the rfs export path @param exportWorkPath the rfs export work path @param exportBackups the number of backups @param useRelativeLinks the relative links value
[ "Adds", "a", "new", "rfs", "rule", "to", "the", "configuration", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsStaticExportManager.java#L416-L451
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.email_pro_service_account_duration_GET
public OvhOrder email_pro_service_account_duration_GET(String service, String duration, Long number) throws IOException { String qPath = "/order/email/pro/{service}/account/{duration}"; StringBuilder sb = path(qPath, service, duration); query(sb, "number", number); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder email_pro_service_account_duration_GET(String service, String duration, Long number) throws IOException { String qPath = "/order/email/pro/{service}/account/{duration}"; StringBuilder sb = path(qPath, service, duration); query(sb, "number", number); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "email_pro_service_account_duration_GET", "(", "String", "service", ",", "String", "duration", ",", "Long", "number", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/email/pro/{service}/account/{duration}\"", ";", "StringBuilder", ...
Get prices and contracts information REST: GET /order/email/pro/{service}/account/{duration} @param number [required] Number of Accounts to order @param service [required] The internal name of your pro organization @param duration [required] Duration
[ "Get", "prices", "and", "contracts", "information" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L4046-L4052
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRPose.java
GVRPose.calcLocal
protected void calcLocal(Bone bone, int parentId) { if (parentId < 0) { bone.LocalMatrix.set(bone.WorldMatrix); return; } /* * WorldMatrix = WorldMatrix(parent) * LocalMatrix * LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix */ getWorldMatrix(parentId, mTempMtxA); // WorldMatrix(par) mTempMtxA.invert(); // INVERSE[ WorldMatrix(parent) ] mTempMtxA.mul(bone.WorldMatrix, bone.LocalMatrix); // LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix }
java
protected void calcLocal(Bone bone, int parentId) { if (parentId < 0) { bone.LocalMatrix.set(bone.WorldMatrix); return; } /* * WorldMatrix = WorldMatrix(parent) * LocalMatrix * LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix */ getWorldMatrix(parentId, mTempMtxA); // WorldMatrix(par) mTempMtxA.invert(); // INVERSE[ WorldMatrix(parent) ] mTempMtxA.mul(bone.WorldMatrix, bone.LocalMatrix); // LocalMatrix = INVERSE[ WorldMatrix(parent) ] * WorldMatrix }
[ "protected", "void", "calcLocal", "(", "Bone", "bone", ",", "int", "parentId", ")", "{", "if", "(", "parentId", "<", "0", ")", "{", "bone", ".", "LocalMatrix", ".", "set", "(", "bone", ".", "WorldMatrix", ")", ";", "return", ";", "}", "/*\n\t * WorldMa...
Calculates the local translation and rotation for a bone. Assumes WorldRot and WorldPos have been calculated for the bone.
[ "Calculates", "the", "local", "translation", "and", "rotation", "for", "a", "bone", ".", "Assumes", "WorldRot", "and", "WorldPos", "have", "been", "calculated", "for", "the", "bone", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/animation/GVRPose.java#L957-L971
bbossgroups/bboss-elasticsearch
bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/client/ResultUtil.java
ResultUtil.getAggBuckets
public static <T> T getAggBuckets(Map<String,?> map ,String metrics,Class<T> typeReference){ if(map != null) { Map<String, Object> metrics_ = (Map<String, Object>) map.get(metrics); if (metrics_ != null) { return (T) metrics_.get("buckets"); } } return (T)null; }
java
public static <T> T getAggBuckets(Map<String,?> map ,String metrics,Class<T> typeReference){ if(map != null) { Map<String, Object> metrics_ = (Map<String, Object>) map.get(metrics); if (metrics_ != null) { return (T) metrics_.get("buckets"); } } return (T)null; }
[ "public", "static", "<", "T", ">", "T", "getAggBuckets", "(", "Map", "<", "String", ",", "?", ">", "map", ",", "String", "metrics", ",", "Class", "<", "T", ">", "typeReference", ")", "{", "if", "(", "map", "!=", "null", ")", "{", "Map", "<", "Str...
{ "key": "demoproject", "doc_count": 30, "successsums": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": 0, "doc_count": 30 } ] } }, @param map @param metrics successsums->buckets @param typeReference @param <T> @return
[ "{", "key", ":", "demoproject", "doc_count", ":", "30", "successsums", ":", "{", "doc_count_error_upper_bound", ":", "0", "sum_other_doc_count", ":", "0", "buckets", ":", "[", "{", "key", ":", "0", "doc_count", ":", "30", "}", "]", "}", "}" ]
train
https://github.com/bbossgroups/bboss-elasticsearch/blob/31717c8aa2c4c880987be53aeeb8a0cf5183c3a7/bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/client/ResultUtil.java#L694-L702
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.executeConnectionAndWait
public static List<Response> executeConnectionAndWait(HttpURLConnection connection, RequestBatch requests) { List<Response> responses = Response.fromHttpConnection(connection, requests); Utility.disconnectQuietly(connection); int numRequests = requests.size(); if (numRequests != responses.size()) { throw new FacebookException(String.format("Received %d responses while expecting %d", responses.size(), numRequests)); } runCallbacks(requests, responses); // See if any of these sessions needs its token to be extended. We do this after issuing the request so as to // reduce network contention. HashSet<Session> sessions = new HashSet<Session>(); for (Request request : requests) { if (request.session != null) { sessions.add(request.session); } } for (Session session : sessions) { session.extendAccessTokenIfNeeded(); } return responses; }
java
public static List<Response> executeConnectionAndWait(HttpURLConnection connection, RequestBatch requests) { List<Response> responses = Response.fromHttpConnection(connection, requests); Utility.disconnectQuietly(connection); int numRequests = requests.size(); if (numRequests != responses.size()) { throw new FacebookException(String.format("Received %d responses while expecting %d", responses.size(), numRequests)); } runCallbacks(requests, responses); // See if any of these sessions needs its token to be extended. We do this after issuing the request so as to // reduce network contention. HashSet<Session> sessions = new HashSet<Session>(); for (Request request : requests) { if (request.session != null) { sessions.add(request.session); } } for (Session session : sessions) { session.extendAccessTokenIfNeeded(); } return responses; }
[ "public", "static", "List", "<", "Response", ">", "executeConnectionAndWait", "(", "HttpURLConnection", "connection", ",", "RequestBatch", "requests", ")", "{", "List", "<", "Response", ">", "responses", "=", "Response", ".", "fromHttpConnection", "(", "connection",...
Executes requests that have already been serialized into an HttpURLConnection. No validation is done that the contents of the connection actually reflect the serialized requests, so it is the caller's responsibility to ensure that it will correctly generate the desired responses. <p/> This should only be called if you have transitioned off the UI thread. @param connection the HttpURLConnection that the requests were serialized into @param requests the RequestBatch represented by the HttpURLConnection @return a list of Responses corresponding to the requests @throws FacebookException If there was an error in the protocol used to communicate with the service
[ "Executes", "requests", "that", "have", "already", "been", "serialized", "into", "an", "HttpURLConnection", ".", "No", "validation", "is", "done", "that", "the", "contents", "of", "the", "connection", "actually", "reflect", "the", "serialized", "requests", "so", ...
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L1552-L1578
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/lifecycle/LifeCycleController.java
LifeCycleController.createLifecycleCallback
private Application.ActivityLifecycleCallbacks createLifecycleCallback() { return new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { handleOnResume(activity.getApplicationContext()); } @Override public void onActivityPaused(Activity activity) { handleOnPause(activity.getApplicationContext()); } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } }; }
java
private Application.ActivityLifecycleCallbacks createLifecycleCallback() { return new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { handleOnResume(activity.getApplicationContext()); } @Override public void onActivityPaused(Activity activity) { handleOnPause(activity.getApplicationContext()); } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } }; }
[ "private", "Application", ".", "ActivityLifecycleCallbacks", "createLifecycleCallback", "(", ")", "{", "return", "new", "Application", ".", "ActivityLifecycleCallbacks", "(", ")", "{", "@", "Override", "public", "void", "onActivityCreated", "(", "Activity", "activity", ...
Creates {@link Application.ActivityLifecycleCallbacks} listener that will respond to onResume and onPause of any Activity in the application obtaining information if the Application is in the background or foreground. @return Application lifecycle callbacks to be registered on the system by the SDK.
[ "Creates", "{", "@link", "Application", ".", "ActivityLifecycleCallbacks", "}", "listener", "that", "will", "respond", "to", "onResume", "and", "onPause", "of", "any", "Activity", "in", "the", "application", "obtaining", "information", "if", "the", "Application", ...
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/lifecycle/LifeCycleController.java#L96-L134
liuyukuai/commons
commons-core/src/main/java/com/itxiaoer/commons/core/beans/ProcessUtils.java
ProcessUtils.processPage
public static <T, R> PageResponse<R> processPage(Class<R> clazz, PageResponse<T> pageResponse) { return processPage(clazz, pageResponse, (r1, src1) -> { }); }
java
public static <T, R> PageResponse<R> processPage(Class<R> clazz, PageResponse<T> pageResponse) { return processPage(clazz, pageResponse, (r1, src1) -> { }); }
[ "public", "static", "<", "T", ",", "R", ">", "PageResponse", "<", "R", ">", "processPage", "(", "Class", "<", "R", ">", "clazz", ",", "PageResponse", "<", "T", ">", "pageResponse", ")", "{", "return", "processPage", "(", "clazz", ",", "pageResponse", "...
拷贝分页对象 @param clazz 目标类型 @param pageResponse 原对象 @param <T> 原数据类型 @param <R> 目标数据类型 @return 目标对象
[ "拷贝分页对象" ]
train
https://github.com/liuyukuai/commons/blob/ba67eddb542446b12f419f1866dbaa82e47fbf35/commons-core/src/main/java/com/itxiaoer/commons/core/beans/ProcessUtils.java#L156-L159
soi-toolkit/soi-toolkit-mule
tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/cli/util/OptionSet.java
OptionSet.addOption
public OptionSet addOption(String key, Options.Multiplicity multiplicity) { return addOption(key, false, Options.Separator.NONE, false, multiplicity); }
java
public OptionSet addOption(String key, Options.Multiplicity multiplicity) { return addOption(key, false, Options.Separator.NONE, false, multiplicity); }
[ "public", "OptionSet", "addOption", "(", "String", "key", ",", "Options", ".", "Multiplicity", "multiplicity", ")", "{", "return", "addOption", "(", "key", ",", "false", ",", "Options", ".", "Separator", ".", "NONE", ",", "false", ",", "multiplicity", ")", ...
Add a non-value option with the given key and multiplicity, and the default prefix <p> @param key The key for the option @param multiplicity The multiplicity for the option <p> @return The set instance itself (to support invocation chaining for <code>addOption()</code> methods) <p> @throws IllegalArgumentException If the <code>key</code> is <code>null</code> or a key with this name has already been defined or if <code>multiplicity</code> is <code>null</code>
[ "Add", "a", "non", "-", "value", "option", "with", "the", "given", "key", "and", "multiplicity", "and", "the", "default", "prefix", "<p", ">" ]
train
https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/tools/soitoolkit-generator/soitoolkit-generator/src/main/java/org/soitoolkit/tools/generator/cli/util/OptionSet.java#L192-L194
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/cache/document/WritableSessionCache.java
WritableSessionCache.completeTransaction
private void completeTransaction(final String txId, String wsName) { getWorkspace().clear(); // reset the ws cache to the shared (global one) setWorkspaceCache(sharedWorkspaceCache()); // and clear some tx specific data COMPLETE_FUNCTION_BY_TX_AND_WS.compute(txId, (transactionId, funcsByWsName) -> { funcsByWsName.remove(wsName); if (funcsByWsName.isEmpty()) { // this is the last ws cache we are clearing for this tx so mark all the keys as unlocked LOCKED_KEYS_BY_TX_ID.remove(txId); // and remove the map return null; } // there are other ws caches which need clearing for this tx, so just return the updated map return funcsByWsName; }); }
java
private void completeTransaction(final String txId, String wsName) { getWorkspace().clear(); // reset the ws cache to the shared (global one) setWorkspaceCache(sharedWorkspaceCache()); // and clear some tx specific data COMPLETE_FUNCTION_BY_TX_AND_WS.compute(txId, (transactionId, funcsByWsName) -> { funcsByWsName.remove(wsName); if (funcsByWsName.isEmpty()) { // this is the last ws cache we are clearing for this tx so mark all the keys as unlocked LOCKED_KEYS_BY_TX_ID.remove(txId); // and remove the map return null; } // there are other ws caches which need clearing for this tx, so just return the updated map return funcsByWsName; }); }
[ "private", "void", "completeTransaction", "(", "final", "String", "txId", ",", "String", "wsName", ")", "{", "getWorkspace", "(", ")", ".", "clear", "(", ")", ";", "// reset the ws cache to the shared (global one)", "setWorkspaceCache", "(", "sharedWorkspaceCache", "(...
Signal that the transaction that was active and in which this session participated has completed and that this session should no longer use a transaction-specific workspace cache.
[ "Signal", "that", "the", "transaction", "that", "was", "active", "and", "in", "which", "this", "session", "participated", "has", "completed", "and", "that", "this", "session", "should", "no", "longer", "use", "a", "transaction", "-", "specific", "workspace", "...
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/cache/document/WritableSessionCache.java#L440-L456
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java
SimpleDocTreeVisitor.visitParam
@Override public R visitParam(ParamTree node, P p) { return defaultAction(node, p); }
java
@Override public R visitParam(ParamTree node, P p) { return defaultAction(node, p); }
[ "@", "Override", "public", "R", "visitParam", "(", "ParamTree", "node", ",", "P", "p", ")", "{", "return", "defaultAction", "(", "node", ",", "p", ")", ";", "}" ]
{@inheritDoc} This implementation calls {@code defaultAction}. @param node {@inheritDoc} @param p {@inheritDoc} @return the result of {@code defaultAction}
[ "{", "@inheritDoc", "}", "This", "implementation", "calls", "{", "@code", "defaultAction", "}", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java#L285-L288
molgenis/molgenis
molgenis-util/src/main/java/org/molgenis/util/file/ZipFileUtil.java
ZipFileUtil.unzipSkipHidden
public static List<File> unzipSkipHidden(File file) { return unzip(file, name -> name.startsWith(".") || name.startsWith("_") ? null : name); }
java
public static List<File> unzipSkipHidden(File file) { return unzip(file, name -> name.startsWith(".") || name.startsWith("_") ? null : name); }
[ "public", "static", "List", "<", "File", ">", "unzipSkipHidden", "(", "File", "file", ")", "{", "return", "unzip", "(", "file", ",", "name", "->", "name", ".", "startsWith", "(", "\".\"", ")", "||", "name", ".", "startsWith", "(", "\"_\"", ")", "?", ...
Unzips a zipfile into the directory it resides in. Skips paths starting with '.' or '_' (typically hidden paths). @param file the file to unzip @return List of Files that got extracted @throws UnzipException if something went wrong
[ "Unzips", "a", "zipfile", "into", "the", "directory", "it", "resides", "in", ".", "Skips", "paths", "starting", "with", ".", "or", "_", "(", "typically", "hidden", "paths", ")", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-util/src/main/java/org/molgenis/util/file/ZipFileUtil.java#L33-L35
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java
DatatypeConverter.getUUID
public static final UUID getUUID(InputStream is) throws IOException { byte[] data = new byte[16]; is.read(data); long long1 = 0; long1 |= ((long) (data[3] & 0xFF)) << 56; long1 |= ((long) (data[2] & 0xFF)) << 48; long1 |= ((long) (data[1] & 0xFF)) << 40; long1 |= ((long) (data[0] & 0xFF)) << 32; long1 |= ((long) (data[5] & 0xFF)) << 24; long1 |= ((long) (data[4] & 0xFF)) << 16; long1 |= ((long) (data[7] & 0xFF)) << 8; long1 |= ((long) (data[6] & 0xFF)) << 0; long long2 = 0; long2 |= ((long) (data[8] & 0xFF)) << 56; long2 |= ((long) (data[9] & 0xFF)) << 48; long2 |= ((long) (data[10] & 0xFF)) << 40; long2 |= ((long) (data[11] & 0xFF)) << 32; long2 |= ((long) (data[12] & 0xFF)) << 24; long2 |= ((long) (data[13] & 0xFF)) << 16; long2 |= ((long) (data[14] & 0xFF)) << 8; long2 |= ((long) (data[15] & 0xFF)) << 0; return new UUID(long1, long2); }
java
public static final UUID getUUID(InputStream is) throws IOException { byte[] data = new byte[16]; is.read(data); long long1 = 0; long1 |= ((long) (data[3] & 0xFF)) << 56; long1 |= ((long) (data[2] & 0xFF)) << 48; long1 |= ((long) (data[1] & 0xFF)) << 40; long1 |= ((long) (data[0] & 0xFF)) << 32; long1 |= ((long) (data[5] & 0xFF)) << 24; long1 |= ((long) (data[4] & 0xFF)) << 16; long1 |= ((long) (data[7] & 0xFF)) << 8; long1 |= ((long) (data[6] & 0xFF)) << 0; long long2 = 0; long2 |= ((long) (data[8] & 0xFF)) << 56; long2 |= ((long) (data[9] & 0xFF)) << 48; long2 |= ((long) (data[10] & 0xFF)) << 40; long2 |= ((long) (data[11] & 0xFF)) << 32; long2 |= ((long) (data[12] & 0xFF)) << 24; long2 |= ((long) (data[13] & 0xFF)) << 16; long2 |= ((long) (data[14] & 0xFF)) << 8; long2 |= ((long) (data[15] & 0xFF)) << 0; return new UUID(long1, long2); }
[ "public", "static", "final", "UUID", "getUUID", "(", "InputStream", "is", ")", "throws", "IOException", "{", "byte", "[", "]", "data", "=", "new", "byte", "[", "16", "]", ";", "is", ".", "read", "(", "data", ")", ";", "long", "long1", "=", "0", ";"...
Retrieve a UUID from an input stream. @param is input stream @return UUID instance
[ "Retrieve", "a", "UUID", "from", "an", "input", "stream", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java#L235-L261
VoltDB/voltdb
src/frontend/org/voltdb/client/ClientStats.java
ClientStats.latencyHistoReport
public String latencyHistoReport() { ByteArrayOutputStream baos= new ByteArrayOutputStream(); PrintStream pw = null; try { pw = new PrintStream(baos, false, Charsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { Throwables.propagate(e); } //Get a latency report in milliseconds m_latencyHistogram.outputPercentileDistributionVolt(pw, 1, 1000.0); return new String(baos.toByteArray(), Charsets.UTF_8); }
java
public String latencyHistoReport() { ByteArrayOutputStream baos= new ByteArrayOutputStream(); PrintStream pw = null; try { pw = new PrintStream(baos, false, Charsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { Throwables.propagate(e); } //Get a latency report in milliseconds m_latencyHistogram.outputPercentileDistributionVolt(pw, 1, 1000.0); return new String(baos.toByteArray(), Charsets.UTF_8); }
[ "public", "String", "latencyHistoReport", "(", ")", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "PrintStream", "pw", "=", "null", ";", "try", "{", "pw", "=", "new", "PrintStream", "(", "baos", ",", "false", ",", ...
Generate a human-readable report of latencies in the form of a histogram. Latency is in milliseconds @return String containing human-readable report.
[ "Generate", "a", "human", "-", "readable", "report", "of", "latencies", "in", "the", "form", "of", "a", "histogram", ".", "Latency", "is", "in", "milliseconds" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/ClientStats.java#L499-L512
ravendb/ravendb-jvm-client
src/main/java/net/ravendb/client/documents/subscriptions/DocumentSubscriptions.java
DocumentSubscriptions.getSubscriptions
public List<SubscriptionState> getSubscriptions(int start, int take, String database) { RequestExecutor requestExecutor = _store.getRequestExecutor(ObjectUtils.firstNonNull(database, _store.getDatabase())); GetSubscriptionsCommand command = new GetSubscriptionsCommand(start, take); requestExecutor.execute(command); return Arrays.asList(command.getResult()); }
java
public List<SubscriptionState> getSubscriptions(int start, int take, String database) { RequestExecutor requestExecutor = _store.getRequestExecutor(ObjectUtils.firstNonNull(database, _store.getDatabase())); GetSubscriptionsCommand command = new GetSubscriptionsCommand(start, take); requestExecutor.execute(command); return Arrays.asList(command.getResult()); }
[ "public", "List", "<", "SubscriptionState", ">", "getSubscriptions", "(", "int", "start", ",", "int", "take", ",", "String", "database", ")", "{", "RequestExecutor", "requestExecutor", "=", "_store", ".", "getRequestExecutor", "(", "ObjectUtils", ".", "firstNonNul...
It downloads a list of all existing subscriptions in a database. @param start Range start @param take Maximum number of items that will be retrieved @param database Database to use @return List of subscriptions state
[ "It", "downloads", "a", "list", "of", "all", "existing", "subscriptions", "in", "a", "database", "." ]
train
https://github.com/ravendb/ravendb-jvm-client/blob/5a45727de507b541d1571e79ddd97c7d88bee787/src/main/java/net/ravendb/client/documents/subscriptions/DocumentSubscriptions.java#L355-L362
apache/flink
flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/PatternStream.java
PatternStream.flatSelect
public <R> SingleOutputStreamOperator<R> flatSelect(final PatternFlatSelectFunction<T, R> patternFlatSelectFunction) { // we have to extract the output type from the provided pattern selection function manually // because the TypeExtractor cannot do that if the method is wrapped in a MapFunction final TypeInformation<R> outTypeInfo = TypeExtractor.getUnaryOperatorReturnType( patternFlatSelectFunction, PatternFlatSelectFunction.class, 0, 1, new int[]{1, 0}, builder.getInputType(), null, false); return flatSelect(patternFlatSelectFunction, outTypeInfo); }
java
public <R> SingleOutputStreamOperator<R> flatSelect(final PatternFlatSelectFunction<T, R> patternFlatSelectFunction) { // we have to extract the output type from the provided pattern selection function manually // because the TypeExtractor cannot do that if the method is wrapped in a MapFunction final TypeInformation<R> outTypeInfo = TypeExtractor.getUnaryOperatorReturnType( patternFlatSelectFunction, PatternFlatSelectFunction.class, 0, 1, new int[]{1, 0}, builder.getInputType(), null, false); return flatSelect(patternFlatSelectFunction, outTypeInfo); }
[ "public", "<", "R", ">", "SingleOutputStreamOperator", "<", "R", ">", "flatSelect", "(", "final", "PatternFlatSelectFunction", "<", "T", ",", "R", ">", "patternFlatSelectFunction", ")", "{", "// we have to extract the output type from the provided pattern selection function m...
Applies a flat select function to the detected pattern sequence. For each pattern sequence the provided {@link PatternFlatSelectFunction} is called. The pattern flat select function can produce an arbitrary number of resulting elements. @param patternFlatSelectFunction The pattern flat select function which is called for each detected pattern sequence. @param <R> Type of the resulting elements @return {@link DataStream} which contains the resulting elements from the pattern flat select function.
[ "Applies", "a", "flat", "select", "function", "to", "the", "detected", "pattern", "sequence", ".", "For", "each", "pattern", "sequence", "the", "provided", "{", "@link", "PatternFlatSelectFunction", "}", "is", "called", ".", "The", "pattern", "flat", "select", ...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/PatternStream.java#L329-L344
banq/jdonframework
src/main/java/com/jdon/container/pico/JdonInstantiatingComponentAdapter.java
JdonInstantiatingComponentAdapter.newInstance
protected Object newInstance(Constructor constructor, Object[] parameters) throws InstantiationException, IllegalAccessException, InvocationTargetException { if (allowNonPublicClasses) { constructor.setAccessible(true); } return constructor.newInstance(parameters); }
java
protected Object newInstance(Constructor constructor, Object[] parameters) throws InstantiationException, IllegalAccessException, InvocationTargetException { if (allowNonPublicClasses) { constructor.setAccessible(true); } return constructor.newInstance(parameters); }
[ "protected", "Object", "newInstance", "(", "Constructor", "constructor", ",", "Object", "[", "]", "parameters", ")", "throws", "InstantiationException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "if", "(", "allowNonPublicClasses", ")", "{", ...
Instantiate an object with given parameters and respect the accessible flag. @param constructor the constructor to use @param parameters the parameters for the constructor @return the new object. @throws InstantiationException @throws IllegalAccessException @throws InvocationTargetException
[ "Instantiate", "an", "object", "with", "given", "parameters", "and", "respect", "the", "accessible", "flag", "." ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/pico/JdonInstantiatingComponentAdapter.java#L212-L218
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java
ComputeNodesImpl.getRemoteLoginSettings
public ComputeNodeGetRemoteLoginSettingsResult getRemoteLoginSettings(String poolId, String nodeId) { return getRemoteLoginSettingsWithServiceResponseAsync(poolId, nodeId).toBlocking().single().body(); }
java
public ComputeNodeGetRemoteLoginSettingsResult getRemoteLoginSettings(String poolId, String nodeId) { return getRemoteLoginSettingsWithServiceResponseAsync(poolId, nodeId).toBlocking().single().body(); }
[ "public", "ComputeNodeGetRemoteLoginSettingsResult", "getRemoteLoginSettings", "(", "String", "poolId", ",", "String", "nodeId", ")", "{", "return", "getRemoteLoginSettingsWithServiceResponseAsync", "(", "poolId", ",", "nodeId", ")", ".", "toBlocking", "(", ")", ".", "s...
Gets the settings required for remote login to a compute node. Before you can remotely login to a node using the remote login settings, you must create a user account on the node. This API can be invoked only on pools created with the virtual machine configuration property. For pools created with a cloud service configuration, see the GetRemoteDesktop API. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the compute node for which to obtain the remote login settings. @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ComputeNodeGetRemoteLoginSettingsResult object if successful.
[ "Gets", "the", "settings", "required", "for", "remote", "login", "to", "a", "compute", "node", ".", "Before", "you", "can", "remotely", "login", "to", "a", "node", "using", "the", "remote", "login", "settings", "you", "must", "create", "a", "user", "accoun...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/ComputeNodesImpl.java#L1929-L1931
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java
ShapeGenerator.addScrollGapPath
private void addScrollGapPath(int x, int y, int w, int h, boolean isAtLeft) { final double hHalf = h / 2.0; final double wFull = isAtLeft ? w : 0; final double wHalfOff = isAtLeft ? w - hHalf : hHalf; path.quadTo(x + wHalfOff, y + h, x + wHalfOff, y + hHalf); path.quadTo(x + wHalfOff, y, x + wFull, y); }
java
private void addScrollGapPath(int x, int y, int w, int h, boolean isAtLeft) { final double hHalf = h / 2.0; final double wFull = isAtLeft ? w : 0; final double wHalfOff = isAtLeft ? w - hHalf : hHalf; path.quadTo(x + wHalfOff, y + h, x + wHalfOff, y + hHalf); path.quadTo(x + wHalfOff, y, x + wFull, y); }
[ "private", "void", "addScrollGapPath", "(", "int", "x", ",", "int", "y", ",", "int", "w", ",", "int", "h", ",", "boolean", "isAtLeft", ")", "{", "final", "double", "hHalf", "=", "h", "/", "2.0", ";", "final", "double", "wFull", "=", "isAtLeft", "?", ...
Adds a hemispherical section to the current path. This is used to create the gap in a scroll bar button or cap into which the scroll bar thumb will fit. @param x the X coordinate of the upper-left corner of the button or cap @param y the Y coordinate of the upper-left corner of the button or cap @param w the width of the button or cap @param h the height of the button or cap @param isAtLeft {@code true} if the gap is at the left end of the button, {@code false} if it is at the right.
[ "Adds", "a", "hemispherical", "section", "to", "the", "current", "path", ".", "This", "is", "used", "to", "create", "the", "gap", "in", "a", "scroll", "bar", "button", "or", "cap", "into", "which", "the", "scroll", "bar", "thumb", "will", "fit", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/util/ShapeGenerator.java#L730-L737
xiancloud/xian
xian-zookeeper/xian-curator/xian-curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatch.java
LeaderLatch.await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { long waitNanos = TimeUnit.NANOSECONDS.convert(timeout, unit); synchronized(this) { while ( (waitNanos > 0) && (state.get() == State.STARTED) && !hasLeadership.get() ) { long startNanos = System.nanoTime(); TimeUnit.NANOSECONDS.timedWait(this, waitNanos); long elapsed = System.nanoTime() - startNanos; waitNanos -= elapsed; } } return hasLeadership(); }
java
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { long waitNanos = TimeUnit.NANOSECONDS.convert(timeout, unit); synchronized(this) { while ( (waitNanos > 0) && (state.get() == State.STARTED) && !hasLeadership.get() ) { long startNanos = System.nanoTime(); TimeUnit.NANOSECONDS.timedWait(this, waitNanos); long elapsed = System.nanoTime() - startNanos; waitNanos -= elapsed; } } return hasLeadership(); }
[ "public", "boolean", "await", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "InterruptedException", "{", "long", "waitNanos", "=", "TimeUnit", ".", "NANOSECONDS", ".", "convert", "(", "timeout", ",", "unit", ")", ";", "synchronized", "(", "...
<p>Causes the current thread to wait until this instance acquires leadership unless the thread is {@linkplain Thread#interrupt interrupted}, the specified waiting time elapses or the instance is {@linkplain #close() closed}.</p> <p></p> <p>If this instance already is the leader then this method returns immediately with the value {@code true}.</p> <p></p> <p>Otherwise the current thread becomes disabled for thread scheduling purposes and lies dormant until one of four things happen:</p> <ul> <li>This instance becomes the leader</li> <li>Some other thread {@linkplain Thread#interrupt interrupts} the current thread</li> <li>The specified waiting time elapses.</li> <li>The instance is {@linkplain #close() closed}</li> </ul> <p></p> <p>If the current thread:</p> <ul> <li>has its interrupted status set on entry to this method; or <li>is {@linkplain Thread#interrupt interrupted} while waiting, </ul> <p>then {@link InterruptedException} is thrown and the current thread's interrupted status is cleared.</p> <p></p> <p>If the specified waiting time elapses or the instance is {@linkplain #close() closed} then the value {@code false} is returned. If the time is less than or equal to zero, the method will not wait at all.</p> @param timeout the maximum time to wait @param unit the time unit of the {@code timeout} argument @return {@code true} if the count reached zero and {@code false} if the waiting time elapsed before the count reached zero or the instances was closed @throws InterruptedException if the current thread is interrupted while waiting
[ "<p", ">", "Causes", "the", "current", "thread", "to", "wait", "until", "this", "instance", "acquires", "leadership", "unless", "the", "thread", "is", "{", "@linkplain", "Thread#interrupt", "interrupted", "}", "the", "specified", "waiting", "time", "elapses", "o...
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatch.java#L376-L391
apache/incubator-gobblin
gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/orc/HiveOrcSerDeManager.java
HiveOrcSerDeManager.isORC
private static boolean isORC(Path file, FileSystem fs) throws IOException { try { FSDataInputStream inputStream = fs.open(file); long size = fs.getFileStatus(file).getLen(); byte[] buffer = new byte[Math.toIntExact(Math.min(size, EXPECTED_FOOTER_SIZE))]; if (size < buffer.length) { return false; } inputStream.readFully(size - buffer.length, buffer); // get length of PostScript - last byte of the file int postScriptSize = buffer[buffer.length - 1] & 0xff; int magicLen = MAGIC_BUFFER.remaining(); if (postScriptSize < magicLen + 1 || postScriptSize >= buffer.length) { return false; } if (!MAGIC_BUFFER.equals(ByteBuffer.wrap(buffer, buffer.length - 1 - magicLen, magicLen))) { // Old versions of ORC (0.11) wrote the magic to the head of the file byte[] headerMagic = new byte[magicLen]; inputStream.readFully(0, headerMagic); // if it isn't there, this isn't an ORC file if (!MAGIC_BUFFER.equals(ByteBuffer.wrap(headerMagic))) { return false; } } return true; } catch (Exception e) { throw new RuntimeException("Error occured when checking the type of file:" + file); } }
java
private static boolean isORC(Path file, FileSystem fs) throws IOException { try { FSDataInputStream inputStream = fs.open(file); long size = fs.getFileStatus(file).getLen(); byte[] buffer = new byte[Math.toIntExact(Math.min(size, EXPECTED_FOOTER_SIZE))]; if (size < buffer.length) { return false; } inputStream.readFully(size - buffer.length, buffer); // get length of PostScript - last byte of the file int postScriptSize = buffer[buffer.length - 1] & 0xff; int magicLen = MAGIC_BUFFER.remaining(); if (postScriptSize < magicLen + 1 || postScriptSize >= buffer.length) { return false; } if (!MAGIC_BUFFER.equals(ByteBuffer.wrap(buffer, buffer.length - 1 - magicLen, magicLen))) { // Old versions of ORC (0.11) wrote the magic to the head of the file byte[] headerMagic = new byte[magicLen]; inputStream.readFully(0, headerMagic); // if it isn't there, this isn't an ORC file if (!MAGIC_BUFFER.equals(ByteBuffer.wrap(headerMagic))) { return false; } } return true; } catch (Exception e) { throw new RuntimeException("Error occured when checking the type of file:" + file); } }
[ "private", "static", "boolean", "isORC", "(", "Path", "file", ",", "FileSystem", "fs", ")", "throws", "IOException", "{", "try", "{", "FSDataInputStream", "inputStream", "=", "fs", ".", "open", "(", "file", ")", ";", "long", "size", "=", "fs", ".", "getF...
Determine if a file is ORC format. Steal ideas & code from presto/OrcReader under Apache License 2.0.
[ "Determine", "if", "a", "file", "is", "ORC", "format", ".", "Steal", "ideas", "&", "code", "from", "presto", "/", "OrcReader", "under", "Apache", "License", "2", ".", "0", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/orc/HiveOrcSerDeManager.java#L203-L238
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/ws/tcpchannel/internal/FilterListSlowStr.java
FilterListSlowStr.findInList
private boolean findInList(String[] address, int index, FilterCellSlowStr cell, int endIndex) { if (cell.getWildcardCell() != null) { // a wildcard, match found return true; } // no wildcard so far, see if there is a still a path FilterCellSlowStr nextCell = cell.findNextCell(address[index]); if (nextCell != null) { // see if we are at the end of a valid path if (index == endIndex) { // this path found a match, unwind returning true return true; } // ok so far, recursively search this path return findInList(address, index + 1, nextCell, endIndex); } // this path did not find a match. return false; }
java
private boolean findInList(String[] address, int index, FilterCellSlowStr cell, int endIndex) { if (cell.getWildcardCell() != null) { // a wildcard, match found return true; } // no wildcard so far, see if there is a still a path FilterCellSlowStr nextCell = cell.findNextCell(address[index]); if (nextCell != null) { // see if we are at the end of a valid path if (index == endIndex) { // this path found a match, unwind returning true return true; } // ok so far, recursively search this path return findInList(address, index + 1, nextCell, endIndex); } // this path did not find a match. return false; }
[ "private", "boolean", "findInList", "(", "String", "[", "]", "address", ",", "int", "index", ",", "FilterCellSlowStr", "cell", ",", "int", "endIndex", ")", "{", "if", "(", "cell", ".", "getWildcardCell", "(", ")", "!=", "null", ")", "{", "// a wildcard, ma...
Determine, recursively, if an address is in the address tree. @param address address to look for as a string array. The 0th index of the array is the rightmost substring of the string and so on. Each substring is the chars between two periods (".") in a URL address. @param index the next index in the address array to match against the tree. @param cell the current cell in the tree that we are matching against @param endIndex the last index in the address array that we need to match @return true if this address is found in the address tree, false if it is not.
[ "Determine", "recursively", "if", "an", "address", "is", "in", "the", "address", "tree", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/tcpchannel/internal/FilterListSlowStr.java#L191-L210
mercadopago/dx-java
src/main/java/com/mercadopago/core/MPBase.java
MPBase.getStandardHeaders
private static Collection<Header> getStandardHeaders() { Collection<Header> colHeaders = new Vector<Header>(); colHeaders.add(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); colHeaders.add(new BasicHeader(HTTP.USER_AGENT, "MercadoPago Java SDK/1.0.10")); colHeaders.add(new BasicHeader("x-product-id", "BC32A7VTRPP001U8NHJ0")); return colHeaders; }
java
private static Collection<Header> getStandardHeaders() { Collection<Header> colHeaders = new Vector<Header>(); colHeaders.add(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); colHeaders.add(new BasicHeader(HTTP.USER_AGENT, "MercadoPago Java SDK/1.0.10")); colHeaders.add(new BasicHeader("x-product-id", "BC32A7VTRPP001U8NHJ0")); return colHeaders; }
[ "private", "static", "Collection", "<", "Header", ">", "getStandardHeaders", "(", ")", "{", "Collection", "<", "Header", ">", "colHeaders", "=", "new", "Vector", "<", "Header", ">", "(", ")", ";", "colHeaders", ".", "add", "(", "new", "BasicHeader", "(", ...
Returns standard headers for all the requests @return a collection with headers objects
[ "Returns", "standard", "headers", "for", "all", "the", "requests" ]
train
https://github.com/mercadopago/dx-java/blob/9df65a6bfb4db0c1fddd7699a5b109643961b03f/src/main/java/com/mercadopago/core/MPBase.java#L435-L441
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/text/FieldPosition.java
FieldPosition.matchesField
private boolean matchesField(Format.Field attribute, int field) { if (this.attribute != null) { return this.attribute.equals(attribute); } return (field == this.field); }
java
private boolean matchesField(Format.Field attribute, int field) { if (this.attribute != null) { return this.attribute.equals(attribute); } return (field == this.field); }
[ "private", "boolean", "matchesField", "(", "Format", ".", "Field", "attribute", ",", "int", "field", ")", "{", "if", "(", "this", ".", "attribute", "!=", "null", ")", "{", "return", "this", ".", "attribute", ".", "equals", "(", "attribute", ")", ";", "...
Return true if the receiver wants a <code>Format.Field</code> value and <code>attribute</code> is equal to it, or true if the receiver represents an inteter constant and <code>field</code> equals it.
[ "Return", "true", "if", "the", "receiver", "wants", "a", "<code", ">", "Format", ".", "Field<", "/", "code", ">", "value", "and", "<code", ">", "attribute<", "/", "code", ">", "is", "equal", "to", "it", "or", "true", "if", "the", "receiver", "represent...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/text/FieldPosition.java#L264-L269
autermann/yaml
src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java
YamlMappingNode.put
public T put(YamlNode key, Long value) { return put(key, getNodeFactory().longNode(value)); }
java
public T put(YamlNode key, Long value) { return put(key, getNodeFactory().longNode(value)); }
[ "public", "T", "put", "(", "YamlNode", "key", ",", "Long", "value", ")", "{", "return", "put", "(", "key", ",", "getNodeFactory", "(", ")", ".", "longNode", "(", "value", ")", ")", ";", "}" ]
Adds the specified {@code key}/{@code value} pair to this mapping. @param key the key @param value the value @return {@code this}
[ "Adds", "the", "specified", "{", "@code", "key", "}", "/", "{", "@code", "value", "}", "pair", "to", "this", "mapping", "." ]
train
https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java#L540-L542
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/util/OgnlUtil.java
OgnlUtil.getValue
public static Object getValue(Object exp, Object root) { return getValue(exp, root, null, 0); }
java
public static Object getValue(Object exp, Object root) { return getValue(exp, root, null, 0); }
[ "public", "static", "Object", "getValue", "(", "Object", "exp", ",", "Object", "root", ")", "{", "return", "getValue", "(", "exp", ",", "root", ",", "null", ",", "0", ")", ";", "}" ]
Returns the value using the OGNL expression and the root object. @param exp the OGNL expression @param root the root object @return the value @see #getValue(Object, Map, Object, String, int)
[ "Returns", "the", "value", "using", "the", "OGNL", "expression", "and", "the", "root", "object", "." ]
train
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/util/OgnlUtil.java#L48-L50
line/armeria
core/src/main/java/com/linecorp/armeria/server/streaming/JsonTextSequences.java
JsonTextSequences.fromStream
public static HttpResponse fromStream(Stream<?> contentStream, Executor executor, ObjectMapper mapper) { return fromStream(defaultHttpHeaders, contentStream, HttpHeaders.EMPTY_HEADERS, executor, mapper); }
java
public static HttpResponse fromStream(Stream<?> contentStream, Executor executor, ObjectMapper mapper) { return fromStream(defaultHttpHeaders, contentStream, HttpHeaders.EMPTY_HEADERS, executor, mapper); }
[ "public", "static", "HttpResponse", "fromStream", "(", "Stream", "<", "?", ">", "contentStream", ",", "Executor", "executor", ",", "ObjectMapper", "mapper", ")", "{", "return", "fromStream", "(", "defaultHttpHeaders", ",", "contentStream", ",", "HttpHeaders", ".",...
Creates a new JSON Text Sequences from the specified {@link Stream}. @param contentStream the {@link Stream} which publishes the objects supposed to send as contents @param executor the executor which iterates the stream
[ "Creates", "a", "new", "JSON", "Text", "Sequences", "from", "the", "specified", "{", "@link", "Stream", "}", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/streaming/JsonTextSequences.java#L166-L169
hazelcast/hazelcast
hazelcast-client/src/main/java/com/hazelcast/client/cache/impl/ClientCacheHelper.java
ClientCacheHelper.getCacheConfig
static <K, V> CacheConfig<K, V> getCacheConfig(HazelcastClientInstanceImpl client, String cacheName, String simpleCacheName) { ClientMessage request = CacheGetConfigCodec.encodeRequest(cacheName, simpleCacheName); try { int partitionId = client.getClientPartitionService().getPartitionId(cacheName); ClientInvocation clientInvocation = new ClientInvocation(client, request, cacheName, partitionId); Future<ClientMessage> future = clientInvocation.invoke(); ClientMessage responseMessage = future.get(); SerializationService serializationService = client.getSerializationService(); return deserializeCacheConfig(client, responseMessage, serializationService, clientInvocation); } catch (Exception e) { throw rethrow(e); } }
java
static <K, V> CacheConfig<K, V> getCacheConfig(HazelcastClientInstanceImpl client, String cacheName, String simpleCacheName) { ClientMessage request = CacheGetConfigCodec.encodeRequest(cacheName, simpleCacheName); try { int partitionId = client.getClientPartitionService().getPartitionId(cacheName); ClientInvocation clientInvocation = new ClientInvocation(client, request, cacheName, partitionId); Future<ClientMessage> future = clientInvocation.invoke(); ClientMessage responseMessage = future.get(); SerializationService serializationService = client.getSerializationService(); return deserializeCacheConfig(client, responseMessage, serializationService, clientInvocation); } catch (Exception e) { throw rethrow(e); } }
[ "static", "<", "K", ",", "V", ">", "CacheConfig", "<", "K", ",", "V", ">", "getCacheConfig", "(", "HazelcastClientInstanceImpl", "client", ",", "String", "cacheName", ",", "String", "simpleCacheName", ")", "{", "ClientMessage", "request", "=", "CacheGetConfigCod...
Gets the cache configuration from the server. @param client the client instance which will send the operation to server @param cacheName full cache name with prefixes @param simpleCacheName pure cache name without any prefix @param <K> type of the key of the cache @param <V> type of the value of the cache @return the cache configuration if it can be found
[ "Gets", "the", "cache", "configuration", "from", "the", "server", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast-client/src/main/java/com/hazelcast/client/cache/impl/ClientCacheHelper.java#L68-L82
xiancloud/xian
xian-gateway/src/main/java/info/xiancloud/gateway/access_token_validation/ValidateAccessToken.java
ValidateAccessToken.fetchAccessTokenAndReturnScope
private static Single<Optional<String>> fetchAccessTokenAndReturnScope(UnitRequest request) { LOG.info("fetchAccessTokenAndReturnScope"); String ip = request.getContext().getIp(); if (StringUtil.isEmpty(ip)) { throw new IllegalArgumentException("Client's ip is empty, please check!"); } if (isWhiteIp(ip)) { LOG.info(new JSONObject().fluentPut("type", LogTypeGateway.whiteIp) .fluentPut("description", "request is from white ip " + ip) .fluentPut("ip", ip)); return Single.just(Optional.of(Scope.api_all)); } String accessToken = request.getContext().getHeader() == null ? null : request.getContext().getHeader().getOrDefault(Constant.XIAN_REQUEST_TOKEN_HEADER, null); if (StringUtil.isEmpty(accessToken)) { return Single.just(Optional.empty()); } else { return forToken(accessToken).map(optionalAccessToken -> { if (optionalAccessToken.isPresent()) { request.getContext().setAccessToken(optionalAccessToken.get()); return Optional.of(optionalAccessToken.get().getScope()); } else { return Optional.empty(); } }); } }
java
private static Single<Optional<String>> fetchAccessTokenAndReturnScope(UnitRequest request) { LOG.info("fetchAccessTokenAndReturnScope"); String ip = request.getContext().getIp(); if (StringUtil.isEmpty(ip)) { throw new IllegalArgumentException("Client's ip is empty, please check!"); } if (isWhiteIp(ip)) { LOG.info(new JSONObject().fluentPut("type", LogTypeGateway.whiteIp) .fluentPut("description", "request is from white ip " + ip) .fluentPut("ip", ip)); return Single.just(Optional.of(Scope.api_all)); } String accessToken = request.getContext().getHeader() == null ? null : request.getContext().getHeader().getOrDefault(Constant.XIAN_REQUEST_TOKEN_HEADER, null); if (StringUtil.isEmpty(accessToken)) { return Single.just(Optional.empty()); } else { return forToken(accessToken).map(optionalAccessToken -> { if (optionalAccessToken.isPresent()) { request.getContext().setAccessToken(optionalAccessToken.get()); return Optional.of(optionalAccessToken.get().getScope()); } else { return Optional.empty(); } }); } }
[ "private", "static", "Single", "<", "Optional", "<", "String", ">", ">", "fetchAccessTokenAndReturnScope", "(", "UnitRequest", "request", ")", "{", "LOG", ".", "info", "(", "\"fetchAccessTokenAndReturnScope\"", ")", ";", "String", "ip", "=", "request", ".", "get...
query for access token info and set it into the request context and return the scope of current token. @return the scope of the request or empty if no token string is provided.
[ "query", "for", "access", "token", "info", "and", "set", "it", "into", "the", "request", "context", "and", "return", "the", "scope", "of", "current", "token", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-gateway/src/main/java/info/xiancloud/gateway/access_token_validation/ValidateAccessToken.java#L75-L101
intive-FDV/DynamicJasper
src/main/java/ar/com/fdvs/dj/domain/builders/DynamicReportBuilder.java
DynamicReportBuilder.setWhenNoData
public DynamicReportBuilder setWhenNoData(String text, Style style, boolean showTitle, boolean showColumnHeader) { this.report.setWhenNoDataStyle(style); this.report.setWhenNoDataText(text); this.report.setWhenNoDataType(DJConstants.WHEN_NO_DATA_TYPE_NO_DATA_SECTION); this.report.setWhenNoDataShowColumnHeader(showColumnHeader); this.report.setWhenNoDataShowTitle(showTitle); return this; }
java
public DynamicReportBuilder setWhenNoData(String text, Style style, boolean showTitle, boolean showColumnHeader) { this.report.setWhenNoDataStyle(style); this.report.setWhenNoDataText(text); this.report.setWhenNoDataType(DJConstants.WHEN_NO_DATA_TYPE_NO_DATA_SECTION); this.report.setWhenNoDataShowColumnHeader(showColumnHeader); this.report.setWhenNoDataShowTitle(showTitle); return this; }
[ "public", "DynamicReportBuilder", "setWhenNoData", "(", "String", "text", ",", "Style", "style", ",", "boolean", "showTitle", ",", "boolean", "showColumnHeader", ")", "{", "this", ".", "report", ".", "setWhenNoDataStyle", "(", "style", ")", ";", "this", ".", "...
Defines the text to show when the data source is empty.<br> @param text @param style : the style of the text @param showTitle : if true, the title is shown @param showColumnHeader : if true, the column headers are shown @return A Dynamic Report Builder
[ "Defines", "the", "text", "to", "show", "when", "the", "data", "source", "is", "empty", ".", "<br", ">" ]
train
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/domain/builders/DynamicReportBuilder.java#L1542-L1549
kiegroup/droolsjbpm-integration
kie-server-parent/kie-server-common/src/main/java/org/kie/server/common/rest/KieServerHttpRequest.java
KieServerHttpRequest.basicAuthorization
public KieServerHttpRequest basicAuthorization(final String name, final String password ) { return header(AUTHORIZATION, "Basic " + org.kie.server.common.rest.Base64Util.encode(name + ':' + password)); }
java
public KieServerHttpRequest basicAuthorization(final String name, final String password ) { return header(AUTHORIZATION, "Basic " + org.kie.server.common.rest.Base64Util.encode(name + ':' + password)); }
[ "public", "KieServerHttpRequest", "basicAuthorization", "(", "final", "String", "name", ",", "final", "String", "password", ")", "{", "return", "header", "(", "AUTHORIZATION", ",", "\"Basic \"", "+", "org", ".", "kie", ".", "server", ".", "common", ".", "rest"...
Set the 'Authorization' header to given values in Basic authentication format @param name @param password @return this request
[ "Set", "the", "Authorization", "header", "to", "given", "values", "in", "Basic", "authentication", "format" ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-common/src/main/java/org/kie/server/common/rest/KieServerHttpRequest.java#L1040-L1042
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_ipLoadbalancing_id_validate_POST
public void project_serviceName_ipLoadbalancing_id_validate_POST(String serviceName, String id) throws IOException { String qPath = "/cloud/project/{serviceName}/ipLoadbalancing/{id}/validate"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "POST", sb.toString(), null); }
java
public void project_serviceName_ipLoadbalancing_id_validate_POST(String serviceName, String id) throws IOException { String qPath = "/cloud/project/{serviceName}/ipLoadbalancing/{id}/validate"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "POST", sb.toString(), null); }
[ "public", "void", "project_serviceName_ipLoadbalancing_id_validate_POST", "(", "String", "serviceName", ",", "String", "id", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/ipLoadbalancing/{id}/validate\"", ";", "StringBuilder", "sb", ...
Validate the import of your load balancing IP into OpenStack REST: POST /cloud/project/{serviceName}/ipLoadbalancing/{id}/validate @param serviceName [required] The project id @param id [required] ID of your load balancing ip import API beta
[ "Validate", "the", "import", "of", "your", "load", "balancing", "IP", "into", "OpenStack" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1611-L1615
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java
MapKeyLoader.startInitialLoad
public Future startInitialLoad(MapStoreContext mapStoreContext, int partitionId) { this.partitionId = partitionId; this.mapNamePartition = partitionService.getPartitionId(toData.apply(mapName)); Role newRole = calculateRole(); role.nextOrStay(newRole); state.next(State.LOADING); if (logger.isFinestEnabled()) { logger.finest("startInitialLoad invoked " + getStateMessage()); } switch (newRole) { case SENDER: return sendKeys(mapStoreContext, false); case SENDER_BACKUP: case RECEIVER: return triggerLoading(); default: return keyLoadFinished; } }
java
public Future startInitialLoad(MapStoreContext mapStoreContext, int partitionId) { this.partitionId = partitionId; this.mapNamePartition = partitionService.getPartitionId(toData.apply(mapName)); Role newRole = calculateRole(); role.nextOrStay(newRole); state.next(State.LOADING); if (logger.isFinestEnabled()) { logger.finest("startInitialLoad invoked " + getStateMessage()); } switch (newRole) { case SENDER: return sendKeys(mapStoreContext, false); case SENDER_BACKUP: case RECEIVER: return triggerLoading(); default: return keyLoadFinished; } }
[ "public", "Future", "startInitialLoad", "(", "MapStoreContext", "mapStoreContext", ",", "int", "partitionId", ")", "{", "this", ".", "partitionId", "=", "partitionId", ";", "this", ".", "mapNamePartition", "=", "partitionService", ".", "getPartitionId", "(", "toData...
Triggers key loading on the map key loader with the {@link Role#SENDER} role. @param mapStoreContext the map store context for this map @param partitionId the partition ID of this map key loader @return a future representing pending completion of the key loading task
[ "Triggers", "key", "loading", "on", "the", "map", "key", "loader", "with", "the", "{", "@link", "Role#SENDER", "}", "role", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/map/impl/MapKeyLoader.java#L184-L205
atomix/copycat
server/src/main/java/io/atomix/copycat/server/state/ServerStateMachine.java
ServerStateMachine.suspectSessions
private void suspectSessions(long exclude, long timestamp) { for (ServerSessionContext session : executor.context().sessions().sessions.values()) { if (session.id() != exclude && timestamp - session.timeout() > session.getTimestamp()) { session.suspect(); } } }
java
private void suspectSessions(long exclude, long timestamp) { for (ServerSessionContext session : executor.context().sessions().sessions.values()) { if (session.id() != exclude && timestamp - session.timeout() > session.getTimestamp()) { session.suspect(); } } }
[ "private", "void", "suspectSessions", "(", "long", "exclude", ",", "long", "timestamp", ")", "{", "for", "(", "ServerSessionContext", "session", ":", "executor", ".", "context", "(", ")", ".", "sessions", "(", ")", ".", "sessions", ".", "values", "(", ")",...
Marked as suspicious any sessions that have timed out according to the given timestamp. <p> Sessions are marked suspicious instead of being expired since log cleaning can result in large gaps in time between entries in the log. Thus, once log compaction has occurred, it's possible that a session could be marked expired when in fact its keep alive entries were simply compacted from the log. Forcing the leader to expire sessions ensures that keep alives are not missed with regard to session expiration.
[ "Marked", "as", "suspicious", "any", "sessions", "that", "have", "timed", "out", "according", "to", "the", "given", "timestamp", ".", "<p", ">", "Sessions", "are", "marked", "suspicious", "instead", "of", "being", "expired", "since", "log", "cleaning", "can", ...
train
https://github.com/atomix/copycat/blob/c90b88ccd5c63d6ea0b49fb77c25e2f3272a7b10/server/src/main/java/io/atomix/copycat/server/state/ServerStateMachine.java#L976-L982
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.leftShift
public static OffsetDateTime leftShift(final ZoneOffset self, LocalDateTime dateTime) { return OffsetDateTime.of(dateTime, self); }
java
public static OffsetDateTime leftShift(final ZoneOffset self, LocalDateTime dateTime) { return OffsetDateTime.of(dateTime, self); }
[ "public", "static", "OffsetDateTime", "leftShift", "(", "final", "ZoneOffset", "self", ",", "LocalDateTime", "dateTime", ")", "{", "return", "OffsetDateTime", ".", "of", "(", "dateTime", ",", "self", ")", ";", "}" ]
Returns an {@link java.time.OffsetDateTime} of this offset and the provided {@link java.time.LocalDateTime}. @param self a ZoneOffset @param dateTime a LocalDateTime @return an OffsetDateTime @since 2.5.0
[ "Returns", "an", "{", "@link", "java", ".", "time", ".", "OffsetDateTime", "}", "of", "this", "offset", "and", "the", "provided", "{", "@link", "java", ".", "time", ".", "LocalDateTime", "}", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L1954-L1956
leancloud/java-sdk-all
android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/game/FloatWindowApi.java
FloatWindowApi.showFinal
private void showFinal(boolean show, Activity activity, HuaweiApiClient client) { // 保存当前浮标显示状态,以便出现异常浮标消失后,能够恢复 isCurFloatShow = show; Activity curActivity = activity!=null ? activity : ActivityMgr.INST.getLastActivity(); // 取得当前 activity 用于展示浮标 if (curActivity == null) { HMSAgentLog.e("activity is null"); return; } if (show) { if (client == null || !client.isConnected()) { HMSAgentLog.e("client is invalid"); ApiClientMgr.INST.connect(new EmptyConnectCallback("try connect end when show float:"), false); return; } HMSAgentLog.d("show begin"); PendingResult<ShowFloatWindowResult> pendingRst = HuaweiGame.HuaweiGameApi.showFloatWindow(client, curActivity); pendingRst.setResultCallback(new ShowFloatWindowCallBack()); } else { HMSAgentLog.d("hide"); HuaweiGame.HuaweiGameApi.hideFloatWindow(client, curActivity); } }
java
private void showFinal(boolean show, Activity activity, HuaweiApiClient client) { // 保存当前浮标显示状态,以便出现异常浮标消失后,能够恢复 isCurFloatShow = show; Activity curActivity = activity!=null ? activity : ActivityMgr.INST.getLastActivity(); // 取得当前 activity 用于展示浮标 if (curActivity == null) { HMSAgentLog.e("activity is null"); return; } if (show) { if (client == null || !client.isConnected()) { HMSAgentLog.e("client is invalid"); ApiClientMgr.INST.connect(new EmptyConnectCallback("try connect end when show float:"), false); return; } HMSAgentLog.d("show begin"); PendingResult<ShowFloatWindowResult> pendingRst = HuaweiGame.HuaweiGameApi.showFloatWindow(client, curActivity); pendingRst.setResultCallback(new ShowFloatWindowCallBack()); } else { HMSAgentLog.d("hide"); HuaweiGame.HuaweiGameApi.hideFloatWindow(client, curActivity); } }
[ "private", "void", "showFinal", "(", "boolean", "show", ",", "Activity", "activity", ",", "HuaweiApiClient", "client", ")", "{", "// 保存当前浮标显示状态,以便出现异常浮标消失后,能够恢复\r", "isCurFloatShow", "=", "show", ";", "Activity", "curActivity", "=", "activity", "!=", "null", "?", ...
最终调用接口显示/隐藏浮标 @param show 是否显示浮标 @param activity 当前界面的activity @param client HuaweiApiClient实例
[ "最终调用接口显示", "/", "隐藏浮标" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/android-sdk/huawei-hmsagent/src/main/java/com/huawei/android/hms/agent/game/FloatWindowApi.java#L102-L129
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.location_pccZone_hostProfile_id_GET
public OvhHostProfile location_pccZone_hostProfile_id_GET(String pccZone, Long id) throws IOException { String qPath = "/dedicatedCloud/location/{pccZone}/hostProfile/{id}"; StringBuilder sb = path(qPath, pccZone, id); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhHostProfile.class); }
java
public OvhHostProfile location_pccZone_hostProfile_id_GET(String pccZone, Long id) throws IOException { String qPath = "/dedicatedCloud/location/{pccZone}/hostProfile/{id}"; StringBuilder sb = path(qPath, pccZone, id); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhHostProfile.class); }
[ "public", "OvhHostProfile", "location_pccZone_hostProfile_id_GET", "(", "String", "pccZone", ",", "Long", "id", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/location/{pccZone}/hostProfile/{id}\"", ";", "StringBuilder", "sb", "=", "path", "...
Get this object properties REST: GET /dedicatedCloud/location/{pccZone}/hostProfile/{id} @param pccZone [required] Name of pccZone @param id [required] Id of Host profile
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L3008-L3013
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java
ReflectUtil.getFieldValue
public static Object getFieldValue(Object obj, Field field) throws UtilException { if (null == obj || null == field) { return null; } field.setAccessible(true); Object result = null; try { result = field.get(obj); } catch (IllegalAccessException e) { throw new UtilException(e, "IllegalAccess for {}.{}", obj.getClass(), field.getName()); } return result; }
java
public static Object getFieldValue(Object obj, Field field) throws UtilException { if (null == obj || null == field) { return null; } field.setAccessible(true); Object result = null; try { result = field.get(obj); } catch (IllegalAccessException e) { throw new UtilException(e, "IllegalAccess for {}.{}", obj.getClass(), field.getName()); } return result; }
[ "public", "static", "Object", "getFieldValue", "(", "Object", "obj", ",", "Field", "field", ")", "throws", "UtilException", "{", "if", "(", "null", "==", "obj", "||", "null", "==", "field", ")", "{", "return", "null", ";", "}", "field", ".", "setAccessib...
获取字段值 @param obj 对象 @param field 字段 @return 字段值 @throws UtilException 包装IllegalAccessException异常
[ "获取字段值" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java#L194-L206
apereo/cas
support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/builders/enc/validate/SamlObjectSignatureValidator.java
SamlObjectSignatureValidator.buildEntityCriteriaForSigningCredential
protected void buildEntityCriteriaForSigningCredential(final RequestAbstractType profileRequest, final CriteriaSet criteriaSet) { criteriaSet.add(new EntityIdCriterion(SamlIdPUtils.getIssuerFromSamlObject(profileRequest))); criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)); }
java
protected void buildEntityCriteriaForSigningCredential(final RequestAbstractType profileRequest, final CriteriaSet criteriaSet) { criteriaSet.add(new EntityIdCriterion(SamlIdPUtils.getIssuerFromSamlObject(profileRequest))); criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)); }
[ "protected", "void", "buildEntityCriteriaForSigningCredential", "(", "final", "RequestAbstractType", "profileRequest", ",", "final", "CriteriaSet", "criteriaSet", ")", "{", "criteriaSet", ".", "add", "(", "new", "EntityIdCriterion", "(", "SamlIdPUtils", ".", "getIssuerFro...
Build entity criteria for signing credential. @param profileRequest the profile request @param criteriaSet the criteria set
[ "Build", "entity", "criteria", "for", "signing", "credential", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/builders/enc/validate/SamlObjectSignatureValidator.java#L266-L269
biojava/biojava
biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java
LinearColorInterpolator.setColorSpace
public void setColorSpace(ColorSpace colorSpace, InterpolationDirection[] dir) { if(dir.length < colorSpace.getNumComponents()) { throw new IllegalArgumentException( "Must specify an interpolation " + "direction for each colorspace component ("+colorSpace.getNumComponents()+")"); } this.colorSpace = colorSpace; this.interpolationDirection = dir; }
java
public void setColorSpace(ColorSpace colorSpace, InterpolationDirection[] dir) { if(dir.length < colorSpace.getNumComponents()) { throw new IllegalArgumentException( "Must specify an interpolation " + "direction for each colorspace component ("+colorSpace.getNumComponents()+")"); } this.colorSpace = colorSpace; this.interpolationDirection = dir; }
[ "public", "void", "setColorSpace", "(", "ColorSpace", "colorSpace", ",", "InterpolationDirection", "[", "]", "dir", ")", "{", "if", "(", "dir", ".", "length", "<", "colorSpace", ".", "getNumComponents", "(", ")", ")", "{", "throw", "new", "IllegalArgumentExcep...
Sets the ColorSpace to use for interpolation. The most common scheme for color spaces is to use linear components between 0 and 1 (for instance red,green,blue). For such a component, a linear interpolation between two colors is used. Sometimes a component may be in cylindrical coordinates. In this case, the component can be mapped in a number of ways. These are set by InterpolationDirections. @param colorSpace The color space for interpolation @param interpDirection An array of size colorSpace.getNumComponents() giving the interpolation direction for each component.
[ "Sets", "the", "ColorSpace", "to", "use", "for", "interpolation", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java#L148-L155
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java
CPInstancePersistenceImpl.findByC_C
@Override public CPInstance findByC_C(long CPDefinitionId, String CPInstanceUuid) throws NoSuchCPInstanceException { CPInstance cpInstance = fetchByC_C(CPDefinitionId, CPInstanceUuid); if (cpInstance == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("CPDefinitionId="); msg.append(CPDefinitionId); msg.append(", CPInstanceUuid="); msg.append(CPInstanceUuid); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPInstanceException(msg.toString()); } return cpInstance; }
java
@Override public CPInstance findByC_C(long CPDefinitionId, String CPInstanceUuid) throws NoSuchCPInstanceException { CPInstance cpInstance = fetchByC_C(CPDefinitionId, CPInstanceUuid); if (cpInstance == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("CPDefinitionId="); msg.append(CPDefinitionId); msg.append(", CPInstanceUuid="); msg.append(CPInstanceUuid); msg.append("}"); if (_log.isDebugEnabled()) { _log.debug(msg.toString()); } throw new NoSuchCPInstanceException(msg.toString()); } return cpInstance; }
[ "@", "Override", "public", "CPInstance", "findByC_C", "(", "long", "CPDefinitionId", ",", "String", "CPInstanceUuid", ")", "throws", "NoSuchCPInstanceException", "{", "CPInstance", "cpInstance", "=", "fetchByC_C", "(", "CPDefinitionId", ",", "CPInstanceUuid", ")", ";"...
Returns the cp instance where CPDefinitionId = &#63; and CPInstanceUuid = &#63; or throws a {@link NoSuchCPInstanceException} if it could not be found. @param CPDefinitionId the cp definition ID @param CPInstanceUuid the cp instance uuid @return the matching cp instance @throws NoSuchCPInstanceException if a matching cp instance could not be found
[ "Returns", "the", "cp", "instance", "where", "CPDefinitionId", "=", "&#63", ";", "and", "CPInstanceUuid", "=", "&#63", ";", "or", "throws", "a", "{", "@link", "NoSuchCPInstanceException", "}", "if", "it", "could", "not", "be", "found", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java#L4086-L4112
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java
Resolve.findImmediateMemberType
Symbol findImmediateMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { for (Symbol sym : c.members().getSymbolsByName(name)) { if (sym.kind == TYP) { return isAccessible(env, site, sym) ? sym : new AccessError(env, site, sym); } } return typeNotFound; }
java
Symbol findImmediateMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { for (Symbol sym : c.members().getSymbolsByName(name)) { if (sym.kind == TYP) { return isAccessible(env, site, sym) ? sym : new AccessError(env, site, sym); } } return typeNotFound; }
[ "Symbol", "findImmediateMemberType", "(", "Env", "<", "AttrContext", ">", "env", ",", "Type", "site", ",", "Name", "name", ",", "TypeSymbol", "c", ")", "{", "for", "(", "Symbol", "sym", ":", "c", ".", "members", "(", ")", ".", "getSymbolsByName", "(", ...
Find a type declared in a scope (not inherited). Return null if none is found. @param env The current environment. @param site The original type from where the selection takes place. @param name The type's name. @param c The class to search for the member type. This is always a superclass or implemented interface of site's class.
[ "Find", "a", "type", "declared", "in", "a", "scope", "(", "not", "inherited", ")", ".", "Return", "null", "if", "none", "is", "found", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L2164-L2176
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/UtilZip.java
UtilZip.getEntriesByExtension
public static Collection<ZipEntry> getEntriesByExtension(File jar, String path, String extension) { Check.notNull(jar); Check.notNull(path); Check.notNull(extension); try (ZipFile zip = new ZipFile(jar)) { return checkEntries(zip, path, extension); } catch (final IOException exception) { throw new LionEngineException(exception, ERROR_OPEN_ZIP + jar.getAbsolutePath()); } }
java
public static Collection<ZipEntry> getEntriesByExtension(File jar, String path, String extension) { Check.notNull(jar); Check.notNull(path); Check.notNull(extension); try (ZipFile zip = new ZipFile(jar)) { return checkEntries(zip, path, extension); } catch (final IOException exception) { throw new LionEngineException(exception, ERROR_OPEN_ZIP + jar.getAbsolutePath()); } }
[ "public", "static", "Collection", "<", "ZipEntry", ">", "getEntriesByExtension", "(", "File", "jar", ",", "String", "path", ",", "String", "extension", ")", "{", "Check", ".", "notNull", "(", "jar", ")", ";", "Check", ".", "notNull", "(", "path", ")", ";...
Get all entries existing in the path considering the extension. @param jar The JAR to check (must not be <code>null</code>). @param path The path to check (must not be <code>null</code>). @param extension The extension without dot; eg: xml (must not be <code>null</code>). @return The entries list. @throws LionEngineException If invalid arguments or unable to open ZIP.
[ "Get", "all", "entries", "existing", "in", "the", "path", "considering", "the", "extension", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/UtilZip.java#L48-L62
burberius/eve-esi
src/main/java/net/troja/eve/esi/auth/OAuth.java
OAuth.finishFlow
public void finishFlow(final String code, final String state) throws ApiException { if (account == null) throw new IllegalArgumentException("Auth is not set"); if (codeVerifier == null) throw new IllegalArgumentException("code_verifier is not set"); if (account.getClientId() == null) throw new IllegalArgumentException("client_id is not set"); StringBuilder builder = new StringBuilder(); builder.append("grant_type="); builder.append(encode("authorization_code")); builder.append("&client_id="); builder.append(encode(account.getClientId())); builder.append("&code="); builder.append(encode(code)); builder.append("&code_verifier="); builder.append(encode(codeVerifier)); update(account, builder.toString()); }
java
public void finishFlow(final String code, final String state) throws ApiException { if (account == null) throw new IllegalArgumentException("Auth is not set"); if (codeVerifier == null) throw new IllegalArgumentException("code_verifier is not set"); if (account.getClientId() == null) throw new IllegalArgumentException("client_id is not set"); StringBuilder builder = new StringBuilder(); builder.append("grant_type="); builder.append(encode("authorization_code")); builder.append("&client_id="); builder.append(encode(account.getClientId())); builder.append("&code="); builder.append(encode(code)); builder.append("&code_verifier="); builder.append(encode(codeVerifier)); update(account, builder.toString()); }
[ "public", "void", "finishFlow", "(", "final", "String", "code", ",", "final", "String", "state", ")", "throws", "ApiException", "{", "if", "(", "account", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Auth is not set\"", ")", ";", "if"...
Finish the oauth flow after the user was redirected back. @param code Code returned by the Eve Online SSO @param state This should be some secret to prevent XRSF see getAuthorizationUri @throws net.troja.eve.esi.ApiException
[ "Finish", "the", "oauth", "flow", "after", "the", "user", "was", "redirected", "back", "." ]
train
https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/auth/OAuth.java#L198-L215
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParseUtil.java
BpmnParseUtil.parseInputParameterElement
public static void parseInputParameterElement(Element inputParameterElement, IoMapping ioMapping) { String nameAttribute = inputParameterElement.attribute("name"); if(nameAttribute == null || nameAttribute.isEmpty()) { throw new BpmnParseException("Missing attribute 'name' for inputParameter", inputParameterElement); } ParameterValueProvider valueProvider = parseNestedParamValueProvider(inputParameterElement); // add parameter ioMapping.addInputParameter(new InputParameter(nameAttribute, valueProvider)); }
java
public static void parseInputParameterElement(Element inputParameterElement, IoMapping ioMapping) { String nameAttribute = inputParameterElement.attribute("name"); if(nameAttribute == null || nameAttribute.isEmpty()) { throw new BpmnParseException("Missing attribute 'name' for inputParameter", inputParameterElement); } ParameterValueProvider valueProvider = parseNestedParamValueProvider(inputParameterElement); // add parameter ioMapping.addInputParameter(new InputParameter(nameAttribute, valueProvider)); }
[ "public", "static", "void", "parseInputParameterElement", "(", "Element", "inputParameterElement", ",", "IoMapping", "ioMapping", ")", "{", "String", "nameAttribute", "=", "inputParameterElement", ".", "attribute", "(", "\"name\"", ")", ";", "if", "(", "nameAttribute"...
Parses a input parameter and adds it to the {@link IoMapping}. @param inputParameterElement the input parameter element @param ioMapping the mapping to add the element @throws BpmnParseException if the input parameter element is malformed
[ "Parses", "a", "input", "parameter", "and", "adds", "it", "to", "the", "{", "@link", "IoMapping", "}", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParseUtil.java#L117-L127
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindM2MBuilder.java
BindM2MBuilder.isMethodAlreadyDefined
private boolean isMethodAlreadyDefined(M2MEntity entity, final String methodName) { final One<Boolean> found = new One<Boolean>(false); SqlBuilderHelper.forEachMethods(entity.daoElement, new MethodFoundListener() { @Override public void onMethod(ExecutableElement executableMethod) { if (executableMethod.getSimpleName().toString().equals(methodName)) { found.value0 = true; } } }); return found.value0; }
java
private boolean isMethodAlreadyDefined(M2MEntity entity, final String methodName) { final One<Boolean> found = new One<Boolean>(false); SqlBuilderHelper.forEachMethods(entity.daoElement, new MethodFoundListener() { @Override public void onMethod(ExecutableElement executableMethod) { if (executableMethod.getSimpleName().toString().equals(methodName)) { found.value0 = true; } } }); return found.value0; }
[ "private", "boolean", "isMethodAlreadyDefined", "(", "M2MEntity", "entity", ",", "final", "String", "methodName", ")", "{", "final", "One", "<", "Boolean", ">", "found", "=", "new", "One", "<", "Boolean", ">", "(", "false", ")", ";", "SqlBuilderHelper", ".",...
analyze DAO definition to check if method is already defined. @param entity the entity @param methodName the method name @return true, if is method already defined
[ "analyze", "DAO", "definition", "to", "check", "if", "method", "is", "already", "defined", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/BindM2MBuilder.java#L313-L328
litsec/swedish-eid-shibboleth-base
shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/service/impl/SignSupportServiceImpl.java
SignSupportServiceImpl.getAuthenticationContext
protected AuthenticationContext getAuthenticationContext(ProfileRequestContext<?, ?> context) throws ExternalAutenticationErrorCodeException { AuthenticationContext authnContext = authenticationContextLookupStrategy.apply(context); if (authnContext == null) { log.error("No AuthenticationContext available [{}]", this.getLogString(context)); throw new ExternalAutenticationErrorCodeException(AuthnEventIds.INVALID_AUTHN_CTX, "Missing AuthenticationContext"); } return authnContext; }
java
protected AuthenticationContext getAuthenticationContext(ProfileRequestContext<?, ?> context) throws ExternalAutenticationErrorCodeException { AuthenticationContext authnContext = authenticationContextLookupStrategy.apply(context); if (authnContext == null) { log.error("No AuthenticationContext available [{}]", this.getLogString(context)); throw new ExternalAutenticationErrorCodeException(AuthnEventIds.INVALID_AUTHN_CTX, "Missing AuthenticationContext"); } return authnContext; }
[ "protected", "AuthenticationContext", "getAuthenticationContext", "(", "ProfileRequestContext", "<", "?", ",", "?", ">", "context", ")", "throws", "ExternalAutenticationErrorCodeException", "{", "AuthenticationContext", "authnContext", "=", "authenticationContextLookupStrategy", ...
Utility method that returns the {@code AuthenticationContext}. @param context the profile context @return the {@code AuthenticationContext} @throws ExternalAutenticationErrorCodeException if the context is not available
[ "Utility", "method", "that", "returns", "the", "{", "@code", "AuthenticationContext", "}", "." ]
train
https://github.com/litsec/swedish-eid-shibboleth-base/blob/aaaa467ff61f07d7dfa31627fb36851a37da6804/shibboleth-base/shibboleth-extensions/src/main/java/se/litsec/shibboleth/idp/authn/service/impl/SignSupportServiceImpl.java#L494-L502
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java
BigDecimal.divideAndRound
private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode, int preferredScale) { boolean isRemainderZero; // record remainder is zero or not int qsign; // quotient sign // Descend into mutables for faster remainder checks MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); MutableBigInteger mq = new MutableBigInteger(); MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag); MutableBigInteger mr = mdividend.divide(mdivisor, mq); isRemainderZero = mr.isZero(); qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; if (!isRemainderZero) { if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) { mq.add(MutableBigInteger.ONE); } return mq.toBigDecimal(qsign, scale); } else { if (preferredScale != scale) { long compactVal = mq.toCompactValue(qsign); if (compactVal != INFLATED) { return createAndStripZerosToMatchScale(compactVal, scale, preferredScale); } BigInteger intVal = mq.toBigInteger(qsign); return createAndStripZerosToMatchScale(intVal, scale, preferredScale); } else { return mq.toBigDecimal(qsign, scale); } } }
java
private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode, int preferredScale) { boolean isRemainderZero; // record remainder is zero or not int qsign; // quotient sign // Descend into mutables for faster remainder checks MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); MutableBigInteger mq = new MutableBigInteger(); MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag); MutableBigInteger mr = mdividend.divide(mdivisor, mq); isRemainderZero = mr.isZero(); qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; if (!isRemainderZero) { if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) { mq.add(MutableBigInteger.ONE); } return mq.toBigDecimal(qsign, scale); } else { if (preferredScale != scale) { long compactVal = mq.toCompactValue(qsign); if (compactVal != INFLATED) { return createAndStripZerosToMatchScale(compactVal, scale, preferredScale); } BigInteger intVal = mq.toBigInteger(qsign); return createAndStripZerosToMatchScale(intVal, scale, preferredScale); } else { return mq.toBigDecimal(qsign, scale); } } }
[ "private", "static", "BigDecimal", "divideAndRound", "(", "BigInteger", "bdividend", ",", "BigInteger", "bdivisor", ",", "int", "scale", ",", "int", "roundingMode", ",", "int", "preferredScale", ")", "{", "boolean", "isRemainderZero", ";", "// record remainder is zero...
Internally used for division operation for division {@code BigInteger} by {@code BigInteger}. The returned {@code BigDecimal} object is the quotient whose scale is set to the passed in scale. If the remainder is not zero, it will be rounded based on the passed in roundingMode. Also, if the remainder is zero and the last parameter, i.e. preferredScale is NOT equal to scale, the trailing zeros of the result is stripped to match the preferredScale.
[ "Internally", "used", "for", "division", "operation", "for", "division", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L4320-L4348
Azure/azure-sdk-for-java
containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/OpenShiftManagedClustersInner.java
OpenShiftManagedClustersInner.getByResourceGroup
public OpenShiftManagedClusterInner getByResourceGroup(String resourceGroupName, String resourceName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); }
java
public OpenShiftManagedClusterInner getByResourceGroup(String resourceGroupName, String resourceName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body(); }
[ "public", "OpenShiftManagedClusterInner", "getByResourceGroup", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "toBlocking", "(", "...
Gets a OpenShift managed cluster. Gets the details of the managed OpenShift cluster with a specified resource group and name. @param resourceGroupName The name of the resource group. @param resourceName The name of the OpenShift managed cluster resource. @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 OpenShiftManagedClusterInner object if successful.
[ "Gets", "a", "OpenShift", "managed", "cluster", ".", "Gets", "the", "details", "of", "the", "managed", "OpenShift", "cluster", "with", "a", "specified", "resource", "group", "and", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/OpenShiftManagedClustersInner.java#L355-L357
jhunters/jprotobuf
src/main/java/com/baidu/bjf/remoting/protobuf/ProtobufIDLProxy.java
ProtobufIDLProxy.createSingle
public static IDLProxyObject createSingle(String data, boolean debug, boolean isUniName) { return createSingle(data, debug, null, isUniName); }
java
public static IDLProxyObject createSingle(String data, boolean debug, boolean isUniName) { return createSingle(data, debug, null, isUniName); }
[ "public", "static", "IDLProxyObject", "createSingle", "(", "String", "data", ",", "boolean", "debug", ",", "boolean", "isUniName", ")", "{", "return", "createSingle", "(", "data", ",", "debug", ",", "null", ",", "isUniName", ")", ";", "}" ]
Creates the single. @param data the data @param debug the debug @param isUniName the is uni name @return the IDL proxy object
[ "Creates", "the", "single", "." ]
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/ProtobufIDLProxy.java#L1109-L1111
ebean-orm/querybean-agent-now-merged-into-ebean-agent-
src/main/java/io/ebean/typequery/agent/AgentManifestReader.java
AgentManifestReader.readManifests
private AgentManifestReader readManifests(ClassLoader classLoader, String path) throws IOException { Enumeration<URL> resources = classLoader.getResources(path); while (resources.hasMoreElements()) { URL url = resources.nextElement(); try { addResource(url.openStream()); } catch (IOException e) { System.err.println("Error reading manifest resources " + url); e.printStackTrace(); } } return this; }
java
private AgentManifestReader readManifests(ClassLoader classLoader, String path) throws IOException { Enumeration<URL> resources = classLoader.getResources(path); while (resources.hasMoreElements()) { URL url = resources.nextElement(); try { addResource(url.openStream()); } catch (IOException e) { System.err.println("Error reading manifest resources " + url); e.printStackTrace(); } } return this; }
[ "private", "AgentManifestReader", "readManifests", "(", "ClassLoader", "classLoader", ",", "String", "path", ")", "throws", "IOException", "{", "Enumeration", "<", "URL", ">", "resources", "=", "classLoader", ".", "getResources", "(", "path", ")", ";", "while", ...
Read all the specific manifest files and return the set of packages containing type query beans.
[ "Read", "all", "the", "specific", "manifest", "files", "and", "return", "the", "set", "of", "packages", "containing", "type", "query", "beans", "." ]
train
https://github.com/ebean-orm/querybean-agent-now-merged-into-ebean-agent-/blob/a063554fabdbed15ff5e10ad0a0b53b67e039006/src/main/java/io/ebean/typequery/agent/AgentManifestReader.java#L68-L80
yegor256/takes
src/main/java/org/takes/facets/auth/TkAuth.java
TkAuth.act
private Response act(final Request req, final Identity identity) throws IOException { Request wrap = new RqWithoutHeader(req, this.header); if (!identity.equals(Identity.ANONYMOUS)) { wrap = new RqWithAuth(identity, this.header, wrap); } return this.pass.exit(this.origin.act(wrap), identity); }
java
private Response act(final Request req, final Identity identity) throws IOException { Request wrap = new RqWithoutHeader(req, this.header); if (!identity.equals(Identity.ANONYMOUS)) { wrap = new RqWithAuth(identity, this.header, wrap); } return this.pass.exit(this.origin.act(wrap), identity); }
[ "private", "Response", "act", "(", "final", "Request", "req", ",", "final", "Identity", "identity", ")", "throws", "IOException", "{", "Request", "wrap", "=", "new", "RqWithoutHeader", "(", "req", ",", "this", ".", "header", ")", ";", "if", "(", "!", "id...
Make take. @param req Request @param identity Identity @return Take @throws IOException If fails
[ "Make", "take", "." ]
train
https://github.com/yegor256/takes/blob/a4f4d939c8f8e0af190025716ad7f22b7de40e70/src/main/java/org/takes/facets/auth/TkAuth.java#L101-L108
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PropertiesConfigHelper.java
PropertiesConfigHelper.getProperty
public String getProperty(String key, String defaultValue) { return props.getProperty(prefix + key, defaultValue); }
java
public String getProperty(String key, String defaultValue) { return props.getProperty(prefix + key, defaultValue); }
[ "public", "String", "getProperty", "(", "String", "key", ",", "String", "defaultValue", ")", "{", "return", "props", ".", "getProperty", "(", "prefix", "+", "key", ",", "defaultValue", ")", ";", "}" ]
Returns the value of a property, or the default value if no value is defined @param key the key of the property @param defaultValue the default value @return the value of a property, or the default value if no value is defined
[ "Returns", "the", "value", "of", "a", "property", "or", "the", "default", "value", "if", "no", "value", "is", "defined" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PropertiesConfigHelper.java#L288-L290
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java
DictionaryImpl.findTransition
protected int findTransition(int state, char c) { int start = d_stateOffsets.get(state); int end = transitionsUpperBound(state) - 1; // Binary search while (end >= start) { int mid = start + ((end - start) / 2); if (d_transitionChars[mid] > c) end = mid - 1; else if (d_transitionChars[mid] < c) start = mid + 1; else return mid; } return -1; }
java
protected int findTransition(int state, char c) { int start = d_stateOffsets.get(state); int end = transitionsUpperBound(state) - 1; // Binary search while (end >= start) { int mid = start + ((end - start) / 2); if (d_transitionChars[mid] > c) end = mid - 1; else if (d_transitionChars[mid] < c) start = mid + 1; else return mid; } return -1; }
[ "protected", "int", "findTransition", "(", "int", "state", ",", "char", "c", ")", "{", "int", "start", "=", "d_stateOffsets", ".", "get", "(", "state", ")", ";", "int", "end", "=", "transitionsUpperBound", "(", "state", ")", "-", "1", ";", "// Binary sea...
Find the transition for the given character in the given state. Since the transitions are ordered by character, we can use a binary search. @param state @param c @return
[ "Find", "the", "transition", "for", "the", "given", "character", "in", "the", "given", "state", ".", "Since", "the", "transitions", "are", "ordered", "by", "character", "we", "can", "use", "a", "binary", "search", "." ]
train
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java#L293-L310
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/ItemCounter.java
ItemCounter.descendingKeys
public List<T> descendingKeys() { List<T> list = new ArrayList<T>(map.keySet()); sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { MutableLong l1 = map.get(o1); MutableLong l2 = map.get(o2); return compare(l2.value, l1.value); } private int compare(long x, long y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } }); return list; }
java
public List<T> descendingKeys() { List<T> list = new ArrayList<T>(map.keySet()); sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { MutableLong l1 = map.get(o1); MutableLong l2 = map.get(o2); return compare(l2.value, l1.value); } private int compare(long x, long y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } }); return list; }
[ "public", "List", "<", "T", ">", "descendingKeys", "(", ")", "{", "List", "<", "T", ">", "list", "=", "new", "ArrayList", "<", "T", ">", "(", "map", ".", "keySet", "(", ")", ")", ";", "sort", "(", "list", ",", "new", "Comparator", "<", "T", ">"...
Returns a List of keys in descending value order. @return the list of keys
[ "Returns", "a", "List", "of", "keys", "in", "descending", "value", "order", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/ItemCounter.java#L63-L80
elki-project/elki
elki-docutil/src/main/java/de/lmu/ifi/dbs/elki/utilities/xml/HTMLUtil.java
HTMLUtil.appendMultilineText
public static Element appendMultilineText(Document htmldoc, Element parent, String text) { String[] parts = text != null ? text.split("\n") : null; if(parts == null || parts.length == 0) { return parent; } parent.appendChild(htmldoc.createTextNode(parts[0])); for(int i = 1; i < parts.length; i++) { parent.appendChild(htmldoc.createElement(HTML_BR_TAG)); parent.appendChild(htmldoc.createTextNode(parts[i])); } return parent; }
java
public static Element appendMultilineText(Document htmldoc, Element parent, String text) { String[] parts = text != null ? text.split("\n") : null; if(parts == null || parts.length == 0) { return parent; } parent.appendChild(htmldoc.createTextNode(parts[0])); for(int i = 1; i < parts.length; i++) { parent.appendChild(htmldoc.createElement(HTML_BR_TAG)); parent.appendChild(htmldoc.createTextNode(parts[i])); } return parent; }
[ "public", "static", "Element", "appendMultilineText", "(", "Document", "htmldoc", ",", "Element", "parent", ",", "String", "text", ")", "{", "String", "[", "]", "parts", "=", "text", "!=", "null", "?", "text", ".", "split", "(", "\"\\n\"", ")", ":", "nul...
Append a multiline text to a node, transforming linewraps into BR tags. @param htmldoc Document @param parent Parent node @param text Text to add. @return parent node
[ "Append", "a", "multiline", "text", "to", "a", "node", "transforming", "linewraps", "into", "BR", "tags", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-docutil/src/main/java/de/lmu/ifi/dbs/elki/utilities/xml/HTMLUtil.java#L294-L305
offbynull/coroutines
instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/MethodHasher.java
MethodHasher.dumpBytecode
private static byte[] dumpBytecode(MethodNode methodNode) { // Calculate label offsets -- required for hash calculation // we only care about where the labels are in relation to the opcode instructions -- we don't care about things like // LocalVariableNode or other ancillary data because these can change without the actual logic changing List<AbstractInsnNode> onlyInstructionsAndLabels = Arrays.stream(methodNode.instructions.toArray()) .filter(x -> x instanceof LabelNode || x.getOpcode() != -1) .collect(Collectors.toList()); Map<Label, Integer> labelOffsets = onlyInstructionsAndLabels.stream() .filter(x -> x instanceof LabelNode) .map(x -> (LabelNode) x) .collect(Collectors.toMap(x -> x.getLabel(), x -> onlyInstructionsAndLabels.indexOf(x))); // Hash based on overall structures and instructions+operands try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos);) { MethodVisitor daosDumpMethodVisitor = new DumpToDaosMethodVisitor(daos, labelOffsets); methodNode.accept(daosDumpMethodVisitor); daos.flush(); // doesn't really need it -- just incase return baos.toByteArray(); } catch (IOException ioe) { throw new IllegalStateException(ioe); // should never happen } }
java
private static byte[] dumpBytecode(MethodNode methodNode) { // Calculate label offsets -- required for hash calculation // we only care about where the labels are in relation to the opcode instructions -- we don't care about things like // LocalVariableNode or other ancillary data because these can change without the actual logic changing List<AbstractInsnNode> onlyInstructionsAndLabels = Arrays.stream(methodNode.instructions.toArray()) .filter(x -> x instanceof LabelNode || x.getOpcode() != -1) .collect(Collectors.toList()); Map<Label, Integer> labelOffsets = onlyInstructionsAndLabels.stream() .filter(x -> x instanceof LabelNode) .map(x -> (LabelNode) x) .collect(Collectors.toMap(x -> x.getLabel(), x -> onlyInstructionsAndLabels.indexOf(x))); // Hash based on overall structures and instructions+operands try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos);) { MethodVisitor daosDumpMethodVisitor = new DumpToDaosMethodVisitor(daos, labelOffsets); methodNode.accept(daosDumpMethodVisitor); daos.flush(); // doesn't really need it -- just incase return baos.toByteArray(); } catch (IOException ioe) { throw new IllegalStateException(ioe); // should never happen } }
[ "private", "static", "byte", "[", "]", "dumpBytecode", "(", "MethodNode", "methodNode", ")", "{", "// Calculate label offsets -- required for hash calculation", "// we only care about where the labels are in relation to the opcode instructions -- we don't care about things like", "// Local...
Takes into account the instructions and operands, as well as the overall structure.
[ "Takes", "into", "account", "the", "instructions", "and", "operands", "as", "well", "as", "the", "overall", "structure", "." ]
train
https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/instrumenter/src/main/java/com/offbynull/coroutines/instrumenter/MethodHasher.java#L60-L85
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/resource/ClassPathResource.java
ClassPathResource.getInputStream
@Nullable public static InputStream getInputStream (@Nonnull @Nonempty final String sPath) { final URL aURL = URLHelper.getClassPathURL (sPath); return _getInputStream (sPath, aURL, (ClassLoader) null); }
java
@Nullable public static InputStream getInputStream (@Nonnull @Nonempty final String sPath) { final URL aURL = URLHelper.getClassPathURL (sPath); return _getInputStream (sPath, aURL, (ClassLoader) null); }
[ "@", "Nullable", "public", "static", "InputStream", "getInputStream", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sPath", ")", "{", "final", "URL", "aURL", "=", "URLHelper", ".", "getClassPathURL", "(", "sPath", ")", ";", "return", "_getInputStre...
Get the input stream for the specified path using automatic class loader handling. The class loaders are iterated in the following order: <ol> <li>Default class loader (usually the context class loader)</li> <li>The class loader of this class</li> <li>The system class loader</li> </ol> @param sPath The path to be resolved. May neither be <code>null</code> nor empty. @return <code>null</code> if the path could not be resolved.
[ "Get", "the", "input", "stream", "for", "the", "specified", "path", "using", "automatic", "class", "loader", "handling", ".", "The", "class", "loaders", "are", "iterated", "in", "the", "following", "order", ":", "<ol", ">", "<li", ">", "Default", "class", ...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/resource/ClassPathResource.java#L232-L237
line/armeria
core/src/main/java/com/linecorp/armeria/server/docs/TypeSignature.java
TypeSignature.ofMap
public static TypeSignature ofMap(TypeSignature keyTypeSignature, TypeSignature valueTypeSignature) { requireNonNull(keyTypeSignature, "keyTypeSignature"); requireNonNull(valueTypeSignature, "valueTypeSignature"); return ofContainer("map", keyTypeSignature, valueTypeSignature); }
java
public static TypeSignature ofMap(TypeSignature keyTypeSignature, TypeSignature valueTypeSignature) { requireNonNull(keyTypeSignature, "keyTypeSignature"); requireNonNull(valueTypeSignature, "valueTypeSignature"); return ofContainer("map", keyTypeSignature, valueTypeSignature); }
[ "public", "static", "TypeSignature", "ofMap", "(", "TypeSignature", "keyTypeSignature", ",", "TypeSignature", "valueTypeSignature", ")", "{", "requireNonNull", "(", "keyTypeSignature", ",", "\"keyTypeSignature\"", ")", ";", "requireNonNull", "(", "valueTypeSignature", ","...
Creates a new type signature for the map with the specified key and value type signatures. This method is a shortcut of: <pre>{@code ofMap("map", keyTypeSignature, valueTypeSignature); }</pre>
[ "Creates", "a", "new", "type", "signature", "for", "the", "map", "with", "the", "specified", "key", "and", "value", "type", "signatures", ".", "This", "method", "is", "a", "shortcut", "of", ":", "<pre", ">", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/docs/TypeSignature.java#L158-L162
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java
MapIterate.getIfAbsentPut
public static <K, V> V getIfAbsentPut(Map<K, V> map, K key, Function0<? extends V> instanceBlock) { if (map instanceof MutableMap) { return ((MutableMap<K, V>) map).getIfAbsentPut(key, instanceBlock); } V result = map.get(key); if (MapIterate.isAbsent(result, map, key)) { result = instanceBlock.value(); map.put(key, result); } return result; }
java
public static <K, V> V getIfAbsentPut(Map<K, V> map, K key, Function0<? extends V> instanceBlock) { if (map instanceof MutableMap) { return ((MutableMap<K, V>) map).getIfAbsentPut(key, instanceBlock); } V result = map.get(key); if (MapIterate.isAbsent(result, map, key)) { result = instanceBlock.value(); map.put(key, result); } return result; }
[ "public", "static", "<", "K", ",", "V", ">", "V", "getIfAbsentPut", "(", "Map", "<", "K", ",", "V", ">", "map", ",", "K", "key", ",", "Function0", "<", "?", "extends", "V", ">", "instanceBlock", ")", "{", "if", "(", "map", "instanceof", "MutableMap...
Get and return the value in the Map at the specified key, or if there is no value at the key, return the result of evaluating the specified {@link Function0}, and put that value in the map at the specified key. <p> This method handles the {@code null}-value-at-key case correctly.
[ "Get", "and", "return", "the", "value", "in", "the", "Map", "at", "the", "specified", "key", "or", "if", "there", "is", "no", "value", "at", "the", "key", "return", "the", "result", "of", "evaluating", "the", "specified", "{" ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java#L137-L150
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/RepositoryApi.java
RepositoryApi.createTag
public Tag createTag(Object projectIdOrPath, String tagName, String ref, String message, String releaseNotes) throws GitLabApiException { Form formData = new GitLabApiForm() .withParam("tag_name", tagName, true) .withParam("ref", ref, true) .withParam("message", message, false) .withParam("release_description", releaseNotes, false); Response response = post(Response.Status.CREATED, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "tags"); return (response.readEntity(Tag.class)); }
java
public Tag createTag(Object projectIdOrPath, String tagName, String ref, String message, String releaseNotes) throws GitLabApiException { Form formData = new GitLabApiForm() .withParam("tag_name", tagName, true) .withParam("ref", ref, true) .withParam("message", message, false) .withParam("release_description", releaseNotes, false); Response response = post(Response.Status.CREATED, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "repository", "tags"); return (response.readEntity(Tag.class)); }
[ "public", "Tag", "createTag", "(", "Object", "projectIdOrPath", ",", "String", "tagName", ",", "String", "ref", ",", "String", "message", ",", "String", "releaseNotes", ")", "throws", "GitLabApiException", "{", "Form", "formData", "=", "new", "GitLabApiForm", "(...
Creates a tag on a particular ref of the given project. A message and release notes are optional. <pre><code>GitLab Endpoint: POST /projects/:id/repository/tags</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param tagName The name of the tag Must be unique for the project @param ref the git ref to place the tag on @param message the message to included with the tag (optional) @param releaseNotes the release notes for the tag (optional) @return a Tag instance containing info on the newly created tag @throws GitLabApiException if any exception occurs @deprecated Replaced by TagsApi.createTag(Object, String, String, String, String)
[ "Creates", "a", "tag", "on", "a", "particular", "ref", "of", "the", "given", "project", ".", "A", "message", "and", "release", "notes", "are", "optional", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryApi.java#L265-L275
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/concurrent/JRebirth.java
JRebirth.runIntoJTPSync
public static void runIntoJTPSync(final String runnableName, final Runnable runnable, final long... timeout) { runIntoJTPSync(new JrbReferenceRunnable(runnableName, runnable), timeout); }
java
public static void runIntoJTPSync(final String runnableName, final Runnable runnable, final long... timeout) { runIntoJTPSync(new JrbReferenceRunnable(runnableName, runnable), timeout); }
[ "public", "static", "void", "runIntoJTPSync", "(", "final", "String", "runnableName", ",", "final", "Runnable", "runnable", ",", "final", "long", "...", "timeout", ")", "{", "runIntoJTPSync", "(", "new", "JrbReferenceRunnable", "(", "runnableName", ",", "runnable"...
Run into the JRebirth Thread Pool [JTP] <b>Synchronously</b>. Be careful this method can be called through any thread. @param runnableName the name of the runnable for logging purpose @param runnable the task to run @param timeout the optional timeout value after which the thread will be released (default is 1000 ms)
[ "Run", "into", "the", "JRebirth", "Thread", "Pool", "[", "JTP", "]", "<b", ">", "Synchronously<", "/", "b", ">", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/concurrent/JRebirth.java#L366-L368
mojohaus/jaxb2-maven-plugin
src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java
ThreadContextClassLoaderBuilder.createFor
public static ThreadContextClassLoaderBuilder createFor(final ClassLoader classLoader, final Log log, final String encoding) { // Check sanity Validate.notNull(classLoader, "classLoader"); Validate.notNull(log, "log"); // All done. return new ThreadContextClassLoaderBuilder(classLoader, log, encoding); }
java
public static ThreadContextClassLoaderBuilder createFor(final ClassLoader classLoader, final Log log, final String encoding) { // Check sanity Validate.notNull(classLoader, "classLoader"); Validate.notNull(log, "log"); // All done. return new ThreadContextClassLoaderBuilder(classLoader, log, encoding); }
[ "public", "static", "ThreadContextClassLoaderBuilder", "createFor", "(", "final", "ClassLoader", "classLoader", ",", "final", "Log", "log", ",", "final", "String", "encoding", ")", "{", "// Check sanity", "Validate", ".", "notNull", "(", "classLoader", ",", "\"class...
Creates a new ThreadContextClassLoaderBuilder using the supplied original classLoader, as well as the supplied Maven Log. @param classLoader The original ClassLoader which should be used as the parent for the ThreadContext ClassLoader produced by the ThreadContextClassLoaderBuilder generated by this builder method. Cannot be null. @param log The active Maven Log. Cannot be null. @param encoding The encoding used by Maven. Cannot be null. @return A ThreadContextClassLoaderBuilder wrapping the supplied members.
[ "Creates", "a", "new", "ThreadContextClassLoaderBuilder", "using", "the", "supplied", "original", "classLoader", "as", "well", "as", "the", "supplied", "Maven", "Log", "." ]
train
https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java#L253-L263
di2e/Argo
clui/src/main/java/net/dharwin/common/tools/cli/api/CLIContext.java
CLIContext.put
public Object put(String key, Object o) { return _properties.put(key, o); }
java
public Object put(String key, Object o) { return _properties.put(key, o); }
[ "public", "Object", "put", "(", "String", "key", ",", "Object", "o", ")", "{", "return", "_properties", ".", "put", "(", "key", ",", "o", ")", ";", "}" ]
Add an object to the context. @param key The key to add. @param o The object to add. @return The previous object associated with this key, or null if there was none.
[ "Add", "an", "object", "to", "the", "context", "." ]
train
https://github.com/di2e/Argo/blob/f537a03d2d25fdfecda7999ec10e1da67dc3b8f3/clui/src/main/java/net/dharwin/common/tools/cli/api/CLIContext.java#L134-L136