repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
jaxio/celerio
celerio-engine/src/main/java/com/jaxio/celerio/util/IOUtil.java
IOUtil.inputStreamToFile
public void inputStreamToFile(InputStream is, String filename) throws IOException { """ Write to a file the bytes read from an input stream. @param filename the full or relative path to the file. """ FileOutputStream fos = new FileOutputStream(filename); inputStreamToOutputStream(is, fos); fos.close(); }
java
public void inputStreamToFile(InputStream is, String filename) throws IOException { FileOutputStream fos = new FileOutputStream(filename); inputStreamToOutputStream(is, fos); fos.close(); }
[ "public", "void", "inputStreamToFile", "(", "InputStream", "is", ",", "String", "filename", ")", "throws", "IOException", "{", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "filename", ")", ";", "inputStreamToOutputStream", "(", "is", ",", "fos", ")", ";", "fos", ".", "close", "(", ")", ";", "}" ]
Write to a file the bytes read from an input stream. @param filename the full or relative path to the file.
[ "Write", "to", "a", "file", "the", "bytes", "read", "from", "an", "input", "stream", "." ]
train
https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/util/IOUtil.java#L92-L96
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/contrib/ComparatorChain.java
ComparatorChain.setComparator
public void setComparator(int index, Comparator<T> comparator) throws IndexOutOfBoundsException { """ Replace the Comparator at the given index, maintaining the existing sortFields order. @param index index of the Comparator to replace @param comparator Comparator to place at the given index @throws IndexOutOfBoundsException if index &lt; 0 or index &gt;= size() """ setComparator(index, comparator, false); }
java
public void setComparator(int index, Comparator<T> comparator) throws IndexOutOfBoundsException { setComparator(index, comparator, false); }
[ "public", "void", "setComparator", "(", "int", "index", ",", "Comparator", "<", "T", ">", "comparator", ")", "throws", "IndexOutOfBoundsException", "{", "setComparator", "(", "index", ",", "comparator", ",", "false", ")", ";", "}" ]
Replace the Comparator at the given index, maintaining the existing sortFields order. @param index index of the Comparator to replace @param comparator Comparator to place at the given index @throws IndexOutOfBoundsException if index &lt; 0 or index &gt;= size()
[ "Replace", "the", "Comparator", "at", "the", "given", "index", "maintaining", "the", "existing", "sortFields", "order", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/contrib/ComparatorChain.java#L151-L153
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/DateField.java
DateField.setDateTime
public int setDateTime(java.util.Date date, boolean bDisplayOption, int iMoveMode) { """ Change the date and time of day. @param date The date to set (only date portion is used). @param bDisplayOption Display changed fields if true. @param iMoveMode The move mode. @return The error code (or NORMAL_RETURN). """ if (date == null) return this.setData(date, bDisplayOption, iMoveMode); m_calendar.setTime(date); m_calendar.set(Calendar.HOUR_OF_DAY, DBConstants.HOUR_DATE_ONLY); m_calendar.set(Calendar.MINUTE, 0); m_calendar.set(Calendar.SECOND, 0); m_calendar.set(Calendar.MILLISECOND, 0); date = m_calendar.getTime(); return this.setValue(date.getTime(), bDisplayOption, iMoveMode); }
java
public int setDateTime(java.util.Date date, boolean bDisplayOption, int iMoveMode) { if (date == null) return this.setData(date, bDisplayOption, iMoveMode); m_calendar.setTime(date); m_calendar.set(Calendar.HOUR_OF_DAY, DBConstants.HOUR_DATE_ONLY); m_calendar.set(Calendar.MINUTE, 0); m_calendar.set(Calendar.SECOND, 0); m_calendar.set(Calendar.MILLISECOND, 0); date = m_calendar.getTime(); return this.setValue(date.getTime(), bDisplayOption, iMoveMode); }
[ "public", "int", "setDateTime", "(", "java", ".", "util", ".", "Date", "date", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "if", "(", "date", "==", "null", ")", "return", "this", ".", "setData", "(", "date", ",", "bDisplayOption", ",", "iMoveMode", ")", ";", "m_calendar", ".", "setTime", "(", "date", ")", ";", "m_calendar", ".", "set", "(", "Calendar", ".", "HOUR_OF_DAY", ",", "DBConstants", ".", "HOUR_DATE_ONLY", ")", ";", "m_calendar", ".", "set", "(", "Calendar", ".", "MINUTE", ",", "0", ")", ";", "m_calendar", ".", "set", "(", "Calendar", ".", "SECOND", ",", "0", ")", ";", "m_calendar", ".", "set", "(", "Calendar", ".", "MILLISECOND", ",", "0", ")", ";", "date", "=", "m_calendar", ".", "getTime", "(", ")", ";", "return", "this", ".", "setValue", "(", "date", ".", "getTime", "(", ")", ",", "bDisplayOption", ",", "iMoveMode", ")", ";", "}" ]
Change the date and time of day. @param date The date to set (only date portion is used). @param bDisplayOption Display changed fields if true. @param iMoveMode The move mode. @return The error code (or NORMAL_RETURN).
[ "Change", "the", "date", "and", "time", "of", "day", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/DateField.java#L137-L148
joniles/mpxj
src/main/java/net/sf/mpxj/common/RtfHelper.java
RtfHelper.stripExtraLineEnd
private static String stripExtraLineEnd(String text, boolean formalRTF) { """ Remove the trailing line end from an RTF block. @param text source text @param formalRTF true if this is a real RTF block @return text with line end stripped """ if (formalRTF && text.endsWith("\n")) { text = text.substring(0, text.length() - 1); } return text; }
java
private static String stripExtraLineEnd(String text, boolean formalRTF) { if (formalRTF && text.endsWith("\n")) { text = text.substring(0, text.length() - 1); } return text; }
[ "private", "static", "String", "stripExtraLineEnd", "(", "String", "text", ",", "boolean", "formalRTF", ")", "{", "if", "(", "formalRTF", "&&", "text", ".", "endsWith", "(", "\"\\n\"", ")", ")", "{", "text", "=", "text", ".", "substring", "(", "0", ",", "text", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "text", ";", "}" ]
Remove the trailing line end from an RTF block. @param text source text @param formalRTF true if this is a real RTF block @return text with line end stripped
[ "Remove", "the", "trailing", "line", "end", "from", "an", "RTF", "block", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/common/RtfHelper.java#L82-L89
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/lss/LssClient.java
LssClient.stopRecording
public StopRecordingResponse stopRecording(String sessionId) { """ Stop live session recording. @param sessionId Live session id. @return the response """ checkStringNotEmpty(sessionId, "The parameter sessionId should NOT be null or empty string."); StopRecordingRequest request = new StopRecordingRequest().withSessionId(sessionId); InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_SESSION, sessionId); internalRequest.addParameter(RECORDING, null); return invokeHttpClient(internalRequest, StopRecordingResponse.class); }
java
public StopRecordingResponse stopRecording(String sessionId) { checkStringNotEmpty(sessionId, "The parameter sessionId should NOT be null or empty string."); StopRecordingRequest request = new StopRecordingRequest().withSessionId(sessionId); InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_SESSION, sessionId); internalRequest.addParameter(RECORDING, null); return invokeHttpClient(internalRequest, StopRecordingResponse.class); }
[ "public", "StopRecordingResponse", "stopRecording", "(", "String", "sessionId", ")", "{", "checkStringNotEmpty", "(", "sessionId", ",", "\"The parameter sessionId should NOT be null or empty string.\"", ")", ";", "StopRecordingRequest", "request", "=", "new", "StopRecordingRequest", "(", ")", ".", "withSessionId", "(", "sessionId", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest", "(", "HttpMethodName", ".", "PUT", ",", "request", ",", "LIVE_SESSION", ",", "sessionId", ")", ";", "internalRequest", ".", "addParameter", "(", "RECORDING", ",", "null", ")", ";", "return", "invokeHttpClient", "(", "internalRequest", ",", "StopRecordingResponse", ".", "class", ")", ";", "}" ]
Stop live session recording. @param sessionId Live session id. @return the response
[ "Stop", "live", "session", "recording", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L1062-L1068
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java
InlineMediaSource.cleanupFileName
private String cleanupFileName(String fileName) { """ Make sure filename contains no invalid characters or path parts @param fileName File name @return Cleaned up file name """ String processedFileName = fileName; // strip off path parts if (StringUtils.contains(processedFileName, "/")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "/"); } if (StringUtils.contains(processedFileName, "\\")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "\\"); } // make sure filename does not contain any invalid characters processedFileName = Escape.validFilename(processedFileName); return processedFileName; }
java
private String cleanupFileName(String fileName) { String processedFileName = fileName; // strip off path parts if (StringUtils.contains(processedFileName, "/")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "/"); } if (StringUtils.contains(processedFileName, "\\")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "\\"); } // make sure filename does not contain any invalid characters processedFileName = Escape.validFilename(processedFileName); return processedFileName; }
[ "private", "String", "cleanupFileName", "(", "String", "fileName", ")", "{", "String", "processedFileName", "=", "fileName", ";", "// strip off path parts", "if", "(", "StringUtils", ".", "contains", "(", "processedFileName", ",", "\"/\"", ")", ")", "{", "processedFileName", "=", "StringUtils", ".", "substringAfterLast", "(", "processedFileName", ",", "\"/\"", ")", ";", "}", "if", "(", "StringUtils", ".", "contains", "(", "processedFileName", ",", "\"\\\\\"", ")", ")", "{", "processedFileName", "=", "StringUtils", ".", "substringAfterLast", "(", "processedFileName", ",", "\"\\\\\"", ")", ";", "}", "// make sure filename does not contain any invalid characters", "processedFileName", "=", "Escape", ".", "validFilename", "(", "processedFileName", ")", ";", "return", "processedFileName", ";", "}" ]
Make sure filename contains no invalid characters or path parts @param fileName File name @return Cleaned up file name
[ "Make", "sure", "filename", "contains", "no", "invalid", "characters", "or", "path", "parts" ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java#L225-L240
vdurmont/emoji-java
src/main/java/com/vdurmont/emoji/EmojiParser.java
EmojiParser.getNextUnicodeCandidate
protected static UnicodeCandidate getNextUnicodeCandidate(char[] chars, int start) { """ Finds the next UnicodeCandidate after a given starting index @param chars char array to find UnicodeCandidate in @param start starting index for search @return the next UnicodeCandidate or null if no UnicodeCandidate is found after start index """ for (int i = start; i < chars.length; i++) { int emojiEnd = getEmojiEndPos(chars, i); if (emojiEnd != -1) { Emoji emoji = EmojiManager.getByUnicode(new String(chars, i, emojiEnd - i)); String fitzpatrickString = (emojiEnd + 2 <= chars.length) ? new String(chars, emojiEnd, 2) : null; return new UnicodeCandidate( emoji, fitzpatrickString, i ); } } return null; }
java
protected static UnicodeCandidate getNextUnicodeCandidate(char[] chars, int start) { for (int i = start; i < chars.length; i++) { int emojiEnd = getEmojiEndPos(chars, i); if (emojiEnd != -1) { Emoji emoji = EmojiManager.getByUnicode(new String(chars, i, emojiEnd - i)); String fitzpatrickString = (emojiEnd + 2 <= chars.length) ? new String(chars, emojiEnd, 2) : null; return new UnicodeCandidate( emoji, fitzpatrickString, i ); } } return null; }
[ "protected", "static", "UnicodeCandidate", "getNextUnicodeCandidate", "(", "char", "[", "]", "chars", ",", "int", "start", ")", "{", "for", "(", "int", "i", "=", "start", ";", "i", "<", "chars", ".", "length", ";", "i", "++", ")", "{", "int", "emojiEnd", "=", "getEmojiEndPos", "(", "chars", ",", "i", ")", ";", "if", "(", "emojiEnd", "!=", "-", "1", ")", "{", "Emoji", "emoji", "=", "EmojiManager", ".", "getByUnicode", "(", "new", "String", "(", "chars", ",", "i", ",", "emojiEnd", "-", "i", ")", ")", ";", "String", "fitzpatrickString", "=", "(", "emojiEnd", "+", "2", "<=", "chars", ".", "length", ")", "?", "new", "String", "(", "chars", ",", "emojiEnd", ",", "2", ")", ":", "null", ";", "return", "new", "UnicodeCandidate", "(", "emoji", ",", "fitzpatrickString", ",", "i", ")", ";", "}", "}", "return", "null", ";", "}" ]
Finds the next UnicodeCandidate after a given starting index @param chars char array to find UnicodeCandidate in @param start starting index for search @return the next UnicodeCandidate or null if no UnicodeCandidate is found after start index
[ "Finds", "the", "next", "UnicodeCandidate", "after", "a", "given", "starting", "index" ]
train
https://github.com/vdurmont/emoji-java/blob/8cf5fbe0d7c1020b926791f2b342a263ed07bb0f/src/main/java/com/vdurmont/emoji/EmojiParser.java#L416-L434
james-hu/jabb-core
src/main/java/net/sf/jabb/util/parallel/BackoffStrategies.java
BackoffStrategies.fixedBackoff
public static BackoffStrategy fixedBackoff(long sleepTime, TimeUnit timeUnit) throws IllegalStateException { """ Returns a backoff strategy that waits a fixed amount of time before retrying. @param sleepTime the time to wait @param timeUnit the unit of the time to wait @return a backoff strategy that waits a fixed amount of time @throws IllegalStateException if the wait time is &lt; 0 """ Preconditions.checkNotNull(timeUnit, "The time unit may not be null"); return new FixedBackoffStrategy(timeUnit.toMillis(sleepTime)); }
java
public static BackoffStrategy fixedBackoff(long sleepTime, TimeUnit timeUnit) throws IllegalStateException { Preconditions.checkNotNull(timeUnit, "The time unit may not be null"); return new FixedBackoffStrategy(timeUnit.toMillis(sleepTime)); }
[ "public", "static", "BackoffStrategy", "fixedBackoff", "(", "long", "sleepTime", ",", "TimeUnit", "timeUnit", ")", "throws", "IllegalStateException", "{", "Preconditions", ".", "checkNotNull", "(", "timeUnit", ",", "\"The time unit may not be null\"", ")", ";", "return", "new", "FixedBackoffStrategy", "(", "timeUnit", ".", "toMillis", "(", "sleepTime", ")", ")", ";", "}" ]
Returns a backoff strategy that waits a fixed amount of time before retrying. @param sleepTime the time to wait @param timeUnit the unit of the time to wait @return a backoff strategy that waits a fixed amount of time @throws IllegalStateException if the wait time is &lt; 0
[ "Returns", "a", "backoff", "strategy", "that", "waits", "a", "fixed", "amount", "of", "time", "before", "retrying", "." ]
train
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/parallel/BackoffStrategies.java#L58-L61
UrielCh/ovh-java-sdk
ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java
ApiOvhClusterhadoop.serviceName_node_hostname_role_POST
public OvhTask serviceName_node_hostname_role_POST(String serviceName, String hostname, OvhRoleTypeEnum type) throws IOException { """ Add the Role to the Node REST: POST /cluster/hadoop/{serviceName}/node/{hostname}/role @param type [required] Role name @param serviceName [required] The internal name of your cluster @param hostname [required] Hostname of the node """ String qPath = "/cluster/hadoop/{serviceName}/node/{hostname}/role"; StringBuilder sb = path(qPath, serviceName, hostname); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "type", type); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask serviceName_node_hostname_role_POST(String serviceName, String hostname, OvhRoleTypeEnum type) throws IOException { String qPath = "/cluster/hadoop/{serviceName}/node/{hostname}/role"; StringBuilder sb = path(qPath, serviceName, hostname); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "type", type); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "serviceName_node_hostname_role_POST", "(", "String", "serviceName", ",", "String", "hostname", ",", "OvhRoleTypeEnum", "type", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cluster/hadoop/{serviceName}/node/{hostname}/role\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "hostname", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"type\"", ",", "type", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
Add the Role to the Node REST: POST /cluster/hadoop/{serviceName}/node/{hostname}/role @param type [required] Role name @param serviceName [required] The internal name of your cluster @param hostname [required] Hostname of the node
[ "Add", "the", "Role", "to", "the", "Node" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-clusterhadoop/src/main/java/net/minidev/ovh/api/ApiOvhClusterhadoop.java#L287-L294
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/h/AdjustHomographyMatrix.java
AdjustHomographyMatrix.adjustHomographSign
protected void adjustHomographSign( AssociatedPair p , DMatrixRMaj H ) { """ Since the sign of the homography is ambiguous a point is required to make sure the correct one was selected. @param p test point, used to determine the sign of the matrix. """ double val = GeometryMath_F64.innerProd(p.p2, H, p.p1); if( val < 0 ) CommonOps_DDRM.scale(-1, H); }
java
protected void adjustHomographSign( AssociatedPair p , DMatrixRMaj H ) { double val = GeometryMath_F64.innerProd(p.p2, H, p.p1); if( val < 0 ) CommonOps_DDRM.scale(-1, H); }
[ "protected", "void", "adjustHomographSign", "(", "AssociatedPair", "p", ",", "DMatrixRMaj", "H", ")", "{", "double", "val", "=", "GeometryMath_F64", ".", "innerProd", "(", "p", ".", "p2", ",", "H", ",", "p", ".", "p1", ")", ";", "if", "(", "val", "<", "0", ")", "CommonOps_DDRM", ".", "scale", "(", "-", "1", ",", "H", ")", ";", "}" ]
Since the sign of the homography is ambiguous a point is required to make sure the correct one was selected. @param p test point, used to determine the sign of the matrix.
[ "Since", "the", "sign", "of", "the", "homography", "is", "ambiguous", "a", "point", "is", "required", "to", "make", "sure", "the", "correct", "one", "was", "selected", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/h/AdjustHomographyMatrix.java#L84-L89
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/stat/rewrite/rewritepolicylabel_stats.java
rewritepolicylabel_stats.get
public static rewritepolicylabel_stats get(nitro_service service, String labelname) throws Exception { """ Use this API to fetch statistics of rewritepolicylabel_stats resource of given name . """ rewritepolicylabel_stats obj = new rewritepolicylabel_stats(); obj.set_labelname(labelname); rewritepolicylabel_stats response = (rewritepolicylabel_stats) obj.stat_resource(service); return response; }
java
public static rewritepolicylabel_stats get(nitro_service service, String labelname) throws Exception{ rewritepolicylabel_stats obj = new rewritepolicylabel_stats(); obj.set_labelname(labelname); rewritepolicylabel_stats response = (rewritepolicylabel_stats) obj.stat_resource(service); return response; }
[ "public", "static", "rewritepolicylabel_stats", "get", "(", "nitro_service", "service", ",", "String", "labelname", ")", "throws", "Exception", "{", "rewritepolicylabel_stats", "obj", "=", "new", "rewritepolicylabel_stats", "(", ")", ";", "obj", ".", "set_labelname", "(", "labelname", ")", ";", "rewritepolicylabel_stats", "response", "=", "(", "rewritepolicylabel_stats", ")", "obj", ".", "stat_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch statistics of rewritepolicylabel_stats resource of given name .
[ "Use", "this", "API", "to", "fetch", "statistics", "of", "rewritepolicylabel_stats", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/rewrite/rewritepolicylabel_stats.java#L149-L154
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/PerformanceCachingGoogleCloudStorage.java
PerformanceCachingGoogleCloudStorage.getItemInfo
@Override public GoogleCloudStorageItemInfo getItemInfo(StorageResourceId resourceId) throws IOException { """ This function may return cached copies of GoogleCloudStorageItemInfo. """ // Get the item from cache. GoogleCloudStorageItemInfo item = cache.getItem(resourceId); // If it wasn't in the cache, list all the objects in the parent directory and cache them // and then retrieve it from the cache. if (item == null && resourceId.isStorageObject()) { String bucketName = resourceId.getBucketName(); String objectName = resourceId.getObjectName(); int lastSlashIndex = objectName.lastIndexOf(PATH_DELIMITER); String directoryName = lastSlashIndex >= 0 ? objectName.substring(0, lastSlashIndex + 1) : null; List<GoogleCloudStorageItemInfo> cachedInDirectory = cache.listItems(bucketName, directoryName); filter(cachedInDirectory, bucketName, directoryName, PATH_DELIMITER); // If there are items already cached in directory, do not prefetch with list requests, // because metadata for this directory already could be prefetched if (cachedInDirectory.isEmpty()) { // make just 1 request to prefetch only 1 page of directory items listObjectInfoPage(bucketName, directoryName, PATH_DELIMITER, /* pageToken= */ null); item = cache.getItem(resourceId); } } // If it wasn't in the cache and wasn't cached in directory list request // then request and cache it directly. if (item == null) { item = super.getItemInfo(resourceId); cache.putItem(item); } return item; }
java
@Override public GoogleCloudStorageItemInfo getItemInfo(StorageResourceId resourceId) throws IOException { // Get the item from cache. GoogleCloudStorageItemInfo item = cache.getItem(resourceId); // If it wasn't in the cache, list all the objects in the parent directory and cache them // and then retrieve it from the cache. if (item == null && resourceId.isStorageObject()) { String bucketName = resourceId.getBucketName(); String objectName = resourceId.getObjectName(); int lastSlashIndex = objectName.lastIndexOf(PATH_DELIMITER); String directoryName = lastSlashIndex >= 0 ? objectName.substring(0, lastSlashIndex + 1) : null; List<GoogleCloudStorageItemInfo> cachedInDirectory = cache.listItems(bucketName, directoryName); filter(cachedInDirectory, bucketName, directoryName, PATH_DELIMITER); // If there are items already cached in directory, do not prefetch with list requests, // because metadata for this directory already could be prefetched if (cachedInDirectory.isEmpty()) { // make just 1 request to prefetch only 1 page of directory items listObjectInfoPage(bucketName, directoryName, PATH_DELIMITER, /* pageToken= */ null); item = cache.getItem(resourceId); } } // If it wasn't in the cache and wasn't cached in directory list request // then request and cache it directly. if (item == null) { item = super.getItemInfo(resourceId); cache.putItem(item); } return item; }
[ "@", "Override", "public", "GoogleCloudStorageItemInfo", "getItemInfo", "(", "StorageResourceId", "resourceId", ")", "throws", "IOException", "{", "// Get the item from cache.", "GoogleCloudStorageItemInfo", "item", "=", "cache", ".", "getItem", "(", "resourceId", ")", ";", "// If it wasn't in the cache, list all the objects in the parent directory and cache them", "// and then retrieve it from the cache.", "if", "(", "item", "==", "null", "&&", "resourceId", ".", "isStorageObject", "(", ")", ")", "{", "String", "bucketName", "=", "resourceId", ".", "getBucketName", "(", ")", ";", "String", "objectName", "=", "resourceId", ".", "getObjectName", "(", ")", ";", "int", "lastSlashIndex", "=", "objectName", ".", "lastIndexOf", "(", "PATH_DELIMITER", ")", ";", "String", "directoryName", "=", "lastSlashIndex", ">=", "0", "?", "objectName", ".", "substring", "(", "0", ",", "lastSlashIndex", "+", "1", ")", ":", "null", ";", "List", "<", "GoogleCloudStorageItemInfo", ">", "cachedInDirectory", "=", "cache", ".", "listItems", "(", "bucketName", ",", "directoryName", ")", ";", "filter", "(", "cachedInDirectory", ",", "bucketName", ",", "directoryName", ",", "PATH_DELIMITER", ")", ";", "// If there are items already cached in directory, do not prefetch with list requests,", "// because metadata for this directory already could be prefetched", "if", "(", "cachedInDirectory", ".", "isEmpty", "(", ")", ")", "{", "// make just 1 request to prefetch only 1 page of directory items", "listObjectInfoPage", "(", "bucketName", ",", "directoryName", ",", "PATH_DELIMITER", ",", "/* pageToken= */", "null", ")", ";", "item", "=", "cache", ".", "getItem", "(", "resourceId", ")", ";", "}", "}", "// If it wasn't in the cache and wasn't cached in directory list request", "// then request and cache it directly.", "if", "(", "item", "==", "null", ")", "{", "item", "=", "super", ".", "getItemInfo", "(", "resourceId", ")", ";", "cache", ".", "putItem", "(", "item", ")", ";", "}", "return", "item", ";", "}" ]
This function may return cached copies of GoogleCloudStorageItemInfo.
[ "This", "function", "may", "return", "cached", "copies", "of", "GoogleCloudStorageItemInfo", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/PerformanceCachingGoogleCloudStorage.java#L256-L289
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/SecurityServletConfiguratorHelper.java
SecurityServletConfiguratorHelper.createWebResourceCollections
private List<WebResourceCollection> createWebResourceCollections(com.ibm.ws.javaee.dd.web.common.SecurityConstraint archiveConstraint, boolean denyUncoveredHttpMethods) { """ Gets a list of zero or more web resource collection objects that represent the web-resource-collection elements in web.xml and/or web-fragment.xml files. @param archiveConstraint the security-constraint @return a list of web resource collections """ List<WebResourceCollection> webResourceCollections = new ArrayList<WebResourceCollection>(); List<com.ibm.ws.javaee.dd.web.common.WebResourceCollection> archiveWebResourceCollections = archiveConstraint.getWebResourceCollections(); for (com.ibm.ws.javaee.dd.web.common.WebResourceCollection archiveWebResourceCollection : archiveWebResourceCollections) { List<String> urlPatterns = archiveWebResourceCollection.getURLPatterns(); List<String> methods = archiveWebResourceCollection.getHTTPMethods(); List<String> omissionMethods = archiveWebResourceCollection.getHTTPMethodOmissions(); webResourceCollections.add(new WebResourceCollection(urlPatterns, methods, omissionMethods, denyUncoveredHttpMethods)); } return webResourceCollections; }
java
private List<WebResourceCollection> createWebResourceCollections(com.ibm.ws.javaee.dd.web.common.SecurityConstraint archiveConstraint, boolean denyUncoveredHttpMethods) { List<WebResourceCollection> webResourceCollections = new ArrayList<WebResourceCollection>(); List<com.ibm.ws.javaee.dd.web.common.WebResourceCollection> archiveWebResourceCollections = archiveConstraint.getWebResourceCollections(); for (com.ibm.ws.javaee.dd.web.common.WebResourceCollection archiveWebResourceCollection : archiveWebResourceCollections) { List<String> urlPatterns = archiveWebResourceCollection.getURLPatterns(); List<String> methods = archiveWebResourceCollection.getHTTPMethods(); List<String> omissionMethods = archiveWebResourceCollection.getHTTPMethodOmissions(); webResourceCollections.add(new WebResourceCollection(urlPatterns, methods, omissionMethods, denyUncoveredHttpMethods)); } return webResourceCollections; }
[ "private", "List", "<", "WebResourceCollection", ">", "createWebResourceCollections", "(", "com", ".", "ibm", ".", "ws", ".", "javaee", ".", "dd", ".", "web", ".", "common", ".", "SecurityConstraint", "archiveConstraint", ",", "boolean", "denyUncoveredHttpMethods", ")", "{", "List", "<", "WebResourceCollection", ">", "webResourceCollections", "=", "new", "ArrayList", "<", "WebResourceCollection", ">", "(", ")", ";", "List", "<", "com", ".", "ibm", ".", "ws", ".", "javaee", ".", "dd", ".", "web", ".", "common", ".", "WebResourceCollection", ">", "archiveWebResourceCollections", "=", "archiveConstraint", ".", "getWebResourceCollections", "(", ")", ";", "for", "(", "com", ".", "ibm", ".", "ws", ".", "javaee", ".", "dd", ".", "web", ".", "common", ".", "WebResourceCollection", "archiveWebResourceCollection", ":", "archiveWebResourceCollections", ")", "{", "List", "<", "String", ">", "urlPatterns", "=", "archiveWebResourceCollection", ".", "getURLPatterns", "(", ")", ";", "List", "<", "String", ">", "methods", "=", "archiveWebResourceCollection", ".", "getHTTPMethods", "(", ")", ";", "List", "<", "String", ">", "omissionMethods", "=", "archiveWebResourceCollection", ".", "getHTTPMethodOmissions", "(", ")", ";", "webResourceCollections", ".", "add", "(", "new", "WebResourceCollection", "(", "urlPatterns", ",", "methods", ",", "omissionMethods", ",", "denyUncoveredHttpMethods", ")", ")", ";", "}", "return", "webResourceCollections", ";", "}" ]
Gets a list of zero or more web resource collection objects that represent the web-resource-collection elements in web.xml and/or web-fragment.xml files. @param archiveConstraint the security-constraint @return a list of web resource collections
[ "Gets", "a", "list", "of", "zero", "or", "more", "web", "resource", "collection", "objects", "that", "represent", "the", "web", "-", "resource", "-", "collection", "elements", "in", "web", ".", "xml", "and", "/", "or", "web", "-", "fragment", ".", "xml", "files", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/metadata/SecurityServletConfiguratorHelper.java#L540-L550
misha/iroh
src/main/java/com/github/msoliter/iroh/container/services/Injector.java
Injector.nullify
private void nullify(Object target, Field field) { """ Implements lazy injection by filling in a "local null" instance of the type required by the field. The original idea was to just define a new location of null itself, but Java didn't like that very much, so now Iroh will generate a reference for every type it encounters to act as the null for fields of that particular type. @param target The target object containing the field to be nullified via injection with a local null generated with Objenesis. @param field The target field in the target object to be nullified. """ Class<?> type = field.getType(); if (!nulls.containsKey(type)) { nulls.put( type, objenesis.newInstance(registrar.resolve(field).getType())); } try { field.set(target, nulls.get(type)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IrohException(e); } }
java
private void nullify(Object target, Field field) { Class<?> type = field.getType(); if (!nulls.containsKey(type)) { nulls.put( type, objenesis.newInstance(registrar.resolve(field).getType())); } try { field.set(target, nulls.get(type)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IrohException(e); } }
[ "private", "void", "nullify", "(", "Object", "target", ",", "Field", "field", ")", "{", "Class", "<", "?", ">", "type", "=", "field", ".", "getType", "(", ")", ";", "if", "(", "!", "nulls", ".", "containsKey", "(", "type", ")", ")", "{", "nulls", ".", "put", "(", "type", ",", "objenesis", ".", "newInstance", "(", "registrar", ".", "resolve", "(", "field", ")", ".", "getType", "(", ")", ")", ")", ";", "}", "try", "{", "field", ".", "set", "(", "target", ",", "nulls", ".", "get", "(", "type", ")", ")", ";", "}", "catch", "(", "IllegalArgumentException", "|", "IllegalAccessException", "e", ")", "{", "throw", "new", "IrohException", "(", "e", ")", ";", "}", "}" ]
Implements lazy injection by filling in a "local null" instance of the type required by the field. The original idea was to just define a new location of null itself, but Java didn't like that very much, so now Iroh will generate a reference for every type it encounters to act as the null for fields of that particular type. @param target The target object containing the field to be nullified via injection with a local null generated with Objenesis. @param field The target field in the target object to be nullified.
[ "Implements", "lazy", "injection", "by", "filling", "in", "a", "local", "null", "instance", "of", "the", "type", "required", "by", "the", "field", ".", "The", "original", "idea", "was", "to", "just", "define", "a", "new", "location", "of", "null", "itself", "but", "Java", "didn", "t", "like", "that", "very", "much", "so", "now", "Iroh", "will", "generate", "a", "reference", "for", "every", "type", "it", "encounters", "to", "act", "as", "the", "null", "for", "fields", "of", "that", "particular", "type", "." ]
train
https://github.com/misha/iroh/blob/5dc92a01d3b2f3ba63e8ad1bf9b5fe342d0b679a/src/main/java/com/github/msoliter/iroh/container/services/Injector.java#L190-L205
martinwithaar/Encryptor4j
src/main/java/org/encryptor4j/OneTimePad.java
OneTimePad.createPadFile
public void createPadFile(File padFile, long size) { """ <p>Creates a padfile containing random bytes.</p> @param padFile @param size """ OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(padFile), ioBufferSize); long totalSize = 0; long bytesLeft; byte[] randomBytes = new byte[workBufferSize]; while (totalSize < size) { random.nextBytes(randomBytes); bytesLeft = size - totalSize; if(bytesLeft < workBufferSize) { os.write(randomBytes, 0, (int) bytesLeft); totalSize += bytesLeft; } else { os.write(randomBytes); totalSize += workBufferSize; } } os.flush(); } catch(IOException e) { throw new RuntimeException(e); } finally { if(os != null) { try { os.close(); } catch(IOException e) { e.printStackTrace(); } } } }
java
public void createPadFile(File padFile, long size) { OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(padFile), ioBufferSize); long totalSize = 0; long bytesLeft; byte[] randomBytes = new byte[workBufferSize]; while (totalSize < size) { random.nextBytes(randomBytes); bytesLeft = size - totalSize; if(bytesLeft < workBufferSize) { os.write(randomBytes, 0, (int) bytesLeft); totalSize += bytesLeft; } else { os.write(randomBytes); totalSize += workBufferSize; } } os.flush(); } catch(IOException e) { throw new RuntimeException(e); } finally { if(os != null) { try { os.close(); } catch(IOException e) { e.printStackTrace(); } } } }
[ "public", "void", "createPadFile", "(", "File", "padFile", ",", "long", "size", ")", "{", "OutputStream", "os", "=", "null", ";", "try", "{", "os", "=", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "padFile", ")", ",", "ioBufferSize", ")", ";", "long", "totalSize", "=", "0", ";", "long", "bytesLeft", ";", "byte", "[", "]", "randomBytes", "=", "new", "byte", "[", "workBufferSize", "]", ";", "while", "(", "totalSize", "<", "size", ")", "{", "random", ".", "nextBytes", "(", "randomBytes", ")", ";", "bytesLeft", "=", "size", "-", "totalSize", ";", "if", "(", "bytesLeft", "<", "workBufferSize", ")", "{", "os", ".", "write", "(", "randomBytes", ",", "0", ",", "(", "int", ")", "bytesLeft", ")", ";", "totalSize", "+=", "bytesLeft", ";", "}", "else", "{", "os", ".", "write", "(", "randomBytes", ")", ";", "totalSize", "+=", "workBufferSize", ";", "}", "}", "os", ".", "flush", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "finally", "{", "if", "(", "os", "!=", "null", ")", "{", "try", "{", "os", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", "}" ]
<p>Creates a padfile containing random bytes.</p> @param padFile @param size
[ "<p", ">", "Creates", "a", "padfile", "containing", "random", "bytes", ".", "<", "/", "p", ">" ]
train
https://github.com/martinwithaar/Encryptor4j/blob/8c31d84d9136309f59d810323ed68d902b9bac55/src/main/java/org/encryptor4j/OneTimePad.java#L82-L112
baneizalfe/PullToDismissPager
PullToDismissPager/src/main/java/com/mrbug/pulltodismisspager/PullToDismissPager.java
PullToDismissPager.collapsePanel
public boolean collapsePanel() { """ Collapse the sliding pane if it is currently slideable. If first layout has already completed this will animate. @return true if the pane was slideable and is now collapsed/in the process of collapsing """ if (mFirstLayout) { mSlideState = SlideState.COLLAPSED; return true; } else { if (mSlideState == SlideState.HIDDEN || mSlideState == SlideState.COLLAPSED) return false; return collapsePanel(mSlideableView, 0); } }
java
public boolean collapsePanel() { if (mFirstLayout) { mSlideState = SlideState.COLLAPSED; return true; } else { if (mSlideState == SlideState.HIDDEN || mSlideState == SlideState.COLLAPSED) return false; return collapsePanel(mSlideableView, 0); } }
[ "public", "boolean", "collapsePanel", "(", ")", "{", "if", "(", "mFirstLayout", ")", "{", "mSlideState", "=", "SlideState", ".", "COLLAPSED", ";", "return", "true", ";", "}", "else", "{", "if", "(", "mSlideState", "==", "SlideState", ".", "HIDDEN", "||", "mSlideState", "==", "SlideState", ".", "COLLAPSED", ")", "return", "false", ";", "return", "collapsePanel", "(", "mSlideableView", ",", "0", ")", ";", "}", "}" ]
Collapse the sliding pane if it is currently slideable. If first layout has already completed this will animate. @return true if the pane was slideable and is now collapsed/in the process of collapsing
[ "Collapse", "the", "sliding", "pane", "if", "it", "is", "currently", "slideable", ".", "If", "first", "layout", "has", "already", "completed", "this", "will", "animate", "." ]
train
https://github.com/baneizalfe/PullToDismissPager/blob/14b12725f8ab9274b2499432d85e1b8b2b1850a5/PullToDismissPager/src/main/java/com/mrbug/pulltodismisspager/PullToDismissPager.java#L705-L714
hortonworks/dstream
dstream-api/src/main/java/io/dstream/AbstractStreamMergingFunction.java
AbstractStreamMergingFunction.addTransformationOrPredicate
public void addTransformationOrPredicate(String operationName, Object transformationOrPredicate) { """ Will add transformation ({@link SerFunction}) or predicate ({@link SerPredicate}) to be applied to the last (current) checkpoint.<br> To ensure that both (transformation and predicate) cold be represented as a {@link SerFunction}, this method will wrap provided 'transformationOrPredicate' with {@link DStreamToStreamAdapterFunction}. @param operationName @param transformationOrPredicate """ DStreamToStreamAdapterFunction incomingFunc = new DStreamToStreamAdapterFunction(operationName, transformationOrPredicate); this.addTransformationOrPredicate(incomingFunc); }
java
public void addTransformationOrPredicate(String operationName, Object transformationOrPredicate) { DStreamToStreamAdapterFunction incomingFunc = new DStreamToStreamAdapterFunction(operationName, transformationOrPredicate); this.addTransformationOrPredicate(incomingFunc); }
[ "public", "void", "addTransformationOrPredicate", "(", "String", "operationName", ",", "Object", "transformationOrPredicate", ")", "{", "DStreamToStreamAdapterFunction", "incomingFunc", "=", "new", "DStreamToStreamAdapterFunction", "(", "operationName", ",", "transformationOrPredicate", ")", ";", "this", ".", "addTransformationOrPredicate", "(", "incomingFunc", ")", ";", "}" ]
Will add transformation ({@link SerFunction}) or predicate ({@link SerPredicate}) to be applied to the last (current) checkpoint.<br> To ensure that both (transformation and predicate) cold be represented as a {@link SerFunction}, this method will wrap provided 'transformationOrPredicate' with {@link DStreamToStreamAdapterFunction}. @param operationName @param transformationOrPredicate
[ "Will", "add", "transformation", "(", "{", "@link", "SerFunction", "}", ")", "or", "predicate", "(", "{", "@link", "SerPredicate", "}", ")", "to", "be", "applied", "to", "the", "last", "(", "current", ")", "checkpoint", ".", "<br", ">", "To", "ensure", "that", "both", "(", "transformation", "and", "predicate", ")", "cold", "be", "represented", "as", "a", "{", "@link", "SerFunction", "}", "this", "method", "will", "wrap", "provided", "transformationOrPredicate", "with", "{", "@link", "DStreamToStreamAdapterFunction", "}", "." ]
train
https://github.com/hortonworks/dstream/blob/3a106c0f14725b028fe7fe2dbc660406d9a5f142/dstream-api/src/main/java/io/dstream/AbstractStreamMergingFunction.java#L111-L114
openCage/eightyfs
src/main/java/de/pfabulist/lindwurm/eighty/EightyUtils.java
EightyUtils.existsEx
public static boolean existsEx( Path path, LinkOption... options ) { """ same as Files.exists( NOFOLLOWLINKS ) but without checking attributes """ if( Files.exists( path ) ) { return true; } if( options.length == 0 || !options[ 0 ].equals( NOFOLLOW_LINKS ) ) { return false; } try { Files.readSymbolicLink( path ); } catch( IOException e ) { return false; } return true; }
java
public static boolean existsEx( Path path, LinkOption... options ) { if( Files.exists( path ) ) { return true; } if( options.length == 0 || !options[ 0 ].equals( NOFOLLOW_LINKS ) ) { return false; } try { Files.readSymbolicLink( path ); } catch( IOException e ) { return false; } return true; }
[ "public", "static", "boolean", "existsEx", "(", "Path", "path", ",", "LinkOption", "...", "options", ")", "{", "if", "(", "Files", ".", "exists", "(", "path", ")", ")", "{", "return", "true", ";", "}", "if", "(", "options", ".", "length", "==", "0", "||", "!", "options", "[", "0", "]", ".", "equals", "(", "NOFOLLOW_LINKS", ")", ")", "{", "return", "false", ";", "}", "try", "{", "Files", ".", "readSymbolicLink", "(", "path", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
same as Files.exists( NOFOLLOWLINKS ) but without checking attributes
[ "same", "as", "Files", ".", "exists", "(", "NOFOLLOWLINKS", ")", "but", "without", "checking", "attributes" ]
train
https://github.com/openCage/eightyfs/blob/708ec4d336ee5e3dbd4196099f64091eaf6b3387/src/main/java/de/pfabulist/lindwurm/eighty/EightyUtils.java#L76-L92
abel533/EasyXls
src/main/java/com/github/abel533/easyxls/common/XmlConfig.java
XmlConfig.WriteXml
public static boolean WriteXml(ExcelConfig dlExcel, String xmlPath) throws Exception { """ 写入到xml文件 @param dlExcel 配置对象 @param xmlPath xml保存路径 @return true成功,false失败 @throws Exception """ //写入xml return XmlUtil.toXml(dlExcel, new File(xmlPath)); }
java
public static boolean WriteXml(ExcelConfig dlExcel, String xmlPath) throws Exception { //写入xml return XmlUtil.toXml(dlExcel, new File(xmlPath)); }
[ "public", "static", "boolean", "WriteXml", "(", "ExcelConfig", "dlExcel", ",", "String", "xmlPath", ")", "throws", "Exception", "{", "//写入xml", "return", "XmlUtil", ".", "toXml", "(", "dlExcel", ",", "new", "File", "(", "xmlPath", ")", ")", ";", "}" ]
写入到xml文件 @param dlExcel 配置对象 @param xmlPath xml保存路径 @return true成功,false失败 @throws Exception
[ "写入到xml文件" ]
train
https://github.com/abel533/EasyXls/blob/f73be23745c2180d7c0b8f0a510e72e61cc37d5d/src/main/java/com/github/abel533/easyxls/common/XmlConfig.java#L47-L50
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/data/model/CorrelationModel.java
CorrelationModel.writeToText
@Override public void writeToText(TextWriterStream out, String label) { """ Implementation of {@link TextWriteable} interface @param label unused parameter """ if(label != null) { out.commentPrintLn(label); } out.commentPrintLn("Model class: " + getClass().getName()); out.commentPrintLn("Centroid: " + getPrototype().toString()); out.commentPrintLn("Strong Eigenvectors:"); String strong = FormatUtil.format(getPCAResult().getStrongEigenvectors()); while(strong.endsWith("\n")) { strong = strong.substring(0, strong.length() - 1); } out.commentPrintLn(strong); out.commentPrintLn("Weak Eigenvectors:"); String weak = FormatUtil.format(getPCAResult().getWeakEigenvectors()); while(weak.endsWith("\n")) { weak = weak.substring(0, weak.length() - 1); } out.commentPrintLn(weak); out.commentPrintLn("Eigenvalues: " + FormatUtil.format(getPCAResult().getEigenvalues())); }
java
@Override public void writeToText(TextWriterStream out, String label) { if(label != null) { out.commentPrintLn(label); } out.commentPrintLn("Model class: " + getClass().getName()); out.commentPrintLn("Centroid: " + getPrototype().toString()); out.commentPrintLn("Strong Eigenvectors:"); String strong = FormatUtil.format(getPCAResult().getStrongEigenvectors()); while(strong.endsWith("\n")) { strong = strong.substring(0, strong.length() - 1); } out.commentPrintLn(strong); out.commentPrintLn("Weak Eigenvectors:"); String weak = FormatUtil.format(getPCAResult().getWeakEigenvectors()); while(weak.endsWith("\n")) { weak = weak.substring(0, weak.length() - 1); } out.commentPrintLn(weak); out.commentPrintLn("Eigenvalues: " + FormatUtil.format(getPCAResult().getEigenvalues())); }
[ "@", "Override", "public", "void", "writeToText", "(", "TextWriterStream", "out", ",", "String", "label", ")", "{", "if", "(", "label", "!=", "null", ")", "{", "out", ".", "commentPrintLn", "(", "label", ")", ";", "}", "out", ".", "commentPrintLn", "(", "\"Model class: \"", "+", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "out", ".", "commentPrintLn", "(", "\"Centroid: \"", "+", "getPrototype", "(", ")", ".", "toString", "(", ")", ")", ";", "out", ".", "commentPrintLn", "(", "\"Strong Eigenvectors:\"", ")", ";", "String", "strong", "=", "FormatUtil", ".", "format", "(", "getPCAResult", "(", ")", ".", "getStrongEigenvectors", "(", ")", ")", ";", "while", "(", "strong", ".", "endsWith", "(", "\"\\n\"", ")", ")", "{", "strong", "=", "strong", ".", "substring", "(", "0", ",", "strong", ".", "length", "(", ")", "-", "1", ")", ";", "}", "out", ".", "commentPrintLn", "(", "strong", ")", ";", "out", ".", "commentPrintLn", "(", "\"Weak Eigenvectors:\"", ")", ";", "String", "weak", "=", "FormatUtil", ".", "format", "(", "getPCAResult", "(", ")", ".", "getWeakEigenvectors", "(", ")", ")", ";", "while", "(", "weak", ".", "endsWith", "(", "\"\\n\"", ")", ")", "{", "weak", "=", "weak", ".", "substring", "(", "0", ",", "weak", ".", "length", "(", ")", "-", "1", ")", ";", "}", "out", ".", "commentPrintLn", "(", "weak", ")", ";", "out", ".", "commentPrintLn", "(", "\"Eigenvalues: \"", "+", "FormatUtil", ".", "format", "(", "getPCAResult", "(", ")", ".", "getEigenvalues", "(", ")", ")", ")", ";", "}" ]
Implementation of {@link TextWriteable} interface @param label unused parameter
[ "Implementation", "of", "{", "@link", "TextWriteable", "}", "interface" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/data/model/CorrelationModel.java#L76-L96
kiswanij/jk-util
src/main/java/com/jk/util/model/table/JKDefaultTableModel.java
JKDefaultTableModel.setDataVector
public void setDataVector(final Object[][] dataVector, final Object[] columnIdentifiers) { """ Replaces the value in the <code>dataVector</code> instance variable with the values in the array <code>dataVector</code>. The first index in the <code>Object[][]</code> array is the row index and the second is the column index. <code>columnIdentifiers</code> are the names of the new columns. @param dataVector the new data vector @param columnIdentifiers the names of the columns @see #setDataVector(Vector, Vector) """ setDataVector(convertToVector(dataVector), convertToVector(columnIdentifiers)); }
java
public void setDataVector(final Object[][] dataVector, final Object[] columnIdentifiers) { setDataVector(convertToVector(dataVector), convertToVector(columnIdentifiers)); }
[ "public", "void", "setDataVector", "(", "final", "Object", "[", "]", "[", "]", "dataVector", ",", "final", "Object", "[", "]", "columnIdentifiers", ")", "{", "setDataVector", "(", "convertToVector", "(", "dataVector", ")", ",", "convertToVector", "(", "columnIdentifiers", ")", ")", ";", "}" ]
Replaces the value in the <code>dataVector</code> instance variable with the values in the array <code>dataVector</code>. The first index in the <code>Object[][]</code> array is the row index and the second is the column index. <code>columnIdentifiers</code> are the names of the new columns. @param dataVector the new data vector @param columnIdentifiers the names of the columns @see #setDataVector(Vector, Vector)
[ "Replaces", "the", "value", "in", "the", "<code", ">", "dataVector<", "/", "code", ">", "instance", "variable", "with", "the", "values", "in", "the", "array", "<code", ">", "dataVector<", "/", "code", ">", ".", "The", "first", "index", "in", "the", "<code", ">", "Object", "[]", "[]", "<", "/", "code", ">", "array", "is", "the", "row", "index", "and", "the", "second", "is", "the", "column", "index", ".", "<code", ">", "columnIdentifiers<", "/", "code", ">", "are", "the", "names", "of", "the", "new", "columns", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/model/table/JKDefaultTableModel.java#L637-L639
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java
QueueEntryRow.getQueueName
public static QueueName getQueueName(String appName, String flowName, byte[] rowBuffer, int rowOffset, int rowLength) { """ Extracts the queue name from the KeyValue row, which the row must be a queue entry. """ // Entry key is always (salt bytes + 1 MD5 byte + queueName + longWritePointer + intCounter) int queueNameEnd = rowOffset + rowLength - Bytes.SIZEOF_LONG - Bytes.SIZEOF_INT; // <flowlet><source> byte[] idWithinFlow = Arrays.copyOfRange(rowBuffer, rowOffset + HBaseQueueAdmin.SALT_BYTES + 1, queueNameEnd); String idWithinFlowAsString = new String(idWithinFlow, Charsets.US_ASCII); // <flowlet><source> String[] parts = idWithinFlowAsString.split("/"); return QueueName.fromFlowlet(appName, flowName, parts[0], parts[1]); }
java
public static QueueName getQueueName(String appName, String flowName, byte[] rowBuffer, int rowOffset, int rowLength) { // Entry key is always (salt bytes + 1 MD5 byte + queueName + longWritePointer + intCounter) int queueNameEnd = rowOffset + rowLength - Bytes.SIZEOF_LONG - Bytes.SIZEOF_INT; // <flowlet><source> byte[] idWithinFlow = Arrays.copyOfRange(rowBuffer, rowOffset + HBaseQueueAdmin.SALT_BYTES + 1, queueNameEnd); String idWithinFlowAsString = new String(idWithinFlow, Charsets.US_ASCII); // <flowlet><source> String[] parts = idWithinFlowAsString.split("/"); return QueueName.fromFlowlet(appName, flowName, parts[0], parts[1]); }
[ "public", "static", "QueueName", "getQueueName", "(", "String", "appName", ",", "String", "flowName", ",", "byte", "[", "]", "rowBuffer", ",", "int", "rowOffset", ",", "int", "rowLength", ")", "{", "// Entry key is always (salt bytes + 1 MD5 byte + queueName + longWritePointer + intCounter)", "int", "queueNameEnd", "=", "rowOffset", "+", "rowLength", "-", "Bytes", ".", "SIZEOF_LONG", "-", "Bytes", ".", "SIZEOF_INT", ";", "// <flowlet><source>", "byte", "[", "]", "idWithinFlow", "=", "Arrays", ".", "copyOfRange", "(", "rowBuffer", ",", "rowOffset", "+", "HBaseQueueAdmin", ".", "SALT_BYTES", "+", "1", ",", "queueNameEnd", ")", ";", "String", "idWithinFlowAsString", "=", "new", "String", "(", "idWithinFlow", ",", "Charsets", ".", "US_ASCII", ")", ";", "// <flowlet><source>", "String", "[", "]", "parts", "=", "idWithinFlowAsString", ".", "split", "(", "\"/\"", ")", ";", "return", "QueueName", ".", "fromFlowlet", "(", "appName", ",", "flowName", ",", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ")", ";", "}" ]
Extracts the queue name from the KeyValue row, which the row must be a queue entry.
[ "Extracts", "the", "queue", "name", "from", "the", "KeyValue", "row", "which", "the", "row", "must", "be", "a", "queue", "entry", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java#L115-L129
mfornos/humanize
humanize-icu/src/main/java/humanize/ICUHumanize.java
ICUHumanize.compactDecimal
public static String compactDecimal(final Number value, final CompactStyle style, final Locale locale) { """ <p> Same as {@link #compactDecimal(Number, CompactStyle) compactDecimal} for the specified locale. </p> @param value The number to be abbreviated @param style The compaction style @param locale The locale @return a compact textual representation of the given value """ return withinLocale(new Callable<String>() { public String call() throws Exception { return compactDecimal(value, style); } }, locale); }
java
public static String compactDecimal(final Number value, final CompactStyle style, final Locale locale) { return withinLocale(new Callable<String>() { public String call() throws Exception { return compactDecimal(value, style); } }, locale); }
[ "public", "static", "String", "compactDecimal", "(", "final", "Number", "value", ",", "final", "CompactStyle", "style", ",", "final", "Locale", "locale", ")", "{", "return", "withinLocale", "(", "new", "Callable", "<", "String", ">", "(", ")", "{", "public", "String", "call", "(", ")", "throws", "Exception", "{", "return", "compactDecimal", "(", "value", ",", "style", ")", ";", "}", "}", ",", "locale", ")", ";", "}" ]
<p> Same as {@link #compactDecimal(Number, CompactStyle) compactDecimal} for the specified locale. </p> @param value The number to be abbreviated @param style The compaction style @param locale The locale @return a compact textual representation of the given value
[ "<p", ">", "Same", "as", "{", "@link", "#compactDecimal", "(", "Number", "CompactStyle", ")", "compactDecimal", "}", "for", "the", "specified", "locale", ".", "<", "/", "p", ">" ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-icu/src/main/java/humanize/ICUHumanize.java#L120-L129
astrapi69/mystic-crypt
crypt-data/src/main/java/de/alpharogroup/crypto/key/PrivateKeyExtensions.java
PrivateKeyExtensions.toHexString
public static String toHexString(final PrivateKey privateKey, final boolean lowerCase) { """ Transform the given {@link PrivateKey} to a hexadecimal {@link String} value. @param privateKey the private key @param lowerCase the flag if the result shell be transform in lower case. If true the result is @return the new hexadecimal {@link String} value. """ final String hexString = HexExtensions.toHexString(privateKey.getEncoded(), lowerCase); return hexString; }
java
public static String toHexString(final PrivateKey privateKey, final boolean lowerCase) { final String hexString = HexExtensions.toHexString(privateKey.getEncoded(), lowerCase); return hexString; }
[ "public", "static", "String", "toHexString", "(", "final", "PrivateKey", "privateKey", ",", "final", "boolean", "lowerCase", ")", "{", "final", "String", "hexString", "=", "HexExtensions", ".", "toHexString", "(", "privateKey", ".", "getEncoded", "(", ")", ",", "lowerCase", ")", ";", "return", "hexString", ";", "}" ]
Transform the given {@link PrivateKey} to a hexadecimal {@link String} value. @param privateKey the private key @param lowerCase the flag if the result shell be transform in lower case. If true the result is @return the new hexadecimal {@link String} value.
[ "Transform", "the", "given", "{", "@link", "PrivateKey", "}", "to", "a", "hexadecimal", "{", "@link", "String", "}", "value", "." ]
train
https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/key/PrivateKeyExtensions.java#L141-L145
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ServerUpgradeCodec.java
Http2ServerUpgradeCodec.createSettingsFrame
private static ByteBuf createSettingsFrame(ChannelHandlerContext ctx, ByteBuf payload) { """ Creates an HTTP2-Settings header with the given payload. The payload buffer is released. """ ByteBuf frame = ctx.alloc().buffer(FRAME_HEADER_LENGTH + payload.readableBytes()); writeFrameHeader(frame, payload.readableBytes(), SETTINGS, new Http2Flags(), 0); frame.writeBytes(payload); payload.release(); return frame; }
java
private static ByteBuf createSettingsFrame(ChannelHandlerContext ctx, ByteBuf payload) { ByteBuf frame = ctx.alloc().buffer(FRAME_HEADER_LENGTH + payload.readableBytes()); writeFrameHeader(frame, payload.readableBytes(), SETTINGS, new Http2Flags(), 0); frame.writeBytes(payload); payload.release(); return frame; }
[ "private", "static", "ByteBuf", "createSettingsFrame", "(", "ChannelHandlerContext", "ctx", ",", "ByteBuf", "payload", ")", "{", "ByteBuf", "frame", "=", "ctx", ".", "alloc", "(", ")", ".", "buffer", "(", "FRAME_HEADER_LENGTH", "+", "payload", ".", "readableBytes", "(", ")", ")", ";", "writeFrameHeader", "(", "frame", ",", "payload", ".", "readableBytes", "(", ")", ",", "SETTINGS", ",", "new", "Http2Flags", "(", ")", ",", "0", ")", ";", "frame", ".", "writeBytes", "(", "payload", ")", ";", "payload", ".", "release", "(", ")", ";", "return", "frame", ";", "}" ]
Creates an HTTP2-Settings header with the given payload. The payload buffer is released.
[ "Creates", "an", "HTTP2", "-", "Settings", "header", "with", "the", "given", "payload", ".", "The", "payload", "buffer", "is", "released", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ServerUpgradeCodec.java#L208-L214
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bos/BosClient.java
BosClient.appendObject
public AppendObjectResponse appendObject( String bucketName, String key, byte[] value, ObjectMetadata metadata) { """ Uploads the appendable bytes and object metadata to Bos under the specified bucket and key name. @param bucketName The name of an existing bucket, to which you have Write permission. @param key The key under which to store the specified file. @param value The bytes containing the value to be uploaded to Bos. @param metadata Additional metadata instructing Bos how to handle the uploaded data (e.g. custom user metadata, hooks for specifying content type, etc.). @return An AppendObjectResponse object containing the information returned by Bos for the newly created object. """ checkNotNull(metadata, "metadata should not be null."); if (metadata.getContentLength() == -1) { metadata.setContentLength(value.length); } return this.appendObject( new AppendObjectRequest(bucketName, key, RestartableInputStream.wrap(value), metadata)); }
java
public AppendObjectResponse appendObject( String bucketName, String key, byte[] value, ObjectMetadata metadata) { checkNotNull(metadata, "metadata should not be null."); if (metadata.getContentLength() == -1) { metadata.setContentLength(value.length); } return this.appendObject( new AppendObjectRequest(bucketName, key, RestartableInputStream.wrap(value), metadata)); }
[ "public", "AppendObjectResponse", "appendObject", "(", "String", "bucketName", ",", "String", "key", ",", "byte", "[", "]", "value", ",", "ObjectMetadata", "metadata", ")", "{", "checkNotNull", "(", "metadata", ",", "\"metadata should not be null.\"", ")", ";", "if", "(", "metadata", ".", "getContentLength", "(", ")", "==", "-", "1", ")", "{", "metadata", ".", "setContentLength", "(", "value", ".", "length", ")", ";", "}", "return", "this", ".", "appendObject", "(", "new", "AppendObjectRequest", "(", "bucketName", ",", "key", ",", "RestartableInputStream", ".", "wrap", "(", "value", ")", ",", "metadata", ")", ")", ";", "}" ]
Uploads the appendable bytes and object metadata to Bos under the specified bucket and key name. @param bucketName The name of an existing bucket, to which you have Write permission. @param key The key under which to store the specified file. @param value The bytes containing the value to be uploaded to Bos. @param metadata Additional metadata instructing Bos how to handle the uploaded data (e.g. custom user metadata, hooks for specifying content type, etc.). @return An AppendObjectResponse object containing the information returned by Bos for the newly created object.
[ "Uploads", "the", "appendable", "bytes", "and", "object", "metadata", "to", "Bos", "under", "the", "specified", "bucket", "and", "key", "name", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bos/BosClient.java#L1747-L1755
apereo/cas
support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/WsFederationHelper.java
WsFederationHelper.getEncryptionCredential
@SneakyThrows private static Credential getEncryptionCredential(final WsFederationConfiguration config) { """ Gets encryption credential. The encryption private key will need to contain the private keypair in PEM format. The encryption certificate is shared with ADFS in DER format, i.e certificate.crt. @param config the config @return the encryption credential """ LOGGER.debug("Locating encryption credential private key [{}]", config.getEncryptionPrivateKey()); val br = new BufferedReader(new InputStreamReader(config.getEncryptionPrivateKey().getInputStream(), StandardCharsets.UTF_8)); Security.addProvider(new BouncyCastleProvider()); LOGGER.debug("Parsing credential private key"); try (val pemParser = new PEMParser(br)) { val privateKeyPemObject = pemParser.readObject(); val converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider()); val kp = FunctionUtils.doIf(Predicates.instanceOf(PEMEncryptedKeyPair.class), Unchecked.supplier(() -> { LOGGER.debug("Encryption private key is an encrypted keypair"); val ckp = (PEMEncryptedKeyPair) privateKeyPemObject; val decProv = new JcePEMDecryptorProviderBuilder().build(config.getEncryptionPrivateKeyPassword().toCharArray()); LOGGER.debug("Attempting to decrypt the encrypted keypair based on the provided encryption private key password"); return converter.getKeyPair(ckp.decryptKeyPair(decProv)); }), Unchecked.supplier(() -> { LOGGER.debug("Extracting a keypair from the private key"); return converter.getKeyPair((PEMKeyPair) privateKeyPemObject); })) .apply(privateKeyPemObject); val certParser = new X509CertParser(); LOGGER.debug("Locating encryption certificate [{}]", config.getEncryptionCertificate()); certParser.engineInit(config.getEncryptionCertificate().getInputStream()); LOGGER.debug("Invoking certificate engine to parse the certificate [{}]", config.getEncryptionCertificate()); val cert = (X509CertificateObject) certParser.engineRead(); LOGGER.debug("Creating final credential based on the certificate [{}] and the private key", cert.getIssuerDN()); return new BasicX509Credential(cert, kp.getPrivate()); } }
java
@SneakyThrows private static Credential getEncryptionCredential(final WsFederationConfiguration config) { LOGGER.debug("Locating encryption credential private key [{}]", config.getEncryptionPrivateKey()); val br = new BufferedReader(new InputStreamReader(config.getEncryptionPrivateKey().getInputStream(), StandardCharsets.UTF_8)); Security.addProvider(new BouncyCastleProvider()); LOGGER.debug("Parsing credential private key"); try (val pemParser = new PEMParser(br)) { val privateKeyPemObject = pemParser.readObject(); val converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider()); val kp = FunctionUtils.doIf(Predicates.instanceOf(PEMEncryptedKeyPair.class), Unchecked.supplier(() -> { LOGGER.debug("Encryption private key is an encrypted keypair"); val ckp = (PEMEncryptedKeyPair) privateKeyPemObject; val decProv = new JcePEMDecryptorProviderBuilder().build(config.getEncryptionPrivateKeyPassword().toCharArray()); LOGGER.debug("Attempting to decrypt the encrypted keypair based on the provided encryption private key password"); return converter.getKeyPair(ckp.decryptKeyPair(decProv)); }), Unchecked.supplier(() -> { LOGGER.debug("Extracting a keypair from the private key"); return converter.getKeyPair((PEMKeyPair) privateKeyPemObject); })) .apply(privateKeyPemObject); val certParser = new X509CertParser(); LOGGER.debug("Locating encryption certificate [{}]", config.getEncryptionCertificate()); certParser.engineInit(config.getEncryptionCertificate().getInputStream()); LOGGER.debug("Invoking certificate engine to parse the certificate [{}]", config.getEncryptionCertificate()); val cert = (X509CertificateObject) certParser.engineRead(); LOGGER.debug("Creating final credential based on the certificate [{}] and the private key", cert.getIssuerDN()); return new BasicX509Credential(cert, kp.getPrivate()); } }
[ "@", "SneakyThrows", "private", "static", "Credential", "getEncryptionCredential", "(", "final", "WsFederationConfiguration", "config", ")", "{", "LOGGER", ".", "debug", "(", "\"Locating encryption credential private key [{}]\"", ",", "config", ".", "getEncryptionPrivateKey", "(", ")", ")", ";", "val", "br", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "config", ".", "getEncryptionPrivateKey", "(", ")", ".", "getInputStream", "(", ")", ",", "StandardCharsets", ".", "UTF_8", ")", ")", ";", "Security", ".", "addProvider", "(", "new", "BouncyCastleProvider", "(", ")", ")", ";", "LOGGER", ".", "debug", "(", "\"Parsing credential private key\"", ")", ";", "try", "(", "val", "pemParser", "=", "new", "PEMParser", "(", "br", ")", ")", "{", "val", "privateKeyPemObject", "=", "pemParser", ".", "readObject", "(", ")", ";", "val", "converter", "=", "new", "JcaPEMKeyConverter", "(", ")", ".", "setProvider", "(", "new", "BouncyCastleProvider", "(", ")", ")", ";", "val", "kp", "=", "FunctionUtils", ".", "doIf", "(", "Predicates", ".", "instanceOf", "(", "PEMEncryptedKeyPair", ".", "class", ")", ",", "Unchecked", ".", "supplier", "(", "(", ")", "->", "{", "LOGGER", ".", "debug", "(", "\"Encryption private key is an encrypted keypair\"", ")", ";", "val", "ckp", "=", "(", "PEMEncryptedKeyPair", ")", "privateKeyPemObject", ";", "val", "decProv", "=", "new", "JcePEMDecryptorProviderBuilder", "(", ")", ".", "build", "(", "config", ".", "getEncryptionPrivateKeyPassword", "(", ")", ".", "toCharArray", "(", ")", ")", ";", "LOGGER", ".", "debug", "(", "\"Attempting to decrypt the encrypted keypair based on the provided encryption private key password\"", ")", ";", "return", "converter", ".", "getKeyPair", "(", "ckp", ".", "decryptKeyPair", "(", "decProv", ")", ")", ";", "}", ")", ",", "Unchecked", ".", "supplier", "(", "(", ")", "->", "{", "LOGGER", ".", "debug", "(", "\"Extracting a keypair from the private key\"", ")", ";", "return", "converter", ".", "getKeyPair", "(", "(", "PEMKeyPair", ")", "privateKeyPemObject", ")", ";", "}", ")", ")", ".", "apply", "(", "privateKeyPemObject", ")", ";", "val", "certParser", "=", "new", "X509CertParser", "(", ")", ";", "LOGGER", ".", "debug", "(", "\"Locating encryption certificate [{}]\"", ",", "config", ".", "getEncryptionCertificate", "(", ")", ")", ";", "certParser", ".", "engineInit", "(", "config", ".", "getEncryptionCertificate", "(", ")", ".", "getInputStream", "(", ")", ")", ";", "LOGGER", ".", "debug", "(", "\"Invoking certificate engine to parse the certificate [{}]\"", ",", "config", ".", "getEncryptionCertificate", "(", ")", ")", ";", "val", "cert", "=", "(", "X509CertificateObject", ")", "certParser", ".", "engineRead", "(", ")", ";", "LOGGER", ".", "debug", "(", "\"Creating final credential based on the certificate [{}] and the private key\"", ",", "cert", ".", "getIssuerDN", "(", ")", ")", ";", "return", "new", "BasicX509Credential", "(", "cert", ",", "kp", ".", "getPrivate", "(", ")", ")", ";", "}", "}" ]
Gets encryption credential. The encryption private key will need to contain the private keypair in PEM format. The encryption certificate is shared with ADFS in DER format, i.e certificate.crt. @param config the config @return the encryption credential
[ "Gets", "encryption", "credential", ".", "The", "encryption", "private", "key", "will", "need", "to", "contain", "the", "private", "keypair", "in", "PEM", "format", ".", "The", "encryption", "certificate", "is", "shared", "with", "ADFS", "in", "DER", "format", "i", ".", "e", "certificate", ".", "crt", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/WsFederationHelper.java#L110-L143
marklogic/marklogic-sesame
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java
MarkLogicRepositoryConnection.prepareBooleanQuery
@Override public MarkLogicBooleanQuery prepareBooleanQuery(String queryString) throws RepositoryException, MalformedQueryException { """ overload for prepareBooleanQuery @param queryString @return MarkLogicBooleanQuery @throws RepositoryException @throws MalformedQueryException """ return prepareBooleanQuery(QueryLanguage.SPARQL, queryString, null); }
java
@Override public MarkLogicBooleanQuery prepareBooleanQuery(String queryString) throws RepositoryException, MalformedQueryException { return prepareBooleanQuery(QueryLanguage.SPARQL, queryString, null); }
[ "@", "Override", "public", "MarkLogicBooleanQuery", "prepareBooleanQuery", "(", "String", "queryString", ")", "throws", "RepositoryException", ",", "MalformedQueryException", "{", "return", "prepareBooleanQuery", "(", "QueryLanguage", ".", "SPARQL", ",", "queryString", ",", "null", ")", ";", "}" ]
overload for prepareBooleanQuery @param queryString @return MarkLogicBooleanQuery @throws RepositoryException @throws MalformedQueryException
[ "overload", "for", "prepareBooleanQuery" ]
train
https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/MarkLogicRepositoryConnection.java#L343-L346
powermock/powermock
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound
static void throwExceptionWhenMultipleMethodMatchesFound(String helpInfo, Method[] methods) { """ Throw exception when multiple method matches found. @param helpInfo the help info @param methods the methods """ if (methods == null || methods.length < 2) { throw new IllegalArgumentException( "Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods."); } StringBuilder sb = new StringBuilder(); sb.append("Several matching methods found, please specify the "); sb.append(helpInfo); sb.append(" so that PowerMock can determine which method you're referring to.\n"); sb.append("Matching methods in class ").append(methods[0].getDeclaringClass().getName()).append(" were:\n"); for (Method method : methods) { sb.append(method.getReturnType().getName()).append(" "); sb.append(method.getName()).append("( "); final Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> paramType : parameterTypes) { sb.append(paramType.getName()).append(".class "); } sb.append(")\n"); } throw new TooManyMethodsFoundException(sb.toString()); }
java
static void throwExceptionWhenMultipleMethodMatchesFound(String helpInfo, Method[] methods) { if (methods == null || methods.length < 2) { throw new IllegalArgumentException( "Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods."); } StringBuilder sb = new StringBuilder(); sb.append("Several matching methods found, please specify the "); sb.append(helpInfo); sb.append(" so that PowerMock can determine which method you're referring to.\n"); sb.append("Matching methods in class ").append(methods[0].getDeclaringClass().getName()).append(" were:\n"); for (Method method : methods) { sb.append(method.getReturnType().getName()).append(" "); sb.append(method.getName()).append("( "); final Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> paramType : parameterTypes) { sb.append(paramType.getName()).append(".class "); } sb.append(")\n"); } throw new TooManyMethodsFoundException(sb.toString()); }
[ "static", "void", "throwExceptionWhenMultipleMethodMatchesFound", "(", "String", "helpInfo", ",", "Method", "[", "]", "methods", ")", "{", "if", "(", "methods", "==", "null", "||", "methods", ".", "length", "<", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods.\"", ")", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"Several matching methods found, please specify the \"", ")", ";", "sb", ".", "append", "(", "helpInfo", ")", ";", "sb", ".", "append", "(", "\" so that PowerMock can determine which method you're referring to.\\n\"", ")", ";", "sb", ".", "append", "(", "\"Matching methods in class \"", ")", ".", "append", "(", "methods", "[", "0", "]", ".", "getDeclaringClass", "(", ")", ".", "getName", "(", ")", ")", ".", "append", "(", "\" were:\\n\"", ")", ";", "for", "(", "Method", "method", ":", "methods", ")", "{", "sb", ".", "append", "(", "method", ".", "getReturnType", "(", ")", ".", "getName", "(", ")", ")", ".", "append", "(", "\" \"", ")", ";", "sb", ".", "append", "(", "method", ".", "getName", "(", ")", ")", ".", "append", "(", "\"( \"", ")", ";", "final", "Class", "<", "?", ">", "[", "]", "parameterTypes", "=", "method", ".", "getParameterTypes", "(", ")", ";", "for", "(", "Class", "<", "?", ">", "paramType", ":", "parameterTypes", ")", "{", "sb", ".", "append", "(", "paramType", ".", "getName", "(", ")", ")", ".", "append", "(", "\".class \"", ")", ";", "}", "sb", ".", "append", "(", "\")\\n\"", ")", ";", "}", "throw", "new", "TooManyMethodsFoundException", "(", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Throw exception when multiple method matches found. @param helpInfo the help info @param methods the methods
[ "Throw", "exception", "when", "multiple", "method", "matches", "found", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1660-L1681
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedhousing/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedhousing.java
ApiOvhDedicatedhousing.serviceName_features_backupFTP_POST
public net.minidev.ovh.api.dedicated.server.OvhTask serviceName_features_backupFTP_POST(String serviceName) throws IOException { """ Create a new Backup FTP space REST: POST /dedicated/housing/{serviceName}/features/backupFTP @param serviceName [required] The internal name of your Housing bay """ String qPath = "/dedicated/housing/{serviceName}/features/backupFTP"; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "POST", sb.toString(), null); return convertTo(resp, net.minidev.ovh.api.dedicated.server.OvhTask.class); }
java
public net.minidev.ovh.api.dedicated.server.OvhTask serviceName_features_backupFTP_POST(String serviceName) throws IOException { String qPath = "/dedicated/housing/{serviceName}/features/backupFTP"; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "POST", sb.toString(), null); return convertTo(resp, net.minidev.ovh.api.dedicated.server.OvhTask.class); }
[ "public", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "dedicated", ".", "server", ".", "OvhTask", "serviceName_features_backupFTP_POST", "(", "String", "serviceName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/housing/{serviceName}/features/backupFTP\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "dedicated", ".", "server", ".", "OvhTask", ".", "class", ")", ";", "}" ]
Create a new Backup FTP space REST: POST /dedicated/housing/{serviceName}/features/backupFTP @param serviceName [required] The internal name of your Housing bay
[ "Create", "a", "new", "Backup", "FTP", "space" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedhousing/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedhousing.java#L118-L123
apache/incubator-heron
heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java
SchedulerUtils.getExecutorCommand
public static String[] getExecutorCommand( Config config, Config runtime, int shardId, Map<ExecutorPort, String> ports) { """ Utils method to construct the command to start heron-executor @param config The static config @param runtime The runtime config @param shardId the executor/container index @param ports a map of ports to use where the key indicate the port type and the value is the port @return String[] representing the command to start heron-executor """ return getExecutorCommand(config, runtime, Integer.toString(shardId), ports); }
java
public static String[] getExecutorCommand( Config config, Config runtime, int shardId, Map<ExecutorPort, String> ports) { return getExecutorCommand(config, runtime, Integer.toString(shardId), ports); }
[ "public", "static", "String", "[", "]", "getExecutorCommand", "(", "Config", "config", ",", "Config", "runtime", ",", "int", "shardId", ",", "Map", "<", "ExecutorPort", ",", "String", ">", "ports", ")", "{", "return", "getExecutorCommand", "(", "config", ",", "runtime", ",", "Integer", ".", "toString", "(", "shardId", ")", ",", "ports", ")", ";", "}" ]
Utils method to construct the command to start heron-executor @param config The static config @param runtime The runtime config @param shardId the executor/container index @param ports a map of ports to use where the key indicate the port type and the value is the port @return String[] representing the command to start heron-executor
[ "Utils", "method", "to", "construct", "the", "command", "to", "start", "heron", "-", "executor" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerUtils.java#L192-L198
lionsoul2014/jcseg
jcseg-server/src/main/java/org/lionsoul/jcseg/json/zip/Unzipper.java
Unzipper.getAndTick
private Object getAndTick(Keep keep, BitReader bitreader) throws JSONException { """ Read enough bits to obtain an integer from the keep, and increase that integer's weight. @param keep The keep providing the context. @param bitreader The bitreader that is the source of bits. @return The value associated with the number. @throws JSONException """ try { int width = keep.bitsize(); int integer = bitreader.read(width); Object value = keep.value(integer); if (JSONzip.probe) { JSONzip.log("\"" + value + "\""); JSONzip.log(integer, width); } if (integer >= keep.length) { throw new JSONException("Deep error."); } keep.tick(integer); return value; } catch (Throwable e) { throw new JSONException(e); } }
java
private Object getAndTick(Keep keep, BitReader bitreader) throws JSONException { try { int width = keep.bitsize(); int integer = bitreader.read(width); Object value = keep.value(integer); if (JSONzip.probe) { JSONzip.log("\"" + value + "\""); JSONzip.log(integer, width); } if (integer >= keep.length) { throw new JSONException("Deep error."); } keep.tick(integer); return value; } catch (Throwable e) { throw new JSONException(e); } }
[ "private", "Object", "getAndTick", "(", "Keep", "keep", ",", "BitReader", "bitreader", ")", "throws", "JSONException", "{", "try", "{", "int", "width", "=", "keep", ".", "bitsize", "(", ")", ";", "int", "integer", "=", "bitreader", ".", "read", "(", "width", ")", ";", "Object", "value", "=", "keep", ".", "value", "(", "integer", ")", ";", "if", "(", "JSONzip", ".", "probe", ")", "{", "JSONzip", ".", "log", "(", "\"\\\"\"", "+", "value", "+", "\"\\\"\"", ")", ";", "JSONzip", ".", "log", "(", "integer", ",", "width", ")", ";", "}", "if", "(", "integer", ">=", "keep", ".", "length", ")", "{", "throw", "new", "JSONException", "(", "\"Deep error.\"", ")", ";", "}", "keep", ".", "tick", "(", "integer", ")", ";", "return", "value", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "throw", "new", "JSONException", "(", "e", ")", ";", "}", "}" ]
Read enough bits to obtain an integer from the keep, and increase that integer's weight. @param keep The keep providing the context. @param bitreader The bitreader that is the source of bits. @return The value associated with the number. @throws JSONException
[ "Read", "enough", "bits", "to", "obtain", "an", "integer", "from", "the", "keep", "and", "increase", "that", "integer", "s", "weight", "." ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-server/src/main/java/org/lionsoul/jcseg/json/zip/Unzipper.java#L87-L105
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/FunctionTable.java
FunctionTable.installFunction
public int installFunction(String name, Class func) { """ Install a built-in function. @param name The unqualified name of the function, must not be null @param func A Implementation of an XPath Function object. @return the position of the function in the internal index. """ int funcIndex; Object funcIndexObj = getFunctionID(name); if (null != funcIndexObj) { funcIndex = ((Integer) funcIndexObj).intValue(); if (funcIndex < NUM_BUILT_IN_FUNCS){ funcIndex = m_funcNextFreeIndex++; m_functionID_customer.put(name, new Integer(funcIndex)); } m_functions_customer[funcIndex - NUM_BUILT_IN_FUNCS] = func; } else { funcIndex = m_funcNextFreeIndex++; m_functions_customer[funcIndex-NUM_BUILT_IN_FUNCS] = func; m_functionID_customer.put(name, new Integer(funcIndex)); } return funcIndex; }
java
public int installFunction(String name, Class func) { int funcIndex; Object funcIndexObj = getFunctionID(name); if (null != funcIndexObj) { funcIndex = ((Integer) funcIndexObj).intValue(); if (funcIndex < NUM_BUILT_IN_FUNCS){ funcIndex = m_funcNextFreeIndex++; m_functionID_customer.put(name, new Integer(funcIndex)); } m_functions_customer[funcIndex - NUM_BUILT_IN_FUNCS] = func; } else { funcIndex = m_funcNextFreeIndex++; m_functions_customer[funcIndex-NUM_BUILT_IN_FUNCS] = func; m_functionID_customer.put(name, new Integer(funcIndex)); } return funcIndex; }
[ "public", "int", "installFunction", "(", "String", "name", ",", "Class", "func", ")", "{", "int", "funcIndex", ";", "Object", "funcIndexObj", "=", "getFunctionID", "(", "name", ")", ";", "if", "(", "null", "!=", "funcIndexObj", ")", "{", "funcIndex", "=", "(", "(", "Integer", ")", "funcIndexObj", ")", ".", "intValue", "(", ")", ";", "if", "(", "funcIndex", "<", "NUM_BUILT_IN_FUNCS", ")", "{", "funcIndex", "=", "m_funcNextFreeIndex", "++", ";", "m_functionID_customer", ".", "put", "(", "name", ",", "new", "Integer", "(", "funcIndex", ")", ")", ";", "}", "m_functions_customer", "[", "funcIndex", "-", "NUM_BUILT_IN_FUNCS", "]", "=", "func", ";", "}", "else", "{", "funcIndex", "=", "m_funcNextFreeIndex", "++", ";", "m_functions_customer", "[", "funcIndex", "-", "NUM_BUILT_IN_FUNCS", "]", "=", "func", ";", "m_functionID_customer", ".", "put", "(", "name", ",", "new", "Integer", "(", "funcIndex", ")", ")", ";", "}", "return", "funcIndex", ";", "}" ]
Install a built-in function. @param name The unqualified name of the function, must not be null @param func A Implementation of an XPath Function object. @return the position of the function in the internal index.
[ "Install", "a", "built", "-", "in", "function", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/FunctionTable.java#L363-L389
line/armeria
core/src/main/java/com/linecorp/armeria/server/composition/AbstractCompositeServiceBuilder.java
AbstractCompositeServiceBuilder.serviceAt
@Deprecated protected T serviceAt(String pathPattern, Service<I, O> service) { """ Binds the specified {@link Service} at the specified path pattern. @deprecated Use {@link #service(String, Service)} instead. """ return service(pathPattern, service); }
java
@Deprecated protected T serviceAt(String pathPattern, Service<I, O> service) { return service(pathPattern, service); }
[ "@", "Deprecated", "protected", "T", "serviceAt", "(", "String", "pathPattern", ",", "Service", "<", "I", ",", "O", ">", "service", ")", "{", "return", "service", "(", "pathPattern", ",", "service", ")", ";", "}" ]
Binds the specified {@link Service} at the specified path pattern. @deprecated Use {@link #service(String, Service)} instead.
[ "Binds", "the", "specified", "{", "@link", "Service", "}", "at", "the", "specified", "path", "pattern", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/composition/AbstractCompositeServiceBuilder.java#L107-L110
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.rotateYXZ
public Matrix4f rotateYXZ(float angleY, float angleX, float angleZ) { """ Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>M * R</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first! <p> This method is equivalent to calling: <code>rotateY(angleY).rotateX(angleX).rotateZ(angleZ)</code> @param angleY the angle to rotate about Y @param angleX the angle to rotate about X @param angleZ the angle to rotate about Z @return a matrix holding the result """ return rotateYXZ(angleY, angleX, angleZ, thisOrNew()); }
java
public Matrix4f rotateYXZ(float angleY, float angleX, float angleZ) { return rotateYXZ(angleY, angleX, angleZ, thisOrNew()); }
[ "public", "Matrix4f", "rotateYXZ", "(", "float", "angleY", ",", "float", "angleX", ",", "float", "angleZ", ")", "{", "return", "rotateYXZ", "(", "angleY", ",", "angleX", ",", "angleZ", ",", "thisOrNew", "(", ")", ")", ";", "}" ]
Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>M * R</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the rotation will be applied first! <p> This method is equivalent to calling: <code>rotateY(angleY).rotateX(angleX).rotateZ(angleZ)</code> @param angleY the angle to rotate about Y @param angleX the angle to rotate about X @param angleZ the angle to rotate about Z @return a matrix holding the result
[ "Apply", "rotation", "of", "<code", ">", "angleY<", "/", "code", ">", "radians", "about", "the", "Y", "axis", "followed", "by", "a", "rotation", "of", "<code", ">", "angleX<", "/", "code", ">", "radians", "about", "the", "X", "axis", "and", "followed", "by", "a", "rotation", "of", "<code", ">", "angleZ<", "/", "code", ">", "radians", "about", "the", "Z", "axis", ".", "<p", ">", "When", "used", "with", "a", "right", "-", "handed", "coordinate", "system", "the", "produced", "rotation", "will", "rotate", "a", "vector", "counter", "-", "clockwise", "around", "the", "rotation", "axis", "when", "viewing", "along", "the", "negative", "axis", "direction", "towards", "the", "origin", ".", "When", "used", "with", "a", "left", "-", "handed", "coordinate", "system", "the", "rotation", "is", "clockwise", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "R<", "/", "code", ">", "the", "rotation", "matrix", "then", "the", "new", "matrix", "will", "be", "<code", ">", "M", "*", "R<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "M", "*", "R", "*", "v<", "/", "code", ">", "the", "rotation", "will", "be", "applied", "first!", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", ":", "<code", ">", "rotateY", "(", "angleY", ")", ".", "rotateX", "(", "angleX", ")", ".", "rotateZ", "(", "angleZ", ")", "<", "/", "code", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L5676-L5678
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Period.java
Period.plusMonths
public Period plusMonths(long monthsToAdd) { """ Returns a copy of this period with the specified months added. <p> This adds the amount to the months unit in a copy of this period. The years and days units are unaffected. For example, "1 year, 6 months and 3 days" plus 2 months returns "1 year, 8 months and 3 days". <p> This instance is immutable and unaffected by this method call. @param monthsToAdd the months to add, positive or negative @return a {@code Period} based on this period with the specified months added, not null @throws ArithmeticException if numeric overflow occurs """ if (monthsToAdd == 0) { return this; } return create(years, Math.toIntExact(Math.addExact(months, monthsToAdd)), days); }
java
public Period plusMonths(long monthsToAdd) { if (monthsToAdd == 0) { return this; } return create(years, Math.toIntExact(Math.addExact(months, monthsToAdd)), days); }
[ "public", "Period", "plusMonths", "(", "long", "monthsToAdd", ")", "{", "if", "(", "monthsToAdd", "==", "0", ")", "{", "return", "this", ";", "}", "return", "create", "(", "years", ",", "Math", ".", "toIntExact", "(", "Math", ".", "addExact", "(", "months", ",", "monthsToAdd", ")", ")", ",", "days", ")", ";", "}" ]
Returns a copy of this period with the specified months added. <p> This adds the amount to the months unit in a copy of this period. The years and days units are unaffected. For example, "1 year, 6 months and 3 days" plus 2 months returns "1 year, 8 months and 3 days". <p> This instance is immutable and unaffected by this method call. @param monthsToAdd the months to add, positive or negative @return a {@code Period} based on this period with the specified months added, not null @throws ArithmeticException if numeric overflow occurs
[ "Returns", "a", "copy", "of", "this", "period", "with", "the", "specified", "months", "added", ".", "<p", ">", "This", "adds", "the", "amount", "to", "the", "months", "unit", "in", "a", "copy", "of", "this", "period", ".", "The", "years", "and", "days", "units", "are", "unaffected", ".", "For", "example", "1", "year", "6", "months", "and", "3", "days", "plus", "2", "months", "returns", "1", "year", "8", "months", "and", "3", "days", ".", "<p", ">", "This", "instance", "is", "immutable", "and", "unaffected", "by", "this", "method", "call", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/Period.java#L660-L665
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java
TableProcessor.populateRelationMetaData
private <X> void populateRelationMetaData(EntityType entityType, Class<X> clazz, EntityMetadata metadata) { """ Populate metadata. @param entityType the EntityType @param <X> the generic type @param metadata the metadata @throws RuleValidationException """ Set<Attribute> attributes = entityType.getAttributes(); for (Attribute attribute : attributes) { if (attribute.isAssociation()) { addRelationIntoMetadata(clazz, (Field) attribute.getJavaMember(), metadata); } } }
java
private <X> void populateRelationMetaData(EntityType entityType, Class<X> clazz, EntityMetadata metadata) { Set<Attribute> attributes = entityType.getAttributes(); for (Attribute attribute : attributes) { if (attribute.isAssociation()) { addRelationIntoMetadata(clazz, (Field) attribute.getJavaMember(), metadata); } } }
[ "private", "<", "X", ">", "void", "populateRelationMetaData", "(", "EntityType", "entityType", ",", "Class", "<", "X", ">", "clazz", ",", "EntityMetadata", "metadata", ")", "{", "Set", "<", "Attribute", ">", "attributes", "=", "entityType", ".", "getAttributes", "(", ")", ";", "for", "(", "Attribute", "attribute", ":", "attributes", ")", "{", "if", "(", "attribute", ".", "isAssociation", "(", ")", ")", "{", "addRelationIntoMetadata", "(", "clazz", ",", "(", "Field", ")", "attribute", ".", "getJavaMember", "(", ")", ",", "metadata", ")", ";", "}", "}", "}" ]
Populate metadata. @param entityType the EntityType @param <X> the generic type @param metadata the metadata @throws RuleValidationException
[ "Populate", "metadata", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java#L168-L181
virgo47/javasimon
examples/src/main/java/org/javasimon/examples/CallbackFilteringExample.java
CallbackFilteringExample.main
public static void main(String[] args) { """ Entry point to the Callback Filtering Example. @param args unused """ // manager with two stopwatches is created Manager manager = new EnabledManager(); Stopwatch sw1 = manager.getStopwatch("org.javasimon.examples.stopwatch1"); Stopwatch sw2 = manager.getStopwatch("other.stopwatch2"); // simple callback printing actions to the stdout is created and installed Callback stdoutCallback = new CallbackSkeleton() { @Override public void onStopwatchStart(Split split) { System.out.println("Starting " + split.getStopwatch().getName()); } @Override public void onStopwatchStop(Split split, StopwatchSample sample) { System.out.println("Stopped " + split.getStopwatch().getName() + " (" + SimonUtils.presentNanoTime(split.runningFor()) + ")"); } }; manager.callback().addCallback(stdoutCallback); // prints start/stop for both stopwatches sw1.start().stop(); sw2.start().stop(); System.out.println(); // we need to remove old callback manager.callback().removeCallback(stdoutCallback); // alternatively you can call this if you want to remove all callbacks SimonManager.callback().removeAllCallbacks(); // filter callback is created CompositeFilterCallback filter = new CompositeFilterCallback(); // rule to filter out all Simons matching pattern "other.*" is added filter.addRule(FilterRule.Type.MUST_NOT, null, "other.*"); // original callback is added after this callback filter.addCallback(stdoutCallback); // filter callback is installed to the manager (with printing callback behind) manager.callback().addCallback(filter); // start/stop is printed only for sw1 because sw2 matches other.* pattern that is excluded (MUST_NOT) sw1.start().stop(); sw2.start().stop(); }
java
public static void main(String[] args) { // manager with two stopwatches is created Manager manager = new EnabledManager(); Stopwatch sw1 = manager.getStopwatch("org.javasimon.examples.stopwatch1"); Stopwatch sw2 = manager.getStopwatch("other.stopwatch2"); // simple callback printing actions to the stdout is created and installed Callback stdoutCallback = new CallbackSkeleton() { @Override public void onStopwatchStart(Split split) { System.out.println("Starting " + split.getStopwatch().getName()); } @Override public void onStopwatchStop(Split split, StopwatchSample sample) { System.out.println("Stopped " + split.getStopwatch().getName() + " (" + SimonUtils.presentNanoTime(split.runningFor()) + ")"); } }; manager.callback().addCallback(stdoutCallback); // prints start/stop for both stopwatches sw1.start().stop(); sw2.start().stop(); System.out.println(); // we need to remove old callback manager.callback().removeCallback(stdoutCallback); // alternatively you can call this if you want to remove all callbacks SimonManager.callback().removeAllCallbacks(); // filter callback is created CompositeFilterCallback filter = new CompositeFilterCallback(); // rule to filter out all Simons matching pattern "other.*" is added filter.addRule(FilterRule.Type.MUST_NOT, null, "other.*"); // original callback is added after this callback filter.addCallback(stdoutCallback); // filter callback is installed to the manager (with printing callback behind) manager.callback().addCallback(filter); // start/stop is printed only for sw1 because sw2 matches other.* pattern that is excluded (MUST_NOT) sw1.start().stop(); sw2.start().stop(); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "// manager with two stopwatches is created", "Manager", "manager", "=", "new", "EnabledManager", "(", ")", ";", "Stopwatch", "sw1", "=", "manager", ".", "getStopwatch", "(", "\"org.javasimon.examples.stopwatch1\"", ")", ";", "Stopwatch", "sw2", "=", "manager", ".", "getStopwatch", "(", "\"other.stopwatch2\"", ")", ";", "// simple callback printing actions to the stdout is created and installed", "Callback", "stdoutCallback", "=", "new", "CallbackSkeleton", "(", ")", "{", "@", "Override", "public", "void", "onStopwatchStart", "(", "Split", "split", ")", "{", "System", ".", "out", ".", "println", "(", "\"Starting \"", "+", "split", ".", "getStopwatch", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "onStopwatchStop", "(", "Split", "split", ",", "StopwatchSample", "sample", ")", "{", "System", ".", "out", ".", "println", "(", "\"Stopped \"", "+", "split", ".", "getStopwatch", "(", ")", ".", "getName", "(", ")", "+", "\" (\"", "+", "SimonUtils", ".", "presentNanoTime", "(", "split", ".", "runningFor", "(", ")", ")", "+", "\")\"", ")", ";", "}", "}", ";", "manager", ".", "callback", "(", ")", ".", "addCallback", "(", "stdoutCallback", ")", ";", "// prints start/stop for both stopwatches", "sw1", ".", "start", "(", ")", ".", "stop", "(", ")", ";", "sw2", ".", "start", "(", ")", ".", "stop", "(", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "// we need to remove old callback", "manager", ".", "callback", "(", ")", ".", "removeCallback", "(", "stdoutCallback", ")", ";", "// alternatively you can call this if you want to remove all callbacks", "SimonManager", ".", "callback", "(", ")", ".", "removeAllCallbacks", "(", ")", ";", "// filter callback is created", "CompositeFilterCallback", "filter", "=", "new", "CompositeFilterCallback", "(", ")", ";", "// rule to filter out all Simons matching pattern \"other.*\" is added", "filter", ".", "addRule", "(", "FilterRule", ".", "Type", ".", "MUST_NOT", ",", "null", ",", "\"other.*\"", ")", ";", "// original callback is added after this callback", "filter", ".", "addCallback", "(", "stdoutCallback", ")", ";", "// filter callback is installed to the manager (with printing callback behind)", "manager", ".", "callback", "(", ")", ".", "addCallback", "(", "filter", ")", ";", "// start/stop is printed only for sw1 because sw2 matches other.* pattern that is excluded (MUST_NOT)", "sw1", ".", "start", "(", ")", ".", "stop", "(", ")", ";", "sw2", ".", "start", "(", ")", ".", "stop", "(", ")", ";", "}" ]
Entry point to the Callback Filtering Example. @param args unused
[ "Entry", "point", "to", "the", "Callback", "Filtering", "Example", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/examples/src/main/java/org/javasimon/examples/CallbackFilteringExample.java#L26-L69
wisdom-framework/wisdom
core/crypto/src/main/java/org/wisdom/crypto/CryptoServiceSingleton.java
CryptoServiceSingleton.compareSignedTokens
@Override public boolean compareSignedTokens(String tokenA, String tokenB) { """ Compares two signed tokens. @param tokenA the first token @param tokenB the second token @return {@code true} if the tokens are equals, {@code false} otherwise """ String a = extractSignedToken(tokenA); String b = extractSignedToken(tokenB); return a != null && b != null && constantTimeEquals(a, b); }
java
@Override public boolean compareSignedTokens(String tokenA, String tokenB) { String a = extractSignedToken(tokenA); String b = extractSignedToken(tokenB); return a != null && b != null && constantTimeEquals(a, b); }
[ "@", "Override", "public", "boolean", "compareSignedTokens", "(", "String", "tokenA", ",", "String", "tokenB", ")", "{", "String", "a", "=", "extractSignedToken", "(", "tokenA", ")", ";", "String", "b", "=", "extractSignedToken", "(", "tokenB", ")", ";", "return", "a", "!=", "null", "&&", "b", "!=", "null", "&&", "constantTimeEquals", "(", "a", ",", "b", ")", ";", "}" ]
Compares two signed tokens. @param tokenA the first token @param tokenB the second token @return {@code true} if the tokens are equals, {@code false} otherwise
[ "Compares", "two", "signed", "tokens", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/crypto/src/main/java/org/wisdom/crypto/CryptoServiceSingleton.java#L484-L489
shrinkwrap/descriptors
metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/MetadataUtil.java
MetadataUtil.getAttributeValue
public static String getAttributeValue(final Element element, final String name) { """ Returns the attribute value for the given attribute name. @param element the w3c dom element. @param name the attribute name @return if present, the the extracted attribute value, otherwise null. """ final Node node = element.getAttributes().getNamedItem(name); if (node != null) { return node.getNodeValue(); } return null; }
java
public static String getAttributeValue(final Element element, final String name) { final Node node = element.getAttributes().getNamedItem(name); if (node != null) { return node.getNodeValue(); } return null; }
[ "public", "static", "String", "getAttributeValue", "(", "final", "Element", "element", ",", "final", "String", "name", ")", "{", "final", "Node", "node", "=", "element", ".", "getAttributes", "(", ")", ".", "getNamedItem", "(", "name", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "return", "node", ".", "getNodeValue", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns the attribute value for the given attribute name. @param element the w3c dom element. @param name the attribute name @return if present, the the extracted attribute value, otherwise null.
[ "Returns", "the", "attribute", "value", "for", "the", "given", "attribute", "name", "." ]
train
https://github.com/shrinkwrap/descriptors/blob/023ba080e6396b9f4dd8275dc4e5c0ebb6b5e6ba/metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/MetadataUtil.java#L46-L53
box/box-java-sdk
src/main/java/com/box/sdk/BoxFile.java
BoxFile.getMetadata
public Metadata getMetadata(String typeName, String scope) { """ Gets the file metadata of specified template type. @param typeName the metadata template type name. @param scope the metadata scope (global or enterprise). @return the metadata returned from the server. """ URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); return new Metadata(JsonObject.readFrom(response.getJSON())); }
java
public Metadata getMetadata(String typeName, String scope) { URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); return new Metadata(JsonObject.readFrom(response.getJSON())); }
[ "public", "Metadata", "getMetadata", "(", "String", "typeName", ",", "String", "scope", ")", "{", "URL", "url", "=", "METADATA_URL_TEMPLATE", ".", "build", "(", "this", ".", "getAPI", "(", ")", ".", "getBaseURL", "(", ")", ",", "this", ".", "getID", "(", ")", ",", "scope", ",", "typeName", ")", ";", "BoxAPIRequest", "request", "=", "new", "BoxAPIRequest", "(", "this", ".", "getAPI", "(", ")", ",", "url", ",", "\"GET\"", ")", ";", "BoxJSONResponse", "response", "=", "(", "BoxJSONResponse", ")", "request", ".", "send", "(", ")", ";", "return", "new", "Metadata", "(", "JsonObject", ".", "readFrom", "(", "response", ".", "getJSON", "(", ")", ")", ")", ";", "}" ]
Gets the file metadata of specified template type. @param typeName the metadata template type name. @param scope the metadata scope (global or enterprise). @return the metadata returned from the server.
[ "Gets", "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#L1276-L1281
aws/aws-sdk-java
aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/MessageMD5ChecksumHandler.java
MessageMD5ChecksumHandler.updateLengthAndBytes
private static void updateLengthAndBytes(MessageDigest digest, String str) throws UnsupportedEncodingException { """ Update the digest using a sequence of bytes that consists of the length (in 4 bytes) of the input String and the actual utf8-encoded byte values. """ byte[] utf8Encoded = str.getBytes(UTF8); ByteBuffer lengthBytes = ByteBuffer.allocate(INTEGER_SIZE_IN_BYTES).putInt(utf8Encoded.length); digest.update(lengthBytes.array()); digest.update(utf8Encoded); }
java
private static void updateLengthAndBytes(MessageDigest digest, String str) throws UnsupportedEncodingException { byte[] utf8Encoded = str.getBytes(UTF8); ByteBuffer lengthBytes = ByteBuffer.allocate(INTEGER_SIZE_IN_BYTES).putInt(utf8Encoded.length); digest.update(lengthBytes.array()); digest.update(utf8Encoded); }
[ "private", "static", "void", "updateLengthAndBytes", "(", "MessageDigest", "digest", ",", "String", "str", ")", "throws", "UnsupportedEncodingException", "{", "byte", "[", "]", "utf8Encoded", "=", "str", ".", "getBytes", "(", "UTF8", ")", ";", "ByteBuffer", "lengthBytes", "=", "ByteBuffer", ".", "allocate", "(", "INTEGER_SIZE_IN_BYTES", ")", ".", "putInt", "(", "utf8Encoded", ".", "length", ")", ";", "digest", ".", "update", "(", "lengthBytes", ".", "array", "(", ")", ")", ";", "digest", ".", "update", "(", "utf8Encoded", ")", ";", "}" ]
Update the digest using a sequence of bytes that consists of the length (in 4 bytes) of the input String and the actual utf8-encoded byte values.
[ "Update", "the", "digest", "using", "a", "sequence", "of", "bytes", "that", "consists", "of", "the", "length", "(", "in", "4", "bytes", ")", "of", "the", "input", "String", "and", "the", "actual", "utf8", "-", "encoded", "byte", "values", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/MessageMD5ChecksumHandler.java#L269-L274
jbundle/jbundle
base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HBasePanel.java
HBasePanel.printHtmlLogo
public void printHtmlLogo(PrintWriter out, ResourceBundle reg) throws DBException { """ Print the top nav menu. @param out The html out stream. @param reg The resources object. @exception DBException File exception. """ char chMenubar = HBasePanel.getFirstToUpper(this.getProperty(DBParams.LOGOS), 'H'); if (chMenubar == 'H') if (((BasePanel)this.getScreenField()).isMainMenu()) chMenubar = 'Y'; if (chMenubar == 'Y') { String strNav = reg.getString("htmlLogo"); strNav = Utility.replaceResources(strNav, reg, null, null); String strScreen = ((BasePanel)this.getScreenField()).getScreenURL(); strScreen = Utility.encodeXML(strScreen); String strUserName = ((MainApplication)this.getTask().getApplication()).getUserName(); if (Utility.isNumeric(strUserName)) strUserName = DBConstants.BLANK; String strLanguage = this.getTask().getApplication().getLanguage(false); strNav = Utility.replace(strNav, HtmlConstants.URL_TAG, strScreen); strNav = Utility.replace(strNav, HtmlConstants.USER_NAME_TAG, strUserName); strNav = Utility.replace(strNav, "<language/>", strLanguage); this.writeHtmlString(strNav, out); } }
java
public void printHtmlLogo(PrintWriter out, ResourceBundle reg) throws DBException { char chMenubar = HBasePanel.getFirstToUpper(this.getProperty(DBParams.LOGOS), 'H'); if (chMenubar == 'H') if (((BasePanel)this.getScreenField()).isMainMenu()) chMenubar = 'Y'; if (chMenubar == 'Y') { String strNav = reg.getString("htmlLogo"); strNav = Utility.replaceResources(strNav, reg, null, null); String strScreen = ((BasePanel)this.getScreenField()).getScreenURL(); strScreen = Utility.encodeXML(strScreen); String strUserName = ((MainApplication)this.getTask().getApplication()).getUserName(); if (Utility.isNumeric(strUserName)) strUserName = DBConstants.BLANK; String strLanguage = this.getTask().getApplication().getLanguage(false); strNav = Utility.replace(strNav, HtmlConstants.URL_TAG, strScreen); strNav = Utility.replace(strNav, HtmlConstants.USER_NAME_TAG, strUserName); strNav = Utility.replace(strNav, "<language/>", strLanguage); this.writeHtmlString(strNav, out); } }
[ "public", "void", "printHtmlLogo", "(", "PrintWriter", "out", ",", "ResourceBundle", "reg", ")", "throws", "DBException", "{", "char", "chMenubar", "=", "HBasePanel", ".", "getFirstToUpper", "(", "this", ".", "getProperty", "(", "DBParams", ".", "LOGOS", ")", ",", "'", "'", ")", ";", "if", "(", "chMenubar", "==", "'", "'", ")", "if", "(", "(", "(", "BasePanel", ")", "this", ".", "getScreenField", "(", ")", ")", ".", "isMainMenu", "(", ")", ")", "chMenubar", "=", "'", "'", ";", "if", "(", "chMenubar", "==", "'", "'", ")", "{", "String", "strNav", "=", "reg", ".", "getString", "(", "\"htmlLogo\"", ")", ";", "strNav", "=", "Utility", ".", "replaceResources", "(", "strNav", ",", "reg", ",", "null", ",", "null", ")", ";", "String", "strScreen", "=", "(", "(", "BasePanel", ")", "this", ".", "getScreenField", "(", ")", ")", ".", "getScreenURL", "(", ")", ";", "strScreen", "=", "Utility", ".", "encodeXML", "(", "strScreen", ")", ";", "String", "strUserName", "=", "(", "(", "MainApplication", ")", "this", ".", "getTask", "(", ")", ".", "getApplication", "(", ")", ")", ".", "getUserName", "(", ")", ";", "if", "(", "Utility", ".", "isNumeric", "(", "strUserName", ")", ")", "strUserName", "=", "DBConstants", ".", "BLANK", ";", "String", "strLanguage", "=", "this", ".", "getTask", "(", ")", ".", "getApplication", "(", ")", ".", "getLanguage", "(", "false", ")", ";", "strNav", "=", "Utility", ".", "replace", "(", "strNav", ",", "HtmlConstants", ".", "URL_TAG", ",", "strScreen", ")", ";", "strNav", "=", "Utility", ".", "replace", "(", "strNav", ",", "HtmlConstants", ".", "USER_NAME_TAG", ",", "strUserName", ")", ";", "strNav", "=", "Utility", ".", "replace", "(", "strNav", ",", "\"<language/>\"", ",", "strLanguage", ")", ";", "this", ".", "writeHtmlString", "(", "strNav", ",", "out", ")", ";", "}", "}" ]
Print the top nav menu. @param out The html out stream. @param reg The resources object. @exception DBException File exception.
[ "Print", "the", "top", "nav", "menu", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HBasePanel.java#L267-L288
aws/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/PurchaseOfferingRequest.java
PurchaseOfferingRequest.withTags
public PurchaseOfferingRequest withTags(java.util.Map<String, String> tags) { """ A collection of key-value pairs @param tags A collection of key-value pairs @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public PurchaseOfferingRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "PurchaseOfferingRequest", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
A collection of key-value pairs @param tags A collection of key-value pairs @return Returns a reference to this object so that method calls can be chained together.
[ "A", "collection", "of", "key", "-", "value", "pairs" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/PurchaseOfferingRequest.java#L250-L253
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/util/dbhandling/TorqueDBHandling.java
TorqueDBHandling.writeCompressedText
private void writeCompressedText(File file, byte[] compressedContent) throws IOException { """ Uncompresses the given textual content and writes it to the given file. @param file The file to write to @param compressedContent The content @throws IOException If an error occurred """ ByteArrayInputStream bais = new ByteArrayInputStream(compressedContent); GZIPInputStream gis = new GZIPInputStream(bais); BufferedReader input = new BufferedReader(new InputStreamReader(gis)); BufferedWriter output = new BufferedWriter(new FileWriter(file)); String line; while ((line = input.readLine()) != null) { output.write(line); output.write('\n'); } input.close(); gis.close(); bais.close(); output.close(); }
java
private void writeCompressedText(File file, byte[] compressedContent) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(compressedContent); GZIPInputStream gis = new GZIPInputStream(bais); BufferedReader input = new BufferedReader(new InputStreamReader(gis)); BufferedWriter output = new BufferedWriter(new FileWriter(file)); String line; while ((line = input.readLine()) != null) { output.write(line); output.write('\n'); } input.close(); gis.close(); bais.close(); output.close(); }
[ "private", "void", "writeCompressedText", "(", "File", "file", ",", "byte", "[", "]", "compressedContent", ")", "throws", "IOException", "{", "ByteArrayInputStream", "bais", "=", "new", "ByteArrayInputStream", "(", "compressedContent", ")", ";", "GZIPInputStream", "gis", "=", "new", "GZIPInputStream", "(", "bais", ")", ";", "BufferedReader", "input", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "gis", ")", ")", ";", "BufferedWriter", "output", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "file", ")", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "input", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "output", ".", "write", "(", "line", ")", ";", "output", ".", "write", "(", "'", "'", ")", ";", "}", "input", ".", "close", "(", ")", ";", "gis", ".", "close", "(", ")", ";", "bais", ".", "close", "(", ")", ";", "output", ".", "close", "(", ")", ";", "}" ]
Uncompresses the given textual content and writes it to the given file. @param file The file to write to @param compressedContent The content @throws IOException If an error occurred
[ "Uncompresses", "the", "given", "textual", "content", "and", "writes", "it", "to", "the", "given", "file", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/dbhandling/TorqueDBHandling.java#L596-L613
cache2k/cache2k
cache2k-core/src/main/java/org/cache2k/core/HeapCache.java
HeapCache.checkForHashCodeChange
private void checkForHashCodeChange(Entry<K, V> e) { """ Check whether the key was modified during the stay of the entry in the cache. We only need to check this when the entry is removed, since we expect that if the key has changed, the stored hash code in the cache will not match any more and the item is evicted very fast. """ K key = extractKeyObj(e); if (extractIntKeyValue(key, modifiedHash(key.hashCode())) != e.hashCode) { if (keyMutationCnt == 0) { getLog().warn("Key mismatch! Key hashcode changed! keyClass=" + e.getKey().getClass().getName()); String s; try { s = e.getKey().toString(); if (s != null) { getLog().warn("Key mismatch! key.toString(): " + s); } } catch (Throwable t) { getLog().warn("Key mismatch! key.toString() threw exception", t); } } keyMutationCnt++; } }
java
private void checkForHashCodeChange(Entry<K, V> e) { K key = extractKeyObj(e); if (extractIntKeyValue(key, modifiedHash(key.hashCode())) != e.hashCode) { if (keyMutationCnt == 0) { getLog().warn("Key mismatch! Key hashcode changed! keyClass=" + e.getKey().getClass().getName()); String s; try { s = e.getKey().toString(); if (s != null) { getLog().warn("Key mismatch! key.toString(): " + s); } } catch (Throwable t) { getLog().warn("Key mismatch! key.toString() threw exception", t); } } keyMutationCnt++; } }
[ "private", "void", "checkForHashCodeChange", "(", "Entry", "<", "K", ",", "V", ">", "e", ")", "{", "K", "key", "=", "extractKeyObj", "(", "e", ")", ";", "if", "(", "extractIntKeyValue", "(", "key", ",", "modifiedHash", "(", "key", ".", "hashCode", "(", ")", ")", ")", "!=", "e", ".", "hashCode", ")", "{", "if", "(", "keyMutationCnt", "==", "0", ")", "{", "getLog", "(", ")", ".", "warn", "(", "\"Key mismatch! Key hashcode changed! keyClass=\"", "+", "e", ".", "getKey", "(", ")", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "String", "s", ";", "try", "{", "s", "=", "e", ".", "getKey", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "s", "!=", "null", ")", "{", "getLog", "(", ")", ".", "warn", "(", "\"Key mismatch! key.toString(): \"", "+", "s", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "getLog", "(", ")", ".", "warn", "(", "\"Key mismatch! key.toString() threw exception\"", ",", "t", ")", ";", "}", "}", "keyMutationCnt", "++", ";", "}", "}" ]
Check whether the key was modified during the stay of the entry in the cache. We only need to check this when the entry is removed, since we expect that if the key has changed, the stored hash code in the cache will not match any more and the item is evicted very fast.
[ "Check", "whether", "the", "key", "was", "modified", "during", "the", "stay", "of", "the", "entry", "in", "the", "cache", ".", "We", "only", "need", "to", "check", "this", "when", "the", "entry", "is", "removed", "since", "we", "expect", "that", "if", "the", "key", "has", "changed", "the", "stored", "hash", "code", "in", "the", "cache", "will", "not", "match", "any", "more", "and", "the", "item", "is", "evicted", "very", "fast", "." ]
train
https://github.com/cache2k/cache2k/blob/3c9ccff12608c598c387ec50957089784cc4b618/cache2k-core/src/main/java/org/cache2k/core/HeapCache.java#L1335-L1352
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/odselement/StylesContainer.java
StylesContainer.writeHiddenDataStyles
public void writeHiddenDataStyles(final XMLUtil util, final Appendable appendable) throws IOException { """ Write the data styles in the automatic-styles. They belong to content.xml/automatic-styles @param util an XML util @param appendable the destination @throws IOException if the styles can't be written """ for (final DataStyle dataStyle : this.dataStylesContainer .getValues(Dest.CONTENT_AUTOMATIC_STYLES)) { dataStyle.appendXMLContent(util, appendable); } }
java
public void writeHiddenDataStyles(final XMLUtil util, final Appendable appendable) throws IOException { for (final DataStyle dataStyle : this.dataStylesContainer .getValues(Dest.CONTENT_AUTOMATIC_STYLES)) { dataStyle.appendXMLContent(util, appendable); } }
[ "public", "void", "writeHiddenDataStyles", "(", "final", "XMLUtil", "util", ",", "final", "Appendable", "appendable", ")", "throws", "IOException", "{", "for", "(", "final", "DataStyle", "dataStyle", ":", "this", ".", "dataStylesContainer", ".", "getValues", "(", "Dest", ".", "CONTENT_AUTOMATIC_STYLES", ")", ")", "{", "dataStyle", ".", "appendXMLContent", "(", "util", ",", "appendable", ")", ";", "}", "}" ]
Write the data styles in the automatic-styles. They belong to content.xml/automatic-styles @param util an XML util @param appendable the destination @throws IOException if the styles can't be written
[ "Write", "the", "data", "styles", "in", "the", "automatic", "-", "styles", ".", "They", "belong", "to", "content", ".", "xml", "/", "automatic", "-", "styles" ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/odselement/StylesContainer.java#L380-L386
Wolfgang-Schuetzelhofer/jcypher
src/main/java/iot/jcypher/domainquery/AbstractDomainQuery.java
AbstractDomainQuery.COLLECT
public Collect COLLECT(JcProperty attribute) { """ Collect the specified attribute from all objects in a DomainObjectMatch @param attribute @return """ CollectExpression ce = new CollectExpression(attribute, this.getIntAccess()); Collect coll = APIAccess.createCollect(ce); this.queryExecutor.addAstObject(ce); QueryRecorder.recordInvocation(this, "COLLECT", coll, QueryRecorder.placeHolder(attribute)); return coll; }
java
public Collect COLLECT(JcProperty attribute) { CollectExpression ce = new CollectExpression(attribute, this.getIntAccess()); Collect coll = APIAccess.createCollect(ce); this.queryExecutor.addAstObject(ce); QueryRecorder.recordInvocation(this, "COLLECT", coll, QueryRecorder.placeHolder(attribute)); return coll; }
[ "public", "Collect", "COLLECT", "(", "JcProperty", "attribute", ")", "{", "CollectExpression", "ce", "=", "new", "CollectExpression", "(", "attribute", ",", "this", ".", "getIntAccess", "(", ")", ")", ";", "Collect", "coll", "=", "APIAccess", ".", "createCollect", "(", "ce", ")", ";", "this", ".", "queryExecutor", ".", "addAstObject", "(", "ce", ")", ";", "QueryRecorder", ".", "recordInvocation", "(", "this", ",", "\"COLLECT\"", ",", "coll", ",", "QueryRecorder", ".", "placeHolder", "(", "attribute", ")", ")", ";", "return", "coll", ";", "}" ]
Collect the specified attribute from all objects in a DomainObjectMatch @param attribute @return
[ "Collect", "the", "specified", "attribute", "from", "all", "objects", "in", "a", "DomainObjectMatch" ]
train
https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/domainquery/AbstractDomainQuery.java#L334-L340
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/osm/OSMTablesFactory.java
OSMTablesFactory.createWayMemberTable
public static PreparedStatement createWayMemberTable(Connection connection, String wayMemberTable) throws SQLException { """ Create a table to store all way members. @param connection @param wayMemberTable @return @throws SQLException """ try (Statement stmt = connection.createStatement()) { StringBuilder sb = new StringBuilder("CREATE TABLE "); sb.append(wayMemberTable); sb.append("(ID_RELATION BIGINT, ID_WAY BIGINT, ROLE VARCHAR, WAY_ORDER INT);"); stmt.execute(sb.toString()); } return connection.prepareStatement("INSERT INTO " + wayMemberTable + " VALUES ( ?,?,?,?);"); }
java
public static PreparedStatement createWayMemberTable(Connection connection, String wayMemberTable) throws SQLException { try (Statement stmt = connection.createStatement()) { StringBuilder sb = new StringBuilder("CREATE TABLE "); sb.append(wayMemberTable); sb.append("(ID_RELATION BIGINT, ID_WAY BIGINT, ROLE VARCHAR, WAY_ORDER INT);"); stmt.execute(sb.toString()); } return connection.prepareStatement("INSERT INTO " + wayMemberTable + " VALUES ( ?,?,?,?);"); }
[ "public", "static", "PreparedStatement", "createWayMemberTable", "(", "Connection", "connection", ",", "String", "wayMemberTable", ")", "throws", "SQLException", "{", "try", "(", "Statement", "stmt", "=", "connection", ".", "createStatement", "(", ")", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "\"CREATE TABLE \"", ")", ";", "sb", ".", "append", "(", "wayMemberTable", ")", ";", "sb", ".", "append", "(", "\"(ID_RELATION BIGINT, ID_WAY BIGINT, ROLE VARCHAR, WAY_ORDER INT);\"", ")", ";", "stmt", ".", "execute", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "return", "connection", ".", "prepareStatement", "(", "\"INSERT INTO \"", "+", "wayMemberTable", "+", "\" VALUES ( ?,?,?,?);\"", ")", ";", "}" ]
Create a table to store all way members. @param connection @param wayMemberTable @return @throws SQLException
[ "Create", "a", "table", "to", "store", "all", "way", "members", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/osm/OSMTablesFactory.java#L290-L298
alkacon/opencms-core
src/org/opencms/ui/apps/user/CmsUserEditDialog.java
CmsUserEditDialog.iniRole
protected static void iniRole(CmsObject cms, String ou, ComboBox roleComboBox, Log log) { """ Initialized the role ComboBox.<p> @param cms CmsObject @param ou to load roles for @param roleComboBox ComboBox @param log LOG """ try { List<CmsRole> roles = OpenCms.getRoleManager().getRoles(cms, ou, false); CmsRole.applySystemRoleOrder(roles); IndexedContainer container = new IndexedContainer(); container.addContainerProperty("caption", String.class, ""); for (CmsRole role : roles) { Item item = container.addItem(role); item.getItemProperty("caption").setValue(role.getDisplayName(cms, A_CmsUI.get().getLocale())); } roleComboBox.setContainerDataSource(container); roleComboBox.setItemCaptionPropertyId("caption"); roleComboBox.setNullSelectionAllowed(false); roleComboBox.setNewItemsAllowed(false); } catch (CmsException e) { if (log != null) { log.error("Unable to read roles.", e); } } }
java
protected static void iniRole(CmsObject cms, String ou, ComboBox roleComboBox, Log log) { try { List<CmsRole> roles = OpenCms.getRoleManager().getRoles(cms, ou, false); CmsRole.applySystemRoleOrder(roles); IndexedContainer container = new IndexedContainer(); container.addContainerProperty("caption", String.class, ""); for (CmsRole role : roles) { Item item = container.addItem(role); item.getItemProperty("caption").setValue(role.getDisplayName(cms, A_CmsUI.get().getLocale())); } roleComboBox.setContainerDataSource(container); roleComboBox.setItemCaptionPropertyId("caption"); roleComboBox.setNullSelectionAllowed(false); roleComboBox.setNewItemsAllowed(false); } catch (CmsException e) { if (log != null) { log.error("Unable to read roles.", e); } } }
[ "protected", "static", "void", "iniRole", "(", "CmsObject", "cms", ",", "String", "ou", ",", "ComboBox", "roleComboBox", ",", "Log", "log", ")", "{", "try", "{", "List", "<", "CmsRole", ">", "roles", "=", "OpenCms", ".", "getRoleManager", "(", ")", ".", "getRoles", "(", "cms", ",", "ou", ",", "false", ")", ";", "CmsRole", ".", "applySystemRoleOrder", "(", "roles", ")", ";", "IndexedContainer", "container", "=", "new", "IndexedContainer", "(", ")", ";", "container", ".", "addContainerProperty", "(", "\"caption\"", ",", "String", ".", "class", ",", "\"\"", ")", ";", "for", "(", "CmsRole", "role", ":", "roles", ")", "{", "Item", "item", "=", "container", ".", "addItem", "(", "role", ")", ";", "item", ".", "getItemProperty", "(", "\"caption\"", ")", ".", "setValue", "(", "role", ".", "getDisplayName", "(", "cms", ",", "A_CmsUI", ".", "get", "(", ")", ".", "getLocale", "(", ")", ")", ")", ";", "}", "roleComboBox", ".", "setContainerDataSource", "(", "container", ")", ";", "roleComboBox", ".", "setItemCaptionPropertyId", "(", "\"caption\"", ")", ";", "roleComboBox", ".", "setNullSelectionAllowed", "(", "false", ")", ";", "roleComboBox", ".", "setNewItemsAllowed", "(", "false", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "if", "(", "log", "!=", "null", ")", "{", "log", ".", "error", "(", "\"Unable to read roles.\"", ",", "e", ")", ";", "}", "}", "}" ]
Initialized the role ComboBox.<p> @param cms CmsObject @param ou to load roles for @param roleComboBox ComboBox @param log LOG
[ "Initialized", "the", "role", "ComboBox", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/user/CmsUserEditDialog.java#L540-L561
pravega/pravega
common/src/main/java/io/pravega/common/util/BitConverter.java
BitConverter.writeUUID
public static int writeUUID(byte[] target, int offset, UUID value) { """ Writes the given 128-bit UUID to the given byte array at the given offset. @param target The byte array to write to. @param offset The offset within the byte array to write at. @param value The value to write. @return The number of bytes written. """ writeLong(target, offset, value.getMostSignificantBits()); writeLong(target, offset + Long.BYTES, value.getLeastSignificantBits()); return 2 * Long.BYTES; }
java
public static int writeUUID(byte[] target, int offset, UUID value) { writeLong(target, offset, value.getMostSignificantBits()); writeLong(target, offset + Long.BYTES, value.getLeastSignificantBits()); return 2 * Long.BYTES; }
[ "public", "static", "int", "writeUUID", "(", "byte", "[", "]", "target", ",", "int", "offset", ",", "UUID", "value", ")", "{", "writeLong", "(", "target", ",", "offset", ",", "value", ".", "getMostSignificantBits", "(", ")", ")", ";", "writeLong", "(", "target", ",", "offset", "+", "Long", ".", "BYTES", ",", "value", ".", "getLeastSignificantBits", "(", ")", ")", ";", "return", "2", "*", "Long", ".", "BYTES", ";", "}" ]
Writes the given 128-bit UUID to the given byte array at the given offset. @param target The byte array to write to. @param offset The offset within the byte array to write at. @param value The value to write. @return The number of bytes written.
[ "Writes", "the", "given", "128", "-", "bit", "UUID", "to", "the", "given", "byte", "array", "at", "the", "given", "offset", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/BitConverter.java#L203-L207
ehcache/ehcache3
impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java
RobustResilienceStrategy.putIfAbsentFailure
@Override public V putIfAbsentFailure(K key, V value, StoreAccessException e) { """ Do nothing and return null. @param key the key being put @param value the value being put @param e the triggered failure @return null """ cleanup(key, e); return null; }
java
@Override public V putIfAbsentFailure(K key, V value, StoreAccessException e) { cleanup(key, e); return null; }
[ "@", "Override", "public", "V", "putIfAbsentFailure", "(", "K", "key", ",", "V", "value", ",", "StoreAccessException", "e", ")", "{", "cleanup", "(", "key", ",", "e", ")", ";", "return", "null", ";", "}" ]
Do nothing and return null. @param key the key being put @param value the value being put @param e the triggered failure @return null
[ "Do", "nothing", "and", "return", "null", "." ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustResilienceStrategy.java#L114-L118
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.put
public JsonObject put(String name, JsonObject value) { """ Stores a {@link JsonObject} value identified by the field name. @param name the name of the JSON field. @param value the value of the JSON field. @return the {@link JsonObject}. """ if (this == value) { throw new IllegalArgumentException("Cannot put self"); } content.put(name, value); if (value != null) { Map<String, String> paths = value.encryptionPathInfo(); if (paths != null && !paths.isEmpty()) { for (Map.Entry<String, String> entry : paths.entrySet()) { addValueEncryptionInfo(name.replace("~", "~0").replace("/", "~1") + "/" + entry.getKey(), entry.getValue(), false); } value.clearEncryptionPaths(); } } return this; }
java
public JsonObject put(String name, JsonObject value) { if (this == value) { throw new IllegalArgumentException("Cannot put self"); } content.put(name, value); if (value != null) { Map<String, String> paths = value.encryptionPathInfo(); if (paths != null && !paths.isEmpty()) { for (Map.Entry<String, String> entry : paths.entrySet()) { addValueEncryptionInfo(name.replace("~", "~0").replace("/", "~1") + "/" + entry.getKey(), entry.getValue(), false); } value.clearEncryptionPaths(); } } return this; }
[ "public", "JsonObject", "put", "(", "String", "name", ",", "JsonObject", "value", ")", "{", "if", "(", "this", "==", "value", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot put self\"", ")", ";", "}", "content", ".", "put", "(", "name", ",", "value", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "Map", "<", "String", ",", "String", ">", "paths", "=", "value", ".", "encryptionPathInfo", "(", ")", ";", "if", "(", "paths", "!=", "null", "&&", "!", "paths", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "paths", ".", "entrySet", "(", ")", ")", "{", "addValueEncryptionInfo", "(", "name", ".", "replace", "(", "\"~\"", ",", "\"~0\"", ")", ".", "replace", "(", "\"/\"", ",", "\"~1\"", ")", "+", "\"/\"", "+", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ",", "false", ")", ";", "}", "value", ".", "clearEncryptionPaths", "(", ")", ";", "}", "}", "return", "this", ";", "}" ]
Stores a {@link JsonObject} value identified by the field name. @param name the name of the JSON field. @param value the value of the JSON field. @return the {@link JsonObject}.
[ "Stores", "a", "{", "@link", "JsonObject", "}", "value", "identified", "by", "the", "field", "name", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L675-L690
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.registry/src/com/ibm/ws/security/wim/registry/util/BridgeUtils.java
BridgeUtils.createRealmDataObject
protected void createRealmDataObject(Root inputRootObject, String inputRealm) { """ Create a DataObject for the realm context. @param inputRootDataObject The root DataObject. @param inputRealm The realm. @pre inputRootDataObject != null @pre inputRealm != null @pre inputRealm != "" """ // use the root DataGraph to create a Context DataGraph List<Context> contexts = inputRootObject.getContexts(); if (contexts != null) { Context ctx = new Context(); // set "WIM.Realm" in the Context DataGraph to the realm ctx.setKey(Service.VALUE_CONTEXT_REALM_KEY); ctx.setValue(inputRealm); contexts.add(ctx); } }
java
protected void createRealmDataObject(Root inputRootObject, String inputRealm) { // use the root DataGraph to create a Context DataGraph List<Context> contexts = inputRootObject.getContexts(); if (contexts != null) { Context ctx = new Context(); // set "WIM.Realm" in the Context DataGraph to the realm ctx.setKey(Service.VALUE_CONTEXT_REALM_KEY); ctx.setValue(inputRealm); contexts.add(ctx); } }
[ "protected", "void", "createRealmDataObject", "(", "Root", "inputRootObject", ",", "String", "inputRealm", ")", "{", "// use the root DataGraph to create a Context DataGraph", "List", "<", "Context", ">", "contexts", "=", "inputRootObject", ".", "getContexts", "(", ")", ";", "if", "(", "contexts", "!=", "null", ")", "{", "Context", "ctx", "=", "new", "Context", "(", ")", ";", "// set \"WIM.Realm\" in the Context DataGraph to the realm", "ctx", ".", "setKey", "(", "Service", ".", "VALUE_CONTEXT_REALM_KEY", ")", ";", "ctx", ".", "setValue", "(", "inputRealm", ")", ";", "contexts", ".", "add", "(", "ctx", ")", ";", "}", "}" ]
Create a DataObject for the realm context. @param inputRootDataObject The root DataObject. @param inputRealm The realm. @pre inputRootDataObject != null @pre inputRealm != null @pre inputRealm != ""
[ "Create", "a", "DataObject", "for", "the", "realm", "context", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.registry/src/com/ibm/ws/security/wim/registry/util/BridgeUtils.java#L347-L358
apache/incubator-gobblin
gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerMetricContext.java
InnerMetricContext.addChildContext
public synchronized void addChildContext(String childContextName, final MetricContext childContext) throws NameConflictException, ExecutionException { """ Add a {@link MetricContext} as a child of this {@link MetricContext} if it is not currently a child. @param childContextName the name of the child {@link MetricContext} @param childContext the child {@link MetricContext} to add """ if (this.children.get(childContextName, new Callable<MetricContext>() { @Override public MetricContext call() throws Exception { return childContext; } }) != childContext) { throw new NameConflictException("A child context with that name already exists."); } }
java
public synchronized void addChildContext(String childContextName, final MetricContext childContext) throws NameConflictException, ExecutionException { if (this.children.get(childContextName, new Callable<MetricContext>() { @Override public MetricContext call() throws Exception { return childContext; } }) != childContext) { throw new NameConflictException("A child context with that name already exists."); } }
[ "public", "synchronized", "void", "addChildContext", "(", "String", "childContextName", ",", "final", "MetricContext", "childContext", ")", "throws", "NameConflictException", ",", "ExecutionException", "{", "if", "(", "this", ".", "children", ".", "get", "(", "childContextName", ",", "new", "Callable", "<", "MetricContext", ">", "(", ")", "{", "@", "Override", "public", "MetricContext", "call", "(", ")", "throws", "Exception", "{", "return", "childContext", ";", "}", "}", ")", "!=", "childContext", ")", "{", "throw", "new", "NameConflictException", "(", "\"A child context with that name already exists.\"", ")", ";", "}", "}" ]
Add a {@link MetricContext} as a child of this {@link MetricContext} if it is not currently a child. @param childContextName the name of the child {@link MetricContext} @param childContext the child {@link MetricContext} to add
[ "Add", "a", "{", "@link", "MetricContext", "}", "as", "a", "child", "of", "this", "{", "@link", "MetricContext", "}", "if", "it", "is", "not", "currently", "a", "child", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/InnerMetricContext.java#L134-L144
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/builder/AbstractProcessorBuilder.java
AbstractProcessorBuilder.getFormatter
@SuppressWarnings("unchecked") public TextFormatter<T> getFormatter(final FieldAccessor field, final Configuration config) { """ 文字列とオブジェクトを相互変換するフォーマッタを取得します。 <p>アノテーション{@link CsvFormat}が指定されている場合は、そちらを優先します。</p> @param field フィールド情報 @param config システム設定 @return フォーマッタを取得します。 """ if(field.hasAnnotation(CsvFormat.class)) { CsvFormat formatAnno = field.getAnnotation(CsvFormat.class).get(); final TextFormatter<T> formatter = (TextFormatter<T>) config.getBeanFactory().create(formatAnno.formatter()); if(!formatAnno.message().isEmpty()) { formatter.setValidationMessage(formatAnno.message()); } return formatter; } else { return getDefaultFormatter(field, config); } }
java
@SuppressWarnings("unchecked") public TextFormatter<T> getFormatter(final FieldAccessor field, final Configuration config) { if(field.hasAnnotation(CsvFormat.class)) { CsvFormat formatAnno = field.getAnnotation(CsvFormat.class).get(); final TextFormatter<T> formatter = (TextFormatter<T>) config.getBeanFactory().create(formatAnno.formatter()); if(!formatAnno.message().isEmpty()) { formatter.setValidationMessage(formatAnno.message()); } return formatter; } else { return getDefaultFormatter(field, config); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "TextFormatter", "<", "T", ">", "getFormatter", "(", "final", "FieldAccessor", "field", ",", "final", "Configuration", "config", ")", "{", "if", "(", "field", ".", "hasAnnotation", "(", "CsvFormat", ".", "class", ")", ")", "{", "CsvFormat", "formatAnno", "=", "field", ".", "getAnnotation", "(", "CsvFormat", ".", "class", ")", ".", "get", "(", ")", ";", "final", "TextFormatter", "<", "T", ">", "formatter", "=", "(", "TextFormatter", "<", "T", ">", ")", "config", ".", "getBeanFactory", "(", ")", ".", "create", "(", "formatAnno", ".", "formatter", "(", ")", ")", ";", "if", "(", "!", "formatAnno", ".", "message", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "formatter", ".", "setValidationMessage", "(", "formatAnno", ".", "message", "(", ")", ")", ";", "}", "return", "formatter", ";", "}", "else", "{", "return", "getDefaultFormatter", "(", "field", ",", "config", ")", ";", "}", "}" ]
文字列とオブジェクトを相互変換するフォーマッタを取得します。 <p>アノテーション{@link CsvFormat}が指定されている場合は、そちらを優先します。</p> @param field フィールド情報 @param config システム設定 @return フォーマッタを取得します。
[ "文字列とオブジェクトを相互変換するフォーマッタを取得します。", "<p", ">", "アノテーション", "{" ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/builder/AbstractProcessorBuilder.java#L226-L242
tvesalainen/util
rpm/src/main/java/org/vesalainen/pm/rpm/RPMBuilder.java
RPMBuilder.addConflict
@Override public RPMBuilder addConflict(String name, String version, Condition... dependency) { """ Add RPMTAG_CONFLICTNAME, RPMTAG_CONFLICTVERSION and RPMTAG_CONFLICTFLAGS @param name @param version @param dependency @return """ addString(RPMTAG_CONFLICTNAME, name); addString(RPMTAG_CONFLICTVERSION, version); addInt32(RPMTAG_CONFLICTFLAGS, Dependency.or(dependency)); ensureVersionReq(version); return this; }
java
@Override public RPMBuilder addConflict(String name, String version, Condition... dependency) { addString(RPMTAG_CONFLICTNAME, name); addString(RPMTAG_CONFLICTVERSION, version); addInt32(RPMTAG_CONFLICTFLAGS, Dependency.or(dependency)); ensureVersionReq(version); return this; }
[ "@", "Override", "public", "RPMBuilder", "addConflict", "(", "String", "name", ",", "String", "version", ",", "Condition", "...", "dependency", ")", "{", "addString", "(", "RPMTAG_CONFLICTNAME", ",", "name", ")", ";", "addString", "(", "RPMTAG_CONFLICTVERSION", ",", "version", ")", ";", "addInt32", "(", "RPMTAG_CONFLICTFLAGS", ",", "Dependency", ".", "or", "(", "dependency", ")", ")", ";", "ensureVersionReq", "(", "version", ")", ";", "return", "this", ";", "}" ]
Add RPMTAG_CONFLICTNAME, RPMTAG_CONFLICTVERSION and RPMTAG_CONFLICTFLAGS @param name @param version @param dependency @return
[ "Add", "RPMTAG_CONFLICTNAME", "RPMTAG_CONFLICTVERSION", "and", "RPMTAG_CONFLICTFLAGS" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/rpm/src/main/java/org/vesalainen/pm/rpm/RPMBuilder.java#L295-L303
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPlot.java
SVGPlot.makeAWTImage
public BufferedImage makeAWTImage(int width, int height) throws TranscoderException { """ Convert the SVG to a thumbnail image. @param width Width of thumbnail @param height Height of thumbnail @return Buffered image """ ThumbnailTranscoder t = new ThumbnailTranscoder(); t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(width)); t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(height)); // Don't clone. Assume this is used safely. TranscoderInput input = new TranscoderInput(document); t.transcode(input, null); return t.getLastImage(); }
java
public BufferedImage makeAWTImage(int width, int height) throws TranscoderException { ThumbnailTranscoder t = new ThumbnailTranscoder(); t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(width)); t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(height)); // Don't clone. Assume this is used safely. TranscoderInput input = new TranscoderInput(document); t.transcode(input, null); return t.getLastImage(); }
[ "public", "BufferedImage", "makeAWTImage", "(", "int", "width", ",", "int", "height", ")", "throws", "TranscoderException", "{", "ThumbnailTranscoder", "t", "=", "new", "ThumbnailTranscoder", "(", ")", ";", "t", ".", "addTranscodingHint", "(", "PNGTranscoder", ".", "KEY_WIDTH", ",", "new", "Float", "(", "width", ")", ")", ";", "t", ".", "addTranscodingHint", "(", "PNGTranscoder", ".", "KEY_HEIGHT", ",", "new", "Float", "(", "height", ")", ")", ";", "// Don't clone. Assume this is used safely.", "TranscoderInput", "input", "=", "new", "TranscoderInput", "(", "document", ")", ";", "t", ".", "transcode", "(", "input", ",", "null", ")", ";", "return", "t", ".", "getLastImage", "(", ")", ";", "}" ]
Convert the SVG to a thumbnail image. @param width Width of thumbnail @param height Height of thumbnail @return Buffered image
[ "Convert", "the", "SVG", "to", "a", "thumbnail", "image", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPlot.java#L599-L607
derari/cthul
objects/src/main/java/org/cthul/objects/reflection/Signatures.java
Signatures.candidateMethods
public static Method[] candidateMethods(Method[] methods, Object[] args) { """ Selects the best equally-matching methods for the given arguments. @param methods @param args @return methods """ return candidateMethods(methods, collectArgTypes(args)); }
java
public static Method[] candidateMethods(Method[] methods, Object[] args) { return candidateMethods(methods, collectArgTypes(args)); }
[ "public", "static", "Method", "[", "]", "candidateMethods", "(", "Method", "[", "]", "methods", ",", "Object", "[", "]", "args", ")", "{", "return", "candidateMethods", "(", "methods", ",", "collectArgTypes", "(", "args", ")", ")", ";", "}" ]
Selects the best equally-matching methods for the given arguments. @param methods @param args @return methods
[ "Selects", "the", "best", "equally", "-", "matching", "methods", "for", "the", "given", "arguments", "." ]
train
https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/objects/src/main/java/org/cthul/objects/reflection/Signatures.java#L197-L199
rterp/GMapsFX
GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptObject.java
JavascriptObject.invokeJavascript
protected Object invokeJavascript(String function, Object... args) { """ Invoke the specified JavaScript function in the JavaScript runtime. @param function The function to invoke @param args Any arguments to pass to the function @return The result of the function. """ Object[] jsArgs = new Object[args.length]; for (int i = 0; i < jsArgs.length; i++) { if (args[i] instanceof JavascriptObject) { jsArgs[i] = ((JavascriptObject) args[i]).getJSObject(); } else if (args[i] instanceof JavascriptEnum) { jsArgs[i] = ((JavascriptEnum) args[i]).getEnumValue(); } else { jsArgs[i] = args[i]; } } return checkUndefined(jsObject.call(function, (Object[]) jsArgs)); }
java
protected Object invokeJavascript(String function, Object... args) { Object[] jsArgs = new Object[args.length]; for (int i = 0; i < jsArgs.length; i++) { if (args[i] instanceof JavascriptObject) { jsArgs[i] = ((JavascriptObject) args[i]).getJSObject(); } else if (args[i] instanceof JavascriptEnum) { jsArgs[i] = ((JavascriptEnum) args[i]).getEnumValue(); } else { jsArgs[i] = args[i]; } } return checkUndefined(jsObject.call(function, (Object[]) jsArgs)); }
[ "protected", "Object", "invokeJavascript", "(", "String", "function", ",", "Object", "...", "args", ")", "{", "Object", "[", "]", "jsArgs", "=", "new", "Object", "[", "args", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "jsArgs", ".", "length", ";", "i", "++", ")", "{", "if", "(", "args", "[", "i", "]", "instanceof", "JavascriptObject", ")", "{", "jsArgs", "[", "i", "]", "=", "(", "(", "JavascriptObject", ")", "args", "[", "i", "]", ")", ".", "getJSObject", "(", ")", ";", "}", "else", "if", "(", "args", "[", "i", "]", "instanceof", "JavascriptEnum", ")", "{", "jsArgs", "[", "i", "]", "=", "(", "(", "JavascriptEnum", ")", "args", "[", "i", "]", ")", ".", "getEnumValue", "(", ")", ";", "}", "else", "{", "jsArgs", "[", "i", "]", "=", "args", "[", "i", "]", ";", "}", "}", "return", "checkUndefined", "(", "jsObject", ".", "call", "(", "function", ",", "(", "Object", "[", "]", ")", "jsArgs", ")", ")", ";", "}" ]
Invoke the specified JavaScript function in the JavaScript runtime. @param function The function to invoke @param args Any arguments to pass to the function @return The result of the function.
[ "Invoke", "the", "specified", "JavaScript", "function", "in", "the", "JavaScript", "runtime", "." ]
train
https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptObject.java#L219-L231
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/util/ByteArrayReader.java
ByteArrayReader.readInt
public static long readInt(byte[] data, int start) { """ Read an integer (4 bytes) from the array. This is returned as a long as we deal with unsigned ints so the value may be higher than the standard java int. @param data @param start @return the value represent by a long. """ long ret = (((long) (data[start] & 0xFF) << 24) & 0xFFFFFFFFL) | ((data[start + 1] & 0xFF) << 16) | ((data[start + 2] & 0xFF) << 8) | ((data[start + 3] & 0xFF) << 0); return ret; }
java
public static long readInt(byte[] data, int start) { long ret = (((long) (data[start] & 0xFF) << 24) & 0xFFFFFFFFL) | ((data[start + 1] & 0xFF) << 16) | ((data[start + 2] & 0xFF) << 8) | ((data[start + 3] & 0xFF) << 0); return ret; }
[ "public", "static", "long", "readInt", "(", "byte", "[", "]", "data", ",", "int", "start", ")", "{", "long", "ret", "=", "(", "(", "(", "long", ")", "(", "data", "[", "start", "]", "&", "0xFF", ")", "<<", "24", ")", "&", "0xFFFFFFFF", "L", ")", "|", "(", "(", "data", "[", "start", "+", "1", "]", "&", "0xFF", ")", "<<", "16", ")", "|", "(", "(", "data", "[", "start", "+", "2", "]", "&", "0xFF", ")", "<<", "8", ")", "|", "(", "(", "data", "[", "start", "+", "3", "]", "&", "0xFF", ")", "<<", "0", ")", ";", "return", "ret", ";", "}" ]
Read an integer (4 bytes) from the array. This is returned as a long as we deal with unsigned ints so the value may be higher than the standard java int. @param data @param start @return the value represent by a long.
[ "Read", "an", "integer", "(", "4", "bytes", ")", "from", "the", "array", ".", "This", "is", "returned", "as", "a", "long", "as", "we", "deal", "with", "unsigned", "ints", "so", "the", "value", "may", "be", "higher", "than", "the", "standard", "java", "int", "." ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/util/ByteArrayReader.java#L170-L177
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/instance/InstanceTypeFactory.java
InstanceTypeFactory.constructFromDescription
public static InstanceType constructFromDescription(String description) { """ Constructs an {@link InstanceType} object by parsing a hardware description string. @param description the hardware description reflected by this instance type @return an instance type reflecting the given hardware description or <code>null</code> if the description cannot be parsed """ final Matcher m = INSTANCE_TYPE_PATTERN.matcher(description); if (!m.matches()) { LOG.error("Cannot extract instance type from string " + description); return null; } final String identifier = m.group(1); final int numComputeUnits = Integer.parseInt(m.group(2)); final int numCores = Integer.parseInt(m.group(3)); final int memorySize = Integer.parseInt(m.group(4)); final int diskCapacity = Integer.parseInt(m.group(5)); final int pricePerHour = Integer.parseInt(m.group(6)); return new InstanceType(identifier, numComputeUnits, numCores, memorySize, diskCapacity, pricePerHour); }
java
public static InstanceType constructFromDescription(String description) { final Matcher m = INSTANCE_TYPE_PATTERN.matcher(description); if (!m.matches()) { LOG.error("Cannot extract instance type from string " + description); return null; } final String identifier = m.group(1); final int numComputeUnits = Integer.parseInt(m.group(2)); final int numCores = Integer.parseInt(m.group(3)); final int memorySize = Integer.parseInt(m.group(4)); final int diskCapacity = Integer.parseInt(m.group(5)); final int pricePerHour = Integer.parseInt(m.group(6)); return new InstanceType(identifier, numComputeUnits, numCores, memorySize, diskCapacity, pricePerHour); }
[ "public", "static", "InstanceType", "constructFromDescription", "(", "String", "description", ")", "{", "final", "Matcher", "m", "=", "INSTANCE_TYPE_PATTERN", ".", "matcher", "(", "description", ")", ";", "if", "(", "!", "m", ".", "matches", "(", ")", ")", "{", "LOG", ".", "error", "(", "\"Cannot extract instance type from string \"", "+", "description", ")", ";", "return", "null", ";", "}", "final", "String", "identifier", "=", "m", ".", "group", "(", "1", ")", ";", "final", "int", "numComputeUnits", "=", "Integer", ".", "parseInt", "(", "m", ".", "group", "(", "2", ")", ")", ";", "final", "int", "numCores", "=", "Integer", ".", "parseInt", "(", "m", ".", "group", "(", "3", ")", ")", ";", "final", "int", "memorySize", "=", "Integer", ".", "parseInt", "(", "m", ".", "group", "(", "4", ")", ")", ";", "final", "int", "diskCapacity", "=", "Integer", ".", "parseInt", "(", "m", ".", "group", "(", "5", ")", ")", ";", "final", "int", "pricePerHour", "=", "Integer", ".", "parseInt", "(", "m", ".", "group", "(", "6", ")", ")", ";", "return", "new", "InstanceType", "(", "identifier", ",", "numComputeUnits", ",", "numCores", ",", "memorySize", ",", "diskCapacity", ",", "pricePerHour", ")", ";", "}" ]
Constructs an {@link InstanceType} object by parsing a hardware description string. @param description the hardware description reflected by this instance type @return an instance type reflecting the given hardware description or <code>null</code> if the description cannot be parsed
[ "Constructs", "an", "{", "@link", "InstanceType", "}", "object", "by", "parsing", "a", "hardware", "description", "string", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/instance/InstanceTypeFactory.java#L52-L68
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderItemPersistenceImpl.java
CommerceOrderItemPersistenceImpl.findByC_S
@Override public List<CommerceOrderItem> findByC_S(long commerceOrderId, boolean subscription, int start, int end) { """ Returns a range of all the commerce order items where commerceOrderId = &#63; and subscription = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderItemModelImpl}. 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 commerceOrderId the commerce order ID @param subscription the subscription @param start the lower bound of the range of commerce order items @param end the upper bound of the range of commerce order items (not inclusive) @return the range of matching commerce order items """ return findByC_S(commerceOrderId, subscription, start, end, null); }
java
@Override public List<CommerceOrderItem> findByC_S(long commerceOrderId, boolean subscription, int start, int end) { return findByC_S(commerceOrderId, subscription, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceOrderItem", ">", "findByC_S", "(", "long", "commerceOrderId", ",", "boolean", "subscription", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByC_S", "(", "commerceOrderId", ",", "subscription", ",", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce order items where commerceOrderId = &#63; and subscription = &#63;. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceOrderItemModelImpl}. 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 commerceOrderId the commerce order ID @param subscription the subscription @param start the lower bound of the range of commerce order items @param end the upper bound of the range of commerce order items (not inclusive) @return the range of matching commerce order items
[ "Returns", "a", "range", "of", "all", "the", "commerce", "order", "items", "where", "commerceOrderId", "=", "&#63", ";", "and", "subscription", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderItemPersistenceImpl.java#L2245-L2249
VoltDB/voltdb
src/frontend/org/voltdb/expressions/ExpressionUtil.java
ExpressionUtil.buildEquavalenceExpression
public static AbstractExpression buildEquavalenceExpression(Collection<AbstractExpression> leftExprs, Collection<AbstractExpression> rightExprs) { """ Given two equal length lists of the expressions build a combined equivalence expression (le1, le2,..., leN) (re1, re2,..., reN) => (le1=re1) AND (le2=re2) AND .... AND (leN=reN) @param leftExprs @param rightExprs @return AbstractExpression """ assert(leftExprs.size() == rightExprs.size()); Iterator<AbstractExpression> leftIt = leftExprs.iterator(); Iterator<AbstractExpression> rightIt = rightExprs.iterator(); AbstractExpression result = null; while (leftIt.hasNext() && rightIt.hasNext()) { AbstractExpression leftExpr = leftIt.next(); AbstractExpression rightExpr = rightIt.next(); AbstractExpression eqaulityExpr = new ComparisonExpression(ExpressionType.COMPARE_EQUAL, leftExpr, rightExpr); if (result == null) { result = eqaulityExpr; } else { result = new ConjunctionExpression(ExpressionType.CONJUNCTION_AND, result, eqaulityExpr); } } return result; }
java
public static AbstractExpression buildEquavalenceExpression(Collection<AbstractExpression> leftExprs, Collection<AbstractExpression> rightExprs) { assert(leftExprs.size() == rightExprs.size()); Iterator<AbstractExpression> leftIt = leftExprs.iterator(); Iterator<AbstractExpression> rightIt = rightExprs.iterator(); AbstractExpression result = null; while (leftIt.hasNext() && rightIt.hasNext()) { AbstractExpression leftExpr = leftIt.next(); AbstractExpression rightExpr = rightIt.next(); AbstractExpression eqaulityExpr = new ComparisonExpression(ExpressionType.COMPARE_EQUAL, leftExpr, rightExpr); if (result == null) { result = eqaulityExpr; } else { result = new ConjunctionExpression(ExpressionType.CONJUNCTION_AND, result, eqaulityExpr); } } return result; }
[ "public", "static", "AbstractExpression", "buildEquavalenceExpression", "(", "Collection", "<", "AbstractExpression", ">", "leftExprs", ",", "Collection", "<", "AbstractExpression", ">", "rightExprs", ")", "{", "assert", "(", "leftExprs", ".", "size", "(", ")", "==", "rightExprs", ".", "size", "(", ")", ")", ";", "Iterator", "<", "AbstractExpression", ">", "leftIt", "=", "leftExprs", ".", "iterator", "(", ")", ";", "Iterator", "<", "AbstractExpression", ">", "rightIt", "=", "rightExprs", ".", "iterator", "(", ")", ";", "AbstractExpression", "result", "=", "null", ";", "while", "(", "leftIt", ".", "hasNext", "(", ")", "&&", "rightIt", ".", "hasNext", "(", ")", ")", "{", "AbstractExpression", "leftExpr", "=", "leftIt", ".", "next", "(", ")", ";", "AbstractExpression", "rightExpr", "=", "rightIt", ".", "next", "(", ")", ";", "AbstractExpression", "eqaulityExpr", "=", "new", "ComparisonExpression", "(", "ExpressionType", ".", "COMPARE_EQUAL", ",", "leftExpr", ",", "rightExpr", ")", ";", "if", "(", "result", "==", "null", ")", "{", "result", "=", "eqaulityExpr", ";", "}", "else", "{", "result", "=", "new", "ConjunctionExpression", "(", "ExpressionType", ".", "CONJUNCTION_AND", ",", "result", ",", "eqaulityExpr", ")", ";", "}", "}", "return", "result", ";", "}" ]
Given two equal length lists of the expressions build a combined equivalence expression (le1, le2,..., leN) (re1, re2,..., reN) => (le1=re1) AND (le2=re2) AND .... AND (leN=reN) @param leftExprs @param rightExprs @return AbstractExpression
[ "Given", "two", "equal", "length", "lists", "of", "the", "expressions", "build", "a", "combined", "equivalence", "expression", "(", "le1", "le2", "...", "leN", ")", "(", "re1", "re2", "...", "reN", ")", "=", ">", "(", "le1", "=", "re1", ")", "AND", "(", "le2", "=", "re2", ")", "AND", "....", "AND", "(", "leN", "=", "reN", ")" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/expressions/ExpressionUtil.java#L697-L713
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/Config.java
Config.copyConfiguration
public static Configuration copyConfiguration(final Configuration original) { """ Creates a deep-copy of the given configuration. This is useful for unit-testing. @param original the configuration to copy. @return a copy of the given configuration. """ Configuration copy = new MapConfiguration(new HashMap<String, Object>()); for (Iterator<?> i = original.getKeys(); i.hasNext();) { String key = (String) i.next(); Object value = original.getProperty(key); if (value instanceof List) { value = new ArrayList((List) value); } copy.setProperty(key, value); } return copy; }
java
public static Configuration copyConfiguration(final Configuration original) { Configuration copy = new MapConfiguration(new HashMap<String, Object>()); for (Iterator<?> i = original.getKeys(); i.hasNext();) { String key = (String) i.next(); Object value = original.getProperty(key); if (value instanceof List) { value = new ArrayList((List) value); } copy.setProperty(key, value); } return copy; }
[ "public", "static", "Configuration", "copyConfiguration", "(", "final", "Configuration", "original", ")", "{", "Configuration", "copy", "=", "new", "MapConfiguration", "(", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ")", ";", "for", "(", "Iterator", "<", "?", ">", "i", "=", "original", ".", "getKeys", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "String", "key", "=", "(", "String", ")", "i", ".", "next", "(", ")", ";", "Object", "value", "=", "original", ".", "getProperty", "(", "key", ")", ";", "if", "(", "value", "instanceof", "List", ")", "{", "value", "=", "new", "ArrayList", "(", "(", "List", ")", "value", ")", ";", "}", "copy", ".", "setProperty", "(", "key", ",", "value", ")", ";", "}", "return", "copy", ";", "}" ]
Creates a deep-copy of the given configuration. This is useful for unit-testing. @param original the configuration to copy. @return a copy of the given configuration.
[ "Creates", "a", "deep", "-", "copy", "of", "the", "given", "configuration", ".", "This", "is", "useful", "for", "unit", "-", "testing", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/Config.java#L98-L113
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/BinaryString.java
BinaryString.fromAddress
public static BinaryString fromAddress( MemorySegment[] segments, int offset, int numBytes) { """ Creates an BinaryString from given address (base and offset) and length. """ return new BinaryString(segments, offset, numBytes); }
java
public static BinaryString fromAddress( MemorySegment[] segments, int offset, int numBytes) { return new BinaryString(segments, offset, numBytes); }
[ "public", "static", "BinaryString", "fromAddress", "(", "MemorySegment", "[", "]", "segments", ",", "int", "offset", ",", "int", "numBytes", ")", "{", "return", "new", "BinaryString", "(", "segments", ",", "offset", ",", "numBytes", ")", ";", "}" ]
Creates an BinaryString from given address (base and offset) and length.
[ "Creates", "an", "BinaryString", "from", "given", "address", "(", "base", "and", "offset", ")", "and", "length", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/BinaryString.java#L69-L72
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountBatchConfigurationsInner.java
IntegrationAccountBatchConfigurationsInner.createOrUpdateAsync
public Observable<BatchConfigurationInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String batchConfigurationName, BatchConfigurationInner batchConfiguration) { """ Create or update a batch configuration for an integration account. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param batchConfigurationName The batch configuration name. @param batchConfiguration The batch configuration. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BatchConfigurationInner object """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, batchConfigurationName, batchConfiguration).map(new Func1<ServiceResponse<BatchConfigurationInner>, BatchConfigurationInner>() { @Override public BatchConfigurationInner call(ServiceResponse<BatchConfigurationInner> response) { return response.body(); } }); }
java
public Observable<BatchConfigurationInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String batchConfigurationName, BatchConfigurationInner batchConfiguration) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, batchConfigurationName, batchConfiguration).map(new Func1<ServiceResponse<BatchConfigurationInner>, BatchConfigurationInner>() { @Override public BatchConfigurationInner call(ServiceResponse<BatchConfigurationInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "BatchConfigurationInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "batchConfigurationName", ",", "BatchConfigurationInner", "batchConfiguration", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "integrationAccountName", ",", "batchConfigurationName", ",", "batchConfiguration", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "BatchConfigurationInner", ">", ",", "BatchConfigurationInner", ">", "(", ")", "{", "@", "Override", "public", "BatchConfigurationInner", "call", "(", "ServiceResponse", "<", "BatchConfigurationInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create or update a batch configuration for an integration account. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param batchConfigurationName The batch configuration name. @param batchConfiguration The batch configuration. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the BatchConfigurationInner object
[ "Create", "or", "update", "a", "batch", "configuration", "for", "an", "integration", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountBatchConfigurationsInner.java#L302-L309
davidmoten/rxjava-extras
src/main/java/com/github/davidmoten/rx/Transformers.java
Transformers.toListWhile
public static <T> Transformer<T, List<T>> toListWhile( final Func2<? super List<T>, ? super T, Boolean> condition) { """ <p> Returns a {@link Transformer} that returns an {@link Observable} that is a buffering of the source Observable into lists of sequential items that satisfy the condition {@code condition}. <p> <img src= "https://github.com/davidmoten/rxjava-extras/blob/master/src/docs/toListWhile.png?raw=true" alt="marble diagram"> @param condition condition function that must return true if an item is to be part of the list being prepared for emission @param <T> the generic type of the source Observable @return transformer as above """ Func0<List<T>> initialState = new Func0<List<T>>() { @Override public List<T> call() { return new ArrayList<T>(); } }; Action2<List<T>, T> collect = new Action2<List<T>, T>() { @Override public void call(List<T> list, T n) { list.add(n); } }; return collectWhile(initialState, collect, condition); }
java
public static <T> Transformer<T, List<T>> toListWhile( final Func2<? super List<T>, ? super T, Boolean> condition) { Func0<List<T>> initialState = new Func0<List<T>>() { @Override public List<T> call() { return new ArrayList<T>(); } }; Action2<List<T>, T> collect = new Action2<List<T>, T>() { @Override public void call(List<T> list, T n) { list.add(n); } }; return collectWhile(initialState, collect, condition); }
[ "public", "static", "<", "T", ">", "Transformer", "<", "T", ",", "List", "<", "T", ">", ">", "toListWhile", "(", "final", "Func2", "<", "?", "super", "List", "<", "T", ">", ",", "?", "super", "T", ",", "Boolean", ">", "condition", ")", "{", "Func0", "<", "List", "<", "T", ">>", "initialState", "=", "new", "Func0", "<", "List", "<", "T", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "T", ">", "call", "(", ")", "{", "return", "new", "ArrayList", "<", "T", ">", "(", ")", ";", "}", "}", ";", "Action2", "<", "List", "<", "T", ">", ",", "T", ">", "collect", "=", "new", "Action2", "<", "List", "<", "T", ">", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "call", "(", "List", "<", "T", ">", "list", ",", "T", "n", ")", "{", "list", ".", "add", "(", "n", ")", ";", "}", "}", ";", "return", "collectWhile", "(", "initialState", ",", "collect", ",", "condition", ")", ";", "}" ]
<p> Returns a {@link Transformer} that returns an {@link Observable} that is a buffering of the source Observable into lists of sequential items that satisfy the condition {@code condition}. <p> <img src= "https://github.com/davidmoten/rxjava-extras/blob/master/src/docs/toListWhile.png?raw=true" alt="marble diagram"> @param condition condition function that must return true if an item is to be part of the list being prepared for emission @param <T> the generic type of the source Observable @return transformer as above
[ "<p", ">", "Returns", "a", "{", "@link", "Transformer", "}", "that", "returns", "an", "{", "@link", "Observable", "}", "that", "is", "a", "buffering", "of", "the", "source", "Observable", "into", "lists", "of", "sequential", "items", "that", "satisfy", "the", "condition", "{", "@code", "condition", "}", "." ]
train
https://github.com/davidmoten/rxjava-extras/blob/a91d2ba7d454843250e0b0fce36084f9fb02a551/src/main/java/com/github/davidmoten/rx/Transformers.java#L497-L515
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/multilayer/SparkDl4jMultiLayer.java
SparkDl4jMultiLayer.scoreExamples
public JavaDoubleRDD scoreExamples(JavaRDD<DataSet> data, boolean includeRegularizationTerms) { """ Score the examples individually, using the default batch size {@link #DEFAULT_EVAL_SCORE_BATCH_SIZE}. Unlike {@link #calculateScore(JavaRDD, boolean)}, this method returns a score for each example separately. If scoring is needed for specific examples use either {@link #scoreExamples(JavaPairRDD, boolean)} or {@link #scoreExamples(JavaPairRDD, boolean, int)} which can have a key for each example. @param data Data to score @param includeRegularizationTerms If true: include the l1/l2 regularization terms with the score (if any) @return A JavaDoubleRDD containing the scores of each example @see MultiLayerNetwork#scoreExamples(DataSet, boolean) """ return scoreExamples(data, includeRegularizationTerms, DEFAULT_EVAL_SCORE_BATCH_SIZE); }
java
public JavaDoubleRDD scoreExamples(JavaRDD<DataSet> data, boolean includeRegularizationTerms) { return scoreExamples(data, includeRegularizationTerms, DEFAULT_EVAL_SCORE_BATCH_SIZE); }
[ "public", "JavaDoubleRDD", "scoreExamples", "(", "JavaRDD", "<", "DataSet", ">", "data", ",", "boolean", "includeRegularizationTerms", ")", "{", "return", "scoreExamples", "(", "data", ",", "includeRegularizationTerms", ",", "DEFAULT_EVAL_SCORE_BATCH_SIZE", ")", ";", "}" ]
Score the examples individually, using the default batch size {@link #DEFAULT_EVAL_SCORE_BATCH_SIZE}. Unlike {@link #calculateScore(JavaRDD, boolean)}, this method returns a score for each example separately. If scoring is needed for specific examples use either {@link #scoreExamples(JavaPairRDD, boolean)} or {@link #scoreExamples(JavaPairRDD, boolean, int)} which can have a key for each example. @param data Data to score @param includeRegularizationTerms If true: include the l1/l2 regularization terms with the score (if any) @return A JavaDoubleRDD containing the scores of each example @see MultiLayerNetwork#scoreExamples(DataSet, boolean)
[ "Score", "the", "examples", "individually", "using", "the", "default", "batch", "size", "{", "@link", "#DEFAULT_EVAL_SCORE_BATCH_SIZE", "}", ".", "Unlike", "{", "@link", "#calculateScore", "(", "JavaRDD", "boolean", ")", "}", "this", "method", "returns", "a", "score", "for", "each", "example", "separately", ".", "If", "scoring", "is", "needed", "for", "specific", "examples", "use", "either", "{", "@link", "#scoreExamples", "(", "JavaPairRDD", "boolean", ")", "}", "or", "{", "@link", "#scoreExamples", "(", "JavaPairRDD", "boolean", "int", ")", "}", "which", "can", "have", "a", "key", "for", "each", "example", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/multilayer/SparkDl4jMultiLayer.java#L410-L412
xetorthio/jedis
src/main/java/redis/clients/jedis/BinaryJedis.java
BinaryJedis.smove
@Override public Long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { """ Move the specified member from the set at srckey to the set at dstkey. This operation is atomic, in every given moment the element will appear to be in the source or destination set for accessing clients. <p> If the source set does not exist or does not contain the specified element no operation is performed and zero is returned, otherwise the element is removed from the source set and added to the destination set. On success one is returned, even if the element was already present in the destination set. <p> An error is raised if the source or destination keys contain a non Set value. <p> Time complexity O(1) @param srckey @param dstkey @param member @return Integer reply, specifically: 1 if the element was moved 0 if the element was not found on the first set and no operation was performed """ checkIsInMultiOrPipeline(); client.smove(srckey, dstkey, member); return client.getIntegerReply(); }
java
@Override public Long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { checkIsInMultiOrPipeline(); client.smove(srckey, dstkey, member); return client.getIntegerReply(); }
[ "@", "Override", "public", "Long", "smove", "(", "final", "byte", "[", "]", "srckey", ",", "final", "byte", "[", "]", "dstkey", ",", "final", "byte", "[", "]", "member", ")", "{", "checkIsInMultiOrPipeline", "(", ")", ";", "client", ".", "smove", "(", "srckey", ",", "dstkey", ",", "member", ")", ";", "return", "client", ".", "getIntegerReply", "(", ")", ";", "}" ]
Move the specified member from the set at srckey to the set at dstkey. This operation is atomic, in every given moment the element will appear to be in the source or destination set for accessing clients. <p> If the source set does not exist or does not contain the specified element no operation is performed and zero is returned, otherwise the element is removed from the source set and added to the destination set. On success one is returned, even if the element was already present in the destination set. <p> An error is raised if the source or destination keys contain a non Set value. <p> Time complexity O(1) @param srckey @param dstkey @param member @return Integer reply, specifically: 1 if the element was moved 0 if the element was not found on the first set and no operation was performed
[ "Move", "the", "specified", "member", "from", "the", "set", "at", "srckey", "to", "the", "set", "at", "dstkey", ".", "This", "operation", "is", "atomic", "in", "every", "given", "moment", "the", "element", "will", "appear", "to", "be", "in", "the", "source", "or", "destination", "set", "for", "accessing", "clients", ".", "<p", ">", "If", "the", "source", "set", "does", "not", "exist", "or", "does", "not", "contain", "the", "specified", "element", "no", "operation", "is", "performed", "and", "zero", "is", "returned", "otherwise", "the", "element", "is", "removed", "from", "the", "source", "set", "and", "added", "to", "the", "destination", "set", ".", "On", "success", "one", "is", "returned", "even", "if", "the", "element", "was", "already", "present", "in", "the", "destination", "set", ".", "<p", ">", "An", "error", "is", "raised", "if", "the", "source", "or", "destination", "keys", "contain", "a", "non", "Set", "value", ".", "<p", ">", "Time", "complexity", "O", "(", "1", ")" ]
train
https://github.com/xetorthio/jedis/blob/ef4ab403f9d8fd88bd05092fea96de2e9db0bede/src/main/java/redis/clients/jedis/BinaryJedis.java#L1466-L1471
google/closure-compiler
src/com/google/javascript/rhino/HamtPMap.java
HamtPMap.equivalent
@Override public boolean equivalent(PMap<K, V> that, BiPredicate<V, V> equivalence) { """ Checks equality recursively based on the given equivalence. Short-circuits as soon as a 'false' result is found. """ return equivalent( !this.isEmpty() ? this : null, !that.isEmpty() ? (HamtPMap<K, V>) that : null, equivalence); }
java
@Override public boolean equivalent(PMap<K, V> that, BiPredicate<V, V> equivalence) { return equivalent( !this.isEmpty() ? this : null, !that.isEmpty() ? (HamtPMap<K, V>) that : null, equivalence); }
[ "@", "Override", "public", "boolean", "equivalent", "(", "PMap", "<", "K", ",", "V", ">", "that", ",", "BiPredicate", "<", "V", ",", "V", ">", "equivalence", ")", "{", "return", "equivalent", "(", "!", "this", ".", "isEmpty", "(", ")", "?", "this", ":", "null", ",", "!", "that", ".", "isEmpty", "(", ")", "?", "(", "HamtPMap", "<", "K", ",", "V", ">", ")", "that", ":", "null", ",", "equivalence", ")", ";", "}" ]
Checks equality recursively based on the given equivalence. Short-circuits as soon as a 'false' result is found.
[ "Checks", "equality", "recursively", "based", "on", "the", "given", "equivalence", ".", "Short", "-", "circuits", "as", "soon", "as", "a", "false", "result", "is", "found", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/HamtPMap.java#L375-L379
wisdom-framework/wisdom
extensions/wisdom-raml/wisdom-source-watcher/src/main/java/org/wisdom/source/ast/util/ExtractUtil.java
ExtractUtil.extractValueByName
public static String extractValueByName(List<MemberValuePair> pairs, String name) { """ Get the value of a {@link MemberValuePair} present in a list from its name. @param pairs The list of MemberValuePair @param name The name of the MemberValuePair we want to get the value from. @return The value of the MemberValuePair of given name, or null if it's not present in the list. """ for(MemberValuePair pair : pairs){ if(pair.getName().equals(name)){ return pair.getValue().toString(); } } return null; }
java
public static String extractValueByName(List<MemberValuePair> pairs, String name){ for(MemberValuePair pair : pairs){ if(pair.getName().equals(name)){ return pair.getValue().toString(); } } return null; }
[ "public", "static", "String", "extractValueByName", "(", "List", "<", "MemberValuePair", ">", "pairs", ",", "String", "name", ")", "{", "for", "(", "MemberValuePair", "pair", ":", "pairs", ")", "{", "if", "(", "pair", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "return", "pair", ".", "getValue", "(", ")", ".", "toString", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Get the value of a {@link MemberValuePair} present in a list from its name. @param pairs The list of MemberValuePair @param name The name of the MemberValuePair we want to get the value from. @return The value of the MemberValuePair of given name, or null if it's not present in the list.
[ "Get", "the", "value", "of", "a", "{", "@link", "MemberValuePair", "}", "present", "in", "a", "list", "from", "its", "name", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-raml/wisdom-source-watcher/src/main/java/org/wisdom/source/ast/util/ExtractUtil.java#L242-L249
joniles/mpxj
src/main/java/net/sf/mpxj/fasttrack/FastTrackData.java
FastTrackData.logColumnData
private void logColumnData(int startIndex, int length) { """ Log the data for a single column. @param startIndex offset into buffer @param length length """ if (m_log != null) { m_log.println(); m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, length, true, 16, "")); m_log.println(); m_log.flush(); } }
java
private void logColumnData(int startIndex, int length) { if (m_log != null) { m_log.println(); m_log.println(FastTrackUtility.hexdump(m_buffer, startIndex, length, true, 16, "")); m_log.println(); m_log.flush(); } }
[ "private", "void", "logColumnData", "(", "int", "startIndex", ",", "int", "length", ")", "{", "if", "(", "m_log", "!=", "null", ")", "{", "m_log", ".", "println", "(", ")", ";", "m_log", ".", "println", "(", "FastTrackUtility", ".", "hexdump", "(", "m_buffer", ",", "startIndex", ",", "length", ",", "true", ",", "16", ",", "\"\"", ")", ")", ";", "m_log", ".", "println", "(", ")", ";", "m_log", ".", "flush", "(", ")", ";", "}", "}" ]
Log the data for a single column. @param startIndex offset into buffer @param length length
[ "Log", "the", "data", "for", "a", "single", "column", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/fasttrack/FastTrackData.java#L454-L463
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/stats/Distribution.java
Distribution.goodTuringWithExplicitUnknown
public static <E> Distribution<E> goodTuringWithExplicitUnknown(Counter<E> counter, E UNK) { """ Creates a Good-Turing smoothed Distribution from the given counter without creating any reserved mass-- instead, the special object UNK in the counter is assumed to be the count of "UNSEEN" items. Probability of objects not in original counter will be zero. @param counter the counter @param UNK the unknown symbol @return a good-turing smoothed distribution """ // gather count-counts int[] countCounts = getCountCounts(counter); // if count-counts are unreliable, we shouldn't be using G-T // revert to laplace for (int i = 1; i <= 10; i++) { if (countCounts[i] < 3) { return laplaceWithExplicitUnknown(counter, 0.5, UNK); } } double observedMass = counter.totalCount(); // calculate and cache adjusted frequencies // also adjusting total mass of observed items double[] adjustedFreq = new double[10]; for (int freq = 1; freq < 10; freq++) { adjustedFreq[freq] = (double) (freq + 1) * (double) countCounts[freq + 1] / countCounts[freq]; observedMass -= (freq - adjustedFreq[freq]) * countCounts[freq]; } Distribution<E> norm = new Distribution<E>(); norm.counter = new ClassicCounter<E>(); // fill in the new Distribution, renormalizing as we go for (E key : counter.keySet()) { int origFreq = (int) Math.round(counter.getCount(key)); if (origFreq < 10) { norm.counter.setCount(key, adjustedFreq[origFreq] / observedMass); } else { norm.counter.setCount(key, origFreq / observedMass); } } norm.numberOfKeys = counter.size(); norm.reservedMass = 0.0; return norm; }
java
public static <E> Distribution<E> goodTuringWithExplicitUnknown(Counter<E> counter, E UNK) { // gather count-counts int[] countCounts = getCountCounts(counter); // if count-counts are unreliable, we shouldn't be using G-T // revert to laplace for (int i = 1; i <= 10; i++) { if (countCounts[i] < 3) { return laplaceWithExplicitUnknown(counter, 0.5, UNK); } } double observedMass = counter.totalCount(); // calculate and cache adjusted frequencies // also adjusting total mass of observed items double[] adjustedFreq = new double[10]; for (int freq = 1; freq < 10; freq++) { adjustedFreq[freq] = (double) (freq + 1) * (double) countCounts[freq + 1] / countCounts[freq]; observedMass -= (freq - adjustedFreq[freq]) * countCounts[freq]; } Distribution<E> norm = new Distribution<E>(); norm.counter = new ClassicCounter<E>(); // fill in the new Distribution, renormalizing as we go for (E key : counter.keySet()) { int origFreq = (int) Math.round(counter.getCount(key)); if (origFreq < 10) { norm.counter.setCount(key, adjustedFreq[origFreq] / observedMass); } else { norm.counter.setCount(key, origFreq / observedMass); } } norm.numberOfKeys = counter.size(); norm.reservedMass = 0.0; return norm; }
[ "public", "static", "<", "E", ">", "Distribution", "<", "E", ">", "goodTuringWithExplicitUnknown", "(", "Counter", "<", "E", ">", "counter", ",", "E", "UNK", ")", "{", "// gather count-counts\r", "int", "[", "]", "countCounts", "=", "getCountCounts", "(", "counter", ")", ";", "// if count-counts are unreliable, we shouldn't be using G-T\r", "// revert to laplace\r", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "10", ";", "i", "++", ")", "{", "if", "(", "countCounts", "[", "i", "]", "<", "3", ")", "{", "return", "laplaceWithExplicitUnknown", "(", "counter", ",", "0.5", ",", "UNK", ")", ";", "}", "}", "double", "observedMass", "=", "counter", ".", "totalCount", "(", ")", ";", "// calculate and cache adjusted frequencies\r", "// also adjusting total mass of observed items\r", "double", "[", "]", "adjustedFreq", "=", "new", "double", "[", "10", "]", ";", "for", "(", "int", "freq", "=", "1", ";", "freq", "<", "10", ";", "freq", "++", ")", "{", "adjustedFreq", "[", "freq", "]", "=", "(", "double", ")", "(", "freq", "+", "1", ")", "*", "(", "double", ")", "countCounts", "[", "freq", "+", "1", "]", "/", "countCounts", "[", "freq", "]", ";", "observedMass", "-=", "(", "freq", "-", "adjustedFreq", "[", "freq", "]", ")", "*", "countCounts", "[", "freq", "]", ";", "}", "Distribution", "<", "E", ">", "norm", "=", "new", "Distribution", "<", "E", ">", "(", ")", ";", "norm", ".", "counter", "=", "new", "ClassicCounter", "<", "E", ">", "(", ")", ";", "// fill in the new Distribution, renormalizing as we go\r", "for", "(", "E", "key", ":", "counter", ".", "keySet", "(", ")", ")", "{", "int", "origFreq", "=", "(", "int", ")", "Math", ".", "round", "(", "counter", ".", "getCount", "(", "key", ")", ")", ";", "if", "(", "origFreq", "<", "10", ")", "{", "norm", ".", "counter", ".", "setCount", "(", "key", ",", "adjustedFreq", "[", "origFreq", "]", "/", "observedMass", ")", ";", "}", "else", "{", "norm", ".", "counter", ".", "setCount", "(", "key", ",", "origFreq", "/", "observedMass", ")", ";", "}", "}", "norm", ".", "numberOfKeys", "=", "counter", ".", "size", "(", ")", ";", "norm", ".", "reservedMass", "=", "0.0", ";", "return", "norm", ";", "}" ]
Creates a Good-Turing smoothed Distribution from the given counter without creating any reserved mass-- instead, the special object UNK in the counter is assumed to be the count of "UNSEEN" items. Probability of objects not in original counter will be zero. @param counter the counter @param UNK the unknown symbol @return a good-turing smoothed distribution
[ "Creates", "a", "Good", "-", "Turing", "smoothed", "Distribution", "from", "the", "given", "counter", "without", "creating", "any", "reserved", "mass", "--", "instead", "the", "special", "object", "UNK", "in", "the", "counter", "is", "assumed", "to", "be", "the", "count", "of", "UNSEEN", "items", ".", "Probability", "of", "objects", "not", "in", "original", "counter", "will", "be", "zero", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/stats/Distribution.java#L386-L425
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRepositoryBaseImpl.java
LogRepositoryBaseImpl.createLockFile
protected void createLockFile(String pid, String label) throws IOException { """ Creates lock file to be used as a pattern for instance repository. Should be called only by parent's manager on start up. @param pid process ID of the parent. @param label label of the parent. @throws IOException if there's a problem to create lock file. """ if (!AccessHelper.isDirectory(repositoryLocation)) { AccessHelper.makeDirectories(repositoryLocation); } // Remove stale lock files if any. for (File lock : listFiles(LOCKFILE_FILTER)) { AccessHelper.deleteFile(lock); } // Create a new lock file. StringBuilder sb = new StringBuilder(); sb.append(getLogDirectoryName(System.currentTimeMillis(), pid, label)).append(LOCK_EXT); AccessHelper.createFileOutputStream(new File(repositoryLocation, sb.toString()), false).close(); }
java
protected void createLockFile(String pid, String label) throws IOException { if (!AccessHelper.isDirectory(repositoryLocation)) { AccessHelper.makeDirectories(repositoryLocation); } // Remove stale lock files if any. for (File lock : listFiles(LOCKFILE_FILTER)) { AccessHelper.deleteFile(lock); } // Create a new lock file. StringBuilder sb = new StringBuilder(); sb.append(getLogDirectoryName(System.currentTimeMillis(), pid, label)).append(LOCK_EXT); AccessHelper.createFileOutputStream(new File(repositoryLocation, sb.toString()), false).close(); }
[ "protected", "void", "createLockFile", "(", "String", "pid", ",", "String", "label", ")", "throws", "IOException", "{", "if", "(", "!", "AccessHelper", ".", "isDirectory", "(", "repositoryLocation", ")", ")", "{", "AccessHelper", ".", "makeDirectories", "(", "repositoryLocation", ")", ";", "}", "// Remove stale lock files if any.", "for", "(", "File", "lock", ":", "listFiles", "(", "LOCKFILE_FILTER", ")", ")", "{", "AccessHelper", ".", "deleteFile", "(", "lock", ")", ";", "}", "// Create a new lock file.", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "getLogDirectoryName", "(", "System", ".", "currentTimeMillis", "(", ")", ",", "pid", ",", "label", ")", ")", ".", "append", "(", "LOCK_EXT", ")", ";", "AccessHelper", ".", "createFileOutputStream", "(", "new", "File", "(", "repositoryLocation", ",", "sb", ".", "toString", "(", ")", ")", ",", "false", ")", ".", "close", "(", ")", ";", "}" ]
Creates lock file to be used as a pattern for instance repository. Should be called only by parent's manager on start up. @param pid process ID of the parent. @param label label of the parent. @throws IOException if there's a problem to create lock file.
[ "Creates", "lock", "file", "to", "be", "used", "as", "a", "pattern", "for", "instance", "repository", ".", "Should", "be", "called", "only", "by", "parent", "s", "manager", "on", "start", "up", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRepositoryBaseImpl.java#L143-L157
VoltDB/voltdb
src/frontend/org/voltdb/ElasticHashinator.java
ElasticHashinator.containingBucket
private static int containingBucket(int token, long interval) { """ Calculate the boundary of the bucket that countain the given token given the token interval. @return The token of the bucket boundary. """ return (int) ((((long) token - Integer.MIN_VALUE) / interval) * interval + Integer.MIN_VALUE); }
java
private static int containingBucket(int token, long interval) { return (int) ((((long) token - Integer.MIN_VALUE) / interval) * interval + Integer.MIN_VALUE); }
[ "private", "static", "int", "containingBucket", "(", "int", "token", ",", "long", "interval", ")", "{", "return", "(", "int", ")", "(", "(", "(", "(", "long", ")", "token", "-", "Integer", ".", "MIN_VALUE", ")", "/", "interval", ")", "*", "interval", "+", "Integer", ".", "MIN_VALUE", ")", ";", "}" ]
Calculate the boundary of the bucket that countain the given token given the token interval. @return The token of the bucket boundary.
[ "Calculate", "the", "boundary", "of", "the", "bucket", "that", "countain", "the", "given", "token", "given", "the", "token", "interval", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ElasticHashinator.java#L767-L770
elastic/elasticsearch-hadoop
mr/src/main/java/org/elasticsearch/hadoop/rest/pooling/TransportPool.java
TransportPool.borrowTransport
synchronized Transport borrowTransport() { """ Borrows a Transport from this pool. If there are no pooled Transports available, a new one is created. @return A Transport backed by a pooled resource """ long now = System.currentTimeMillis(); List<PooledTransport> garbageTransports = new ArrayList<PooledTransport>(); PooledTransport candidate = null; // Grab a transport for (Map.Entry<PooledTransport, Long> entry : idle.entrySet()) { PooledTransport transport = entry.getKey(); if (validate(transport)) { candidate = transport; break; } else { garbageTransports.add(transport); } } // Remove any dead connections found for (PooledTransport transport : garbageTransports) { idle.remove(transport); release(transport); } // Create the connection if we didn't find any, remove it from the pool if we did. if (candidate == null) { candidate = create(); } else { idle.remove(candidate); } // Lease. leased.put(candidate, now); return new LeasedTransport(candidate, this); }
java
synchronized Transport borrowTransport() { long now = System.currentTimeMillis(); List<PooledTransport> garbageTransports = new ArrayList<PooledTransport>(); PooledTransport candidate = null; // Grab a transport for (Map.Entry<PooledTransport, Long> entry : idle.entrySet()) { PooledTransport transport = entry.getKey(); if (validate(transport)) { candidate = transport; break; } else { garbageTransports.add(transport); } } // Remove any dead connections found for (PooledTransport transport : garbageTransports) { idle.remove(transport); release(transport); } // Create the connection if we didn't find any, remove it from the pool if we did. if (candidate == null) { candidate = create(); } else { idle.remove(candidate); } // Lease. leased.put(candidate, now); return new LeasedTransport(candidate, this); }
[ "synchronized", "Transport", "borrowTransport", "(", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "List", "<", "PooledTransport", ">", "garbageTransports", "=", "new", "ArrayList", "<", "PooledTransport", ">", "(", ")", ";", "PooledTransport", "candidate", "=", "null", ";", "// Grab a transport", "for", "(", "Map", ".", "Entry", "<", "PooledTransport", ",", "Long", ">", "entry", ":", "idle", ".", "entrySet", "(", ")", ")", "{", "PooledTransport", "transport", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "validate", "(", "transport", ")", ")", "{", "candidate", "=", "transport", ";", "break", ";", "}", "else", "{", "garbageTransports", ".", "add", "(", "transport", ")", ";", "}", "}", "// Remove any dead connections found", "for", "(", "PooledTransport", "transport", ":", "garbageTransports", ")", "{", "idle", ".", "remove", "(", "transport", ")", ";", "release", "(", "transport", ")", ";", "}", "// Create the connection if we didn't find any, remove it from the pool if we did.", "if", "(", "candidate", "==", "null", ")", "{", "candidate", "=", "create", "(", ")", ";", "}", "else", "{", "idle", ".", "remove", "(", "candidate", ")", ";", "}", "// Lease.", "leased", ".", "put", "(", "candidate", ",", "now", ")", ";", "return", "new", "LeasedTransport", "(", "candidate", ",", "this", ")", ";", "}" ]
Borrows a Transport from this pool. If there are no pooled Transports available, a new one is created. @return A Transport backed by a pooled resource
[ "Borrows", "a", "Transport", "from", "this", "pool", ".", "If", "there", "are", "no", "pooled", "Transports", "available", "a", "new", "one", "is", "created", "." ]
train
https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/rest/pooling/TransportPool.java#L122-L155
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/socialnet/googleplus/share/GooglePlusSharePanel.java
GooglePlusSharePanel.newLabel
protected Label newLabel(final String id, final IModel<GooglePlusShareModelBean> model) { """ Factory method for creating the new {@link Label}. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link Label}. @param id the id @param model the model @return the new {@link Label} """ final Label googleScriptLabel = ComponentFactory.newLabel(id, Model.of("{lang: '" + model.getObject().getLocale() + "'}")); googleScriptLabel.setEscapeModelStrings(false); googleScriptLabel.add(new AttributeModifier("src", model.getObject().getScriptSrc())); return googleScriptLabel; }
java
protected Label newLabel(final String id, final IModel<GooglePlusShareModelBean> model) { final Label googleScriptLabel = ComponentFactory.newLabel(id, Model.of("{lang: '" + model.getObject().getLocale() + "'}")); googleScriptLabel.setEscapeModelStrings(false); googleScriptLabel.add(new AttributeModifier("src", model.getObject().getScriptSrc())); return googleScriptLabel; }
[ "protected", "Label", "newLabel", "(", "final", "String", "id", ",", "final", "IModel", "<", "GooglePlusShareModelBean", ">", "model", ")", "{", "final", "Label", "googleScriptLabel", "=", "ComponentFactory", ".", "newLabel", "(", "id", ",", "Model", ".", "of", "(", "\"{lang: '\"", "+", "model", ".", "getObject", "(", ")", ".", "getLocale", "(", ")", "+", "\"'}\"", ")", ")", ";", "googleScriptLabel", ".", "setEscapeModelStrings", "(", "false", ")", ";", "googleScriptLabel", ".", "add", "(", "new", "AttributeModifier", "(", "\"src\"", ",", "model", ".", "getObject", "(", ")", ".", "getScriptSrc", "(", ")", ")", ")", ";", "return", "googleScriptLabel", ";", "}" ]
Factory method for creating the new {@link Label}. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link Label}. @param id the id @param model the model @return the new {@link Label}
[ "Factory", "method", "for", "creating", "the", "new", "{", "@link", "Label", "}", ".", "This", "method", "is", "invoked", "in", "the", "constructor", "from", "the", "derived", "classes", "and", "can", "be", "overridden", "so", "users", "can", "provide", "their", "own", "version", "of", "a", "new", "{", "@link", "Label", "}", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/socialnet/googleplus/share/GooglePlusSharePanel.java#L82-L89
gresrun/jesque
src/main/java/net/greghaines/jesque/client/AbstractClient.java
AbstractClient.doBatchEnqueue
public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) { """ Helper method that encapsulates the minimum logic for adding jobs to a queue. @param jedis the connection to Redis @param namespace the Resque namespace @param queue the Resque queue name @param jobJsons a list of jobs serialized as JSON """ Pipeline pipelined = jedis.pipelined(); pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue); for (String jobJson : jobJsons) { pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson); } pipelined.sync(); }
java
public static void doBatchEnqueue(final Jedis jedis, final String namespace, final String queue, final List<String> jobJsons) { Pipeline pipelined = jedis.pipelined(); pipelined.sadd(JesqueUtils.createKey(namespace, QUEUES), queue); for (String jobJson : jobJsons) { pipelined.rpush(JesqueUtils.createKey(namespace, QUEUE, queue), jobJson); } pipelined.sync(); }
[ "public", "static", "void", "doBatchEnqueue", "(", "final", "Jedis", "jedis", ",", "final", "String", "namespace", ",", "final", "String", "queue", ",", "final", "List", "<", "String", ">", "jobJsons", ")", "{", "Pipeline", "pipelined", "=", "jedis", ".", "pipelined", "(", ")", ";", "pipelined", ".", "sadd", "(", "JesqueUtils", ".", "createKey", "(", "namespace", ",", "QUEUES", ")", ",", "queue", ")", ";", "for", "(", "String", "jobJson", ":", "jobJsons", ")", "{", "pipelined", ".", "rpush", "(", "JesqueUtils", ".", "createKey", "(", "namespace", ",", "QUEUE", ",", "queue", ")", ",", "jobJson", ")", ";", "}", "pipelined", ".", "sync", "(", ")", ";", "}" ]
Helper method that encapsulates the minimum logic for adding jobs to a queue. @param jedis the connection to Redis @param namespace the Resque namespace @param queue the Resque queue name @param jobJsons a list of jobs serialized as JSON
[ "Helper", "method", "that", "encapsulates", "the", "minimum", "logic", "for", "adding", "jobs", "to", "a", "queue", "." ]
train
https://github.com/gresrun/jesque/blob/44749183dccc40962a94c2af547ea7d0d880b5d1/src/main/java/net/greghaines/jesque/client/AbstractClient.java#L234-L241
cchantep/acolyte
jdbc-java8/src/main/java/acolyte/jdbc/Java8CompositeHandler.java
Java8CompositeHandler.withQueryHandler1
public Java8CompositeHandler withQueryHandler1(RowListQueryHandler h) { """ Returns handler that delegates query execution to |h| function. Given function will be used only if executed statement is detected as a query by withQueryDetection. @param h the new query handler <pre> {@code import acolyte.jdbc.StatementHandler.Parameter; import static acolyte.jdbc.AcolyteDSL.handleStatement; handleStatement.withQueryHandler1((String sql, List<Parameter> ps) -> { if (sql == "SELECT * FROM Test WHERE id = ?") return aRowList; else return anotherRowList; }); } </pre> """ final QueryHandler qh = new QueryHandler() { public QueryResult apply(String sql, List<Parameter> ps) throws SQLException { return h.apply(sql, ps).asResult(); } }; return withQueryHandler(qh); }
java
public Java8CompositeHandler withQueryHandler1(RowListQueryHandler h) { final QueryHandler qh = new QueryHandler() { public QueryResult apply(String sql, List<Parameter> ps) throws SQLException { return h.apply(sql, ps).asResult(); } }; return withQueryHandler(qh); }
[ "public", "Java8CompositeHandler", "withQueryHandler1", "(", "RowListQueryHandler", "h", ")", "{", "final", "QueryHandler", "qh", "=", "new", "QueryHandler", "(", ")", "{", "public", "QueryResult", "apply", "(", "String", "sql", ",", "List", "<", "Parameter", ">", "ps", ")", "throws", "SQLException", "{", "return", "h", ".", "apply", "(", "sql", ",", "ps", ")", ".", "asResult", "(", ")", ";", "}", "}", ";", "return", "withQueryHandler", "(", "qh", ")", ";", "}" ]
Returns handler that delegates query execution to |h| function. Given function will be used only if executed statement is detected as a query by withQueryDetection. @param h the new query handler <pre> {@code import acolyte.jdbc.StatementHandler.Parameter; import static acolyte.jdbc.AcolyteDSL.handleStatement; handleStatement.withQueryHandler1((String sql, List<Parameter> ps) -> { if (sql == "SELECT * FROM Test WHERE id = ?") return aRowList; else return anotherRowList; }); } </pre>
[ "Returns", "handler", "that", "delegates", "query", "execution", "to", "|h|", "function", ".", "Given", "function", "will", "be", "used", "only", "if", "executed", "statement", "is", "detected", "as", "a", "query", "by", "withQueryDetection", "." ]
train
https://github.com/cchantep/acolyte/blob/a383dff20fadc08ec9306f2f1f24b2a7e0047449/jdbc-java8/src/main/java/acolyte/jdbc/Java8CompositeHandler.java#L99-L108
xvik/generics-resolver
src/main/java/ru/vyarus/java/generics/resolver/util/GenericsUtils.java
GenericsUtils.recordVariable
private static void recordVariable(final TypeVariable var, final List<TypeVariable> found) { """ variables could also contain variables, e.g. <T, K extends List<T>> """ // prevent cycles if (!found.contains(var)) { found.add(var); for (Type type : var.getBounds()) { findVariables(type, found); } } }
java
private static void recordVariable(final TypeVariable var, final List<TypeVariable> found) { // prevent cycles if (!found.contains(var)) { found.add(var); for (Type type : var.getBounds()) { findVariables(type, found); } } }
[ "private", "static", "void", "recordVariable", "(", "final", "TypeVariable", "var", ",", "final", "List", "<", "TypeVariable", ">", "found", ")", "{", "// prevent cycles", "if", "(", "!", "found", ".", "contains", "(", "var", ")", ")", "{", "found", ".", "add", "(", "var", ")", ";", "for", "(", "Type", "type", ":", "var", ".", "getBounds", "(", ")", ")", "{", "findVariables", "(", "type", ",", "found", ")", ";", "}", "}", "}" ]
variables could also contain variables, e.g. <T, K extends List<T>>
[ "variables", "could", "also", "contain", "variables", "e", ".", "g", ".", "<T", "K", "extends", "List<T", ">>" ]
train
https://github.com/xvik/generics-resolver/blob/d7d9d2783265df1178230e8f0b7cb6d853b67a7b/src/main/java/ru/vyarus/java/generics/resolver/util/GenericsUtils.java#L617-L625
lessthanoptimal/BoofCV
main/boofcv-io/src/main/java/boofcv/io/UtilIO.java
UtilIO.pathExampleURL
public static URL pathExampleURL( String path ) { """ Returns an absolute path to the file that is relative to the example directory @param path File path relative to root directory @return Absolute path to file """ try { File fpath = new File(path); if (fpath.isAbsolute()) return fpath.toURI().toURL(); // Assume we are running inside of the project come String pathToBase = getPathToBase(); if( pathToBase != null ) { File pathExample = new File(pathToBase, "data/example/"); if (pathExample.exists()) { return new File(pathExample.getPath(), path).getAbsoluteFile().toURL(); } } // System.out.println("-----------------------"); // maybe we are running inside an app and all data is stored inside as a resource // System.out.println("Attempting to load resource "+path); URL url = UtilIO.class.getClassLoader().getResource(path); if (url == null) { System.err.println(); System.err.println("Can't find data/example directory! There are three likely causes for this problem."); System.err.println(); System.err.println("1) You checked out the source code from git and did not pull the data submodule too."); System.err.println("2) You are trying to run an example from outside the BoofCV directory tree."); System.err.println("3) You are trying to pass in your own image."); System.err.println(); System.err.println("Solutions:"); System.err.println("1) Follow instructions in the boofcv/readme.md file to grab the data directory."); System.err.println("2) Launch the example from inside BoofCV's directory tree!"); System.err.println("3) Don't use this function and just pass in the path directly"); System.exit(1); } return url; } catch (MalformedURLException e) { throw new RuntimeException(e); } }
java
public static URL pathExampleURL( String path ) { try { File fpath = new File(path); if (fpath.isAbsolute()) return fpath.toURI().toURL(); // Assume we are running inside of the project come String pathToBase = getPathToBase(); if( pathToBase != null ) { File pathExample = new File(pathToBase, "data/example/"); if (pathExample.exists()) { return new File(pathExample.getPath(), path).getAbsoluteFile().toURL(); } } // System.out.println("-----------------------"); // maybe we are running inside an app and all data is stored inside as a resource // System.out.println("Attempting to load resource "+path); URL url = UtilIO.class.getClassLoader().getResource(path); if (url == null) { System.err.println(); System.err.println("Can't find data/example directory! There are three likely causes for this problem."); System.err.println(); System.err.println("1) You checked out the source code from git and did not pull the data submodule too."); System.err.println("2) You are trying to run an example from outside the BoofCV directory tree."); System.err.println("3) You are trying to pass in your own image."); System.err.println(); System.err.println("Solutions:"); System.err.println("1) Follow instructions in the boofcv/readme.md file to grab the data directory."); System.err.println("2) Launch the example from inside BoofCV's directory tree!"); System.err.println("3) Don't use this function and just pass in the path directly"); System.exit(1); } return url; } catch (MalformedURLException e) { throw new RuntimeException(e); } }
[ "public", "static", "URL", "pathExampleURL", "(", "String", "path", ")", "{", "try", "{", "File", "fpath", "=", "new", "File", "(", "path", ")", ";", "if", "(", "fpath", ".", "isAbsolute", "(", ")", ")", "return", "fpath", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ";", "// Assume we are running inside of the project come", "String", "pathToBase", "=", "getPathToBase", "(", ")", ";", "if", "(", "pathToBase", "!=", "null", ")", "{", "File", "pathExample", "=", "new", "File", "(", "pathToBase", ",", "\"data/example/\"", ")", ";", "if", "(", "pathExample", ".", "exists", "(", ")", ")", "{", "return", "new", "File", "(", "pathExample", ".", "getPath", "(", ")", ",", "path", ")", ".", "getAbsoluteFile", "(", ")", ".", "toURL", "(", ")", ";", "}", "}", "//\t\t\tSystem.out.println(\"-----------------------\");", "// maybe we are running inside an app and all data is stored inside as a resource", "//\t\t\tSystem.out.println(\"Attempting to load resource \"+path);", "URL", "url", "=", "UtilIO", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResource", "(", "path", ")", ";", "if", "(", "url", "==", "null", ")", "{", "System", ".", "err", ".", "println", "(", ")", ";", "System", ".", "err", ".", "println", "(", "\"Can't find data/example directory! There are three likely causes for this problem.\"", ")", ";", "System", ".", "err", ".", "println", "(", ")", ";", "System", ".", "err", ".", "println", "(", "\"1) You checked out the source code from git and did not pull the data submodule too.\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"2) You are trying to run an example from outside the BoofCV directory tree.\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"3) You are trying to pass in your own image.\"", ")", ";", "System", ".", "err", ".", "println", "(", ")", ";", "System", ".", "err", ".", "println", "(", "\"Solutions:\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"1) Follow instructions in the boofcv/readme.md file to grab the data directory.\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"2) Launch the example from inside BoofCV's directory tree!\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"3) Don't use this function and just pass in the path directly\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "return", "url", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Returns an absolute path to the file that is relative to the example directory @param path File path relative to root directory @return Absolute path to file
[ "Returns", "an", "absolute", "path", "to", "the", "file", "that", "is", "relative", "to", "the", "example", "directory" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-io/src/main/java/boofcv/io/UtilIO.java#L44-L81
mapfish/mapfish-print
core/src/main/java/org/mapfish/print/URIUtils.java
URIUtils.setQueryParams
public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) { """ Construct a new uri by replacing query parameters in initialUri with the query parameters provided. @param initialUri the initial/template URI @param queryParams the new query parameters. """ StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> entry: queryParams.entries()) { if (queryString.length() > 0) { queryString.append("&"); } queryString.append(entry.getKey()).append("=").append(entry.getValue()); } try { if (initialUri.getHost() == null && initialUri.getAuthority() != null) { return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(), queryString.toString(), initialUri.getFragment()); } else { return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(), initialUri.getPort(), initialUri.getPath(), queryString.toString(), initialUri.getFragment()); } } catch (URISyntaxException e) { throw ExceptionUtils.getRuntimeException(e); } }
java
public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) { StringBuilder queryString = new StringBuilder(); for (Map.Entry<String, String> entry: queryParams.entries()) { if (queryString.length() > 0) { queryString.append("&"); } queryString.append(entry.getKey()).append("=").append(entry.getValue()); } try { if (initialUri.getHost() == null && initialUri.getAuthority() != null) { return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(), queryString.toString(), initialUri.getFragment()); } else { return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(), initialUri.getPort(), initialUri.getPath(), queryString.toString(), initialUri.getFragment()); } } catch (URISyntaxException e) { throw ExceptionUtils.getRuntimeException(e); } }
[ "public", "static", "URI", "setQueryParams", "(", "final", "URI", "initialUri", ",", "final", "Multimap", "<", "String", ",", "String", ">", "queryParams", ")", "{", "StringBuilder", "queryString", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "queryParams", ".", "entries", "(", ")", ")", "{", "if", "(", "queryString", ".", "length", "(", ")", ">", "0", ")", "{", "queryString", ".", "append", "(", "\"&\"", ")", ";", "}", "queryString", ".", "append", "(", "entry", ".", "getKey", "(", ")", ")", ".", "append", "(", "\"=\"", ")", ".", "append", "(", "entry", ".", "getValue", "(", ")", ")", ";", "}", "try", "{", "if", "(", "initialUri", ".", "getHost", "(", ")", "==", "null", "&&", "initialUri", ".", "getAuthority", "(", ")", "!=", "null", ")", "{", "return", "new", "URI", "(", "initialUri", ".", "getScheme", "(", ")", ",", "initialUri", ".", "getAuthority", "(", ")", ",", "initialUri", ".", "getPath", "(", ")", ",", "queryString", ".", "toString", "(", ")", ",", "initialUri", ".", "getFragment", "(", ")", ")", ";", "}", "else", "{", "return", "new", "URI", "(", "initialUri", ".", "getScheme", "(", ")", ",", "initialUri", ".", "getUserInfo", "(", ")", ",", "initialUri", ".", "getHost", "(", ")", ",", "initialUri", ".", "getPort", "(", ")", ",", "initialUri", ".", "getPath", "(", ")", ",", "queryString", ".", "toString", "(", ")", ",", "initialUri", ".", "getFragment", "(", ")", ")", ";", "}", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "ExceptionUtils", ".", "getRuntimeException", "(", "e", ")", ";", "}", "}" ]
Construct a new uri by replacing query parameters in initialUri with the query parameters provided. @param initialUri the initial/template URI @param queryParams the new query parameters.
[ "Construct", "a", "new", "uri", "by", "replacing", "query", "parameters", "in", "initialUri", "with", "the", "query", "parameters", "provided", "." ]
train
https://github.com/mapfish/mapfish-print/blob/25a452cb39f592bd8a53b20db1037703898e1e22/core/src/main/java/org/mapfish/print/URIUtils.java#L200-L222
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/optionhandling/OptionUtil.java
OptionUtil.formatForConsole
public static void formatForConsole(StringBuilder buf, int width, Collection<TrackedParameter> options) { """ Format a list of options (and associated owning objects) for console help output. @param buf Serialization buffer @param width Screen width @param options List of options """ for(TrackedParameter pair : options) { Parameter<?> par = pair.getParameter(); println(buf// .append(SerializedParameterization.OPTION_PREFIX).append(par.getOptionID().getName()) // .append(' ').append(par.getSyntax()).append(FormatUtil.NEWLINE), // width, getFullDescription(par)); } }
java
public static void formatForConsole(StringBuilder buf, int width, Collection<TrackedParameter> options) { for(TrackedParameter pair : options) { Parameter<?> par = pair.getParameter(); println(buf// .append(SerializedParameterization.OPTION_PREFIX).append(par.getOptionID().getName()) // .append(' ').append(par.getSyntax()).append(FormatUtil.NEWLINE), // width, getFullDescription(par)); } }
[ "public", "static", "void", "formatForConsole", "(", "StringBuilder", "buf", ",", "int", "width", ",", "Collection", "<", "TrackedParameter", ">", "options", ")", "{", "for", "(", "TrackedParameter", "pair", ":", "options", ")", "{", "Parameter", "<", "?", ">", "par", "=", "pair", ".", "getParameter", "(", ")", ";", "println", "(", "buf", "//", ".", "append", "(", "SerializedParameterization", ".", "OPTION_PREFIX", ")", ".", "append", "(", "par", ".", "getOptionID", "(", ")", ".", "getName", "(", ")", ")", "//", ".", "append", "(", "'", "'", ")", ".", "append", "(", "par", ".", "getSyntax", "(", ")", ")", ".", "append", "(", "FormatUtil", ".", "NEWLINE", ")", ",", "//", "width", ",", "getFullDescription", "(", "par", ")", ")", ";", "}", "}" ]
Format a list of options (and associated owning objects) for console help output. @param buf Serialization buffer @param width Screen width @param options List of options
[ "Format", "a", "list", "of", "options", "(", "and", "associated", "owning", "objects", ")", "for", "console", "help", "output", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/optionhandling/OptionUtil.java#L62-L70
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/SerializerBase.java
SerializerBase.fireCharEvent
protected void fireCharEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { """ Report the characters trace event @param chars content of characters @param start starting index of characters to output @param length number of characters to output """ if (m_tracer != null) { flushMyWriter(); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length); } }
java
protected void fireCharEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { if (m_tracer != null) { flushMyWriter(); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length); } }
[ "protected", "void", "fireCharEvent", "(", "char", "[", "]", "chars", ",", "int", "start", ",", "int", "length", ")", "throws", "org", ".", "xml", ".", "sax", ".", "SAXException", "{", "if", "(", "m_tracer", "!=", "null", ")", "{", "flushMyWriter", "(", ")", ";", "m_tracer", ".", "fireGenerateEvent", "(", "SerializerTrace", ".", "EVENTTYPE_CHARACTERS", ",", "chars", ",", "start", ",", "length", ")", ";", "}", "}" ]
Report the characters trace event @param chars content of characters @param start starting index of characters to output @param length number of characters to output
[ "Report", "the", "characters", "trace", "event" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/SerializerBase.java#L111-L119
datastax/java-driver
query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.java
SchemaBuilder.dropType
@NonNull public static Drop dropType(@Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier typeName) { """ Starts a DROP TYPE query for the given view name for the given type name. """ return new DefaultDrop(keyspace, typeName, "TYPE"); }
java
@NonNull public static Drop dropType(@Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier typeName) { return new DefaultDrop(keyspace, typeName, "TYPE"); }
[ "@", "NonNull", "public", "static", "Drop", "dropType", "(", "@", "Nullable", "CqlIdentifier", "keyspace", ",", "@", "NonNull", "CqlIdentifier", "typeName", ")", "{", "return", "new", "DefaultDrop", "(", "keyspace", ",", "typeName", ",", "\"TYPE\"", ")", ";", "}" ]
Starts a DROP TYPE query for the given view name for the given type name.
[ "Starts", "a", "DROP", "TYPE", "query", "for", "the", "given", "view", "name", "for", "the", "given", "type", "name", "." ]
train
https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.java#L400-L403
alkacon/opencms-core
src/org/opencms/cmis/CmsCmisUtil.java
CmsCmisUtil.addAction
public static void addAction(Set<Action> aas, Action action, boolean condition) { """ Adds an action to a set of actions if a condition is fulfilled.<p> @param aas the set of actions @param action the action to add @param condition the value of the condition for adding the action """ if (condition) { aas.add(action); } }
java
public static void addAction(Set<Action> aas, Action action, boolean condition) { if (condition) { aas.add(action); } }
[ "public", "static", "void", "addAction", "(", "Set", "<", "Action", ">", "aas", ",", "Action", "action", ",", "boolean", "condition", ")", "{", "if", "(", "condition", ")", "{", "aas", ".", "add", "(", "action", ")", ";", "}", "}" ]
Adds an action to a set of actions if a condition is fulfilled.<p> @param aas the set of actions @param action the action to add @param condition the value of the condition for adding the action
[ "Adds", "an", "action", "to", "a", "set", "of", "actions", "if", "a", "condition", "is", "fulfilled", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cmis/CmsCmisUtil.java#L91-L96
exoplatform/jcr
exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/Utils.java
Utils.readDate
Date readDate(Node node, String propertyName) throws OrganizationServiceException { """ Returns property value represented in {@link Date}. @param node the parent node @param propertyName the property name to read from @return the date value if property exists or null otherwise @throws OrganizationServiceException if unexpected exception is occurred during reading """ try { return node.getProperty(propertyName).getDate().getTime(); } catch (PathNotFoundException e) { return null; } catch (ValueFormatException e) { throw new OrganizationServiceException("Property " + propertyName + " contains wrong value format", e); } catch (RepositoryException e) { throw new OrganizationServiceException("Can not read property " + propertyName, e); } }
java
Date readDate(Node node, String propertyName) throws OrganizationServiceException { try { return node.getProperty(propertyName).getDate().getTime(); } catch (PathNotFoundException e) { return null; } catch (ValueFormatException e) { throw new OrganizationServiceException("Property " + propertyName + " contains wrong value format", e); } catch (RepositoryException e) { throw new OrganizationServiceException("Can not read property " + propertyName, e); } }
[ "Date", "readDate", "(", "Node", "node", ",", "String", "propertyName", ")", "throws", "OrganizationServiceException", "{", "try", "{", "return", "node", ".", "getProperty", "(", "propertyName", ")", ".", "getDate", "(", ")", ".", "getTime", "(", ")", ";", "}", "catch", "(", "PathNotFoundException", "e", ")", "{", "return", "null", ";", "}", "catch", "(", "ValueFormatException", "e", ")", "{", "throw", "new", "OrganizationServiceException", "(", "\"Property \"", "+", "propertyName", "+", "\" contains wrong value format\"", ",", "e", ")", ";", "}", "catch", "(", "RepositoryException", "e", ")", "{", "throw", "new", "OrganizationServiceException", "(", "\"Can not read property \"", "+", "propertyName", ",", "e", ")", ";", "}", "}" ]
Returns property value represented in {@link Date}. @param node the parent node @param propertyName the property name to read from @return the date value if property exists or null otherwise @throws OrganizationServiceException if unexpected exception is occurred during reading
[ "Returns", "property", "value", "represented", "in", "{", "@link", "Date", "}", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/Utils.java#L64-L82
knowm/XChange
xchange-anx/src/main/java/org/knowm/xchange/anx/ANXUtils.java
ANXUtils.findLimitOrder
public static boolean findLimitOrder(List<LimitOrder> orders, LimitOrder order, String id) { """ Find and match an order with id in orders @param orders @param order @param id @return """ boolean found = false; for (LimitOrder openOrder : orders) { if (openOrder.getId().equalsIgnoreCase(id)) { if (order.getCurrencyPair().equals(openOrder.getCurrencyPair()) && (order.getOriginalAmount().compareTo(openOrder.getOriginalAmount()) == 0) && (order.getLimitPrice().compareTo(openOrder.getLimitPrice()) == 0)) { found = true; } } } return found; }
java
public static boolean findLimitOrder(List<LimitOrder> orders, LimitOrder order, String id) { boolean found = false; for (LimitOrder openOrder : orders) { if (openOrder.getId().equalsIgnoreCase(id)) { if (order.getCurrencyPair().equals(openOrder.getCurrencyPair()) && (order.getOriginalAmount().compareTo(openOrder.getOriginalAmount()) == 0) && (order.getLimitPrice().compareTo(openOrder.getLimitPrice()) == 0)) { found = true; } } } return found; }
[ "public", "static", "boolean", "findLimitOrder", "(", "List", "<", "LimitOrder", ">", "orders", ",", "LimitOrder", "order", ",", "String", "id", ")", "{", "boolean", "found", "=", "false", ";", "for", "(", "LimitOrder", "openOrder", ":", "orders", ")", "{", "if", "(", "openOrder", ".", "getId", "(", ")", ".", "equalsIgnoreCase", "(", "id", ")", ")", "{", "if", "(", "order", ".", "getCurrencyPair", "(", ")", ".", "equals", "(", "openOrder", ".", "getCurrencyPair", "(", ")", ")", "&&", "(", "order", ".", "getOriginalAmount", "(", ")", ".", "compareTo", "(", "openOrder", ".", "getOriginalAmount", "(", ")", ")", "==", "0", ")", "&&", "(", "order", ".", "getLimitPrice", "(", ")", ".", "compareTo", "(", "openOrder", ".", "getLimitPrice", "(", ")", ")", "==", "0", ")", ")", "{", "found", "=", "true", ";", "}", "}", "}", "return", "found", ";", "}" ]
Find and match an order with id in orders @param orders @param order @param id @return
[ "Find", "and", "match", "an", "order", "with", "id", "in", "orders" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-anx/src/main/java/org/knowm/xchange/anx/ANXUtils.java#L28-L43
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
StrBuilder.appendFixedWidthPadLeft
public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) { """ Appends an object to the builder padding on the left to a fixed width. The <code>toString</code> of the object is used. If the object is larger than the length, the left hand side is lost. If the object is null, the null text value is used. @param obj the object to append, null uses null text @param width the fixed field width, zero or negative has no effect @param padChar the pad character to use @return this, to enable chaining """ if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); if (str == null) { str = StringUtils.EMPTY; } final int strLen = str.length(); if (strLen >= width) { str.getChars(strLen - width, strLen, buffer, size); } else { final int padLen = width - strLen; for (int i = 0; i < padLen; i++) { buffer[size + i] = padChar; } str.getChars(0, strLen, buffer, size + padLen); } size += width; } return this; }
java
public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) { if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); if (str == null) { str = StringUtils.EMPTY; } final int strLen = str.length(); if (strLen >= width) { str.getChars(strLen - width, strLen, buffer, size); } else { final int padLen = width - strLen; for (int i = 0; i < padLen; i++) { buffer[size + i] = padChar; } str.getChars(0, strLen, buffer, size + padLen); } size += width; } return this; }
[ "public", "StrBuilder", "appendFixedWidthPadLeft", "(", "final", "Object", "obj", ",", "final", "int", "width", ",", "final", "char", "padChar", ")", "{", "if", "(", "width", ">", "0", ")", "{", "ensureCapacity", "(", "size", "+", "width", ")", ";", "String", "str", "=", "(", "obj", "==", "null", "?", "getNullText", "(", ")", ":", "obj", ".", "toString", "(", ")", ")", ";", "if", "(", "str", "==", "null", ")", "{", "str", "=", "StringUtils", ".", "EMPTY", ";", "}", "final", "int", "strLen", "=", "str", ".", "length", "(", ")", ";", "if", "(", "strLen", ">=", "width", ")", "{", "str", ".", "getChars", "(", "strLen", "-", "width", ",", "strLen", ",", "buffer", ",", "size", ")", ";", "}", "else", "{", "final", "int", "padLen", "=", "width", "-", "strLen", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "padLen", ";", "i", "++", ")", "{", "buffer", "[", "size", "+", "i", "]", "=", "padChar", ";", "}", "str", ".", "getChars", "(", "0", ",", "strLen", ",", "buffer", ",", "size", "+", "padLen", ")", ";", "}", "size", "+=", "width", ";", "}", "return", "this", ";", "}" ]
Appends an object to the builder padding on the left to a fixed width. The <code>toString</code> of the object is used. If the object is larger than the length, the left hand side is lost. If the object is null, the null text value is used. @param obj the object to append, null uses null text @param width the fixed field width, zero or negative has no effect @param padChar the pad character to use @return this, to enable chaining
[ "Appends", "an", "object", "to", "the", "builder", "padding", "on", "the", "left", "to", "a", "fixed", "width", ".", "The", "<code", ">", "toString<", "/", "code", ">", "of", "the", "object", "is", "used", ".", "If", "the", "object", "is", "larger", "than", "the", "length", "the", "left", "hand", "side", "is", "lost", ".", "If", "the", "object", "is", "null", "the", "null", "text", "value", "is", "used", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrBuilder.java#L1502-L1522
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.sabrBerestyckiNormalVolatilityApproximation
public static double sabrBerestyckiNormalVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity) { """ Return the implied normal volatility (Bachelier volatility) under a SABR model using the approximation of Berestycki. @param alpha initial value of the stochastic volatility process of the SABR model. @param beta CEV parameter of the SABR model. @param rho Correlation (leverages) of the stochastic volatility. @param nu Volatility of the stochastic volatility (vol-of-vol). @param displacement The displacement parameter d. @param underlying Underlying (spot) value. @param strike Strike. @param maturity Maturity. @return The implied normal volatility (Bachelier volatility) """ // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; strike += displacement; double forwardStrikeAverage = (underlying+strike) / 2.0; // Original paper uses a geometric average here double z; if(beta < 1.0) { z = nu / alpha * (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)) / (1.0-beta); } else { z = nu / alpha * Math.log(underlying/strike); } double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho)); double term1; if(Math.abs(underlying - strike) < 1E-10 * (1+Math.abs(underlying))) { // ATM case - we assume underlying = strike term1 = alpha * Math.pow(underlying, beta); } else { term1 = nu * (underlying-strike) / x; } double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24)); return Math.max(sigma, 0.0); }
java
public static double sabrBerestyckiNormalVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity) { // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; strike += displacement; double forwardStrikeAverage = (underlying+strike) / 2.0; // Original paper uses a geometric average here double z; if(beta < 1.0) { z = nu / alpha * (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)) / (1.0-beta); } else { z = nu / alpha * Math.log(underlying/strike); } double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho)); double term1; if(Math.abs(underlying - strike) < 1E-10 * (1+Math.abs(underlying))) { // ATM case - we assume underlying = strike term1 = alpha * Math.pow(underlying, beta); } else { term1 = nu * (underlying-strike) / x; } double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24)); return Math.max(sigma, 0.0); }
[ "public", "static", "double", "sabrBerestyckiNormalVolatilityApproximation", "(", "double", "alpha", ",", "double", "beta", ",", "double", "rho", ",", "double", "nu", ",", "double", "displacement", ",", "double", "underlying", ",", "double", "strike", ",", "double", "maturity", ")", "{", "// Apply displacement. Displaced model is just a shift on underlying and strike.", "underlying", "+=", "displacement", ";", "strike", "+=", "displacement", ";", "double", "forwardStrikeAverage", "=", "(", "underlying", "+", "strike", ")", "/", "2.0", ";", "// Original paper uses a geometric average here", "double", "z", ";", "if", "(", "beta", "<", "1.0", ")", "{", "z", "=", "nu", "/", "alpha", "*", "(", "Math", ".", "pow", "(", "underlying", ",", "1.0", "-", "beta", ")", "-", "Math", ".", "pow", "(", "strike", ",", "1.0", "-", "beta", ")", ")", "/", "(", "1.0", "-", "beta", ")", ";", "}", "else", "{", "z", "=", "nu", "/", "alpha", "*", "Math", ".", "log", "(", "underlying", "/", "strike", ")", ";", "}", "double", "x", "=", "Math", ".", "log", "(", "(", "Math", ".", "sqrt", "(", "1.0", "-", "2.0", "*", "rho", "*", "z", "+", "z", "*", "z", ")", "+", "z", "-", "rho", ")", "/", "(", "1.0", "-", "rho", ")", ")", ";", "double", "term1", ";", "if", "(", "Math", ".", "abs", "(", "underlying", "-", "strike", ")", "<", "1E-10", "*", "(", "1", "+", "Math", ".", "abs", "(", "underlying", ")", ")", ")", "{", "// ATM case - we assume underlying = strike", "term1", "=", "alpha", "*", "Math", ".", "pow", "(", "underlying", ",", "beta", ")", ";", "}", "else", "{", "term1", "=", "nu", "*", "(", "underlying", "-", "strike", ")", "/", "x", ";", "}", "double", "sigma", "=", "term1", "*", "(", "1.0", "+", "maturity", "*", "(", "(", "-", "beta", "*", "(", "2", "-", "beta", ")", "*", "alpha", "*", "alpha", ")", "/", "(", "24", "*", "Math", ".", "pow", "(", "forwardStrikeAverage", ",", "2.0", "*", "(", "1.0", "-", "beta", ")", ")", ")", "+", "beta", "*", "alpha", "*", "rho", "*", "nu", "/", "(", "4", "*", "Math", ".", "pow", "(", "forwardStrikeAverage", ",", "(", "1.0", "-", "beta", ")", ")", ")", "+", "(", "2.0", "-", "3.0", "*", "rho", "*", "rho", ")", "*", "nu", "*", "nu", "/", "24", ")", ")", ";", "return", "Math", ".", "max", "(", "sigma", ",", "0.0", ")", ";", "}" ]
Return the implied normal volatility (Bachelier volatility) under a SABR model using the approximation of Berestycki. @param alpha initial value of the stochastic volatility process of the SABR model. @param beta CEV parameter of the SABR model. @param rho Correlation (leverages) of the stochastic volatility. @param nu Volatility of the stochastic volatility (vol-of-vol). @param displacement The displacement parameter d. @param underlying Underlying (spot) value. @param strike Strike. @param maturity Maturity. @return The implied normal volatility (Bachelier volatility)
[ "Return", "the", "implied", "normal", "volatility", "(", "Bachelier", "volatility", ")", "under", "a", "SABR", "model", "using", "the", "approximation", "of", "Berestycki", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L1092-L1120
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java
StrSubstitutor.replaceIn
public boolean replaceIn(final StringBuffer source) { """ Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver. The buffer is updated with the result. @param source the buffer to replace in, updated, null returns zero @return true if altered """ if (source == null) { return false; } return replaceIn(source, 0, source.length()); }
java
public boolean replaceIn(final StringBuffer source) { if (source == null) { return false; } return replaceIn(source, 0, source.length()); }
[ "public", "boolean", "replaceIn", "(", "final", "StringBuffer", "source", ")", "{", "if", "(", "source", "==", "null", ")", "{", "return", "false", ";", "}", "return", "replaceIn", "(", "source", ",", "0", ",", "source", ".", "length", "(", ")", ")", ";", "}" ]
Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver. The buffer is updated with the result. @param source the buffer to replace in, updated, null returns zero @return true if altered
[ "Replaces", "all", "the", "occurrences", "of", "variables", "within", "the", "given", "source", "buffer", "with", "their", "matching", "values", "from", "the", "resolver", ".", "The", "buffer", "is", "updated", "with", "the", "result", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java#L621-L626
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.core/src/com/ibm/ws/security/wim/adapter/urbridge/utils/URBridgeEntity.java
URBridgeEntity.getGroupsForUser
public void getGroupsForUser(List<String> grpMbrshipAttrs, int countLimit) throws Exception { """ Ensure that an exception will be thrown if this function is called but not implemented by the child class. @param grpMbrshipAttrs @throws Exception on all calls. """ throw new WIMApplicationException(WIMMessageKey.METHOD_NOT_IMPLEMENTED, Tr.formatMessage(tc, WIMMessageKey.METHOD_NOT_IMPLEMENTED)); }
java
public void getGroupsForUser(List<String> grpMbrshipAttrs, int countLimit) throws Exception { throw new WIMApplicationException(WIMMessageKey.METHOD_NOT_IMPLEMENTED, Tr.formatMessage(tc, WIMMessageKey.METHOD_NOT_IMPLEMENTED)); }
[ "public", "void", "getGroupsForUser", "(", "List", "<", "String", ">", "grpMbrshipAttrs", ",", "int", "countLimit", ")", "throws", "Exception", "{", "throw", "new", "WIMApplicationException", "(", "WIMMessageKey", ".", "METHOD_NOT_IMPLEMENTED", ",", "Tr", ".", "formatMessage", "(", "tc", ",", "WIMMessageKey", ".", "METHOD_NOT_IMPLEMENTED", ")", ")", ";", "}" ]
Ensure that an exception will be thrown if this function is called but not implemented by the child class. @param grpMbrshipAttrs @throws Exception on all calls.
[ "Ensure", "that", "an", "exception", "will", "be", "thrown", "if", "this", "function", "is", "called", "but", "not", "implemented", "by", "the", "child", "class", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.core/src/com/ibm/ws/security/wim/adapter/urbridge/utils/URBridgeEntity.java#L264-L266
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateUtils.java
DateUtils.setDays
public static Date setDays(final Date date, final int amount) { """ Sets the day of month field to a date returning a new object. The original {@code Date} is unchanged. @param date the date, not null @param amount the amount to set @return a new {@code Date} set with the specified value @throws IllegalArgumentException if the date is null @since 2.4 """ return set(date, Calendar.DAY_OF_MONTH, amount); }
java
public static Date setDays(final Date date, final int amount) { return set(date, Calendar.DAY_OF_MONTH, amount); }
[ "public", "static", "Date", "setDays", "(", "final", "Date", "date", ",", "final", "int", "amount", ")", "{", "return", "set", "(", "date", ",", "Calendar", ".", "DAY_OF_MONTH", ",", "amount", ")", ";", "}" ]
Sets the day of month field to a date returning a new object. The original {@code Date} is unchanged. @param date the date, not null @param amount the amount to set @return a new {@code Date} set with the specified value @throws IllegalArgumentException if the date is null @since 2.4
[ "Sets", "the", "day", "of", "month", "field", "to", "a", "date", "returning", "a", "new", "object", ".", "The", "original", "{", "@code", "Date", "}", "is", "unchanged", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateUtils.java#L570-L572
opentable/otj-jaxrs
client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java
JaxRsClientFactory.newBuilder
public synchronized ClientBuilder newBuilder(String clientName, JaxRsFeatureGroup feature, JaxRsFeatureGroup... moreFeatures) { """ Create a new {@link ClientBuilder} instance with the given name and groups. You own the returned client and are responsible for managing its cleanup. """ return newBuilder(clientName, ImmutableList.<JaxRsFeatureGroup>builder() .add(feature) .addAll(Arrays.asList(moreFeatures)) .build()); }
java
public synchronized ClientBuilder newBuilder(String clientName, JaxRsFeatureGroup feature, JaxRsFeatureGroup... moreFeatures) { return newBuilder(clientName, ImmutableList.<JaxRsFeatureGroup>builder() .add(feature) .addAll(Arrays.asList(moreFeatures)) .build()); }
[ "public", "synchronized", "ClientBuilder", "newBuilder", "(", "String", "clientName", ",", "JaxRsFeatureGroup", "feature", ",", "JaxRsFeatureGroup", "...", "moreFeatures", ")", "{", "return", "newBuilder", "(", "clientName", ",", "ImmutableList", ".", "<", "JaxRsFeatureGroup", ">", "builder", "(", ")", ".", "add", "(", "feature", ")", ".", "addAll", "(", "Arrays", ".", "asList", "(", "moreFeatures", ")", ")", ".", "build", "(", ")", ")", ";", "}" ]
Create a new {@link ClientBuilder} instance with the given name and groups. You own the returned client and are responsible for managing its cleanup.
[ "Create", "a", "new", "{" ]
train
https://github.com/opentable/otj-jaxrs/blob/384e7094fe5a56d41b2a9970bfd783fa85cbbcb8/client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java#L217-L222
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMBuilder.java
DOMBuilder.startPrefixMapping
public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException { """ Begin the scope of a prefix-URI Namespace mapping. <p>The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default).</p> <p>There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary.</p> <p>Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not guaranteed.</p> @param prefix The Namespace prefix being declared. @param uri The Namespace URI the prefix is mapped to. @see #endPrefixMapping @see #startElement """ if(null == prefix || prefix.equals("")) prefix = "xmlns"; else prefix = "xmlns:"+prefix; m_prefixMappings.addElement(prefix); m_prefixMappings.addElement(uri); }
java
public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException { if(null == prefix || prefix.equals("")) prefix = "xmlns"; else prefix = "xmlns:"+prefix; m_prefixMappings.addElement(prefix); m_prefixMappings.addElement(uri); }
[ "public", "void", "startPrefixMapping", "(", "String", "prefix", ",", "String", "uri", ")", "throws", "org", ".", "xml", ".", "sax", ".", "SAXException", "{", "if", "(", "null", "==", "prefix", "||", "prefix", ".", "equals", "(", "\"\"", ")", ")", "prefix", "=", "\"xmlns\"", ";", "else", "prefix", "=", "\"xmlns:\"", "+", "prefix", ";", "m_prefixMappings", ".", "addElement", "(", "prefix", ")", ";", "m_prefixMappings", ".", "addElement", "(", "uri", ")", ";", "}" ]
Begin the scope of a prefix-URI Namespace mapping. <p>The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the http://xml.org/sax/features/namespaces feature is true (the default).</p> <p>There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the start/endPrefixMapping event supplies the information to the application to expand prefixes in those contexts itself, if necessary.</p> <p>Note that start/endPrefixMapping events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping events will occur before the corresponding startElement event, and all endPrefixMapping events will occur after the corresponding endElement event, but their order is not guaranteed.</p> @param prefix The Namespace prefix being declared. @param uri The Namespace URI the prefix is mapped to. @see #endPrefixMapping @see #startElement
[ "Begin", "the", "scope", "of", "a", "prefix", "-", "URI", "Namespace", "mapping", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMBuilder.java#L755-L763
wildfly/wildfly-core
cli/src/main/java/org/jboss/as/cli/handlers/DeploymentOverlayHandler.java
DeploymentOverlayHandler.getName
private String getName(CommandContext ctx, boolean failInBatch) throws CommandLineException { """ Validate that the overlay exists. If it doesn't exist, throws an exception if not in batch mode or if failInBatch is true. In batch mode, we could be in the case that the overlay doesn't exist yet. """ final ParsedCommandLine args = ctx.getParsedCommandLine(); final String name = this.name.getValue(args, true); if (name == null) { throw new CommandFormatException(this.name + " is missing value."); } if (!ctx.isBatchMode() || failInBatch) { if (!Util.isValidPath(ctx.getModelControllerClient(), Util.DEPLOYMENT_OVERLAY, name)) { throw new CommandFormatException("Deployment overlay " + name + " does not exist."); } } return name; }
java
private String getName(CommandContext ctx, boolean failInBatch) throws CommandLineException { final ParsedCommandLine args = ctx.getParsedCommandLine(); final String name = this.name.getValue(args, true); if (name == null) { throw new CommandFormatException(this.name + " is missing value."); } if (!ctx.isBatchMode() || failInBatch) { if (!Util.isValidPath(ctx.getModelControllerClient(), Util.DEPLOYMENT_OVERLAY, name)) { throw new CommandFormatException("Deployment overlay " + name + " does not exist."); } } return name; }
[ "private", "String", "getName", "(", "CommandContext", "ctx", ",", "boolean", "failInBatch", ")", "throws", "CommandLineException", "{", "final", "ParsedCommandLine", "args", "=", "ctx", ".", "getParsedCommandLine", "(", ")", ";", "final", "String", "name", "=", "this", ".", "name", ".", "getValue", "(", "args", ",", "true", ")", ";", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "CommandFormatException", "(", "this", ".", "name", "+", "\" is missing value.\"", ")", ";", "}", "if", "(", "!", "ctx", ".", "isBatchMode", "(", ")", "||", "failInBatch", ")", "{", "if", "(", "!", "Util", ".", "isValidPath", "(", "ctx", ".", "getModelControllerClient", "(", ")", ",", "Util", ".", "DEPLOYMENT_OVERLAY", ",", "name", ")", ")", "{", "throw", "new", "CommandFormatException", "(", "\"Deployment overlay \"", "+", "name", "+", "\" does not exist.\"", ")", ";", "}", "}", "return", "name", ";", "}" ]
Validate that the overlay exists. If it doesn't exist, throws an exception if not in batch mode or if failInBatch is true. In batch mode, we could be in the case that the overlay doesn't exist yet.
[ "Validate", "that", "the", "overlay", "exists", ".", "If", "it", "doesn", "t", "exist", "throws", "an", "exception", "if", "not", "in", "batch", "mode", "or", "if", "failInBatch", "is", "true", ".", "In", "batch", "mode", "we", "could", "be", "in", "the", "case", "that", "the", "overlay", "doesn", "t", "exist", "yet", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/handlers/DeploymentOverlayHandler.java#L545-L557
prestodb/presto
presto-accumulo/src/main/java/com/facebook/presto/accumulo/AccumuloMetadata.java
AccumuloMetadata.listViews
private List<SchemaTableName> listViews(Optional<String> filterSchema) { """ Gets all views in the given schema, or all schemas if null. @param filterSchema Schema to filter the views, or absent to list all schemas @return List of views """ ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder(); if (filterSchema.isPresent()) { for (String view : client.getViewNames(filterSchema.get())) { builder.add(new SchemaTableName(filterSchema.get(), view)); } } else { for (String schemaName : client.getSchemaNames()) { for (String view : client.getViewNames(schemaName)) { builder.add(new SchemaTableName(schemaName, view)); } } } return builder.build(); }
java
private List<SchemaTableName> listViews(Optional<String> filterSchema) { ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder(); if (filterSchema.isPresent()) { for (String view : client.getViewNames(filterSchema.get())) { builder.add(new SchemaTableName(filterSchema.get(), view)); } } else { for (String schemaName : client.getSchemaNames()) { for (String view : client.getViewNames(schemaName)) { builder.add(new SchemaTableName(schemaName, view)); } } } return builder.build(); }
[ "private", "List", "<", "SchemaTableName", ">", "listViews", "(", "Optional", "<", "String", ">", "filterSchema", ")", "{", "ImmutableList", ".", "Builder", "<", "SchemaTableName", ">", "builder", "=", "ImmutableList", ".", "builder", "(", ")", ";", "if", "(", "filterSchema", ".", "isPresent", "(", ")", ")", "{", "for", "(", "String", "view", ":", "client", ".", "getViewNames", "(", "filterSchema", ".", "get", "(", ")", ")", ")", "{", "builder", ".", "add", "(", "new", "SchemaTableName", "(", "filterSchema", ".", "get", "(", ")", ",", "view", ")", ")", ";", "}", "}", "else", "{", "for", "(", "String", "schemaName", ":", "client", ".", "getSchemaNames", "(", ")", ")", "{", "for", "(", "String", "view", ":", "client", ".", "getViewNames", "(", "schemaName", ")", ")", "{", "builder", ".", "add", "(", "new", "SchemaTableName", "(", "schemaName", ",", "view", ")", ")", ";", "}", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Gets all views in the given schema, or all schemas if null. @param filterSchema Schema to filter the views, or absent to list all schemas @return List of views
[ "Gets", "all", "views", "in", "the", "given", "schema", "or", "all", "schemas", "if", "null", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-accumulo/src/main/java/com/facebook/presto/accumulo/AccumuloMetadata.java#L187-L204
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/CpuMemoryManager.java
CpuMemoryManager.allocate
@Override public Pointer allocate(long bytes, MemoryKind kind, boolean initialize) { """ This method returns PLEASE NOTE: Cache options depend on specific implementations @param bytes @param kind @param initialize """ Pointer ptr = NativeOpsHolder.getInstance().getDeviceNativeOps().mallocHost(bytes, 0); if (ptr == null || ptr.address() == 0L) throw new OutOfMemoryError("Failed to allocate [" + bytes + "] bytes"); //log.info("Allocating {} bytes at MemoryManager", bytes); if (initialize) Pointer.memset(ptr, 0, bytes); return ptr; }
java
@Override public Pointer allocate(long bytes, MemoryKind kind, boolean initialize) { Pointer ptr = NativeOpsHolder.getInstance().getDeviceNativeOps().mallocHost(bytes, 0); if (ptr == null || ptr.address() == 0L) throw new OutOfMemoryError("Failed to allocate [" + bytes + "] bytes"); //log.info("Allocating {} bytes at MemoryManager", bytes); if (initialize) Pointer.memset(ptr, 0, bytes); return ptr; }
[ "@", "Override", "public", "Pointer", "allocate", "(", "long", "bytes", ",", "MemoryKind", "kind", ",", "boolean", "initialize", ")", "{", "Pointer", "ptr", "=", "NativeOpsHolder", ".", "getInstance", "(", ")", ".", "getDeviceNativeOps", "(", ")", ".", "mallocHost", "(", "bytes", ",", "0", ")", ";", "if", "(", "ptr", "==", "null", "||", "ptr", ".", "address", "(", ")", "==", "0L", ")", "throw", "new", "OutOfMemoryError", "(", "\"Failed to allocate [\"", "+", "bytes", "+", "\"] bytes\"", ")", ";", "//log.info(\"Allocating {} bytes at MemoryManager\", bytes);", "if", "(", "initialize", ")", "Pointer", ".", "memset", "(", "ptr", ",", "0", ",", "bytes", ")", ";", "return", "ptr", ";", "}" ]
This method returns PLEASE NOTE: Cache options depend on specific implementations @param bytes @param kind @param initialize
[ "This", "method", "returns", "PLEASE", "NOTE", ":", "Cache", "options", "depend", "on", "specific", "implementations" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/CpuMemoryManager.java#L46-L59
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Optional.java
Optional.ifPresentOrElse
public void ifPresentOrElse(@NotNull Consumer<? super T> consumer, @NotNull Runnable emptyAction) { """ If a value is present, performs the given action with the value, otherwise performs the given empty-based action. @param consumer the consumer function to be executed, if a value is present @param emptyAction the empty-based action to be performed, if no value is present @throws NullPointerException if a value is present and the given consumer function is null, or no value is present and the given empty-based action is null. """ if (value != null) { consumer.accept(value); } else { emptyAction.run(); } }
java
public void ifPresentOrElse(@NotNull Consumer<? super T> consumer, @NotNull Runnable emptyAction) { if (value != null) { consumer.accept(value); } else { emptyAction.run(); } }
[ "public", "void", "ifPresentOrElse", "(", "@", "NotNull", "Consumer", "<", "?", "super", "T", ">", "consumer", ",", "@", "NotNull", "Runnable", "emptyAction", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "consumer", ".", "accept", "(", "value", ")", ";", "}", "else", "{", "emptyAction", ".", "run", "(", ")", ";", "}", "}" ]
If a value is present, performs the given action with the value, otherwise performs the given empty-based action. @param consumer the consumer function to be executed, if a value is present @param emptyAction the empty-based action to be performed, if no value is present @throws NullPointerException if a value is present and the given consumer function is null, or no value is present and the given empty-based action is null.
[ "If", "a", "value", "is", "present", "performs", "the", "given", "action", "with", "the", "value", "otherwise", "performs", "the", "given", "empty", "-", "based", "action", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Optional.java#L131-L137