repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
looly/hutool
hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java
KeyUtil.generateKey
public static SecretKey generateKey(String algorithm, int keySize) { algorithm = getMainAlgorithm(algorithm); final KeyGenerator keyGenerator = getKeyGenerator(algorithm); if (keySize > 0) { keyGenerator.init(keySize); } else if (SymmetricAlgorithm.AES.getValue().equals(algorithm)) { // 对于AES的密钥,除非指定,否则强制使用128位 keyGenerator.init(128); } return keyGenerator.generateKey(); }
java
public static SecretKey generateKey(String algorithm, int keySize) { algorithm = getMainAlgorithm(algorithm); final KeyGenerator keyGenerator = getKeyGenerator(algorithm); if (keySize > 0) { keyGenerator.init(keySize); } else if (SymmetricAlgorithm.AES.getValue().equals(algorithm)) { // 对于AES的密钥,除非指定,否则强制使用128位 keyGenerator.init(128); } return keyGenerator.generateKey(); }
[ "public", "static", "SecretKey", "generateKey", "(", "String", "algorithm", ",", "int", "keySize", ")", "{", "algorithm", "=", "getMainAlgorithm", "(", "algorithm", ")", ";", "final", "KeyGenerator", "keyGenerator", "=", "getKeyGenerator", "(", "algorithm", ")", ...
生成 {@link SecretKey},仅用于对称加密和摘要算法密钥生成 @param algorithm 算法,支持PBE算法 @param keySize 密钥长度 @return {@link SecretKey} @since 3.1.2
[ "生成", "{", "@link", "SecretKey", "}", ",仅用于对称加密和摘要算法密钥生成" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/KeyUtil.java#L94-L105
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java
Collections.arrayWithin
public static WhenBuilder arrayWithin(Expression arrayExpression, String variable, Expression expression) { return new WhenBuilder(x("ARRAY " + arrayExpression.toString() + " FOR"), variable, expression, false); }
java
public static WhenBuilder arrayWithin(Expression arrayExpression, String variable, Expression expression) { return new WhenBuilder(x("ARRAY " + arrayExpression.toString() + " FOR"), variable, expression, false); }
[ "public", "static", "WhenBuilder", "arrayWithin", "(", "Expression", "arrayExpression", ",", "String", "variable", ",", "Expression", "expression", ")", "{", "return", "new", "WhenBuilder", "(", "x", "(", "\"ARRAY \"", "+", "arrayExpression", ".", "toString", "(",...
Create an ARRAY comprehension with a first WITHIN range. The ARRAY operator lets you map and filter the elements or attributes of a collection, object, or objects. It evaluates to an array of the operand expression, that satisfies the WHEN clause, if provided. For elements, IN ranges in the direct elements of its array expression, WITHIN also ranges in its descendants.
[ "Create", "an", "ARRAY", "comprehension", "with", "a", "first", "WITHIN", "range", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/Collections.java#L239-L242
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java
CQJDBCStorageConnection.readACLOwner
protected String readACLOwner(String cid, Map<String, SortedSet<TempPropertyData>> properties) throws IllegalACLException, IOException { SortedSet<TempPropertyData> ownerValues = properties.get(Constants.EXO_OWNER.getAsString()); if (ownerValues != null) { try { return ValueDataUtil.getString(ownerValues.first().getValueData()); } catch (RepositoryException e) { throw new IOException(e.getMessage(), e); } } else { throw new IllegalACLException("Property exo:owner is not found for node with id: " + getIdentifier(cid)); } }
java
protected String readACLOwner(String cid, Map<String, SortedSet<TempPropertyData>> properties) throws IllegalACLException, IOException { SortedSet<TempPropertyData> ownerValues = properties.get(Constants.EXO_OWNER.getAsString()); if (ownerValues != null) { try { return ValueDataUtil.getString(ownerValues.first().getValueData()); } catch (RepositoryException e) { throw new IOException(e.getMessage(), e); } } else { throw new IllegalACLException("Property exo:owner is not found for node with id: " + getIdentifier(cid)); } }
[ "protected", "String", "readACLOwner", "(", "String", "cid", ",", "Map", "<", "String", ",", "SortedSet", "<", "TempPropertyData", ">", ">", "properties", ")", "throws", "IllegalACLException", ",", "IOException", "{", "SortedSet", "<", "TempPropertyData", ">", "...
Read ACL owner. @param cid - node id (used only in exception message) @param properties - Property name and property values @return ACL owner @throws IllegalACLException @throws IOException
[ "Read", "ACL", "owner", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/optimisation/CQJDBCStorageConnection.java#L1288-L1307
apache/incubator-heron
heron/common/src/java/org/apache/heron/common/utils/logging/ErrorReportLoggingHandler.java
ErrorReportLoggingHandler.publish
@Override public void publish(LogRecord record) { // Convert Log Throwable throwable = record.getThrown(); if (throwable != null) { synchronized (ExceptionRepositoryAsMetrics.INSTANCE) { // We would not include the message if already exceeded the exceptions limit if (ExceptionRepositoryAsMetrics.INSTANCE.getExceptionsCount() >= exceptionsLimit) { droppedExceptionsCount.incr(); return; } // Convert the record StringWriter sink = new StringWriter(); throwable.printStackTrace(new PrintWriter(sink, true)); String trace = sink.toString(); Metrics.ExceptionData.Builder exceptionDataBuilder = ExceptionRepositoryAsMetrics.INSTANCE.getExceptionInfo(trace); exceptionDataBuilder.setCount(exceptionDataBuilder.getCount() + 1); exceptionDataBuilder.setLasttime(new Date().toString()); exceptionDataBuilder.setStacktrace(trace); // Can cause NPE and crash HI //exceptionDataBuilder.setLogging(record.getMessage()); if (record.getMessage() == null) { exceptionDataBuilder.setLogging(""); } else { exceptionDataBuilder.setLogging(record.getMessage()); } } } }
java
@Override public void publish(LogRecord record) { // Convert Log Throwable throwable = record.getThrown(); if (throwable != null) { synchronized (ExceptionRepositoryAsMetrics.INSTANCE) { // We would not include the message if already exceeded the exceptions limit if (ExceptionRepositoryAsMetrics.INSTANCE.getExceptionsCount() >= exceptionsLimit) { droppedExceptionsCount.incr(); return; } // Convert the record StringWriter sink = new StringWriter(); throwable.printStackTrace(new PrintWriter(sink, true)); String trace = sink.toString(); Metrics.ExceptionData.Builder exceptionDataBuilder = ExceptionRepositoryAsMetrics.INSTANCE.getExceptionInfo(trace); exceptionDataBuilder.setCount(exceptionDataBuilder.getCount() + 1); exceptionDataBuilder.setLasttime(new Date().toString()); exceptionDataBuilder.setStacktrace(trace); // Can cause NPE and crash HI //exceptionDataBuilder.setLogging(record.getMessage()); if (record.getMessage() == null) { exceptionDataBuilder.setLogging(""); } else { exceptionDataBuilder.setLogging(record.getMessage()); } } } }
[ "@", "Override", "public", "void", "publish", "(", "LogRecord", "record", ")", "{", "// Convert Log", "Throwable", "throwable", "=", "record", ".", "getThrown", "(", ")", ";", "if", "(", "throwable", "!=", "null", ")", "{", "synchronized", "(", "ExceptionRep...
will flush the exception to metrics manager during getValueAndReset call.
[ "will", "flush", "the", "exception", "to", "metrics", "manager", "during", "getValueAndReset", "call", "." ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/utils/logging/ErrorReportLoggingHandler.java#L90-L123
jayantk/jklol
src/com/jayantkrish/jklol/ccg/SyntacticCategory.java
SyntacticCategory.isUnifiableWith
public boolean isUnifiableWith(SyntacticCategory other) { Map<Integer, String> myAssignedVariables = Maps.newHashMap(); Map<Integer, String> otherAssignedVariables = Maps.newHashMap(); Map<Integer, Integer> variableRelabeling = Maps.newHashMap(); // System.err.println("unifying: " + this + " " + other); return isUnifiableWith(other, myAssignedVariables, otherAssignedVariables, variableRelabeling); }
java
public boolean isUnifiableWith(SyntacticCategory other) { Map<Integer, String> myAssignedVariables = Maps.newHashMap(); Map<Integer, String> otherAssignedVariables = Maps.newHashMap(); Map<Integer, Integer> variableRelabeling = Maps.newHashMap(); // System.err.println("unifying: " + this + " " + other); return isUnifiableWith(other, myAssignedVariables, otherAssignedVariables, variableRelabeling); }
[ "public", "boolean", "isUnifiableWith", "(", "SyntacticCategory", "other", ")", "{", "Map", "<", "Integer", ",", "String", ">", "myAssignedVariables", "=", "Maps", ".", "newHashMap", "(", ")", ";", "Map", "<", "Integer", ",", "String", ">", "otherAssignedVaria...
Returns {@code true} if this category is unifiable with {@code other}. Two categories are unifiable if there exist assignments to the feature variables of each category which make both categories equal. @param other @return
[ "Returns", "{", "@code", "true", "}", "if", "this", "category", "is", "unifiable", "with", "{", "@code", "other", "}", ".", "Two", "categories", "are", "unifiable", "if", "there", "exist", "assignments", "to", "the", "feature", "variables", "of", "each", "...
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/SyntacticCategory.java#L477-L484
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.editProjectBadge
public GitlabBadge editProjectBadge(Serializable projectId, Integer badgeId, String linkUrl, String imageUrl) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + "/" + badgeId; GitlabHTTPRequestor requestor = retrieve().method(PUT); requestor.with("link_url", linkUrl) .with("image_url", imageUrl); return requestor.to(tailUrl, GitlabBadge.class); }
java
public GitlabBadge editProjectBadge(Serializable projectId, Integer badgeId, String linkUrl, String imageUrl) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + "/" + badgeId; GitlabHTTPRequestor requestor = retrieve().method(PUT); requestor.with("link_url", linkUrl) .with("image_url", imageUrl); return requestor.to(tailUrl, GitlabBadge.class); }
[ "public", "GitlabBadge", "editProjectBadge", "(", "Serializable", "projectId", ",", "Integer", "badgeId", ",", "String", "linkUrl", ",", "String", "imageUrl", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "GitlabProject", ".", "URL", "+", "\"/\"", ...
Edit project badge @param projectId The id of the project for which the badge should be edited @param badgeId The id of the badge that should be edited @param linkUrl The URL that the badge should link to @param imageUrl The URL to the badge image @return The updated badge @throws IOException on GitLab API call error
[ "Edit", "project", "badge" ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2651-L2658
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRApplication.java
GVRApplication.enableGestureDetector
public synchronized void enableGestureDetector() { final GVRTouchPadGestureListener gestureListener = new GVRTouchPadGestureListener() { @Override public boolean onSwipe(MotionEvent e, Action action, float vx, float vy) { if (null != mGVRMain) { mGVRMain.onSwipe(action, vx); } return true; } @Override public boolean onSingleTapUp(MotionEvent e) { if (null != mGVRMain) { mGVRMain.onSingleTapUp(e); } return true; } }; mGestureDetector = new GestureDetector(mActivity.getApplicationContext(), gestureListener); getEventReceiver().addListener(new GVREventListeners.ActivityEvents() { @Override public void dispatchTouchEvent(MotionEvent event) { mGestureDetector.onTouchEvent(event); } }); }
java
public synchronized void enableGestureDetector() { final GVRTouchPadGestureListener gestureListener = new GVRTouchPadGestureListener() { @Override public boolean onSwipe(MotionEvent e, Action action, float vx, float vy) { if (null != mGVRMain) { mGVRMain.onSwipe(action, vx); } return true; } @Override public boolean onSingleTapUp(MotionEvent e) { if (null != mGVRMain) { mGVRMain.onSingleTapUp(e); } return true; } }; mGestureDetector = new GestureDetector(mActivity.getApplicationContext(), gestureListener); getEventReceiver().addListener(new GVREventListeners.ActivityEvents() { @Override public void dispatchTouchEvent(MotionEvent event) { mGestureDetector.onTouchEvent(event); } }); }
[ "public", "synchronized", "void", "enableGestureDetector", "(", ")", "{", "final", "GVRTouchPadGestureListener", "gestureListener", "=", "new", "GVRTouchPadGestureListener", "(", ")", "{", "@", "Override", "public", "boolean", "onSwipe", "(", "MotionEvent", "e", ",", ...
Enables the Android GestureDetector which in turn fires the appropriate {@link GVRMain} callbacks. By default it is not. @see GVRMain#onSwipe(GVRTouchPadGestureListener.Action, float) @see GVRMain#onSingleTapUp(MotionEvent) @see GVRTouchPadGestureListener
[ "Enables", "the", "Android", "GestureDetector", "which", "in", "turn", "fires", "the", "appropriate", "{" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRApplication.java#L710-L735
StripesFramework/stripes-stuff
src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java
WaitPageInterceptor.copyErrors
protected void copyErrors(ActionBeanContext source, ActionBeanContext destination) { destination.getValidationErrors().putAll(source.getValidationErrors()); }
java
protected void copyErrors(ActionBeanContext source, ActionBeanContext destination) { destination.getValidationErrors().putAll(source.getValidationErrors()); }
[ "protected", "void", "copyErrors", "(", "ActionBeanContext", "source", ",", "ActionBeanContext", "destination", ")", "{", "destination", ".", "getValidationErrors", "(", ")", ".", "putAll", "(", "source", ".", "getValidationErrors", "(", ")", ")", ";", "}" ]
Copy errors from a context to another context. @param source source containing errors to copy @param destination where errors will be copied
[ "Copy", "errors", "from", "a", "context", "to", "another", "context", "." ]
train
https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L350-L352
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/misc/PixelMath.java
PixelMath.diffAbs
public static void diffAbs( GrayU8 imgA , GrayU8 imgB , GrayU8 output ) { InputSanityCheck.checkSameShape(imgA,imgB); output.reshape(imgA.width,imgA.height); if( BoofConcurrency.USE_CONCURRENT ) { ImplPixelMath_MT.diffAbs(imgA, imgB, output); } else { ImplPixelMath.diffAbs(imgA, imgB, output); } }
java
public static void diffAbs( GrayU8 imgA , GrayU8 imgB , GrayU8 output ) { InputSanityCheck.checkSameShape(imgA,imgB); output.reshape(imgA.width,imgA.height); if( BoofConcurrency.USE_CONCURRENT ) { ImplPixelMath_MT.diffAbs(imgA, imgB, output); } else { ImplPixelMath.diffAbs(imgA, imgB, output); } }
[ "public", "static", "void", "diffAbs", "(", "GrayU8", "imgA", ",", "GrayU8", "imgB", ",", "GrayU8", "output", ")", "{", "InputSanityCheck", ".", "checkSameShape", "(", "imgA", ",", "imgB", ")", ";", "output", ".", "reshape", "(", "imgA", ".", "width", ",...
<p> Computes the absolute value of the difference between each pixel in the two images.<br> d(x,y) = |img1(x,y) - img2(x,y)| </p> @param imgA Input image. Not modified. @param imgB Input image. Not modified. @param output Absolute value of difference image. Can be either input. Modified.
[ "<p", ">", "Computes", "the", "absolute", "value", "of", "the", "difference", "between", "each", "pixel", "in", "the", "two", "images", ".", "<br", ">", "d", "(", "x", "y", ")", "=", "|img1", "(", "x", "y", ")", "-", "img2", "(", "x", "y", ")", ...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/PixelMath.java#L4311-L4320
sebastiangraf/jSCSI
bundles/commons/src/main/java/org/jscsi/parser/ProtocolDataUnit.java
ProtocolDataUnit.serializeAdditionalHeaderSegments
private final int serializeAdditionalHeaderSegments (final ByteBuffer dst, final int offset) throws InternetSCSIException { int off = offset; for (AdditionalHeaderSegment ahs : additionalHeaderSegments) { off += ahs.serialize(dst, off); } return off - offset; }
java
private final int serializeAdditionalHeaderSegments (final ByteBuffer dst, final int offset) throws InternetSCSIException { int off = offset; for (AdditionalHeaderSegment ahs : additionalHeaderSegments) { off += ahs.serialize(dst, off); } return off - offset; }
[ "private", "final", "int", "serializeAdditionalHeaderSegments", "(", "final", "ByteBuffer", "dst", ",", "final", "int", "offset", ")", "throws", "InternetSCSIException", "{", "int", "off", "=", "offset", ";", "for", "(", "AdditionalHeaderSegment", "ahs", ":", "add...
Serialize all the contained additional header segments to the destination array starting from the given offset. @param dst The destination array to write in. @param offset The offset to start to write in <code>dst</code>. @return The written length. @throws InternetSCSIException If any violation of the iSCSI-Standard emerge.
[ "Serialize", "all", "the", "contained", "additional", "header", "segments", "to", "the", "destination", "array", "starting", "from", "the", "given", "offset", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/commons/src/main/java/org/jscsi/parser/ProtocolDataUnit.java#L250-L258
apache/incubator-shardingsphere
sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/common/MemoryQueryResultRow.java
MemoryQueryResultRow.setCell
public void setCell(final int columnIndex, final Object value) { Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.length + 1); data[columnIndex - 1] = value; }
java
public void setCell(final int columnIndex, final Object value) { Preconditions.checkArgument(columnIndex > 0 && columnIndex < data.length + 1); data[columnIndex - 1] = value; }
[ "public", "void", "setCell", "(", "final", "int", "columnIndex", ",", "final", "Object", "value", ")", "{", "Preconditions", ".", "checkArgument", "(", "columnIndex", ">", "0", "&&", "columnIndex", "<", "data", ".", "length", "+", "1", ")", ";", "data", ...
Set data for cell. @param columnIndex column index @param value data for cell
[ "Set", "data", "for", "cell", "." ]
train
https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/common/MemoryQueryResultRow.java#L64-L67
cdapio/tephra
tephra-core/src/main/java/co/cask/tephra/persist/TransactionEditCodecs.java
TransactionEditCodecs.encode
public static void encode(TransactionEdit src, DataOutput out) throws IOException { TransactionEditCodec latestCodec = CODECS.get(CODECS.firstKey()); out.writeByte(latestCodec.getVersion()); latestCodec.encode(src, out); }
java
public static void encode(TransactionEdit src, DataOutput out) throws IOException { TransactionEditCodec latestCodec = CODECS.get(CODECS.firstKey()); out.writeByte(latestCodec.getVersion()); latestCodec.encode(src, out); }
[ "public", "static", "void", "encode", "(", "TransactionEdit", "src", ",", "DataOutput", "out", ")", "throws", "IOException", "{", "TransactionEditCodec", "latestCodec", "=", "CODECS", ".", "get", "(", "CODECS", ".", "firstKey", "(", ")", ")", ";", "out", "."...
Serializes the given {@code TransactionEdit} instance with the latest available codec. This will first write out the version of the codec used to serialize the instance so that the correct codec can be used when calling {@link #decode(TransactionEdit, DataInput)}. @param src the transaction edit to serialize @param out the output stream to contain the data @throws IOException if an error occurs while serializing to the output stream
[ "Serializes", "the", "given", "{", "@code", "TransactionEdit", "}", "instance", "with", "the", "latest", "available", "codec", ".", "This", "will", "first", "write", "out", "the", "version", "of", "the", "codec", "used", "to", "serialize", "the", "instance", ...
train
https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/persist/TransactionEditCodecs.java#L79-L83
wigforss/Ka-Commons-Reflection
src/main/java/org/kasource/commons/reflection/util/AnnotationUtils.java
AnnotationUtils.getAnnotation
public static <T extends Annotation> T getAnnotation( Class<?> target, Class<T> annotationClass) { Class<?> clazz = target; T annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } while((clazz = clazz.getSuperclass()) != null) { annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } } return null; }
java
public static <T extends Annotation> T getAnnotation( Class<?> target, Class<T> annotationClass) { Class<?> clazz = target; T annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } while((clazz = clazz.getSuperclass()) != null) { annotation = clazz.getAnnotation(annotationClass); if(annotation != null) { return annotation; } } return null; }
[ "public", "static", "<", "T", "extends", "Annotation", ">", "T", "getAnnotation", "(", "Class", "<", "?", ">", "target", ",", "Class", "<", "T", ">", "annotationClass", ")", "{", "Class", "<", "?", ">", "clazz", "=", "target", ";", "T", "annotation", ...
Returns the annotation of the annotationClass of the clazz or any of it super classes. @param clazz The class to inspect. @param annotationClass Class of the annotation to return @return The annotation of annnotationClass if found else null.
[ "Returns", "the", "annotation", "of", "the", "annotationClass", "of", "the", "clazz", "or", "any", "of", "it", "super", "classes", "." ]
train
https://github.com/wigforss/Ka-Commons-Reflection/blob/a80f7a164cd800089e4f4dd948ca6f0e7badcf33/src/main/java/org/kasource/commons/reflection/util/AnnotationUtils.java#L67-L80
michael-rapp/AndroidMaterialDialog
library/src/main/java/de/mrapp/android/dialog/view/DialogRootView.java
DialogRootView.applyDialogPaddingBottom
private void applyDialogPaddingBottom(@NonNull final Area area, @NonNull final View view) { if (area != Area.HEADER && area != Area.BUTTON_BAR) { view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), dialogPadding[3]); } }
java
private void applyDialogPaddingBottom(@NonNull final Area area, @NonNull final View view) { if (area != Area.HEADER && area != Area.BUTTON_BAR) { view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), dialogPadding[3]); } }
[ "private", "void", "applyDialogPaddingBottom", "(", "@", "NonNull", "final", "Area", "area", ",", "@", "NonNull", "final", "View", "view", ")", "{", "if", "(", "area", "!=", "Area", ".", "HEADER", "&&", "area", "!=", "Area", ".", "BUTTON_BAR", ")", "{", ...
Applies the dialog's bottom padding to the view of a specific area. @param area The area, the view, the padding should be applied to, corresponds to, as an instance of the class {@link Area}. The area may not be null @param view The view, the padding should be applied to, as an instance of the class {@link View}. The view may not be null
[ "Applies", "the", "dialog", "s", "bottom", "padding", "to", "the", "view", "of", "a", "specific", "area", "." ]
train
https://github.com/michael-rapp/AndroidMaterialDialog/blob/8990eed72ee5f5a9720836ee708f71ac0d43053b/library/src/main/java/de/mrapp/android/dialog/view/DialogRootView.java#L720-L725
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/resource/BatchLinkingService.java
BatchLinkingService.resolveBatched
public EObject resolveBatched(EObject context, EReference reference, String uriFragment) { return resolveBatched(context, reference, uriFragment, CancelIndicator.NullImpl); }
java
public EObject resolveBatched(EObject context, EReference reference, String uriFragment) { return resolveBatched(context, reference, uriFragment, CancelIndicator.NullImpl); }
[ "public", "EObject", "resolveBatched", "(", "EObject", "context", ",", "EReference", "reference", ",", "String", "uriFragment", ")", "{", "return", "resolveBatched", "(", "context", ",", "reference", ",", "uriFragment", ",", "CancelIndicator", ".", "NullImpl", ")"...
@param context the current instance that owns the referenced proxy. @param reference the {@link EReference} that has the proxy value. @param uriFragment the lazy linking fragment. @return the resolved object for the given context or <code>null</code> if it couldn't be resolved
[ "@param", "context", "the", "current", "instance", "that", "owns", "the", "referenced", "proxy", ".", "@param", "reference", "the", "{", "@link", "EReference", "}", "that", "has", "the", "proxy", "value", ".", "@param", "uriFragment", "the", "lazy", "linking",...
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/resource/BatchLinkingService.java#L40-L42
apptik/jus
examples-android/src/main/java/io/apptik/comm/jus/examples/nav/JToggle.java
JToggle.onDrawerSlide
@Override public void onDrawerSlide(View drawerView, float slideOffset) { mSlider.setPosition(Math.min(1f, Math.max(0, slideOffset))); }
java
@Override public void onDrawerSlide(View drawerView, float slideOffset) { mSlider.setPosition(Math.min(1f, Math.max(0, slideOffset))); }
[ "@", "Override", "public", "void", "onDrawerSlide", "(", "View", "drawerView", ",", "float", "slideOffset", ")", "{", "mSlider", ".", "setPosition", "(", "Math", ".", "min", "(", "1f", ",", "Math", ".", "max", "(", "0", ",", "slideOffset", ")", ")", ")...
{@link DrawerLayout.DrawerListener} callback method. If you do not use your JToggle instance directly as your DrawerLayout's listener, you should call through to this method from your own listener object. @param drawerView The child view that was moved @param slideOffset The new offset of this drawer within its range, from 0-1
[ "{", "@link", "DrawerLayout", ".", "DrawerListener", "}", "callback", "method", ".", "If", "you", "do", "not", "use", "your", "JToggle", "instance", "directly", "as", "your", "DrawerLayout", "s", "listener", "you", "should", "call", "through", "to", "this", ...
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/examples-android/src/main/java/io/apptik/comm/jus/examples/nav/JToggle.java#L377-L380
strator-dev/greenpepper
greenpepper/core/src/main/java/com/greenpepper/systemunderdevelopment/DefaultSystemUnderDevelopment.java
DefaultSystemUnderDevelopment.getFixture
public Fixture getFixture( String name, String... params ) throws Throwable { Type<?> type = loadType( name ); Object target = type.newInstanceUsingCoercion( params ); return new DefaultFixture( target ); }
java
public Fixture getFixture( String name, String... params ) throws Throwable { Type<?> type = loadType( name ); Object target = type.newInstanceUsingCoercion( params ); return new DefaultFixture( target ); }
[ "public", "Fixture", "getFixture", "(", "String", "name", ",", "String", "...", "params", ")", "throws", "Throwable", "{", "Type", "<", "?", ">", "type", "=", "loadType", "(", "name", ")", ";", "Object", "target", "=", "type", ".", "newInstanceUsingCoercio...
Creates a new instance of a fixture class using a set of parameters. @param name the name of the class to instantiate @param params the parameters (constructor arguments) @return a new instance of the fixtureClass with fields populated using Constructor @throws Exception if any. @throws java.lang.Throwable if any.
[ "Creates", "a", "new", "instance", "of", "a", "fixture", "class", "using", "a", "set", "of", "parameters", "." ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/core/src/main/java/com/greenpepper/systemunderdevelopment/DefaultSystemUnderDevelopment.java#L77-L82
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/split/ST_Split.java
ST_Split.splitPolygonWithLine
private static Geometry splitPolygonWithLine(Polygon polygon, LineString lineString) throws SQLException { Collection<Polygon> pols = polygonWithLineSplitter(polygon, lineString); if (pols != null) { return FACTORY.buildGeometry(polygonWithLineSplitter(polygon, lineString)); } return null; }
java
private static Geometry splitPolygonWithLine(Polygon polygon, LineString lineString) throws SQLException { Collection<Polygon> pols = polygonWithLineSplitter(polygon, lineString); if (pols != null) { return FACTORY.buildGeometry(polygonWithLineSplitter(polygon, lineString)); } return null; }
[ "private", "static", "Geometry", "splitPolygonWithLine", "(", "Polygon", "polygon", ",", "LineString", "lineString", ")", "throws", "SQLException", "{", "Collection", "<", "Polygon", ">", "pols", "=", "polygonWithLineSplitter", "(", "polygon", ",", "lineString", ")"...
Splits a Polygon using a LineString. @param polygon @param lineString @return
[ "Splits", "a", "Polygon", "using", "a", "LineString", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/split/ST_Split.java#L254-L260
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/converters/Converters.java
Converters.toDBObject
public void toDBObject(final Object containingObject, final MappedField mf, final DBObject dbObj, final MapperOptions opts) { final Object fieldValue = mf.getFieldValue(containingObject); final TypeConverter enc = getEncoder(fieldValue, mf); final Object encoded = enc.encode(fieldValue, mf); if (encoded != null || opts.isStoreNulls()) { dbObj.put(mf.getNameToStore(), encoded); } }
java
public void toDBObject(final Object containingObject, final MappedField mf, final DBObject dbObj, final MapperOptions opts) { final Object fieldValue = mf.getFieldValue(containingObject); final TypeConverter enc = getEncoder(fieldValue, mf); final Object encoded = enc.encode(fieldValue, mf); if (encoded != null || opts.isStoreNulls()) { dbObj.put(mf.getNameToStore(), encoded); } }
[ "public", "void", "toDBObject", "(", "final", "Object", "containingObject", ",", "final", "MappedField", "mf", ",", "final", "DBObject", "dbObj", ",", "final", "MapperOptions", "opts", ")", "{", "final", "Object", "fieldValue", "=", "mf", ".", "getFieldValue", ...
Converts an entity to a DBObject @param containingObject The object to convert @param mf the MappedField to extract @param dbObj the DBObject to populate @param opts the options to apply
[ "Converts", "an", "entity", "to", "a", "DBObject" ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/converters/Converters.java#L239-L247
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.executeConnectionAsync
public static RequestAsyncTask executeConnectionAsync(Handler callbackHandler, HttpURLConnection connection, RequestBatch requests) { Validate.notNull(connection, "connection"); RequestAsyncTask asyncTask = new RequestAsyncTask(connection, requests); requests.setCallbackHandler(callbackHandler); asyncTask.executeOnSettingsExecutor(); return asyncTask; }
java
public static RequestAsyncTask executeConnectionAsync(Handler callbackHandler, HttpURLConnection connection, RequestBatch requests) { Validate.notNull(connection, "connection"); RequestAsyncTask asyncTask = new RequestAsyncTask(connection, requests); requests.setCallbackHandler(callbackHandler); asyncTask.executeOnSettingsExecutor(); return asyncTask; }
[ "public", "static", "RequestAsyncTask", "executeConnectionAsync", "(", "Handler", "callbackHandler", ",", "HttpURLConnection", "connection", ",", "RequestBatch", "requests", ")", "{", "Validate", ".", "notNull", "(", "connection", ",", "\"connection\"", ")", ";", "Req...
Asynchronously 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. This function will return immediately, and the requests will be processed on a separate thread. In order to process results of a request, or determine whether a request succeeded or failed, a callback must be specified (see the {@link #setCallback(Callback) setCallback} method) <p/> This should only be called from the UI thread. @param callbackHandler a Handler that will be used to post calls to the callback for each request; if null, a Handler will be instantiated on the calling thread @param connection the HttpURLConnection that the requests were serialized into @param requests the requests represented by the HttpURLConnection @return a RequestAsyncTask that is executing the request
[ "Asynchronously", "executes", "requests", "that", "have", "already", "been", "serialized", "into", "an", "HttpURLConnection", ".", "No", "validation", "is", "done", "that", "the", "contents", "of", "the", "connection", "actually", "reflect", "the", "serialized", "...
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L1619-L1627
agmip/translator-dssat
src/main/java/org/agmip/translators/dssat/DssatControllerOutput.java
DssatControllerOutput.writeSingleExp
private void writeSingleExp(String arg0, Map result, DssatCommonOutput output, String file) { futFiles.put(file, executor.submit(new DssatTranslateRunner(output, result, arg0))); }
java
private void writeSingleExp(String arg0, Map result, DssatCommonOutput output, String file) { futFiles.put(file, executor.submit(new DssatTranslateRunner(output, result, arg0))); }
[ "private", "void", "writeSingleExp", "(", "String", "arg0", ",", "Map", "result", ",", "DssatCommonOutput", "output", ",", "String", "file", ")", "{", "futFiles", ".", "put", "(", "file", ",", "executor", ".", "submit", "(", "new", "DssatTranslateRunner", "(...
Write files and add file objects in the array @param arg0 file output path @param result data holder object @param output DSSAT translator object @param file Generated DSSAT file identifier
[ "Write", "files", "and", "add", "file", "objects", "in", "the", "array" ]
train
https://github.com/agmip/translator-dssat/blob/4be61d998f106eb7234ea8701b63c3746ae688f4/src/main/java/org/agmip/translators/dssat/DssatControllerOutput.java#L274-L276
i-net-software/jlessc
src/com/inet/lib/less/UrlUtils.java
UrlUtils.dataUri
static void dataUri( CssFormatter formatter, byte[] bytes, String urlStr, String type ) { if( type == null ) { switch( urlStr.substring( urlStr.lastIndexOf( '.' ) + 1 ) ) { case "gif": type = "image/gif;base64"; break; case "png": type = "image/png;base64"; break; case "jpg": case "jpeg": type = "image/jpeg;base64"; break; default: type = "text/html"; } } else { type = removeQuote( type ); } if( type.endsWith( "base64" ) ) { formatter.append( "url(\"data:" ).append( type ).append( ',' ); formatter.append( toBase64( bytes ) ); formatter.append( "\")" ); } else { formatter.append( "url(\"data:" ).append( type ).append( ',' ); appendEncode( formatter, bytes ); formatter.append( "\")" ); } }
java
static void dataUri( CssFormatter formatter, byte[] bytes, String urlStr, String type ) { if( type == null ) { switch( urlStr.substring( urlStr.lastIndexOf( '.' ) + 1 ) ) { case "gif": type = "image/gif;base64"; break; case "png": type = "image/png;base64"; break; case "jpg": case "jpeg": type = "image/jpeg;base64"; break; default: type = "text/html"; } } else { type = removeQuote( type ); } if( type.endsWith( "base64" ) ) { formatter.append( "url(\"data:" ).append( type ).append( ',' ); formatter.append( toBase64( bytes ) ); formatter.append( "\")" ); } else { formatter.append( "url(\"data:" ).append( type ).append( ',' ); appendEncode( formatter, bytes ); formatter.append( "\")" ); } }
[ "static", "void", "dataUri", "(", "CssFormatter", "formatter", ",", "byte", "[", "]", "bytes", ",", "String", "urlStr", ",", "String", "type", ")", "{", "if", "(", "type", "==", "null", ")", "{", "switch", "(", "urlStr", ".", "substring", "(", "urlStr"...
Write the bytes as inline url. @param formatter current formatter @param bytes the bytes @param urlStr used if mime type is null to detect the mime type @param type the mime type
[ "Write", "the", "bytes", "as", "inline", "url", "." ]
train
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/UrlUtils.java#L217-L246
HubSpot/Singularity
SingularityService/src/main/java/com/hubspot/singularity/data/SingularityValidator.java
SingularityValidator.getNewDayOfWeekValue
private String getNewDayOfWeekValue(String schedule, int dayOfWeekValue) { String newDayOfWeekValue = null; checkBadRequest(dayOfWeekValue >= 0 && dayOfWeekValue <= 7, "Schedule %s is invalid, day of week (%s) is not 0-7", schedule, dayOfWeekValue); switch (dayOfWeekValue) { case 7: case 0: newDayOfWeekValue = "SUN"; break; case 1: newDayOfWeekValue = "MON"; break; case 2: newDayOfWeekValue = "TUE"; break; case 3: newDayOfWeekValue = "WED"; break; case 4: newDayOfWeekValue = "THU"; break; case 5: newDayOfWeekValue = "FRI"; break; case 6: newDayOfWeekValue = "SAT"; break; default: badRequest("Schedule %s is invalid, day of week (%s) is not 0-7", schedule, dayOfWeekValue); break; } return newDayOfWeekValue; }
java
private String getNewDayOfWeekValue(String schedule, int dayOfWeekValue) { String newDayOfWeekValue = null; checkBadRequest(dayOfWeekValue >= 0 && dayOfWeekValue <= 7, "Schedule %s is invalid, day of week (%s) is not 0-7", schedule, dayOfWeekValue); switch (dayOfWeekValue) { case 7: case 0: newDayOfWeekValue = "SUN"; break; case 1: newDayOfWeekValue = "MON"; break; case 2: newDayOfWeekValue = "TUE"; break; case 3: newDayOfWeekValue = "WED"; break; case 4: newDayOfWeekValue = "THU"; break; case 5: newDayOfWeekValue = "FRI"; break; case 6: newDayOfWeekValue = "SAT"; break; default: badRequest("Schedule %s is invalid, day of week (%s) is not 0-7", schedule, dayOfWeekValue); break; } return newDayOfWeekValue; }
[ "private", "String", "getNewDayOfWeekValue", "(", "String", "schedule", ",", "int", "dayOfWeekValue", ")", "{", "String", "newDayOfWeekValue", "=", "null", ";", "checkBadRequest", "(", "dayOfWeekValue", ">=", "0", "&&", "dayOfWeekValue", "<=", "7", ",", "\"Schedul...
Standard cron: day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0) Quartz: 1-7 or SUN-SAT
[ "Standard", "cron", ":", "day", "of", "week", "(", "0", "-", "6", ")", "(", "0", "to", "6", "are", "Sunday", "to", "Saturday", "or", "use", "names", ";", "7", "is", "Sunday", "the", "same", "as", "0", ")", "Quartz", ":", "1", "-", "7", "or", ...
train
https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityService/src/main/java/com/hubspot/singularity/data/SingularityValidator.java#L644-L678
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.entryEquals
public static boolean entryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) { try { return doEntryEquals(zf1, zf2, path1, path2); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } }
java
public static boolean entryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) { try { return doEntryEquals(zf1, zf2, path1, path2); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } }
[ "public", "static", "boolean", "entryEquals", "(", "ZipFile", "zf1", ",", "ZipFile", "zf2", ",", "String", "path1", ",", "String", "path2", ")", "{", "try", "{", "return", "doEntryEquals", "(", "zf1", ",", "zf2", ",", "path1", ",", "path2", ")", ";", "...
Compares two ZIP entries (byte-by-byte). . @param zf1 first ZIP file. @param zf2 second ZIP file. @param path1 name of the first entry. @param path2 name of the second entry. @return <code>true</code> if the contents of the entries were same.
[ "Compares", "two", "ZIP", "entries", "(", "byte", "-", "by", "-", "byte", ")", ".", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L3263-L3270
pryzach/midao
midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java
TypeHandlerUtils.convertClob
public static Object convertClob(Object clob, InputStream input) throws SQLException { return convertClob(clob, toByteArray(input)); }
java
public static Object convertClob(Object clob, InputStream input) throws SQLException { return convertClob(clob, toByteArray(input)); }
[ "public", "static", "Object", "convertClob", "(", "Object", "clob", ",", "InputStream", "input", ")", "throws", "SQLException", "{", "return", "convertClob", "(", "clob", ",", "toByteArray", "(", "input", ")", ")", ";", "}" ]
Transfers data from InputStream into sql.Clob <p/> Using default locale. If different locale is required see {@link #convertClob(java.sql.Connection, String)} @param clob sql.Clob which would be filled @param input InputStream @return sql.Clob from InputStream @throws SQLException
[ "Transfers", "data", "from", "InputStream", "into", "sql", ".", "Clob", "<p", "/", ">", "Using", "default", "locale", ".", "If", "different", "locale", "is", "required", "see", "{", "@link", "#convertClob", "(", "java", ".", "sql", ".", "Connection", "Stri...
train
https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/type/TypeHandlerUtils.java#L261-L263
Stratio/stratio-cassandra
src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java
DebuggableThreadPoolExecutor.createWithMaximumPoolSize
public static DebuggableThreadPoolExecutor createWithMaximumPoolSize(String threadPoolName, int size, int keepAliveTime, TimeUnit unit) { return new DebuggableThreadPoolExecutor(size, Integer.MAX_VALUE, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(threadPoolName)); }
java
public static DebuggableThreadPoolExecutor createWithMaximumPoolSize(String threadPoolName, int size, int keepAliveTime, TimeUnit unit) { return new DebuggableThreadPoolExecutor(size, Integer.MAX_VALUE, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(threadPoolName)); }
[ "public", "static", "DebuggableThreadPoolExecutor", "createWithMaximumPoolSize", "(", "String", "threadPoolName", ",", "int", "size", ",", "int", "keepAliveTime", ",", "TimeUnit", "unit", ")", "{", "return", "new", "DebuggableThreadPoolExecutor", "(", "size", ",", "In...
Returns a ThreadPoolExecutor with a fixed maximum number of threads, but whose threads are terminated when idle for too long. When all threads are actively executing tasks, new tasks are queued. @param threadPoolName the name of the threads created by this executor @param size the maximum number of threads for this executor @param keepAliveTime the time an idle thread is kept alive before being terminated @param unit tht time unit for {@code keepAliveTime} @return the new DebuggableThreadPoolExecutor
[ "Returns", "a", "ThreadPoolExecutor", "with", "a", "fixed", "maximum", "number", "of", "threads", "but", "whose", "threads", "are", "terminated", "when", "idle", "for", "too", "long", ".", "When", "all", "threads", "are", "actively", "executing", "tasks", "new...
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/DebuggableThreadPoolExecutor.java#L125-L128
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java
DfuBaseService.openInputStream
private InputStream openInputStream(@NonNull final String filePath, final String mimeType, final int mbrSize, final int types) throws IOException { final InputStream is = new FileInputStream(filePath); if (MIME_TYPE_ZIP.equals(mimeType)) return new ArchiveInputStream(is, mbrSize, types); if (filePath.toLowerCase(Locale.US).endsWith("hex")) return new HexInputStream(is, mbrSize); return is; }
java
private InputStream openInputStream(@NonNull final String filePath, final String mimeType, final int mbrSize, final int types) throws IOException { final InputStream is = new FileInputStream(filePath); if (MIME_TYPE_ZIP.equals(mimeType)) return new ArchiveInputStream(is, mbrSize, types); if (filePath.toLowerCase(Locale.US).endsWith("hex")) return new HexInputStream(is, mbrSize); return is; }
[ "private", "InputStream", "openInputStream", "(", "@", "NonNull", "final", "String", "filePath", ",", "final", "String", "mimeType", ",", "final", "int", "mbrSize", ",", "final", "int", "types", ")", "throws", "IOException", "{", "final", "InputStream", "is", ...
Opens the binary input stream that returns the firmware image content. A Path to the file is given. @param filePath the path to the HEX, BIN or ZIP file. @param mimeType the file type. @param mbrSize the size of MBR, by default 0x1000. @param types the content files types in ZIP. @return The input stream with binary image content.
[ "Opens", "the", "binary", "input", "stream", "that", "returns", "the", "firmware", "image", "content", ".", "A", "Path", "to", "the", "file", "is", "given", "." ]
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/DfuBaseService.java#L1416-L1424
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/tracker/klt/KltTracker.java
KltTracker.unsafe_setImage
public void unsafe_setImage(I image, D derivX, D derivY) { this.image = image; this.interpInput.setImage(image); this.derivX = derivX; this.derivY = derivY; }
java
public void unsafe_setImage(I image, D derivX, D derivY) { this.image = image; this.interpInput.setImage(image); this.derivX = derivX; this.derivY = derivY; }
[ "public", "void", "unsafe_setImage", "(", "I", "image", ",", "D", "derivX", ",", "D", "derivY", ")", "{", "this", ".", "image", "=", "image", ";", "this", ".", "interpInput", ".", "setImage", "(", "image", ")", ";", "this", ".", "derivX", "=", "deriv...
Same as {@link #setImage}, but it doesn't check to see if the images are the same size each time
[ "Same", "as", "{" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/tracker/klt/KltTracker.java#L132-L138
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/Zodiac.java
Zodiac.getZodiac
public static String getZodiac(int month, int day) { // 在分隔日前为前一个星座,否则为后一个星座 return day < dayArr[month] ? ZODIACS[month] : ZODIACS[month + 1]; }
java
public static String getZodiac(int month, int day) { // 在分隔日前为前一个星座,否则为后一个星座 return day < dayArr[month] ? ZODIACS[month] : ZODIACS[month + 1]; }
[ "public", "static", "String", "getZodiac", "(", "int", "month", ",", "int", "day", ")", "{", "// 在分隔日前为前一个星座,否则为后一个星座\r", "return", "day", "<", "dayArr", "[", "month", "]", "?", "ZODIACS", "[", "month", "]", ":", "ZODIACS", "[", "month", "+", "1", "]", ...
通过生日计算星座 @param month 月,从0开始计数,见{@link Month#getValue()} @param day 天 @return 星座名
[ "通过生日计算星座" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/Zodiac.java#L62-L65
apache/groovy
src/main/groovy/groovy/transform/stc/ClosureSignatureHint.java
ClosureSignatureHint.pickGenericType
public static ClassNode pickGenericType(ClassNode type, int gtIndex) { final GenericsType[] genericsTypes = type.getGenericsTypes(); if (genericsTypes==null || genericsTypes.length<gtIndex) { return ClassHelper.OBJECT_TYPE; } return genericsTypes[gtIndex].getType(); }
java
public static ClassNode pickGenericType(ClassNode type, int gtIndex) { final GenericsType[] genericsTypes = type.getGenericsTypes(); if (genericsTypes==null || genericsTypes.length<gtIndex) { return ClassHelper.OBJECT_TYPE; } return genericsTypes[gtIndex].getType(); }
[ "public", "static", "ClassNode", "pickGenericType", "(", "ClassNode", "type", ",", "int", "gtIndex", ")", "{", "final", "GenericsType", "[", "]", "genericsTypes", "=", "type", ".", "getGenericsTypes", "(", ")", ";", "if", "(", "genericsTypes", "==", "null", ...
A helper method which will extract the n-th generic type from a class node. @param type the class node from which to pick a generic type @param gtIndex the index of the generic type to extract @return the n-th generic type, or {@link org.codehaus.groovy.ast.ClassHelper#OBJECT_TYPE} if it doesn't exist.
[ "A", "helper", "method", "which", "will", "extract", "the", "n", "-", "th", "generic", "type", "from", "a", "class", "node", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/transform/stc/ClosureSignatureHint.java#L61-L67
weld/core
impl/src/main/java/org/jboss/weld/security/GetDeclaredMethodAction.java
GetDeclaredMethodAction.wrapException
public static PrivilegedAction<Method> wrapException(Class<?> javaClass, String methodName, Class<?>... parameterTypes) { return new WrappingAction(javaClass, methodName, parameterTypes); }
java
public static PrivilegedAction<Method> wrapException(Class<?> javaClass, String methodName, Class<?>... parameterTypes) { return new WrappingAction(javaClass, methodName, parameterTypes); }
[ "public", "static", "PrivilegedAction", "<", "Method", ">", "wrapException", "(", "Class", "<", "?", ">", "javaClass", ",", "String", "methodName", ",", "Class", "<", "?", ">", "...", "parameterTypes", ")", "{", "return", "new", "WrappingAction", "(", "javaC...
Returns {@link PrivilegedAction} instead of {@link PrivilegedExceptionAction}. If {@link NoSuchMethodException} is thrown it is wrapped within {@link WeldException} using {@link ReflectionLogger#noSuchMethodWrapper(NoSuchMethodException, String)}.
[ "Returns", "{" ]
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/security/GetDeclaredMethodAction.java#L36-L38
hankcs/HanLP
src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java
TfIdf.idfFromTfs
public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs) { return idfFromTfs(tfs, true, true); }
java
public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs) { return idfFromTfs(tfs, true, true); }
[ "public", "static", "<", "TERM", ">", "Map", "<", "TERM", ",", "Double", ">", "idfFromTfs", "(", "Iterable", "<", "Map", "<", "TERM", ",", "Double", ">", ">", "tfs", ")", "{", "return", "idfFromTfs", "(", "tfs", ",", "true", ",", "true", ")", ";", ...
从词频集合建立倒排频率(默认平滑词频,且加一平滑tf-idf) @param tfs 次品集合 @param <TERM> 词语类型 @return 一个词语->倒排文档的Map
[ "从词频集合建立倒排频率(默认平滑词频,且加一平滑tf", "-", "idf)" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java#L243-L246
cdk/cdk
legacy/src/main/java/org/openscience/cdk/smsd/tools/BondEnergies.java
BondEnergies.getEnergies
public int getEnergies(IAtom sourceAtom, IAtom targetAtom, Order bondOrder) { int dKJPerMol = -1; for (Map.Entry<Integer, BondEnergy> entry : bondEngergies.entrySet()) { BondEnergy bondEnergy = entry.getValue(); String atom1 = bondEnergy.getSymbolFirstAtom(); String atom2 = bondEnergy.getSymbolSecondAtom(); if ((atom1.equalsIgnoreCase(sourceAtom.getSymbol()) && atom2.equalsIgnoreCase(targetAtom.getSymbol())) || (atom2.equalsIgnoreCase(sourceAtom.getSymbol()) && atom1 .equalsIgnoreCase(targetAtom.getSymbol()))) { Order order = bondEnergy.getBondOrder(); if (order.compareTo(bondOrder) == 0) { dKJPerMol = bondEnergy.getEnergy(); } } } return dKJPerMol; }
java
public int getEnergies(IAtom sourceAtom, IAtom targetAtom, Order bondOrder) { int dKJPerMol = -1; for (Map.Entry<Integer, BondEnergy> entry : bondEngergies.entrySet()) { BondEnergy bondEnergy = entry.getValue(); String atom1 = bondEnergy.getSymbolFirstAtom(); String atom2 = bondEnergy.getSymbolSecondAtom(); if ((atom1.equalsIgnoreCase(sourceAtom.getSymbol()) && atom2.equalsIgnoreCase(targetAtom.getSymbol())) || (atom2.equalsIgnoreCase(sourceAtom.getSymbol()) && atom1 .equalsIgnoreCase(targetAtom.getSymbol()))) { Order order = bondEnergy.getBondOrder(); if (order.compareTo(bondOrder) == 0) { dKJPerMol = bondEnergy.getEnergy(); } } } return dKJPerMol; }
[ "public", "int", "getEnergies", "(", "IAtom", "sourceAtom", ",", "IAtom", "targetAtom", ",", "Order", "bondOrder", ")", "{", "int", "dKJPerMol", "=", "-", "1", ";", "for", "(", "Map", ".", "Entry", "<", "Integer", ",", "BondEnergy", ">", "entry", ":", ...
Returns bond energy for a bond type, given atoms and bond type @param sourceAtom First bondEnergy @param targetAtom Second bondEnergy @param bondOrder (single, double etc) @return bond energy
[ "Returns", "bond", "energy", "for", "a", "bond", "type", "given", "atoms", "and", "bond", "type" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/smsd/tools/BondEnergies.java#L244-L262
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/util/binary/BitInputStream.java
BitInputStream.readAhead
public Bits readAhead(final int bytes) throws IOException { assert (0 < bytes); if (0 < bytes) { final byte[] buffer = new byte[bytes]; int bytesRead = this.inner.read(buffer); if (bytesRead > 0) { this.remainder = this.remainder.concatenate(new Bits(Arrays.copyOf(buffer, bytesRead))); } } return this.remainder; }
java
public Bits readAhead(final int bytes) throws IOException { assert (0 < bytes); if (0 < bytes) { final byte[] buffer = new byte[bytes]; int bytesRead = this.inner.read(buffer); if (bytesRead > 0) { this.remainder = this.remainder.concatenate(new Bits(Arrays.copyOf(buffer, bytesRead))); } } return this.remainder; }
[ "public", "Bits", "readAhead", "(", "final", "int", "bytes", ")", "throws", "IOException", "{", "assert", "(", "0", "<", "bytes", ")", ";", "if", "(", "0", "<", "bytes", ")", "{", "final", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "bytes...
Read ahead bits. @param bytes the bytes @return the bits @throws IOException the io exception
[ "Read", "ahead", "bits", "." ]
train
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/binary/BitInputStream.java#L150-L160
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java
SDBaseOps.gt
public SDVariable gt(SDVariable x, SDVariable y) { return gt(null, x, y); }
java
public SDVariable gt(SDVariable x, SDVariable y) { return gt(null, x, y); }
[ "public", "SDVariable", "gt", "(", "SDVariable", "x", ",", "SDVariable", "y", ")", "{", "return", "gt", "(", "null", ",", "x", ",", "y", ")", ";", "}" ]
Greater than operation: elementwise x > y<br> If x and y arrays have equal shape, the output shape is the same as these inputs.<br> Note: supports broadcasting if x and y have different shapes and are broadcastable.<br> Returns an array with values 1 where condition is satisfied, or value 0 otherwise. @param x Input 1 @param y Input 2 @return Output SDVariable with values 0 and 1 based on where the condition is satisfied
[ "Greater", "than", "operation", ":", "elementwise", "x", ">", "y<br", ">", "If", "x", "and", "y", "arrays", "have", "equal", "shape", "the", "output", "shape", "is", "the", "same", "as", "these", "inputs", ".", "<br", ">", "Note", ":", "supports", "bro...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L650-L652
Netflix/governator
governator-servlet/src/main/java/com/netflix/governator/guice/servlet/GovernatorServletContextListener.java
GovernatorServletContextListener.getInjector
protected final Injector getInjector() { if (injector != null) { throw new IllegalStateException("Injector already created."); } try { injector = createInjector(); } catch (Exception e) { LOG.error("Failed to created injector", e); throw new ProvisionException("Failed to create injector", e); } return injector; }
java
protected final Injector getInjector() { if (injector != null) { throw new IllegalStateException("Injector already created."); } try { injector = createInjector(); } catch (Exception e) { LOG.error("Failed to created injector", e); throw new ProvisionException("Failed to create injector", e); } return injector; }
[ "protected", "final", "Injector", "getInjector", "(", ")", "{", "if", "(", "injector", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Injector already created.\"", ")", ";", "}", "try", "{", "injector", "=", "createInjector", "(", ")"...
Override this method to create (or otherwise obtain a reference to) your injector. NOTE: If everything is set up right, then this method should only be called once during application startup.
[ "Override", "this", "method", "to", "create", "(", "or", "otherwise", "obtain", "a", "reference", "to", ")", "your", "injector", ".", "NOTE", ":", "If", "everything", "is", "set", "up", "right", "then", "this", "method", "should", "only", "be", "called", ...
train
https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-servlet/src/main/java/com/netflix/governator/guice/servlet/GovernatorServletContextListener.java#L102-L114
lamydev/Android-Notification
core/src/zemin/notification/NotificationViewCallback.java
NotificationViewCallback.onUpdateNotification
public void onUpdateNotification(NotificationView view, View contentView, NotificationEntry entry, int layoutId) { if (DBG) Log.v(TAG, "onUpdateNotification - " + entry.ID); final Drawable icon = entry.iconDrawable; final CharSequence title = entry.title; final CharSequence text = entry.text; final CharSequence when = entry.showWhen ? entry.whenFormatted : null; ChildViewManager mgr = view.getChildViewManager(); mgr.setImageDrawable(ICON, icon, false); mgr.setText(TITLE, title, false); mgr.setText(TEXT, text, false); mgr.setText(WHEN, when, false); }
java
public void onUpdateNotification(NotificationView view, View contentView, NotificationEntry entry, int layoutId) { if (DBG) Log.v(TAG, "onUpdateNotification - " + entry.ID); final Drawable icon = entry.iconDrawable; final CharSequence title = entry.title; final CharSequence text = entry.text; final CharSequence when = entry.showWhen ? entry.whenFormatted : null; ChildViewManager mgr = view.getChildViewManager(); mgr.setImageDrawable(ICON, icon, false); mgr.setText(TITLE, title, false); mgr.setText(TEXT, text, false); mgr.setText(WHEN, when, false); }
[ "public", "void", "onUpdateNotification", "(", "NotificationView", "view", ",", "View", "contentView", ",", "NotificationEntry", "entry", ",", "int", "layoutId", ")", "{", "if", "(", "DBG", ")", "Log", ".", "v", "(", "TAG", ",", "\"onUpdateNotification - \"", ...
Called when a notification is being updated. @param view @param contentView @param entry @param layoutId
[ "Called", "when", "a", "notification", "is", "being", "updated", "." ]
train
https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationViewCallback.java#L153-L167
shrinkwrap/shrinkwrap
api/src/main/java/org/jboss/shrinkwrap/api/ShrinkWrap.java
ShrinkWrap.createFromZipFile
public static <T extends Assignable> T createFromZipFile(final Class<T> type, final File archiveFile) throws IllegalArgumentException, ArchiveImportException { // Delegate return getDefaultDomain().getArchiveFactory().createFromZipFile(type, archiveFile); }
java
public static <T extends Assignable> T createFromZipFile(final Class<T> type, final File archiveFile) throws IllegalArgumentException, ArchiveImportException { // Delegate return getDefaultDomain().getArchiveFactory().createFromZipFile(type, archiveFile); }
[ "public", "static", "<", "T", "extends", "Assignable", ">", "T", "createFromZipFile", "(", "final", "Class", "<", "T", ">", "type", ",", "final", "File", "archiveFile", ")", "throws", "IllegalArgumentException", ",", "ArchiveImportException", "{", "// Delegate", ...
Creates a new archive of the specified type as imported from the specified {@link File}. The file is expected to be encoded as ZIP (ie. JAR/WAR/EAR). The name of the archive will be set to {@link File#getName()}. The archive will be be backed by the {@link Configuration} within the {@link ShrinkWrap#getDefaultDomain()} @param type The type of the archive e.g. {@link org.jboss.shrinkwrap.api.spec.WebArchive} @param archiveFile the archiveName to use @return An {@link Assignable} view @throws IllegalArgumentException If either argument is not supplied, if the specified {@link File} does not exist, or is not a valid ZIP file @throws org.jboss.shrinkwrap.api.importer.ArchiveImportException If an error occurred during the import process
[ "Creates", "a", "new", "archive", "of", "the", "specified", "type", "as", "imported", "from", "the", "specified", "{", "@link", "File", "}", ".", "The", "file", "is", "expected", "to", "be", "encoded", "as", "ZIP", "(", "ie", ".", "JAR", "/", "WAR", ...
train
https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/api/src/main/java/org/jboss/shrinkwrap/api/ShrinkWrap.java#L182-L186
CenturyLinkCloud/mdw
mdw-hub/src/com/centurylink/mdw/hub/servlet/SoapServlet.java
SoapServlet.createSoapFaultResponse
protected String createSoapFaultResponse(String soapVersion, String code, String message) throws SOAPException, TransformerException { SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage(); SOAPBody soapBody = soapMessage.getSOAPBody(); /** * Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use * the elementName otherwise it throws an exception * * @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html */ SOAPFault fault = null; if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL)) { // existing 1.1 functionality fault = soapBody.addFault(soapMessage.getSOAPHeader().getElementName(), message); if (code != null) fault.setFaultCode(code); } else if (soapVersion.equals(SOAPConstants.SOAP_1_2_PROTOCOL)) { /** * For 1.2 there are only a set number of allowed codes, so we can't * just use any one like what we did in 1.1. The recommended one to * use is SOAPConstants.SOAP_RECEIVER_FAULT */ fault = soapBody.addFault(SOAPConstants.SOAP_RECEIVER_FAULT, code == null ? message : code + " : " + message); } return DomHelper.toXml(soapMessage.getSOAPPart().getDocumentElement()); }
java
protected String createSoapFaultResponse(String soapVersion, String code, String message) throws SOAPException, TransformerException { SOAPMessage soapMessage = getSoapMessageFactory(soapVersion).createMessage(); SOAPBody soapBody = soapMessage.getSOAPBody(); /** * Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use * the elementName otherwise it throws an exception * * @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html */ SOAPFault fault = null; if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL)) { // existing 1.1 functionality fault = soapBody.addFault(soapMessage.getSOAPHeader().getElementName(), message); if (code != null) fault.setFaultCode(code); } else if (soapVersion.equals(SOAPConstants.SOAP_1_2_PROTOCOL)) { /** * For 1.2 there are only a set number of allowed codes, so we can't * just use any one like what we did in 1.1. The recommended one to * use is SOAPConstants.SOAP_RECEIVER_FAULT */ fault = soapBody.addFault(SOAPConstants.SOAP_RECEIVER_FAULT, code == null ? message : code + " : " + message); } return DomHelper.toXml(soapMessage.getSOAPPart().getDocumentElement()); }
[ "protected", "String", "createSoapFaultResponse", "(", "String", "soapVersion", ",", "String", "code", ",", "String", "message", ")", "throws", "SOAPException", ",", "TransformerException", "{", "SOAPMessage", "soapMessage", "=", "getSoapMessageFactory", "(", "soapVersi...
Allow version specific factory passed in to support SOAP 1.1 and 1.2 <b>Important</b> Faults are treated differently for 1.1 and 1.2 For 1.2 you can't use the elementName otherwise it throws an exception @see http://docs.oracle.com/cd/E19159-01/819-3669/bnbip/index.html @param factory @param code @param message @return Xml fault string @throws SOAPException @throws TransformerException
[ "Allow", "version", "specific", "factory", "passed", "in", "to", "support", "SOAP", "1", ".", "1", "and", "1", ".", "2", "<b", ">", "Important<", "/", "b", ">", "Faults", "are", "treated", "differently", "for", "1", ".", "1", "and", "1", ".", "2", ...
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-hub/src/com/centurylink/mdw/hub/servlet/SoapServlet.java#L410-L440
apache/incubator-heron
heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java
NetworkUtils.establishSSHTunnelIfNeeded
private static Pair<InetSocketAddress, Process> establishSSHTunnelIfNeeded( InetSocketAddress endpoint, String tunnelHost, TunnelType tunnelType, Duration timeout, int retryCount, Duration retryInterval, int verifyCount) { if (NetworkUtils.isLocationReachable(endpoint, timeout, retryCount, retryInterval)) { // Already reachable, return original endpoint directly return new Pair<InetSocketAddress, Process>(endpoint, null); } else { // Can not reach directly, trying to do ssh tunnel int localFreePort = SysUtils.getFreePort(); InetSocketAddress newEndpoint = new InetSocketAddress(LOCAL_HOST, localFreePort); LOG.log(Level.FINE, "Trying to opening up tunnel to {0} from {1}", new Object[]{endpoint.toString(), newEndpoint.toString()}); // Set up the tunnel process final Process tunnelProcess; switch (tunnelType) { case PORT_FORWARD: tunnelProcess = ShellUtils.establishSSHTunnelProcess( tunnelHost, localFreePort, endpoint.getHostString(), endpoint.getPort()); break; case SOCKS_PROXY: tunnelProcess = ShellUtils.establishSocksProxyProcess(tunnelHost, localFreePort); break; default: throw new IllegalArgumentException("Unrecognized TunnelType passed: " + tunnelType); } // Tunnel can take time to setup. // Verify whether the tunnel process is working fine. if (tunnelProcess != null && tunnelProcess.isAlive() && NetworkUtils.isLocationReachable( newEndpoint, timeout, verifyCount, retryInterval)) { java.lang.Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { tunnelProcess.destroy(); } }); // Can reach the destination via ssh tunnel return new Pair<InetSocketAddress, Process>(newEndpoint, tunnelProcess); } LOG.log(Level.FINE, "Failed to opening up tunnel to {0} from {1}. Releasing process..", new Object[]{endpoint, newEndpoint}); tunnelProcess.destroy(); } // No way to reach the destination. Return null. return new Pair<InetSocketAddress, Process>(null, null); }
java
private static Pair<InetSocketAddress, Process> establishSSHTunnelIfNeeded( InetSocketAddress endpoint, String tunnelHost, TunnelType tunnelType, Duration timeout, int retryCount, Duration retryInterval, int verifyCount) { if (NetworkUtils.isLocationReachable(endpoint, timeout, retryCount, retryInterval)) { // Already reachable, return original endpoint directly return new Pair<InetSocketAddress, Process>(endpoint, null); } else { // Can not reach directly, trying to do ssh tunnel int localFreePort = SysUtils.getFreePort(); InetSocketAddress newEndpoint = new InetSocketAddress(LOCAL_HOST, localFreePort); LOG.log(Level.FINE, "Trying to opening up tunnel to {0} from {1}", new Object[]{endpoint.toString(), newEndpoint.toString()}); // Set up the tunnel process final Process tunnelProcess; switch (tunnelType) { case PORT_FORWARD: tunnelProcess = ShellUtils.establishSSHTunnelProcess( tunnelHost, localFreePort, endpoint.getHostString(), endpoint.getPort()); break; case SOCKS_PROXY: tunnelProcess = ShellUtils.establishSocksProxyProcess(tunnelHost, localFreePort); break; default: throw new IllegalArgumentException("Unrecognized TunnelType passed: " + tunnelType); } // Tunnel can take time to setup. // Verify whether the tunnel process is working fine. if (tunnelProcess != null && tunnelProcess.isAlive() && NetworkUtils.isLocationReachable( newEndpoint, timeout, verifyCount, retryInterval)) { java.lang.Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { tunnelProcess.destroy(); } }); // Can reach the destination via ssh tunnel return new Pair<InetSocketAddress, Process>(newEndpoint, tunnelProcess); } LOG.log(Level.FINE, "Failed to opening up tunnel to {0} from {1}. Releasing process..", new Object[]{endpoint, newEndpoint}); tunnelProcess.destroy(); } // No way to reach the destination. Return null. return new Pair<InetSocketAddress, Process>(null, null); }
[ "private", "static", "Pair", "<", "InetSocketAddress", ",", "Process", ">", "establishSSHTunnelIfNeeded", "(", "InetSocketAddress", "endpoint", ",", "String", "tunnelHost", ",", "TunnelType", "tunnelType", ",", "Duration", "timeout", ",", "int", "retryCount", ",", "...
Tests if a network location is reachable. This is best effort and may give false not reachable. @param endpoint the endpoint to connect to @param tunnelHost the host used to tunnel @param tunnelType what type of tunnel should be established @param timeout Open connection will wait for this timeout in ms. @param retryCount In case of connection timeout try retryCount times. @param retryInterval the interval in ms to retryCount @param verifyCount In case of longer tunnel setup, try verify times to wait @return a &lt;new_reachable_endpoint, tunnelProcess&gt; pair. If the endpoint already reachable, then new_reachable_endpoint equals to original endpoint, and tunnelProcess is null. If no way to reach even through ssh tunneling, then both new_reachable_endpoint and tunnelProcess are null.
[ "Tests", "if", "a", "network", "location", "is", "reachable", ".", "This", "is", "best", "effort", "and", "may", "give", "false", "not", "reachable", "." ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java#L470-L526
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/BoardsApi.java
BoardsApi.createBoardList
public BoardList createBoardList(Object projectIdOrPath, Integer boardId, Integer labelId) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("label_id", labelId, true); Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists"); return (response.readEntity(BoardList.class)); }
java
public BoardList createBoardList(Object projectIdOrPath, Integer boardId, Integer labelId) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("label_id", labelId, true); Response response = post(Response.Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "boards", boardId, "lists"); return (response.readEntity(BoardList.class)); }
[ "public", "BoardList", "createBoardList", "(", "Object", "projectIdOrPath", ",", "Integer", "boardId", ",", "Integer", "labelId", ")", "throws", "GitLabApiException", "{", "GitLabApiForm", "formData", "=", "new", "GitLabApiForm", "(", ")", ".", "withParam", "(", "...
Creates a new Issue Board list. <pre><code>GitLab Endpoint: POST /projects/:id/boards/:board_id/lists</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param boardId the ID of the board @param labelId the ID of the label @return the created BoardList instance @throws GitLabApiException if any exception occurs
[ "Creates", "a", "new", "Issue", "Board", "list", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/BoardsApi.java#L290-L295
mozilla/rhino
src/org/mozilla/javascript/ScriptRuntime.java
ScriptRuntime.throwCustomError
public static JavaScriptException throwCustomError(Context cx, Scriptable scope, String constructorName, String message) { int[] linep = { 0 }; String filename = Context.getSourcePositionFromStack(linep); final Scriptable error = cx.newObject(scope, constructorName, new Object[] { message, filename, Integer.valueOf(linep[0]) }); return new JavaScriptException(error, filename, linep[0]); }
java
public static JavaScriptException throwCustomError(Context cx, Scriptable scope, String constructorName, String message) { int[] linep = { 0 }; String filename = Context.getSourcePositionFromStack(linep); final Scriptable error = cx.newObject(scope, constructorName, new Object[] { message, filename, Integer.valueOf(linep[0]) }); return new JavaScriptException(error, filename, linep[0]); }
[ "public", "static", "JavaScriptException", "throwCustomError", "(", "Context", "cx", ",", "Scriptable", "scope", ",", "String", "constructorName", ",", "String", "message", ")", "{", "int", "[", "]", "linep", "=", "{", "0", "}", ";", "String", "filename", "=...
Equivalent to executing "new $constructorName(message, sourceFileName, sourceLineNo)" from JavaScript. @param cx the current context @param scope the current scope @param message the message @return a JavaScriptException you should throw
[ "Equivalent", "to", "executing", "new", "$constructorName", "(", "message", "sourceFileName", "sourceLineNo", ")", "from", "JavaScript", "." ]
train
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ScriptRuntime.java#L4575-L4582
joniles/mpxj
src/main/java/net/sf/mpxj/turboproject/PEPUtility.java
PEPUtility.getShort
public static final int getShort(byte[] data, int offset) { int result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 16; shiftBy += 8) { result |= ((data[i] & 0xff)) << shiftBy; ++i; } return result; }
java
public static final int getShort(byte[] data, int offset) { int result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 16; shiftBy += 8) { result |= ((data[i] & 0xff)) << shiftBy; ++i; } return result; }
[ "public", "static", "final", "int", "getShort", "(", "byte", "[", "]", "data", ",", "int", "offset", ")", "{", "int", "result", "=", "0", ";", "int", "i", "=", "offset", ";", "for", "(", "int", "shiftBy", "=", "0", ";", "shiftBy", "<", "16", ";",...
Read a two byte integer. @param data byte array @param offset offset into array @return integer value
[ "Read", "a", "two", "byte", "integer", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/turboproject/PEPUtility.java#L61-L71
ReactiveX/RxJavaAsyncUtil
src/main/java/rx/util/async/Async.java
Async.toAsync
public static FuncN<Observable<Void>> toAsync(ActionN action) { return toAsync(action, Schedulers.computation()); }
java
public static FuncN<Observable<Void>> toAsync(ActionN action) { return toAsync(action, Schedulers.computation()); }
[ "public", "static", "FuncN", "<", "Observable", "<", "Void", ">", ">", "toAsync", "(", "ActionN", "action", ")", "{", "return", "toAsync", "(", "action", ",", "Schedulers", ".", "computation", "(", ")", ")", ";", "}" ]
Convert a synchronous action call into an asynchronous function call through an Observable. <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.an.png" alt=""> @param action the action to convert @return a function that returns an Observable that executes the {@code action} and emits {@code null} @see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a>
[ "Convert", "a", "synchronous", "action", "call", "into", "an", "asynchronous", "function", "call", "through", "an", "Observable", ".", "<p", ">", "<img", "width", "=", "640", "src", "=", "https", ":", "//", "raw", ".", "github", ".", "com", "/", "wiki", ...
train
https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L720-L722
DDTH/ddth-zookeeper
src/main/java/com/github/ddth/zookeeper/ZooKeeperClient.java
ZooKeeperClient.setData
public boolean setData(String path, byte[] value, boolean createNodes) throws ZooKeeperException { return _write(path, value, createNodes); }
java
public boolean setData(String path, byte[] value, boolean createNodes) throws ZooKeeperException { return _write(path, value, createNodes); }
[ "public", "boolean", "setData", "(", "String", "path", ",", "byte", "[", "]", "value", ",", "boolean", "createNodes", ")", "throws", "ZooKeeperException", "{", "return", "_write", "(", "path", ",", "value", ",", "createNodes", ")", ";", "}" ]
Writes raw data to a node. @param path @param value @param createNodes {@code true} to have nodes to be created if not exist @return {@code true} if write successfully, {@code false} otherwise (note does not exist, for example) @throws ZooKeeperException
[ "Writes", "raw", "data", "to", "a", "node", "." ]
train
https://github.com/DDTH/ddth-zookeeper/blob/0994eea8b25fa3d885f3da4579768b7d08c1c32b/src/main/java/com/github/ddth/zookeeper/ZooKeeperClient.java#L656-L659
javalite/activeweb
javalite-async/src/main/java/org/javalite/async/Async.java
Async.getTopTextMessages
public List<String> getTopTextMessages(int maxSize, String queueName) { checkStarted(); List<String> res = new ArrayList<>(); try(Session session = consumerConnection.createSession()) { Queue queue = (Queue) jmsServer.lookup(QUEUE_NAMESPACE + queueName); Enumeration messages = session.createBrowser(queue).getEnumeration(); for(int i = 0; i < maxSize && messages.hasMoreElements(); i++) { TextMessage message = (TextMessage) messages.nextElement(); res.add(message.getText()); } return res; } catch (Exception e) { throw new AsyncException("Could not lookup messages", e); } }
java
public List<String> getTopTextMessages(int maxSize, String queueName) { checkStarted(); List<String> res = new ArrayList<>(); try(Session session = consumerConnection.createSession()) { Queue queue = (Queue) jmsServer.lookup(QUEUE_NAMESPACE + queueName); Enumeration messages = session.createBrowser(queue).getEnumeration(); for(int i = 0; i < maxSize && messages.hasMoreElements(); i++) { TextMessage message = (TextMessage) messages.nextElement(); res.add(message.getText()); } return res; } catch (Exception e) { throw new AsyncException("Could not lookup messages", e); } }
[ "public", "List", "<", "String", ">", "getTopTextMessages", "(", "int", "maxSize", ",", "String", "queueName", ")", "{", "checkStarted", "(", ")", ";", "List", "<", "String", ">", "res", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "(", "Sessio...
Returns top <code>TextMessage</code>s in queue. Does not remove anything from queue. This method can be used for an admin tool to peek inside the queue. @param maxSize max number of messages to lookup. @return top commands in queue or empty list is nothing is found in queue.
[ "Returns", "top", "<code", ">", "TextMessage<", "/", "code", ">", "s", "in", "queue", ".", "Does", "not", "remove", "anything", "from", "queue", ".", "This", "method", "can", "be", "used", "for", "an", "admin", "tool", "to", "peek", "inside", "the", "q...
train
https://github.com/javalite/activeweb/blob/f25f589da94852b6f5625182360732e0861794a6/javalite-async/src/main/java/org/javalite/async/Async.java#L574-L588
cryptomator/webdav-nio-adapter
src/main/java/org/cryptomator/frontend/webdav/mount/ProcessUtil.java
ProcessUtil.waitFor
public static void waitFor(Process proc, long timeout, TimeUnit unit) throws CommandTimeoutException { try { boolean finishedInTime = proc.waitFor(timeout, unit); if (!finishedInTime) { proc.destroyForcibly(); throw new CommandTimeoutException(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
java
public static void waitFor(Process proc, long timeout, TimeUnit unit) throws CommandTimeoutException { try { boolean finishedInTime = proc.waitFor(timeout, unit); if (!finishedInTime) { proc.destroyForcibly(); throw new CommandTimeoutException(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
[ "public", "static", "void", "waitFor", "(", "Process", "proc", ",", "long", "timeout", ",", "TimeUnit", "unit", ")", "throws", "CommandTimeoutException", "{", "try", "{", "boolean", "finishedInTime", "=", "proc", ".", "waitFor", "(", "timeout", ",", "unit", ...
Waits for the process to terminate or throws an exception if it fails to do so within the given timeout. @param proc A started process @param timeout Maximum time to wait @param unit Time unit of <code>timeout</code> @throws CommandTimeoutException Thrown in case of a timeout
[ "Waits", "for", "the", "process", "to", "terminate", "or", "throws", "an", "exception", "if", "it", "fails", "to", "do", "so", "within", "the", "given", "timeout", "." ]
train
https://github.com/cryptomator/webdav-nio-adapter/blob/55b0d7dccea9a4ede0a30a95583d8f04c8a86d18/src/main/java/org/cryptomator/frontend/webdav/mount/ProcessUtil.java#L63-L73
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java
AbstractQueryProtocol.readPacket
private void readPacket(Results results) throws SQLException { Buffer buffer; try { buffer = reader.getPacket(true); } catch (IOException e) { throw handleIoException(e); } switch (buffer.getByteAt(0)) { //********************************************************************************************************* //* OK response //********************************************************************************************************* case OK: readOkPacket(buffer, results); break; //********************************************************************************************************* //* ERROR response //********************************************************************************************************* case ERROR: throw readErrorPacket(buffer, results); //********************************************************************************************************* //* LOCAL INFILE response //********************************************************************************************************* case LOCAL_INFILE: readLocalInfilePacket(buffer, results); break; //********************************************************************************************************* //* ResultSet //********************************************************************************************************* default: readResultSet(buffer, results); break; } }
java
private void readPacket(Results results) throws SQLException { Buffer buffer; try { buffer = reader.getPacket(true); } catch (IOException e) { throw handleIoException(e); } switch (buffer.getByteAt(0)) { //********************************************************************************************************* //* OK response //********************************************************************************************************* case OK: readOkPacket(buffer, results); break; //********************************************************************************************************* //* ERROR response //********************************************************************************************************* case ERROR: throw readErrorPacket(buffer, results); //********************************************************************************************************* //* LOCAL INFILE response //********************************************************************************************************* case LOCAL_INFILE: readLocalInfilePacket(buffer, results); break; //********************************************************************************************************* //* ResultSet //********************************************************************************************************* default: readResultSet(buffer, results); break; } }
[ "private", "void", "readPacket", "(", "Results", "results", ")", "throws", "SQLException", "{", "Buffer", "buffer", ";", "try", "{", "buffer", "=", "reader", ".", "getPacket", "(", "true", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw...
Read server response packet. @param results result object @throws SQLException if sub-result connection fail @see <a href="https://mariadb.com/kb/en/mariadb/4-server-response-packets/">server response packets</a>
[ "Read", "server", "response", "packet", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/protocol/AbstractQueryProtocol.java#L1432-L1471
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cli/CliClient.java
CliClient.getIndexTypeFromString
private IndexType getIndexTypeFromString(String indexTypeAsString) { IndexType indexType; try { indexType = IndexType.findByValue(new Integer(indexTypeAsString)); } catch (NumberFormatException e) { try { // if this is not an integer lets try to get IndexType by name indexType = IndexType.valueOf(indexTypeAsString); } catch (IllegalArgumentException ie) { throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.", ie); } } if (indexType == null) { throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported."); } return indexType; }
java
private IndexType getIndexTypeFromString(String indexTypeAsString) { IndexType indexType; try { indexType = IndexType.findByValue(new Integer(indexTypeAsString)); } catch (NumberFormatException e) { try { // if this is not an integer lets try to get IndexType by name indexType = IndexType.valueOf(indexTypeAsString); } catch (IllegalArgumentException ie) { throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported.", ie); } } if (indexType == null) { throw new RuntimeException("IndexType '" + indexTypeAsString + "' is unsupported."); } return indexType; }
[ "private", "IndexType", "getIndexTypeFromString", "(", "String", "indexTypeAsString", ")", "{", "IndexType", "indexType", ";", "try", "{", "indexType", "=", "IndexType", ".", "findByValue", "(", "new", "Integer", "(", "indexTypeAsString", ")", ")", ";", "}", "ca...
Getting IndexType object from indexType string @param indexTypeAsString - string return by parser corresponding to IndexType @return IndexType - an IndexType object
[ "Getting", "IndexType", "object", "from", "indexType", "string" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L2516-L2543
alkacon/opencms-core
src/org/opencms/file/types/A_CmsResourceType.java
A_CmsResourceType.getMacroResolver
protected CmsMacroResolver getMacroResolver(CmsObject cms, String resourcename) { CmsMacroResolver result = CmsMacroResolver.newInstance().setCmsObject(cms); if (isFolder() && (!CmsResource.isFolder(resourcename))) { // ensure folder ends with "/" so resourcename = resourcename.concat("/"); } // add special mappings for macros in default properties result.addMacro(MACRO_RESOURCE_ROOT_PATH, cms.getRequestContext().addSiteRoot(resourcename)); result.addMacro(MACRO_RESOURCE_SITE_PATH, resourcename); result.addMacro(MACRO_RESOURCE_FOLDER_PATH, CmsResource.getFolderPath(resourcename)); result.addMacro(MACRO_RESOURCE_FOLDER_PATH_TOUCH, CmsResource.getFolderPath(resourcename)); result.addMacro(MACRO_RESOURCE_PARENT_PATH, CmsResource.getParentFolder(resourcename)); result.addMacro(MACRO_RESOURCE_NAME, CmsResource.getName(resourcename)); return result; }
java
protected CmsMacroResolver getMacroResolver(CmsObject cms, String resourcename) { CmsMacroResolver result = CmsMacroResolver.newInstance().setCmsObject(cms); if (isFolder() && (!CmsResource.isFolder(resourcename))) { // ensure folder ends with "/" so resourcename = resourcename.concat("/"); } // add special mappings for macros in default properties result.addMacro(MACRO_RESOURCE_ROOT_PATH, cms.getRequestContext().addSiteRoot(resourcename)); result.addMacro(MACRO_RESOURCE_SITE_PATH, resourcename); result.addMacro(MACRO_RESOURCE_FOLDER_PATH, CmsResource.getFolderPath(resourcename)); result.addMacro(MACRO_RESOURCE_FOLDER_PATH_TOUCH, CmsResource.getFolderPath(resourcename)); result.addMacro(MACRO_RESOURCE_PARENT_PATH, CmsResource.getParentFolder(resourcename)); result.addMacro(MACRO_RESOURCE_NAME, CmsResource.getName(resourcename)); return result; }
[ "protected", "CmsMacroResolver", "getMacroResolver", "(", "CmsObject", "cms", ",", "String", "resourcename", ")", "{", "CmsMacroResolver", "result", "=", "CmsMacroResolver", ".", "newInstance", "(", ")", ".", "setCmsObject", "(", "cms", ")", ";", "if", "(", "isF...
Creates a macro resolver based on the current users OpenCms context and the provided resource name.<p> @param cms the current OpenCms user context @param resourcename the resource name for macros like {@link A_CmsResourceType#MACRO_RESOURCE_FOLDER_PATH} @return a macro resolver based on the current users OpenCms context and the provided resource name
[ "Creates", "a", "macro", "resolver", "based", "on", "the", "current", "users", "OpenCms", "context", "and", "the", "provided", "resource", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/types/A_CmsResourceType.java#L1049-L1065
google/closure-compiler
src/com/google/javascript/jscomp/JsMessageVisitor.java
JsMessageVisitor.trackMessage
private void trackMessage( NodeTraversal t, JsMessage message, String msgName, Node msgNode, boolean isUnnamedMessage) { if (!isUnnamedMessage) { MessageLocation location = new MessageLocation(message, msgNode); messageNames.put(msgName, location); } else { Var var = t.getScope().getVar(msgName); if (var != null) { unnamedMessages.put(var, message); } } }
java
private void trackMessage( NodeTraversal t, JsMessage message, String msgName, Node msgNode, boolean isUnnamedMessage) { if (!isUnnamedMessage) { MessageLocation location = new MessageLocation(message, msgNode); messageNames.put(msgName, location); } else { Var var = t.getScope().getVar(msgName); if (var != null) { unnamedMessages.put(var, message); } } }
[ "private", "void", "trackMessage", "(", "NodeTraversal", "t", ",", "JsMessage", "message", ",", "String", "msgName", ",", "Node", "msgNode", ",", "boolean", "isUnnamedMessage", ")", "{", "if", "(", "!", "isUnnamedMessage", ")", "{", "MessageLocation", "location"...
Track a message for later retrieval. This is used for tracking duplicates, and for figuring out message fallback. Not all message types are trackable, because that would require a more sophisticated analysis. e.g., function f(s) { s.MSG_UNNAMED_X = 'Some untrackable message'; }
[ "Track", "a", "message", "for", "later", "retrieval", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JsMessageVisitor.java#L346-L358
graphql-java/graphql-java
src/main/java/graphql/language/AstSignature.java
AstSignature.signatureQuery
public Document signatureQuery(Document document, String operationName) { return sortAST( removeAliases( hideLiterals( dropUnusedQueryDefinitions(document, operationName))) ); }
java
public Document signatureQuery(Document document, String operationName) { return sortAST( removeAliases( hideLiterals( dropUnusedQueryDefinitions(document, operationName))) ); }
[ "public", "Document", "signatureQuery", "(", "Document", "document", ",", "String", "operationName", ")", "{", "return", "sortAST", "(", "removeAliases", "(", "hideLiterals", "(", "dropUnusedQueryDefinitions", "(", "document", ",", "operationName", ")", ")", ")", ...
This can produce a "signature" canonical AST that conforms to the algorithm as outlined <a href="https://github.com/apollographql/apollo-server/blob/master/packages/apollo-engine-reporting/src/signature.ts">here</a> which removes excess operations, removes any field aliases, hides literal values and sorts the result into a canonical query @param document the document to make a signature query from @param operationName the name of the operation to do it for (since only one query can be run at a time) @return the signature query in document form
[ "This", "can", "produce", "a", "signature", "canonical", "AST", "that", "conforms", "to", "the", "algorithm", "as", "outlined", "<a", "href", "=", "https", ":", "//", "github", ".", "com", "/", "apollographql", "/", "apollo", "-", "server", "/", "blob", ...
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/language/AstSignature.java#L35-L41
networknt/light-4j
metrics/src/main/java/io/dropwizard/metrics/InstrumentedExecutors.java
InstrumentedExecutors.newFixedThreadPool
public static InstrumentedExecutorService newFixedThreadPool(int nThreads, MetricRegistry registry) { return new InstrumentedExecutorService(Executors.newFixedThreadPool(nThreads), registry); }
java
public static InstrumentedExecutorService newFixedThreadPool(int nThreads, MetricRegistry registry) { return new InstrumentedExecutorService(Executors.newFixedThreadPool(nThreads), registry); }
[ "public", "static", "InstrumentedExecutorService", "newFixedThreadPool", "(", "int", "nThreads", ",", "MetricRegistry", "registry", ")", "{", "return", "new", "InstrumentedExecutorService", "(", "Executors", ".", "newFixedThreadPool", "(", "nThreads", ")", ",", "registr...
Creates an instrumented thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most {@code nThreads} threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly {@link java.util.concurrent.ExecutorService#shutdown shutdown}. @param nThreads the number of threads in the pool @param registry the {@link MetricRegistry} that will contain the metrics. @return the newly created thread pool @throws IllegalArgumentException if {@code nThreads <= 0} @see Executors#newFixedThreadPool(int)
[ "Creates", "an", "instrumented", "thread", "pool", "that", "reuses", "a", "fixed", "number", "of", "threads", "operating", "off", "a", "shared", "unbounded", "queue", ".", "At", "any", "point", "at", "most", "{", "@code", "nThreads", "}", "threads", "will", ...
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/metrics/src/main/java/io/dropwizard/metrics/InstrumentedExecutors.java#L82-L84
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/GregorianCalendar.java
GregorianCalendar.getWeekNumber
private int getWeekNumber(long fixedDay1, long fixedDate) { // We can always use `gcal' since Julian and Gregorian are the // same thing for this calculation. long fixedDay1st = Gregorian.getDayOfWeekDateOnOrBefore(fixedDay1 + 6, getFirstDayOfWeek()); int ndays = (int)(fixedDay1st - fixedDay1); assert ndays <= 7; if (ndays >= getMinimalDaysInFirstWeek()) { fixedDay1st -= 7; } int normalizedDayOfPeriod = (int)(fixedDate - fixedDay1st); if (normalizedDayOfPeriod >= 0) { return normalizedDayOfPeriod / 7 + 1; } return CalendarUtils.floorDivide(normalizedDayOfPeriod, 7) + 1; }
java
private int getWeekNumber(long fixedDay1, long fixedDate) { // We can always use `gcal' since Julian and Gregorian are the // same thing for this calculation. long fixedDay1st = Gregorian.getDayOfWeekDateOnOrBefore(fixedDay1 + 6, getFirstDayOfWeek()); int ndays = (int)(fixedDay1st - fixedDay1); assert ndays <= 7; if (ndays >= getMinimalDaysInFirstWeek()) { fixedDay1st -= 7; } int normalizedDayOfPeriod = (int)(fixedDate - fixedDay1st); if (normalizedDayOfPeriod >= 0) { return normalizedDayOfPeriod / 7 + 1; } return CalendarUtils.floorDivide(normalizedDayOfPeriod, 7) + 1; }
[ "private", "int", "getWeekNumber", "(", "long", "fixedDay1", ",", "long", "fixedDate", ")", "{", "// We can always use `gcal' since Julian and Gregorian are the", "// same thing for this calculation.", "long", "fixedDay1st", "=", "Gregorian", ".", "getDayOfWeekDateOnOrBefore", ...
Returns the number of weeks in a period between fixedDay1 and fixedDate. The getFirstDayOfWeek-getMinimalDaysInFirstWeek rule is applied to calculate the number of weeks. @param fixedDay1 the fixed date of the first day of the period @param fixedDate the fixed date of the last day of the period @return the number of weeks of the given period
[ "Returns", "the", "number", "of", "weeks", "in", "a", "period", "between", "fixedDay1", "and", "fixedDate", ".", "The", "getFirstDayOfWeek", "-", "getMinimalDaysInFirstWeek", "rule", "is", "applied", "to", "calculate", "the", "number", "of", "weeks", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/GregorianCalendar.java#L2598-L2613
knowm/XChange
xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java
WexAdapters.adaptOrder
public static LimitOrder adaptOrder( BigDecimal amount, BigDecimal price, CurrencyPair currencyPair, OrderType orderType, String id) { return new LimitOrder(orderType, amount, currencyPair, id, null, price); }
java
public static LimitOrder adaptOrder( BigDecimal amount, BigDecimal price, CurrencyPair currencyPair, OrderType orderType, String id) { return new LimitOrder(orderType, amount, currencyPair, id, null, price); }
[ "public", "static", "LimitOrder", "adaptOrder", "(", "BigDecimal", "amount", ",", "BigDecimal", "price", ",", "CurrencyPair", "currencyPair", ",", "OrderType", "orderType", ",", "String", "id", ")", "{", "return", "new", "LimitOrder", "(", "orderType", ",", "amo...
Adapts a WexOrder to a LimitOrder @param amount @param price @param currencyPair @param orderType @param id @return
[ "Adapts", "a", "WexOrder", "to", "a", "LimitOrder" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-wex/src/main/java/org/knowm/xchange/wex/v3/WexAdapters.java#L86-L94
Stratio/stratio-cassandra
src/java/org/apache/cassandra/locator/TokenMetadata.java
TokenMetadata.cloneOnlyTokenMap
public TokenMetadata cloneOnlyTokenMap() { lock.readLock().lock(); try { return new TokenMetadata(SortedBiMultiValMap.<Token, InetAddress>create(tokenToEndpointMap, null, inetaddressCmp), HashBiMap.create(endpointToHostIdMap), new Topology(topology)); } finally { lock.readLock().unlock(); } }
java
public TokenMetadata cloneOnlyTokenMap() { lock.readLock().lock(); try { return new TokenMetadata(SortedBiMultiValMap.<Token, InetAddress>create(tokenToEndpointMap, null, inetaddressCmp), HashBiMap.create(endpointToHostIdMap), new Topology(topology)); } finally { lock.readLock().unlock(); } }
[ "public", "TokenMetadata", "cloneOnlyTokenMap", "(", ")", "{", "lock", ".", "readLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "return", "new", "TokenMetadata", "(", "SortedBiMultiValMap", ".", "<", "Token", ",", "InetAddress", ">", "create", "(...
Create a copy of TokenMetadata with only tokenToEndpointMap. That is, pending ranges, bootstrap tokens and leaving endpoints are not included in the copy.
[ "Create", "a", "copy", "of", "TokenMetadata", "with", "only", "tokenToEndpointMap", ".", "That", "is", "pending", "ranges", "bootstrap", "tokens", "and", "leaving", "endpoints", "are", "not", "included", "in", "the", "copy", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/locator/TokenMetadata.java#L517-L530
astefanutti/camel-cdi
maven/src/main/java/org/apache/camel/maven/RunMojo.java
RunMojo.addRelevantProjectDependenciesToClasspath
private void addRelevantProjectDependenciesToClasspath(Set<URL> path) throws MojoExecutionException { if (this.includeProjectDependencies) { try { getLog().debug("Project Dependencies will be included."); URL mainClasses = new File(project.getBuild().getOutputDirectory()).toURI().toURL(); getLog().debug("Adding to classpath : " + mainClasses); path.add(mainClasses); Set<Artifact> dependencies = CastUtils.cast(project.getArtifacts()); // system scope dependencies are not returned by maven 2.0. See // MEXEC-17 dependencies.addAll(getAllNonTestScopedDependencies()); Iterator<Artifact> iter = dependencies.iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); getLog().debug("Adding project dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); File file = classPathElement.getFile(); if (file != null) { path.add(file.toURI().toURL()); } } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } else { getLog().debug("Project Dependencies will be excluded."); } }
java
private void addRelevantProjectDependenciesToClasspath(Set<URL> path) throws MojoExecutionException { if (this.includeProjectDependencies) { try { getLog().debug("Project Dependencies will be included."); URL mainClasses = new File(project.getBuild().getOutputDirectory()).toURI().toURL(); getLog().debug("Adding to classpath : " + mainClasses); path.add(mainClasses); Set<Artifact> dependencies = CastUtils.cast(project.getArtifacts()); // system scope dependencies are not returned by maven 2.0. See // MEXEC-17 dependencies.addAll(getAllNonTestScopedDependencies()); Iterator<Artifact> iter = dependencies.iterator(); while (iter.hasNext()) { Artifact classPathElement = iter.next(); getLog().debug("Adding project dependency artifact: " + classPathElement.getArtifactId() + " to classpath"); File file = classPathElement.getFile(); if (file != null) { path.add(file.toURI().toURL()); } } } catch (MalformedURLException e) { throw new MojoExecutionException("Error during setting up classpath", e); } } else { getLog().debug("Project Dependencies will be excluded."); } }
[ "private", "void", "addRelevantProjectDependenciesToClasspath", "(", "Set", "<", "URL", ">", "path", ")", "throws", "MojoExecutionException", "{", "if", "(", "this", ".", "includeProjectDependencies", ")", "{", "try", "{", "getLog", "(", ")", ".", "debug", "(", ...
Add any relevant project dependencies to the classpath. Takes includeProjectDependencies into consideration. @param path classpath of {@link java.net.URL} objects @throws MojoExecutionException
[ "Add", "any", "relevant", "project", "dependencies", "to", "the", "classpath", ".", "Takes", "includeProjectDependencies", "into", "consideration", "." ]
train
https://github.com/astefanutti/camel-cdi/blob/686c7f5fe3a706f47378e0c49c323040795ddff8/maven/src/main/java/org/apache/camel/maven/RunMojo.java#L807-L840
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java
JournalCreator.modifyDatastreamByReference
public Date modifyDatastreamByReference(Context context, String pid, String datastreamID, String[] altIDs, String dsLabel, String mimeType, String formatURI, String dsLocation, String checksumType, String checksum, String logMessage, Date lastModifiedDate) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_MODIFY_DATASTREAM_BY_REFERENCE, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, datastreamID); cje.addArgument(ARGUMENT_NAME_ALT_IDS, altIDs); cje.addArgument(ARGUMENT_NAME_DS_LABEL, dsLabel); cje.addArgument(ARGUMENT_NAME_MIME_TYPE, mimeType); cje.addArgument(ARGUMENT_NAME_FORMAT_URI, formatURI); cje.addArgument(ARGUMENT_NAME_DS_LOCATION, dsLocation); cje.addArgument(ARGUMENT_NAME_CHECKSUM_TYPE, checksumType); cje.addArgument(ARGUMENT_NAME_CHECKSUM, checksum); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); cje.addArgument(ARGUMENT_NAME_LAST_MODIFIED_DATE, lastModifiedDate); return (Date) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
java
public Date modifyDatastreamByReference(Context context, String pid, String datastreamID, String[] altIDs, String dsLabel, String mimeType, String formatURI, String dsLocation, String checksumType, String checksum, String logMessage, Date lastModifiedDate) throws ServerException { try { CreatorJournalEntry cje = new CreatorJournalEntry(METHOD_MODIFY_DATASTREAM_BY_REFERENCE, context); cje.addArgument(ARGUMENT_NAME_PID, pid); cje.addArgument(ARGUMENT_NAME_DS_ID, datastreamID); cje.addArgument(ARGUMENT_NAME_ALT_IDS, altIDs); cje.addArgument(ARGUMENT_NAME_DS_LABEL, dsLabel); cje.addArgument(ARGUMENT_NAME_MIME_TYPE, mimeType); cje.addArgument(ARGUMENT_NAME_FORMAT_URI, formatURI); cje.addArgument(ARGUMENT_NAME_DS_LOCATION, dsLocation); cje.addArgument(ARGUMENT_NAME_CHECKSUM_TYPE, checksumType); cje.addArgument(ARGUMENT_NAME_CHECKSUM, checksum); cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage); cje.addArgument(ARGUMENT_NAME_LAST_MODIFIED_DATE, lastModifiedDate); return (Date) cje.invokeAndClose(delegate, writer); } catch (JournalException e) { throw new GeneralException("Problem creating the Journal", e); } }
[ "public", "Date", "modifyDatastreamByReference", "(", "Context", "context", ",", "String", "pid", ",", "String", "datastreamID", ",", "String", "[", "]", "altIDs", ",", "String", "dsLabel", ",", "String", "mimeType", ",", "String", "formatURI", ",", "String", ...
Create a journal entry, add the arguments, and invoke the method.
[ "Create", "a", "journal", "entry", "add", "the", "arguments", "and", "invoke", "the", "method", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalCreator.java#L240-L272
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Dict.java
Dict.parseBean
public <T> Dict parseBean(T bean, boolean isToUnderlineCase, boolean ignoreNullValue) { Assert.notNull(bean, "Bean class must be not null"); this.putAll(BeanUtil.beanToMap(bean, isToUnderlineCase, ignoreNullValue)); return this; }
java
public <T> Dict parseBean(T bean, boolean isToUnderlineCase, boolean ignoreNullValue) { Assert.notNull(bean, "Bean class must be not null"); this.putAll(BeanUtil.beanToMap(bean, isToUnderlineCase, ignoreNullValue)); return this; }
[ "public", "<", "T", ">", "Dict", "parseBean", "(", "T", "bean", ",", "boolean", "isToUnderlineCase", ",", "boolean", "ignoreNullValue", ")", "{", "Assert", ".", "notNull", "(", "bean", ",", "\"Bean class must be not null\"", ")", ";", "this", ".", "putAll", ...
将值对象转换为Dict<br> 类名会被当作表名,小写第一个字母 @param <T> Bean类型 @param bean 值对象 @param isToUnderlineCase 是否转换为下划线模式 @param ignoreNullValue 是否忽略值为空的字段 @return 自己
[ "将值对象转换为Dict<br", ">", "类名会被当作表名,小写第一个字母" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Dict.java#L181-L185
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/base64/Base64.java
Base64.safeDecode
@Nullable @ReturnsMutableCopy public static byte [] safeDecode (@Nullable final byte [] aEncodedBytes, @Nonnegative final int nOfs, @Nonnegative final int nLen, final int nOptions) { if (aEncodedBytes != null) try { return decode (aEncodedBytes, nOfs, nLen, nOptions); } catch (final IOException | IllegalArgumentException ex) { // fall through } return null; }
java
@Nullable @ReturnsMutableCopy public static byte [] safeDecode (@Nullable final byte [] aEncodedBytes, @Nonnegative final int nOfs, @Nonnegative final int nLen, final int nOptions) { if (aEncodedBytes != null) try { return decode (aEncodedBytes, nOfs, nLen, nOptions); } catch (final IOException | IllegalArgumentException ex) { // fall through } return null; }
[ "@", "Nullable", "@", "ReturnsMutableCopy", "public", "static", "byte", "[", "]", "safeDecode", "(", "@", "Nullable", "final", "byte", "[", "]", "aEncodedBytes", ",", "@", "Nonnegative", "final", "int", "nOfs", ",", "@", "Nonnegative", "final", "int", "nLen"...
Decode the byte array. @param aEncodedBytes The encoded byte array. @param nOfs The offset of where to begin decoding @param nLen The number of characters to decode @param nOptions Decoding options. @return <code>null</code> if decoding failed.
[ "Decode", "the", "byte", "array", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/base64/Base64.java#L2636-L2653
Alluxio/alluxio
core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournal.java
UfsJournal.losePrimacy
public synchronized void losePrimacy() throws IOException { Preconditions.checkState(mState == State.PRIMARY, "unexpected state " + mState); Preconditions.checkState(mWriter != null, "writer thread must not be null in primary mode"); Preconditions.checkState(mTailerThread == null, "tailer thread must be null in primary mode"); mWriter.close(); mWriter = null; mAsyncWriter = null; mMaster.resetState(); mTailerThread = new UfsJournalCheckpointThread(mMaster, this); mTailerThread.start(); mState = State.SECONDARY; }
java
public synchronized void losePrimacy() throws IOException { Preconditions.checkState(mState == State.PRIMARY, "unexpected state " + mState); Preconditions.checkState(mWriter != null, "writer thread must not be null in primary mode"); Preconditions.checkState(mTailerThread == null, "tailer thread must be null in primary mode"); mWriter.close(); mWriter = null; mAsyncWriter = null; mMaster.resetState(); mTailerThread = new UfsJournalCheckpointThread(mMaster, this); mTailerThread.start(); mState = State.SECONDARY; }
[ "public", "synchronized", "void", "losePrimacy", "(", ")", "throws", "IOException", "{", "Preconditions", ".", "checkState", "(", "mState", "==", "State", ".", "PRIMARY", ",", "\"unexpected state \"", "+", "mState", ")", ";", "Preconditions", ".", "checkState", ...
Transitions the journal from primary to secondary mode. The journal will no longer allow writes, and the state machine is rebuilt from the journal and kept up to date.
[ "Transitions", "the", "journal", "from", "primary", "to", "secondary", "mode", ".", "The", "journal", "will", "no", "longer", "allow", "writes", "and", "the", "state", "machine", "is", "rebuilt", "from", "the", "journal", "and", "kept", "up", "to", "date", ...
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/journal/ufs/UfsJournal.java#L220-L231
box/box-java-sdk
src/main/java/com/box/sdk/BoxFile.java
BoxFile.deleteMetadata
public void deleteMetadata(String typeName, String scope) { URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); request.send(); }
java
public void deleteMetadata(String typeName, String scope) { URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); request.send(); }
[ "public", "void", "deleteMetadata", "(", "String", "typeName", ",", "String", "scope", ")", "{", "URL", "url", "=", "METADATA_URL_TEMPLATE", ".", "build", "(", "this", ".", "getAPI", "(", ")", ".", "getBaseURL", "(", ")", ",", "this", ".", "getID", "(", ...
Deletes the file metadata of specified template type. @param typeName the metadata template type name. @param scope the metadata scope (global or enterprise).
[ "Deletes", "the", "file", "metadata", "of", "specified", "template", "type", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxFile.java#L1329-L1333
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/http/HttpHeaderMap.java
HttpHeaderMap.setDateHeader
public void setDateHeader (@Nonnull @Nonempty final String sName, @Nonnull final ZonedDateTime aDT) { _setHeader (sName, getDateTimeAsString (aDT)); }
java
public void setDateHeader (@Nonnull @Nonempty final String sName, @Nonnull final ZonedDateTime aDT) { _setHeader (sName, getDateTimeAsString (aDT)); }
[ "public", "void", "setDateHeader", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sName", ",", "@", "Nonnull", "final", "ZonedDateTime", "aDT", ")", "{", "_setHeader", "(", "sName", ",", "getDateTimeAsString", "(", "aDT", ")", ")", ";", "}" ]
Set the passed header as a date header. @param sName Header name. May neither be <code>null</code> nor empty. @param aDT The DateTime to set as a date. May not be <code>null</code>.
[ "Set", "the", "passed", "header", "as", "a", "date", "header", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/http/HttpHeaderMap.java#L277-L280
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddressSection.java
IPAddressSection.isZeroHost
public boolean isZeroHost(int prefixLength) { if(prefixLength < 0 || prefixLength > getBitCount()) { throw new PrefixLenException(this, prefixLength); } return isZeroHost(prefixLength, getSegments(), getBytesPerSegment(), getBitsPerSegment(), getBitCount()); }
java
public boolean isZeroHost(int prefixLength) { if(prefixLength < 0 || prefixLength > getBitCount()) { throw new PrefixLenException(this, prefixLength); } return isZeroHost(prefixLength, getSegments(), getBytesPerSegment(), getBitsPerSegment(), getBitCount()); }
[ "public", "boolean", "isZeroHost", "(", "int", "prefixLength", ")", "{", "if", "(", "prefixLength", "<", "0", "||", "prefixLength", ">", "getBitCount", "(", ")", ")", "{", "throw", "new", "PrefixLenException", "(", "this", ",", "prefixLength", ")", ";", "}...
Returns whether the host is zero for the given prefix length for this section or all sections in this set of address sections. If this section already has a prefix length, then that prefix length is ignored. If the host section is zero length (there are no host bits at all), returns false. @return
[ "Returns", "whether", "the", "host", "is", "zero", "for", "the", "given", "prefix", "length", "for", "this", "section", "or", "all", "sections", "in", "this", "set", "of", "address", "sections", ".", "If", "this", "section", "already", "has", "a", "prefix"...
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/IPAddressSection.java#L2168-L2173
csc19601128/Phynixx
phynixx/phynixx-watchdog/src/main/java/org/csc/phynixx/watchdog/RestartCondition.java
RestartCondition.conditionViolated
public void conditionViolated() { if (this.watchdogReference.isStale()) { throw new IllegalStateException("Watchdog is stale and does not exist any longer"); } Watchdog wd = this.watchdogReference.getWatchdog(); wd.restart(); if (log.isInfoEnabled()) { log.info(new ConditionViolatedLog(this, "Watchdog " + wd.getId() + " is restarted by Condition " + this.toString()).toString()); } }
java
public void conditionViolated() { if (this.watchdogReference.isStale()) { throw new IllegalStateException("Watchdog is stale and does not exist any longer"); } Watchdog wd = this.watchdogReference.getWatchdog(); wd.restart(); if (log.isInfoEnabled()) { log.info(new ConditionViolatedLog(this, "Watchdog " + wd.getId() + " is restarted by Condition " + this.toString()).toString()); } }
[ "public", "void", "conditionViolated", "(", ")", "{", "if", "(", "this", ".", "watchdogReference", ".", "isStale", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Watchdog is stale and does not exist any longer\"", ")", ";", "}", "Watchdog", "...
Not synchronized as to be meant for the watch dog exclusively Do not call it unsynchronized
[ "Not", "synchronized", "as", "to", "be", "meant", "for", "the", "watch", "dog", "exclusively" ]
train
https://github.com/csc19601128/Phynixx/blob/a26c03bc229a8882c647799834115bec6bdc0ac8/phynixx/phynixx-watchdog/src/main/java/org/csc/phynixx/watchdog/RestartCondition.java#L84-L96
liferay/com-liferay-commerce
commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java
CommerceDiscountRelPersistenceImpl.findAll
@Override public List<CommerceDiscountRel> findAll(int start, int end) { return findAll(start, end, null); }
java
@Override public List<CommerceDiscountRel> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceDiscountRel", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce discount rels. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceDiscountRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce discount rels @param end the upper bound of the range of commerce discount rels (not inclusive) @return the range of commerce discount rels
[ "Returns", "a", "range", "of", "all", "the", "commerce", "discount", "rels", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-discount-service/src/main/java/com/liferay/commerce/discount/service/persistence/impl/CommerceDiscountRelPersistenceImpl.java#L2302-L2305
alkacon/opencms-core
src/org/opencms/ui/apps/user/CmsImportExportUserDialog.java
CmsImportExportUserDialog.getGroupSelect
protected CmsPrincipalSelect getGroupSelect(String ou, boolean enabled, CmsUUID groupID) { CmsPrincipalSelect select = new CmsPrincipalSelect(); select.setOU(ou); select.setEnabled(enabled); select.setRealPrincipalsOnly(true); select.setPrincipalType(I_CmsPrincipal.PRINCIPAL_GROUP); select.setWidgetType(WidgetType.groupwidget); if (groupID != null) { try { select.setValue(m_cms.readGroup(groupID).getName()); } catch (CmsException e) { LOG.error("Unable to read group", e); } } //OU Change enabled because ou-user can be part of other ou-groups return select; }
java
protected CmsPrincipalSelect getGroupSelect(String ou, boolean enabled, CmsUUID groupID) { CmsPrincipalSelect select = new CmsPrincipalSelect(); select.setOU(ou); select.setEnabled(enabled); select.setRealPrincipalsOnly(true); select.setPrincipalType(I_CmsPrincipal.PRINCIPAL_GROUP); select.setWidgetType(WidgetType.groupwidget); if (groupID != null) { try { select.setValue(m_cms.readGroup(groupID).getName()); } catch (CmsException e) { LOG.error("Unable to read group", e); } } //OU Change enabled because ou-user can be part of other ou-groups return select; }
[ "protected", "CmsPrincipalSelect", "getGroupSelect", "(", "String", "ou", ",", "boolean", "enabled", ",", "CmsUUID", "groupID", ")", "{", "CmsPrincipalSelect", "select", "=", "new", "CmsPrincipalSelect", "(", ")", ";", "select", ".", "setOU", "(", "ou", ")", "...
Get a principle select for choosing groups.<p> @param ou name @param enabled enabled? @param groupID default value @return CmsPrinicpalSelect
[ "Get", "a", "principle", "select", "for", "choosing", "groups", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/user/CmsImportExportUserDialog.java#L506-L525
kiegroup/drools
kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java
DMNDTAnalyser.canBeNewCurrInterval
private static boolean canBeNewCurrInterval(Bound<?> lastBound, Bound<?> currentBound) { int vCompare = BoundValueComparator.compareValueDispatchingToInf(lastBound, currentBound); if (vCompare != 0) { return true; } else { if (lastBound.isLowerBound() && currentBound.isUpperBound()) { return true; } else if (lastBound.isUpperBound() && lastBound.getBoundaryType() == RangeBoundary.OPEN && currentBound.isLowerBound() && currentBound.getBoundaryType() == RangeBoundary.OPEN) { return true; // the case x) (x } else { return false; } } }
java
private static boolean canBeNewCurrInterval(Bound<?> lastBound, Bound<?> currentBound) { int vCompare = BoundValueComparator.compareValueDispatchingToInf(lastBound, currentBound); if (vCompare != 0) { return true; } else { if (lastBound.isLowerBound() && currentBound.isUpperBound()) { return true; } else if (lastBound.isUpperBound() && lastBound.getBoundaryType() == RangeBoundary.OPEN && currentBound.isLowerBound() && currentBound.getBoundaryType() == RangeBoundary.OPEN) { return true; // the case x) (x } else { return false; } } }
[ "private", "static", "boolean", "canBeNewCurrInterval", "(", "Bound", "<", "?", ">", "lastBound", ",", "Bound", "<", "?", ">", "currentBound", ")", "{", "int", "vCompare", "=", "BoundValueComparator", ".", "compareValueDispatchingToInf", "(", "lastBound", ",", "...
Avoid a situation to "open" a new currentInterval for pair of same-side equals bounds like: x], x]
[ "Avoid", "a", "situation", "to", "open", "a", "new", "currentInterval", "for", "pair", "of", "same", "-", "side", "equals", "bounds", "like", ":", "x", "]", "x", "]" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java#L421-L435
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/parser/GosuParserFactoryImpl.java
GosuParserFactoryImpl.createParser
public IGosuParser createParser( String strSource, ISymbolTable symTable, IScriptabilityModifier scriptabilityConstraint ) { IGosuParser parser = new GosuParser( symTable, scriptabilityConstraint ); parser.setScript( strSource ); return parser; }
java
public IGosuParser createParser( String strSource, ISymbolTable symTable, IScriptabilityModifier scriptabilityConstraint ) { IGosuParser parser = new GosuParser( symTable, scriptabilityConstraint ); parser.setScript( strSource ); return parser; }
[ "public", "IGosuParser", "createParser", "(", "String", "strSource", ",", "ISymbolTable", "symTable", ",", "IScriptabilityModifier", "scriptabilityConstraint", ")", "{", "IGosuParser", "parser", "=", "new", "GosuParser", "(", "symTable", ",", "scriptabilityConstraint", ...
Creates an IGosuParser appropriate for parsing and executing Gosu. @param strSource The text of the the rule source @param symTable The symbol table the parser uses to parse and execute the rule @param scriptabilityConstraint Specifies the types of methods/properties that are visible @return A parser appropriate for parsing Gosu source.
[ "Creates", "an", "IGosuParser", "appropriate", "for", "parsing", "and", "executing", "Gosu", "." ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/parser/GosuParserFactoryImpl.java#L33-L39
xiancloud/xian
xian-zookeeper/xian-curator/xian-curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelector.java
LeaderSelector.getParticipants
public Collection<Participant> getParticipants() throws Exception { Collection<String> participantNodes = mutex.getParticipantNodes(); return getParticipants(client, participantNodes); }
java
public Collection<Participant> getParticipants() throws Exception { Collection<String> participantNodes = mutex.getParticipantNodes(); return getParticipants(client, participantNodes); }
[ "public", "Collection", "<", "Participant", ">", "getParticipants", "(", ")", "throws", "Exception", "{", "Collection", "<", "String", ">", "participantNodes", "=", "mutex", ".", "getParticipantNodes", "(", ")", ";", "return", "getParticipants", "(", "client", "...
<p> Returns the set of current participants in the leader selection </p> <p> <p> <B>NOTE</B> - this method polls the ZK server. Therefore it can possibly return a value that does not match {@link #hasLeadership()} as hasLeadership uses a local field of the class. </p> @return participants @throws Exception ZK errors, interruptions, etc.
[ "<p", ">", "Returns", "the", "set", "of", "current", "participants", "in", "the", "leader", "selection", "<", "/", "p", ">", "<p", ">", "<p", ">", "<B", ">", "NOTE<", "/", "B", ">", "-", "this", "method", "polls", "the", "ZK", "server", ".", "There...
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-zookeeper/xian-curator/xian-curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelector.java#L292-L297
alkacon/opencms-core
src/org/opencms/staticexport/CmsLinkManager.java
CmsLinkManager.substituteLink
public String substituteLink(CmsObject cms, CmsResource resource) { return substituteLinkForRootPath(cms, resource.getRootPath()); }
java
public String substituteLink(CmsObject cms, CmsResource resource) { return substituteLinkForRootPath(cms, resource.getRootPath()); }
[ "public", "String", "substituteLink", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ")", "{", "return", "substituteLinkForRootPath", "(", "cms", ",", "resource", ".", "getRootPath", "(", ")", ")", ";", "}" ]
Returns a link <i>from</i> the URI stored in the provided OpenCms user context <i>to</i> the given VFS resource, for use on web pages.<p> The result will contain the configured context path and servlet name, and in the case of the "online" project it will also be rewritten according to to the configured static export settings.<p> Should the current site of the given OpenCms user context <code>cms</code> be different from the site root of the given resource, the result will contain the full server URL to the target resource.<p> Please note the above text describes the default behavior as implemented by {@link CmsDefaultLinkSubstitutionHandler}, which can be fully customized using the {@link I_CmsLinkSubstitutionHandler} interface.<p> @param cms the current OpenCms user context @param resource the VFS resource the link should point to @return a link <i>from</i> the URI stored in the provided OpenCms user context <i>to</i> the given VFS resource, for use on web pages
[ "Returns", "a", "link", "<i", ">", "from<", "/", "i", ">", "the", "URI", "stored", "in", "the", "provided", "OpenCms", "user", "context", "<i", ">", "to<", "/", "i", ">", "the", "given", "VFS", "resource", "for", "use", "on", "web", "pages", ".", "...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L652-L655
app55/app55-java
src/support/java/com/googlecode/openbeans/Encoder.java
Encoder.writeExpression
public void writeExpression(Expression oldExp) { if (oldExp == null) { throw new NullPointerException(); } try { // if oldValue exists, no operation Object oldValue = expressionValue(oldExp); if (oldValue == null || get(oldValue) != null) { return; } // copy to newExp Expression newExp = (Expression) createNewStatement(oldExp); // relate oldValue to newValue try { oldNewMap.put(oldValue, newExp.getValue()); } catch (IndexOutOfBoundsException e) { // container does not have any component, set newVal null } // force same state writeObject(oldValue); } catch (Exception e) { listener.exceptionThrown(new Exception("failed to write expression: " + oldExp, e)); //$NON-NLS-1$ } }
java
public void writeExpression(Expression oldExp) { if (oldExp == null) { throw new NullPointerException(); } try { // if oldValue exists, no operation Object oldValue = expressionValue(oldExp); if (oldValue == null || get(oldValue) != null) { return; } // copy to newExp Expression newExp = (Expression) createNewStatement(oldExp); // relate oldValue to newValue try { oldNewMap.put(oldValue, newExp.getValue()); } catch (IndexOutOfBoundsException e) { // container does not have any component, set newVal null } // force same state writeObject(oldValue); } catch (Exception e) { listener.exceptionThrown(new Exception("failed to write expression: " + oldExp, e)); //$NON-NLS-1$ } }
[ "public", "void", "writeExpression", "(", "Expression", "oldExp", ")", "{", "if", "(", "oldExp", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "try", "{", "// if oldValue exists, no operation", "Object", "oldValue", "=", "...
Write an expression of old objects. <p> The implementation first check the return value of the expression. If there exists a new version of the object, simply return. </p> <p> A new expression is created using the new versions of the target and the arguments. If any of the old objects do not have its new version yet, <code>writeObject()</code> is called to create the new version. </p> <p> The new expression is then executed to obtained a new copy of the old return value. </p> <p> Call <code>writeObject()</code> with the old return value, so that more statements will be executed on its new version to change it into the same state as the old value. </p> @param oldExp the expression to write. The target, arguments, and return value of the expression are all old objects.
[ "Write", "an", "expression", "of", "old", "objects", ".", "<p", ">", "The", "implementation", "first", "check", "the", "return", "value", "of", "the", "expression", ".", "If", "there", "exists", "a", "new", "version", "of", "the", "object", "simply", "retu...
train
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Encoder.java#L373-L407
OpenLiberty/open-liberty
dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java
RepositoryResolver.createInstallList
List<RepositoryResource> createInstallList(SampleResource resource) { Map<String, Integer> maxDistanceMap = new HashMap<>(); List<MissingRequirement> missingRequirements = new ArrayList<>(); boolean allDependenciesResolved = true; if (resource.getRequireFeature() != null) { for (String featureName : resource.getRequireFeature()) { // Check that the sample actually exists ProvisioningFeatureDefinition feature = resolverRepository.getFeature(featureName); if (feature == null) { allDependenciesResolved = false; // Unless we know it exists but applies to another product, note the missing requirement as well if (!requirementsFoundForOtherProducts.contains(featureName)) { missingRequirements.add(new MissingRequirement(featureName, resource)); } } // Build distance map and check dependencies allDependenciesResolved &= populateMaxDistanceMap(maxDistanceMap, featureName, 1, new HashSet<ProvisioningFeatureDefinition>(), missingRequirements); } } if (!allDependenciesResolved) { missingTopLevelRequirements.add(resource.getShortName()); this.missingRequirements.addAll(missingRequirements); } ArrayList<RepositoryResource> installList = new ArrayList<>(); installList.addAll(convertFeatureNamesToResources(maxDistanceMap.keySet())); Collections.sort(installList, byMaxDistance(maxDistanceMap)); installList.add(resource); return installList; }
java
List<RepositoryResource> createInstallList(SampleResource resource) { Map<String, Integer> maxDistanceMap = new HashMap<>(); List<MissingRequirement> missingRequirements = new ArrayList<>(); boolean allDependenciesResolved = true; if (resource.getRequireFeature() != null) { for (String featureName : resource.getRequireFeature()) { // Check that the sample actually exists ProvisioningFeatureDefinition feature = resolverRepository.getFeature(featureName); if (feature == null) { allDependenciesResolved = false; // Unless we know it exists but applies to another product, note the missing requirement as well if (!requirementsFoundForOtherProducts.contains(featureName)) { missingRequirements.add(new MissingRequirement(featureName, resource)); } } // Build distance map and check dependencies allDependenciesResolved &= populateMaxDistanceMap(maxDistanceMap, featureName, 1, new HashSet<ProvisioningFeatureDefinition>(), missingRequirements); } } if (!allDependenciesResolved) { missingTopLevelRequirements.add(resource.getShortName()); this.missingRequirements.addAll(missingRequirements); } ArrayList<RepositoryResource> installList = new ArrayList<>(); installList.addAll(convertFeatureNamesToResources(maxDistanceMap.keySet())); Collections.sort(installList, byMaxDistance(maxDistanceMap)); installList.add(resource); return installList; }
[ "List", "<", "RepositoryResource", ">", "createInstallList", "(", "SampleResource", "resource", ")", "{", "Map", "<", "String", ",", "Integer", ">", "maxDistanceMap", "=", "new", "HashMap", "<>", "(", ")", ";", "List", "<", "MissingRequirement", ">", "missingR...
Create a list of resources which should be installed in order to install the given sample. <p> The install list consists of all the dependencies which are needed by {@code resource}, ordered so that each resource in the list comes after its dependencies. @param resource the resource which is to be installed @return the ordered list of resources to install
[ "Create", "a", "list", "of", "resources", "which", "should", "be", "installed", "in", "order", "to", "install", "the", "given", "sample", ".", "<p", ">", "The", "install", "list", "consists", "of", "all", "the", "dependencies", "which", "are", "needed", "b...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java#L499-L535
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/BackendUser.java
BackendUser.signInInBackground
public static Observable<BackendUser> signInInBackground(String email, String password){ return getAM().loginASync(new LoginCredentials(email, password)); }
java
public static Observable<BackendUser> signInInBackground(String email, String password){ return getAM().loginASync(new LoginCredentials(email, password)); }
[ "public", "static", "Observable", "<", "BackendUser", ">", "signInInBackground", "(", "String", "email", ",", "String", "password", ")", "{", "return", "getAM", "(", ")", ".", "loginASync", "(", "new", "LoginCredentials", "(", "email", ",", "password", ")", ...
Perform asyncronously login attempt. @param email user email address @param password user password @return login results as observable.
[ "Perform", "asyncronously", "login", "attempt", "." ]
train
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/BackendUser.java#L182-L184
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/registry/GlobalTransformerRegistry.java
GlobalTransformerRegistry.registerTransformer
public void registerTransformer(final PathAddress address, final ModelVersion version, String operationName, OperationTransformer transformer) { registerTransformer(address.iterator(), version, operationName, new OperationTransformerRegistry.OperationTransformerEntry(transformer, false)); }
java
public void registerTransformer(final PathAddress address, final ModelVersion version, String operationName, OperationTransformer transformer) { registerTransformer(address.iterator(), version, operationName, new OperationTransformerRegistry.OperationTransformerEntry(transformer, false)); }
[ "public", "void", "registerTransformer", "(", "final", "PathAddress", "address", ",", "final", "ModelVersion", "version", ",", "String", "operationName", ",", "OperationTransformer", "transformer", ")", "{", "registerTransformer", "(", "address", ".", "iterator", "(",...
Register an operation transformer. @param address the operation handler address @param version the model version @param operationName the operation name @param transformer the operation transformer
[ "Register", "an", "operation", "transformer", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/registry/GlobalTransformerRegistry.java#L136-L138
audit4j/audit4j-core
src/main/java/org/audit4j/core/util/ReflectUtil.java
ReflectUtil.getNewInstance
@SuppressWarnings("unchecked") public I getNewInstance(String className) { try { return getNewInstance((Class<I>) Class.forName(className)); } catch (ClassNotFoundException e) { throw new InitializationException("Given class not found", e); } }
java
@SuppressWarnings("unchecked") public I getNewInstance(String className) { try { return getNewInstance((Class<I>) Class.forName(className)); } catch (ClassNotFoundException e) { throw new InitializationException("Given class not found", e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "I", "getNewInstance", "(", "String", "className", ")", "{", "try", "{", "return", "getNewInstance", "(", "(", "Class", "<", "I", ">", ")", "Class", ".", "forName", "(", "className", ")", ")", ...
Gets the new instance. @param className the class name @return the new instance
[ "Gets", "the", "new", "instance", "." ]
train
https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/util/ReflectUtil.java#L61-L68
ehcache/ehcache3
core/src/main/java/org/ehcache/core/config/DefaultConfiguration.java
DefaultConfiguration.addCacheConfiguration
public void addCacheConfiguration(final String alias, final CacheConfiguration<?, ?> config) { if (caches.put(alias, config) != null) { throw new IllegalStateException("Cache '" + alias + "' already present!"); } }
java
public void addCacheConfiguration(final String alias, final CacheConfiguration<?, ?> config) { if (caches.put(alias, config) != null) { throw new IllegalStateException("Cache '" + alias + "' already present!"); } }
[ "public", "void", "addCacheConfiguration", "(", "final", "String", "alias", ",", "final", "CacheConfiguration", "<", "?", ",", "?", ">", "config", ")", "{", "if", "(", "caches", ".", "put", "(", "alias", ",", "config", ")", "!=", "null", ")", "{", "thr...
Adds a {@link CacheConfiguration} tied to the provided alias. @param alias the alias of the cache @param config the configuration of the cache
[ "Adds", "a", "{", "@link", "CacheConfiguration", "}", "tied", "to", "the", "provided", "alias", "." ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/config/DefaultConfiguration.java#L121-L125
dain/leveldb
leveldb/src/main/java/org/iq80/leveldb/util/Slice.java
Slice.setBytes
public int setBytes(int index, InputStream in, int length) throws IOException { checkPositionIndexes(index, index + length, this.length); index += offset; int readBytes = 0; do { int localReadBytes = in.read(data, index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); return readBytes; }
java
public int setBytes(int index, InputStream in, int length) throws IOException { checkPositionIndexes(index, index + length, this.length); index += offset; int readBytes = 0; do { int localReadBytes = in.read(data, index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); return readBytes; }
[ "public", "int", "setBytes", "(", "int", "index", ",", "InputStream", "in", ",", "int", "length", ")", "throws", "IOException", "{", "checkPositionIndexes", "(", "index", ",", "index", "+", "length", ",", "this", ".", "length", ")", ";", "index", "+=", "...
Transfers the content of the specified source stream to this buffer starting at the specified absolute {@code index}. @param length the number of bytes to transfer @return the actual number of bytes read in from the specified channel. {@code -1} if the specified channel is closed. @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or if {@code index + length} is greater than {@code this.capacity} @throws java.io.IOException if the specified stream threw an exception during I/O
[ "Transfers", "the", "content", "of", "the", "specified", "source", "stream", "to", "this", "buffer", "starting", "at", "the", "specified", "absolute", "{", "@code", "index", "}", "." ]
train
https://github.com/dain/leveldb/blob/7994065b48eada2ef29e7fefd172c2ad1e0110eb/leveldb/src/main/java/org/iq80/leveldb/util/Slice.java#L417-L439
mojohaus/jaxb2-maven-plugin
src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java
Validate.notNull
public static void notNull(final Object object, final String argumentName) { if (object == null) { throw new NullPointerException(getMessage("null", argumentName)); } }
java
public static void notNull(final Object object, final String argumentName) { if (object == null) { throw new NullPointerException(getMessage("null", argumentName)); } }
[ "public", "static", "void", "notNull", "(", "final", "Object", "object", ",", "final", "String", "argumentName", ")", "{", "if", "(", "object", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "getMessage", "(", "\"null\"", ",", "argument...
Validates that the supplied object is not null, and throws a NullPointerException otherwise. @param object The object to validate for {@code null}-ness. @param argumentName The argument name of the object to validate. If supplied (i.e. non-{@code null}), this value is used in composing a better exception message.
[ "Validates", "that", "the", "supplied", "object", "is", "not", "null", "and", "throws", "a", "NullPointerException", "otherwise", "." ]
train
https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java#L43-L47
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java
ExpectedConditions.attributeContains
public static ExpectedCondition<Boolean> attributeContains(final WebElement element, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { private String currentValue = null; @Override public Boolean apply(WebDriver driver) { return getAttributeOrCssValue(element, attribute) .map(seen -> seen.contains(value)) .orElse(false); } @Override public String toString() { return String.format("value to contain \"%s\". Current value: \"%s\"", value, currentValue); } }; }
java
public static ExpectedCondition<Boolean> attributeContains(final WebElement element, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { private String currentValue = null; @Override public Boolean apply(WebDriver driver) { return getAttributeOrCssValue(element, attribute) .map(seen -> seen.contains(value)) .orElse(false); } @Override public String toString() { return String.format("value to contain \"%s\". Current value: \"%s\"", value, currentValue); } }; }
[ "public", "static", "ExpectedCondition", "<", "Boolean", ">", "attributeContains", "(", "final", "WebElement", "element", ",", "final", "String", "attribute", ",", "final", "String", "value", ")", "{", "return", "new", "ExpectedCondition", "<", "Boolean", ">", "...
An expectation for checking WebElement with given locator has attribute which contains specific value @param element used to check its parameters @param attribute used to define css or html attribute @param value used as expected attribute value @return Boolean true when element has css or html attribute which contains the value
[ "An", "expectation", "for", "checking", "WebElement", "with", "given", "locator", "has", "attribute", "which", "contains", "specific", "value" ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java#L1076-L1094
VoltDB/voltdb
src/frontend/org/voltdb/iv2/MpRoSitePool.java
MpRoSitePool.completeWork
void completeWork(long txnId) { if (m_shuttingDown) { return; } MpRoSiteContext site = m_busySites.remove(txnId); if (site == null) { throw new RuntimeException("No busy site for txnID: " + txnId + " found, shouldn't happen."); } // check the catalog versions, only push back onto idle if the catalog hasn't changed // otherwise, just let it get garbage collected and let doWork() construct new ones for the // pool with the updated catalog. if (site.getCatalogCRC() == m_catalogContext.getCatalogCRC() && site.getCatalogVersion() == m_catalogContext.catalogVersion) { m_idleSites.push(site); } else { site.shutdown(); m_allSites.remove(site); } }
java
void completeWork(long txnId) { if (m_shuttingDown) { return; } MpRoSiteContext site = m_busySites.remove(txnId); if (site == null) { throw new RuntimeException("No busy site for txnID: " + txnId + " found, shouldn't happen."); } // check the catalog versions, only push back onto idle if the catalog hasn't changed // otherwise, just let it get garbage collected and let doWork() construct new ones for the // pool with the updated catalog. if (site.getCatalogCRC() == m_catalogContext.getCatalogCRC() && site.getCatalogVersion() == m_catalogContext.catalogVersion) { m_idleSites.push(site); } else { site.shutdown(); m_allSites.remove(site); } }
[ "void", "completeWork", "(", "long", "txnId", ")", "{", "if", "(", "m_shuttingDown", ")", "{", "return", ";", "}", "MpRoSiteContext", "site", "=", "m_busySites", ".", "remove", "(", "txnId", ")", ";", "if", "(", "site", "==", "null", ")", "{", "throw",...
Inform the pool that the work associated with the given txnID is complete
[ "Inform", "the", "pool", "that", "the", "work", "associated", "with", "the", "given", "txnID", "is", "complete" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/iv2/MpRoSitePool.java#L250-L271
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockWithChecksumFileWriter.java
BlockWithChecksumFileWriter.setChannelPosition
public void setChannelPosition(long dataOffset, long ckOffset) throws IOException { long channelSize = blockDataWriter.getChannelSize(); if (channelSize < dataOffset) { String fileName; if (datanode.data instanceof FSDataset) { FSDataset fsDataset = (FSDataset) datanode.data; fileName = fsDataset.getDatanodeBlockInfo(namespaceId, block) .getBlockDataFile().getTmpFile(namespaceId, block).toString(); } else { fileName = "unknown"; } String msg = "Trying to change block file offset of block " + block + " file " + fileName + " to " + dataOffset + " but actual size of file is " + blockDataWriter.getChannelSize(); throw new IOException(msg); } if (dataOffset > channelSize) { throw new IOException("Set position over the end of the data file."); } if (dataOffset % bytesPerChecksum != 0 && channelSize != dataOffset) { DFSClient.LOG.warn("Non-inline Checksum Block " + block + " channel size " + channelSize + " but data starts from " + dataOffset); } blockDataWriter.position(dataOffset); setChecksumOffset(ckOffset); }
java
public void setChannelPosition(long dataOffset, long ckOffset) throws IOException { long channelSize = blockDataWriter.getChannelSize(); if (channelSize < dataOffset) { String fileName; if (datanode.data instanceof FSDataset) { FSDataset fsDataset = (FSDataset) datanode.data; fileName = fsDataset.getDatanodeBlockInfo(namespaceId, block) .getBlockDataFile().getTmpFile(namespaceId, block).toString(); } else { fileName = "unknown"; } String msg = "Trying to change block file offset of block " + block + " file " + fileName + " to " + dataOffset + " but actual size of file is " + blockDataWriter.getChannelSize(); throw new IOException(msg); } if (dataOffset > channelSize) { throw new IOException("Set position over the end of the data file."); } if (dataOffset % bytesPerChecksum != 0 && channelSize != dataOffset) { DFSClient.LOG.warn("Non-inline Checksum Block " + block + " channel size " + channelSize + " but data starts from " + dataOffset); } blockDataWriter.position(dataOffset); setChecksumOffset(ckOffset); }
[ "public", "void", "setChannelPosition", "(", "long", "dataOffset", ",", "long", "ckOffset", ")", "throws", "IOException", "{", "long", "channelSize", "=", "blockDataWriter", ".", "getChannelSize", "(", ")", ";", "if", "(", "channelSize", "<", "dataOffset", ")", ...
Sets the offset in the block to which the the next write will write data to.
[ "Sets", "the", "offset", "in", "the", "block", "to", "which", "the", "the", "next", "write", "will", "write", "data", "to", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockWithChecksumFileWriter.java#L235-L263
amaembo/streamex
src/main/java/one/util/streamex/StreamEx.java
StreamEx.cartesianProduct
public static <T, U> StreamEx<U> cartesianProduct(Collection<? extends Collection<T>> source, U identity, BiFunction<U, ? super T, U> accumulator) { if (source.isEmpty()) return of(identity); return of(new CrossSpliterator.Reducing<>(source, identity, accumulator)); }
java
public static <T, U> StreamEx<U> cartesianProduct(Collection<? extends Collection<T>> source, U identity, BiFunction<U, ? super T, U> accumulator) { if (source.isEmpty()) return of(identity); return of(new CrossSpliterator.Reducing<>(source, identity, accumulator)); }
[ "public", "static", "<", "T", ",", "U", ">", "StreamEx", "<", "U", ">", "cartesianProduct", "(", "Collection", "<", "?", "extends", "Collection", "<", "T", ">", ">", "source", ",", "U", "identity", ",", "BiFunction", "<", "U", ",", "?", "super", "T",...
Returns a new {@code StreamEx} which elements are results of reduction of all possible tuples composed from the elements of supplied collection of collections. The whole stream forms an n-fold Cartesian product (or cross-product) of the input collections. <p> The reduction is performed using the provided identity object and the accumulator function which is capable to accumulate new element. The accumulator function must not modify the previous accumulated value, but must produce new value instead. That's because partially accumulated values are reused for subsequent elements. <p> This method is equivalent to the following: <pre> {@code StreamEx.cartesianProduct(source).map(list -> StreamEx.of(list).foldLeft(identity, accumulator))} </pre> <p> However it may perform much faster as partial reduction results are reused. <p> The supplied collection is assumed to be unchanged during the operation. @param <T> the type of the input elements @param <U> the type of the elements of the resulting stream @param source the input collection of collections which is used to generate the cross-product. @param identity the identity value @param accumulator a <a href="package-summary.html#NonInterference">non-interfering </a>, <a href="package-summary.html#Statelessness">stateless</a> function for incorporating an additional element from source collection into a stream element. @return the new stream. @see #cartesianProduct(Collection) @see #cartesianPower(int, Collection, Object, BiFunction) @since 0.4.0
[ "Returns", "a", "new", "{", "@code", "StreamEx", "}", "which", "elements", "are", "results", "of", "reduction", "of", "all", "possible", "tuples", "composed", "from", "the", "elements", "of", "supplied", "collection", "of", "collections", ".", "The", "whole", ...
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L3139-L3144
wisdom-framework/wisdom
core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/WisdomExecutor.java
WisdomExecutor.appendSystemPropertiesToCommandLine
private static void appendSystemPropertiesToCommandLine(AbstractWisdomMojo mojo, CommandLine cmd) { Properties userProperties = mojo.session.getUserProperties(); if (userProperties != null) { //noinspection unchecked Enumeration<String> names = (Enumeration<String>) userProperties.propertyNames(); while (names.hasMoreElements()) { String name = names.nextElement(); cmd.addArgument("-D" + name + "=" + userProperties.getProperty(name)); } } }
java
private static void appendSystemPropertiesToCommandLine(AbstractWisdomMojo mojo, CommandLine cmd) { Properties userProperties = mojo.session.getUserProperties(); if (userProperties != null) { //noinspection unchecked Enumeration<String> names = (Enumeration<String>) userProperties.propertyNames(); while (names.hasMoreElements()) { String name = names.nextElement(); cmd.addArgument("-D" + name + "=" + userProperties.getProperty(name)); } } }
[ "private", "static", "void", "appendSystemPropertiesToCommandLine", "(", "AbstractWisdomMojo", "mojo", ",", "CommandLine", "cmd", ")", "{", "Properties", "userProperties", "=", "mojo", ".", "session", ".", "getUserProperties", "(", ")", ";", "if", "(", "userProperti...
Appends the properties from the Maven session (user properties) to the command line. As the command line is intended to be a Chameleon process, arguments are passed using the {@literal -Dkey=value} syntax. @param mojo the mojo @param cmd the command line to extend
[ "Appends", "the", "properties", "from", "the", "Maven", "session", "(", "user", "properties", ")", "to", "the", "command", "line", ".", "As", "the", "command", "line", "is", "intended", "to", "be", "a", "Chameleon", "process", "arguments", "are", "passed", ...
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-maven-plugin/src/main/java/org/wisdom/maven/utils/WisdomExecutor.java#L170-L180
gallandarakhneorg/afc
advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributeCollection.java
DBaseFileAttributeCollection.fireAttributeRemovedEvent
protected void fireAttributeRemovedEvent(String name, AttributeValue oldValue) { if (this.listeners != null && isEventFirable()) { final AttributeChangeEvent event = new AttributeChangeEvent( //source this, //type Type.REMOVAL, //old name name, //old value oldValue, //current name name, //current value oldValue); for (final AttributeChangeListener listener : this.listeners) { listener.onAttributeChangeEvent(event); } } }
java
protected void fireAttributeRemovedEvent(String name, AttributeValue oldValue) { if (this.listeners != null && isEventFirable()) { final AttributeChangeEvent event = new AttributeChangeEvent( //source this, //type Type.REMOVAL, //old name name, //old value oldValue, //current name name, //current value oldValue); for (final AttributeChangeListener listener : this.listeners) { listener.onAttributeChangeEvent(event); } } }
[ "protected", "void", "fireAttributeRemovedEvent", "(", "String", "name", ",", "AttributeValue", "oldValue", ")", "{", "if", "(", "this", ".", "listeners", "!=", "null", "&&", "isEventFirable", "(", ")", ")", "{", "final", "AttributeChangeEvent", "event", "=", ...
Fire the an attribute removal event. @param name is the name of the attribute for which the event occured. @param oldValue is the previous value of the attribute
[ "Fire", "the", "an", "attribute", "removal", "event", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/attr/DBaseFileAttributeCollection.java#L936-L955
OpenLiberty/open-liberty
dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceFormatter.java
BaseTraceFormatter.messageLogFormat
public String messageLogFormat(LogRecord logRecord, String formattedVerboseMsg) { // This is a very light trace format, based on enhanced: StringBuilder sb = new StringBuilder(256); String sym = getMarker(logRecord); String name = nonNullString(logRecord.getLoggerName(), logRecord.getSourceClassName()); sb.append('[').append(DateFormatHelper.formatTime(logRecord.getMillis(), useIsoDateFormat)).append("] "); sb.append(DataFormatHelper.getThreadId()).append(' '); formatFixedString(sb, name, enhancedNameLength); sb.append(sym); // sym has built-in padding sb.append(formattedVerboseMsg); if (logRecord.getThrown() != null) { String stackTrace = getStackTrace(logRecord); if (stackTrace != null) sb.append(LoggingConstants.nl).append(stackTrace); } return sb.toString(); }
java
public String messageLogFormat(LogRecord logRecord, String formattedVerboseMsg) { // This is a very light trace format, based on enhanced: StringBuilder sb = new StringBuilder(256); String sym = getMarker(logRecord); String name = nonNullString(logRecord.getLoggerName(), logRecord.getSourceClassName()); sb.append('[').append(DateFormatHelper.formatTime(logRecord.getMillis(), useIsoDateFormat)).append("] "); sb.append(DataFormatHelper.getThreadId()).append(' '); formatFixedString(sb, name, enhancedNameLength); sb.append(sym); // sym has built-in padding sb.append(formattedVerboseMsg); if (logRecord.getThrown() != null) { String stackTrace = getStackTrace(logRecord); if (stackTrace != null) sb.append(LoggingConstants.nl).append(stackTrace); } return sb.toString(); }
[ "public", "String", "messageLogFormat", "(", "LogRecord", "logRecord", ",", "String", "formattedVerboseMsg", ")", "{", "// This is a very light trace format, based on enhanced:", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "256", ")", ";", "String", "sym", ...
The messages log always uses the same/enhanced format, and relies on already formatted messages. This does the formatting needed to take a message suitable for console.log and wrap it to fit into messages.log. @param logRecord @param formattedVerboseMsg the result of {@link #formatVerboseMessage} @return Formatted string for messages.log
[ "The", "messages", "log", "always", "uses", "the", "same", "/", "enhanced", "format", "and", "relies", "on", "already", "formatted", "messages", ".", "This", "does", "the", "formatting", "needed", "to", "take", "a", "message", "suitable", "for", "console", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/BaseTraceFormatter.java#L458-L477
alkacon/opencms-core
src/org/opencms/xml/CmsXmlContentDefinition.java
CmsXmlContentDefinition.findSchemaTypesForPath
public boolean findSchemaTypesForPath(String path, BiConsumer<I_CmsXmlSchemaType, String> consumer) { path = CmsXmlUtils.removeAllXpathIndices(path); List<String> pathComponents = CmsXmlUtils.splitXpath(path); List<I_CmsXmlSchemaType> result = new ArrayList<>(); CmsXmlContentDefinition currentContentDef = this; for (int i = 0; i < pathComponents.size(); i++) { String pathComponent = pathComponents.get(i); if (currentContentDef == null) { return false; } I_CmsXmlSchemaType schemaType = currentContentDef.getSchemaType(pathComponent); if (schemaType == null) { return false; } else { String remainingPath = CmsStringUtil.listAsString( pathComponents.subList(i + 1, pathComponents.size()), "/"); consumer.accept(schemaType, remainingPath); result.add(schemaType); if (schemaType instanceof CmsXmlNestedContentDefinition) { currentContentDef = ((CmsXmlNestedContentDefinition)schemaType).getNestedContentDefinition(); } else { currentContentDef = null; // } } } return true; }
java
public boolean findSchemaTypesForPath(String path, BiConsumer<I_CmsXmlSchemaType, String> consumer) { path = CmsXmlUtils.removeAllXpathIndices(path); List<String> pathComponents = CmsXmlUtils.splitXpath(path); List<I_CmsXmlSchemaType> result = new ArrayList<>(); CmsXmlContentDefinition currentContentDef = this; for (int i = 0; i < pathComponents.size(); i++) { String pathComponent = pathComponents.get(i); if (currentContentDef == null) { return false; } I_CmsXmlSchemaType schemaType = currentContentDef.getSchemaType(pathComponent); if (schemaType == null) { return false; } else { String remainingPath = CmsStringUtil.listAsString( pathComponents.subList(i + 1, pathComponents.size()), "/"); consumer.accept(schemaType, remainingPath); result.add(schemaType); if (schemaType instanceof CmsXmlNestedContentDefinition) { currentContentDef = ((CmsXmlNestedContentDefinition)schemaType).getNestedContentDefinition(); } else { currentContentDef = null; // } } } return true; }
[ "public", "boolean", "findSchemaTypesForPath", "(", "String", "path", ",", "BiConsumer", "<", "I_CmsXmlSchemaType", ",", "String", ">", "consumer", ")", "{", "path", "=", "CmsXmlUtils", ".", "removeAllXpathIndices", "(", "path", ")", ";", "List", "<", "String", ...
Iterates over all schema types along a given xpath, starting from a root content definition.<p> @param path the path @param consumer a handler that consumes both the schema type and the remaining suffix of the path, relative to the schema type @return true if for all path components a schema type could be found
[ "Iterates", "over", "all", "schema", "types", "along", "a", "given", "xpath", "starting", "from", "a", "root", "content", "definition", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlContentDefinition.java#L1278-L1307
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java
JobsImpl.listNext
public PagedList<CloudJob> listNext(final String nextPageLink, final JobListNextOptions jobListNextOptions) { ServiceResponseWithHeaders<Page<CloudJob>, JobListHeaders> response = listNextSinglePageAsync(nextPageLink, jobListNextOptions).toBlocking().single(); return new PagedList<CloudJob>(response.body()) { @Override public Page<CloudJob> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink, jobListNextOptions).toBlocking().single().body(); } }; }
java
public PagedList<CloudJob> listNext(final String nextPageLink, final JobListNextOptions jobListNextOptions) { ServiceResponseWithHeaders<Page<CloudJob>, JobListHeaders> response = listNextSinglePageAsync(nextPageLink, jobListNextOptions).toBlocking().single(); return new PagedList<CloudJob>(response.body()) { @Override public Page<CloudJob> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink, jobListNextOptions).toBlocking().single().body(); } }; }
[ "public", "PagedList", "<", "CloudJob", ">", "listNext", "(", "final", "String", "nextPageLink", ",", "final", "JobListNextOptions", "jobListNextOptions", ")", "{", "ServiceResponseWithHeaders", "<", "Page", "<", "CloudJob", ">", ",", "JobListHeaders", ">", "respons...
Lists all of the jobs in the specified account. @param nextPageLink The NextLink from the previous successful call to List operation. @param jobListNextOptions Additional parameters for the operation @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 PagedList&lt;CloudJob&gt; object if successful.
[ "Lists", "all", "of", "the", "jobs", "in", "the", "specified", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L3427-L3435
alkacon/opencms-core
src/org/opencms/workplace/editors/directedit/CmsAdvancedDirectEditProvider.java
CmsAdvancedDirectEditProvider.startDirectEditDisabled
public String startDirectEditDisabled(CmsDirectEditParams params, CmsDirectEditResourceInfo resourceInfo) { StringBuffer result = new StringBuffer(256); result.append("<!-- EDIT BLOCK START (DISABLED): "); result.append(params.m_resourceName); result.append(" ["); result.append(resourceInfo.getResource().getState()); result.append("] "); if (!resourceInfo.getLock().isUnlocked()) { result.append(" locked "); result.append(resourceInfo.getLock().getProject().getName()); } result.append(" -->\n"); return result.toString(); }
java
public String startDirectEditDisabled(CmsDirectEditParams params, CmsDirectEditResourceInfo resourceInfo) { StringBuffer result = new StringBuffer(256); result.append("<!-- EDIT BLOCK START (DISABLED): "); result.append(params.m_resourceName); result.append(" ["); result.append(resourceInfo.getResource().getState()); result.append("] "); if (!resourceInfo.getLock().isUnlocked()) { result.append(" locked "); result.append(resourceInfo.getLock().getProject().getName()); } result.append(" -->\n"); return result.toString(); }
[ "public", "String", "startDirectEditDisabled", "(", "CmsDirectEditParams", "params", ",", "CmsDirectEditResourceInfo", "resourceInfo", ")", "{", "StringBuffer", "result", "=", "new", "StringBuffer", "(", "256", ")", ";", "result", ".", "append", "(", "\"<!-- EDIT BLOC...
Returns the start HTML for a disabled direct edit button.<p> @param params the direct edit parameters @param resourceInfo contains information about the resource to edit @return the start HTML for a disabled direct edit button
[ "Returns", "the", "start", "HTML", "for", "a", "disabled", "direct", "edit", "button", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/directedit/CmsAdvancedDirectEditProvider.java#L297-L312
azkaban/azkaban
azkaban-common/src/main/java/azkaban/executor/FetchActiveFlowDao.java
FetchActiveFlowDao.fetchActiveFlows
Map<Integer, Pair<ExecutionReference, ExecutableFlow>> fetchActiveFlows() throws ExecutorManagerException { try { return this.dbOperator.query(FetchActiveExecutableFlows.FETCH_ACTIVE_EXECUTABLE_FLOWS, new FetchActiveExecutableFlows()); } catch (final SQLException e) { throw new ExecutorManagerException("Error fetching active flows", e); } }
java
Map<Integer, Pair<ExecutionReference, ExecutableFlow>> fetchActiveFlows() throws ExecutorManagerException { try { return this.dbOperator.query(FetchActiveExecutableFlows.FETCH_ACTIVE_EXECUTABLE_FLOWS, new FetchActiveExecutableFlows()); } catch (final SQLException e) { throw new ExecutorManagerException("Error fetching active flows", e); } }
[ "Map", "<", "Integer", ",", "Pair", "<", "ExecutionReference", ",", "ExecutableFlow", ">", ">", "fetchActiveFlows", "(", ")", "throws", "ExecutorManagerException", "{", "try", "{", "return", "this", ".", "dbOperator", ".", "query", "(", "FetchActiveExecutableFlows...
Fetch flows that are dispatched and not yet finished. @return active flows map @throws ExecutorManagerException the executor manager exception
[ "Fetch", "flows", "that", "are", "dispatched", "and", "not", "yet", "finished", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/executor/FetchActiveFlowDao.java#L145-L153
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java
NetworkEnvironmentConfiguration.createNettyConfig
@Nullable private static NettyConfig createNettyConfig( Configuration configuration, boolean localTaskManagerCommunication, InetAddress taskManagerAddress, int dataport) { final NettyConfig nettyConfig; if (!localTaskManagerCommunication) { final InetSocketAddress taskManagerInetSocketAddress = new InetSocketAddress(taskManagerAddress, dataport); nettyConfig = new NettyConfig(taskManagerInetSocketAddress.getAddress(), taskManagerInetSocketAddress.getPort(), getPageSize(configuration), ConfigurationParserUtils.getSlot(configuration), configuration); } else { nettyConfig = null; } return nettyConfig; }
java
@Nullable private static NettyConfig createNettyConfig( Configuration configuration, boolean localTaskManagerCommunication, InetAddress taskManagerAddress, int dataport) { final NettyConfig nettyConfig; if (!localTaskManagerCommunication) { final InetSocketAddress taskManagerInetSocketAddress = new InetSocketAddress(taskManagerAddress, dataport); nettyConfig = new NettyConfig(taskManagerInetSocketAddress.getAddress(), taskManagerInetSocketAddress.getPort(), getPageSize(configuration), ConfigurationParserUtils.getSlot(configuration), configuration); } else { nettyConfig = null; } return nettyConfig; }
[ "@", "Nullable", "private", "static", "NettyConfig", "createNettyConfig", "(", "Configuration", "configuration", ",", "boolean", "localTaskManagerCommunication", ",", "InetAddress", "taskManagerAddress", ",", "int", "dataport", ")", "{", "final", "NettyConfig", "nettyConf...
Generates {@link NettyConfig} from Flink {@link Configuration}. @param configuration configuration object @param localTaskManagerCommunication true, to skip initializing the network stack @param taskManagerAddress identifying the IP address under which the TaskManager will be accessible @param dataport data port for communication and data exchange @return the netty configuration or {@code null} if communication is in the same task manager
[ "Generates", "{", "@link", "NettyConfig", "}", "from", "Flink", "{", "@link", "Configuration", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java#L424-L442
grails/grails-core
grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java
GroovyPagesUriSupport.getTemplateURI
@Override public String getTemplateURI(String controllerName, String templateName, boolean includeExtension) { if (templateName.startsWith(SLASH_STR)) { return getAbsoluteTemplateURI(templateName, includeExtension); } else if(templateName.startsWith(RELATIVE_STRING)) { return getRelativeTemplateURIInternal(templateName, includeExtension); } FastStringWriter buf = new FastStringWriter(); String pathToTemplate = BLANK; int lastSlash = templateName.lastIndexOf(SLASH); if (lastSlash > -1) { pathToTemplate = templateName.substring(0, lastSlash + 1); templateName = templateName.substring(lastSlash + 1); } if(controllerName != null) { buf.append(SLASH) .append(controllerName); } buf.append(SLASH) .append(pathToTemplate) .append(UNDERSCORE) .append(templateName); if(includeExtension) { return buf.append(EXTENSION).toString(); } else { return buf.toString(); } }
java
@Override public String getTemplateURI(String controllerName, String templateName, boolean includeExtension) { if (templateName.startsWith(SLASH_STR)) { return getAbsoluteTemplateURI(templateName, includeExtension); } else if(templateName.startsWith(RELATIVE_STRING)) { return getRelativeTemplateURIInternal(templateName, includeExtension); } FastStringWriter buf = new FastStringWriter(); String pathToTemplate = BLANK; int lastSlash = templateName.lastIndexOf(SLASH); if (lastSlash > -1) { pathToTemplate = templateName.substring(0, lastSlash + 1); templateName = templateName.substring(lastSlash + 1); } if(controllerName != null) { buf.append(SLASH) .append(controllerName); } buf.append(SLASH) .append(pathToTemplate) .append(UNDERSCORE) .append(templateName); if(includeExtension) { return buf.append(EXTENSION).toString(); } else { return buf.toString(); } }
[ "@", "Override", "public", "String", "getTemplateURI", "(", "String", "controllerName", ",", "String", "templateName", ",", "boolean", "includeExtension", ")", "{", "if", "(", "templateName", ".", "startsWith", "(", "SLASH_STR", ")", ")", "{", "return", "getAbso...
Obtains the URI to a template using the controller name and template name @param controllerName The controller name @param templateName The template name @param includeExtension The flag to include the template extension @return The template URI
[ "Obtains", "the", "URI", "to", "a", "template", "using", "the", "controller", "name", "and", "template", "name" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-web-common/src/main/groovy/org/grails/web/pages/GroovyPagesUriSupport.java#L116-L148
ckpoint/CheckPoint
src/main/java/hsim/checkpoint/util/ValidationObjUtil.java
ValidationObjUtil.getSetterMethodNotCheckParamType
public static Method getSetterMethodNotCheckParamType(Class<?> cType, String fieldName) { String methodName = getMethodName(fieldName, SET_METHOD_PREFIX); Method[] methods = cType.getMethods(); for (Method m : methods) { if (m.getName().equals(methodName) && m.getParameterCount() == 1) { return m; } } return null; }
java
public static Method getSetterMethodNotCheckParamType(Class<?> cType, String fieldName) { String methodName = getMethodName(fieldName, SET_METHOD_PREFIX); Method[] methods = cType.getMethods(); for (Method m : methods) { if (m.getName().equals(methodName) && m.getParameterCount() == 1) { return m; } } return null; }
[ "public", "static", "Method", "getSetterMethodNotCheckParamType", "(", "Class", "<", "?", ">", "cType", ",", "String", "fieldName", ")", "{", "String", "methodName", "=", "getMethodName", "(", "fieldName", ",", "SET_METHOD_PREFIX", ")", ";", "Method", "[", "]", ...
Gets setter method not check param type. @param cType the c type @param fieldName the field name @return the setter method not check param type
[ "Gets", "setter", "method", "not", "check", "param", "type", "." ]
train
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/util/ValidationObjUtil.java#L141-L150
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java
TableProcessor.onFamilyType
private void onFamilyType(EntityMetadata entityMetadata, final Class clazz, Field f) { if (entityMetadata.getType() == null || !entityMetadata.getType().equals(Type.SUPER_COLUMN_FAMILY)) { if ((f.isAnnotationPresent(Embedded.class) && f.getType().getAnnotation(Embeddable.class) != null)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else if (f.isAnnotationPresent(ElementCollection.class) && !MetadataUtils.isBasicElementCollectionField(f)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else { entityMetadata.setType(Type.COLUMN_FAMILY); } } }
java
private void onFamilyType(EntityMetadata entityMetadata, final Class clazz, Field f) { if (entityMetadata.getType() == null || !entityMetadata.getType().equals(Type.SUPER_COLUMN_FAMILY)) { if ((f.isAnnotationPresent(Embedded.class) && f.getType().getAnnotation(Embeddable.class) != null)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else if (f.isAnnotationPresent(ElementCollection.class) && !MetadataUtils.isBasicElementCollectionField(f)) { entityMetadata.setType(Type.SUPER_COLUMN_FAMILY); } else { entityMetadata.setType(Type.COLUMN_FAMILY); } } }
[ "private", "void", "onFamilyType", "(", "EntityMetadata", "entityMetadata", ",", "final", "Class", "clazz", ",", "Field", "f", ")", "{", "if", "(", "entityMetadata", ".", "getType", "(", ")", "==", "null", "||", "!", "entityMetadata", ".", "getType", "(", ...
On family type. @param entityMetadata the entity metadata @param clazz the clazz @param f the f
[ "On", "family", "type", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java#L332-L349
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/ChangeFocusOnChangeHandler.java
ChangeFocusOnChangeHandler.fieldChanged
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { if (m_screenField == null) this.lookupSField(); if (m_bChangeIfNull != null) { if ((m_bChangeIfNull.booleanValue()) && (!this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; if ((!m_bChangeIfNull.booleanValue()) && (this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; } if (m_screenField != null) m_screenField.requestFocus(); return DBConstants.NORMAL_RETURN; }
java
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { if (m_screenField == null) this.lookupSField(); if (m_bChangeIfNull != null) { if ((m_bChangeIfNull.booleanValue()) && (!this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; if ((!m_bChangeIfNull.booleanValue()) && (this.getOwner().isNull())) return DBConstants.NORMAL_RETURN; } if (m_screenField != null) m_screenField.requestFocus(); return DBConstants.NORMAL_RETURN; }
[ "public", "int", "fieldChanged", "(", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "if", "(", "m_screenField", "==", "null", ")", "this", ".", "lookupSField", "(", ")", ";", "if", "(", "m_bChangeIfNull", "!=", "null", ")", "{", "if", "...
The Field has Changed. Change to focus to the target field. @param bDisplayOption If true, display the change. @param iMoveMode The type of move being done (init/read/screen). @return The error code (or NORMAL_RETURN if okay).
[ "The", "Field", "has", "Changed", ".", "Change", "to", "focus", "to", "the", "target", "field", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/ChangeFocusOnChangeHandler.java#L102-L116
deeplearning4j/deeplearning4j
arbiter/arbiter-deeplearning4j/src/main/java/org/deeplearning4j/arbiter/scoring/util/ScoreUtil.java
ScoreUtil.score
public static double score(ComputationGraph model, DataSetIterator testSet, RegressionValue regressionValue) { RegressionEvaluation evaluation = model.evaluateRegression(testSet); return getScoreFromRegressionEval(evaluation, regressionValue); }
java
public static double score(ComputationGraph model, DataSetIterator testSet, RegressionValue regressionValue) { RegressionEvaluation evaluation = model.evaluateRegression(testSet); return getScoreFromRegressionEval(evaluation, regressionValue); }
[ "public", "static", "double", "score", "(", "ComputationGraph", "model", ",", "DataSetIterator", "testSet", ",", "RegressionValue", "regressionValue", ")", "{", "RegressionEvaluation", "evaluation", "=", "model", ".", "evaluateRegression", "(", "testSet", ")", ";", ...
Run a {@link RegressionEvaluation} over a {@link DataSetIterator} @param model the model to use @param testSet the test set iterator @param regressionValue the regression type to use @return
[ "Run", "a", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/arbiter/arbiter-deeplearning4j/src/main/java/org/deeplearning4j/arbiter/scoring/util/ScoreUtil.java#L252-L255
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/TagsApi.java
TagsApi.getClusterPhotos
public Photos getClusterPhotos(String tag, List<String> clusterId) throws JinxException { JinxUtils.validateParams(tag, clusterId); StringBuilder sb = new StringBuilder(); for (String s : clusterId) { sb.append(s).append("-"); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return getClusterPhotos(tag, sb.toString()); }
java
public Photos getClusterPhotos(String tag, List<String> clusterId) throws JinxException { JinxUtils.validateParams(tag, clusterId); StringBuilder sb = new StringBuilder(); for (String s : clusterId) { sb.append(s).append("-"); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return getClusterPhotos(tag, sb.toString()); }
[ "public", "Photos", "getClusterPhotos", "(", "String", "tag", ",", "List", "<", "String", ">", "clusterId", ")", "throws", "JinxException", "{", "JinxUtils", ".", "validateParams", "(", "tag", ",", "clusterId", ")", ";", "StringBuilder", "sb", "=", "new", "S...
Returns the first 24 photos for a given tag cluster This method does not require authentication. This method will combine the Strings in the clusterId list. @param tag the tag that the cluster belongs to. Required. @param clusterId top three tags for the cluster. Required. @return first 24 photos for a given tag cluster. @throws JinxException if required parameters are missing, or if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.tags.getClusterPhotos.html">flickr.tags.getClusterPhotos</a>
[ "Returns", "the", "first", "24", "photos", "for", "a", "given", "tag", "cluster" ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/TagsApi.java#L85-L95
icode/ameba
src/main/java/ameba/lib/Fibers.java
Fibers.runInFiberRuntime
public static <V> V runInFiberRuntime(FiberScheduler scheduler, SuspendableCallable<V> target) throws InterruptedException { return FiberUtil.runInFiberRuntime(scheduler, target); }
java
public static <V> V runInFiberRuntime(FiberScheduler scheduler, SuspendableCallable<V> target) throws InterruptedException { return FiberUtil.runInFiberRuntime(scheduler, target); }
[ "public", "static", "<", "V", ">", "V", "runInFiberRuntime", "(", "FiberScheduler", "scheduler", ",", "SuspendableCallable", "<", "V", ">", "target", ")", "throws", "InterruptedException", "{", "return", "FiberUtil", ".", "runInFiberRuntime", "(", "scheduler", ","...
Runs an action in a new fiber, awaits the fiber's termination, and returns its result. Unlike {@link #runInFiber(FiberScheduler, SuspendableCallable) runInFiber} this method does not throw {@link ExecutionException}, but wraps any checked exception thrown by the operation in a {@link RuntimeException}. @param <V> @param scheduler the {@link FiberScheduler} to use when scheduling the fiber. @param target the operation @return the operations return value @throws InterruptedException
[ "Runs", "an", "action", "in", "a", "new", "fiber", "awaits", "the", "fiber", "s", "termination", "and", "returns", "its", "result", ".", "Unlike", "{", "@link", "#runInFiber", "(", "FiberScheduler", "SuspendableCallable", ")", "runInFiber", "}", "this", "metho...
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/lib/Fibers.java#L317-L319
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java
ApiOvhHostingprivateDatabase.serviceName_changeVersion_POST
public OvhTask serviceName_changeVersion_POST(String serviceName, OvhAvailableVersionEnum version) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/changeVersion"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask serviceName_changeVersion_POST(String serviceName, OvhAvailableVersionEnum version) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}/changeVersion"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "serviceName_changeVersion_POST", "(", "String", "serviceName", ",", "OvhAvailableVersionEnum", "version", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/privateDatabase/{serviceName}/changeVersion\"", ";", "StringBuilder", "sb", "...
Change the private database engine version REST: POST /hosting/privateDatabase/{serviceName}/changeVersion @param version [required] Private database versions @param serviceName [required] The internal name of your private database
[ "Change", "the", "private", "database", "engine", "version" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L90-L97
ModeShape/modeshape
sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/dialect/derby/DerbyDdlParser.java
DerbyDdlParser.parseColumns
protected void parseColumns( DdlTokenStream tokens, AstNode tableNode, boolean isAlterTable ) throws ParsingException { String tableElementString = getTableElementsString(tokens, false); DdlTokenStream localTokens = new DdlTokenStream(tableElementString, DdlTokenStream.ddlTokenizer(false), false); localTokens.start(); StringBuilder unusedTokensSB = new StringBuilder(); do { if (isColumnDefinitionStart(localTokens)) { parseColumnDefinition(localTokens, tableNode, isAlterTable); } else { // THIS IS AN ERROR. NOTHING FOUND. // NEED TO absorb tokens unusedTokensSB.append(SPACE).append(localTokens.consume()); } } while (localTokens.canConsume(COMMA)); if (unusedTokensSB.length() > 0) { String msg = DdlSequencerI18n.unusedTokensParsingColumnDefinition.text(tableNode.getName()); DdlParserProblem problem = new DdlParserProblem(Problems.WARNING, getCurrentMarkedPosition(), msg); problem.setUnusedSource(unusedTokensSB.toString()); addProblem(problem, tableNode); } }
java
protected void parseColumns( DdlTokenStream tokens, AstNode tableNode, boolean isAlterTable ) throws ParsingException { String tableElementString = getTableElementsString(tokens, false); DdlTokenStream localTokens = new DdlTokenStream(tableElementString, DdlTokenStream.ddlTokenizer(false), false); localTokens.start(); StringBuilder unusedTokensSB = new StringBuilder(); do { if (isColumnDefinitionStart(localTokens)) { parseColumnDefinition(localTokens, tableNode, isAlterTable); } else { // THIS IS AN ERROR. NOTHING FOUND. // NEED TO absorb tokens unusedTokensSB.append(SPACE).append(localTokens.consume()); } } while (localTokens.canConsume(COMMA)); if (unusedTokensSB.length() > 0) { String msg = DdlSequencerI18n.unusedTokensParsingColumnDefinition.text(tableNode.getName()); DdlParserProblem problem = new DdlParserProblem(Problems.WARNING, getCurrentMarkedPosition(), msg); problem.setUnusedSource(unusedTokensSB.toString()); addProblem(problem, tableNode); } }
[ "protected", "void", "parseColumns", "(", "DdlTokenStream", "tokens", ",", "AstNode", "tableNode", ",", "boolean", "isAlterTable", ")", "throws", "ParsingException", "{", "String", "tableElementString", "=", "getTableElementsString", "(", "tokens", ",", "false", ")", ...
Utility method designed to parse columns within an ALTER TABLE ADD statement. @param tokens the tokenized {@link DdlTokenStream} of the DDL input content; may not be null @param tableNode @param isAlterTable @throws ParsingException
[ "Utility", "method", "designed", "to", "parse", "columns", "within", "an", "ALTER", "TABLE", "ADD", "statement", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/dialect/derby/DerbyDdlParser.java#L887-L914