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
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/IndexCache.java
IndexCache.getIndexInformation
public IndexRecord getIndexInformation(String mapId, int reduce, Path fileName) throws IOException { """ This method gets the index information for the given mapId and reduce. It reads the index file into cache if it is not already present. @param mapId @param reduce @param fileName The file to read the index information from if it is not already present in the cache @return The Index Information @throws IOException """ IndexInformation info = cache.get(mapId); if (info == null) { info = readIndexFileToCache(fileName, mapId); } else { synchronized (info) { while (null == info.mapSpillRecord) { try { info.wait(); } catch (InterruptedException e) { throw new IOException("Interrupted waiting for construction", e); } } } LOG.debug("IndexCache HIT: MapId " + mapId + " found"); } if (info.mapSpillRecord.size() == 0 || info.mapSpillRecord.size() < reduce) { throw new IOException("Invalid request " + " Map Id = " + mapId + " Reducer = " + reduce + " Index Info Length = " + info.mapSpillRecord.size()); } return info.mapSpillRecord.getIndex(reduce); }
java
public IndexRecord getIndexInformation(String mapId, int reduce, Path fileName) throws IOException { IndexInformation info = cache.get(mapId); if (info == null) { info = readIndexFileToCache(fileName, mapId); } else { synchronized (info) { while (null == info.mapSpillRecord) { try { info.wait(); } catch (InterruptedException e) { throw new IOException("Interrupted waiting for construction", e); } } } LOG.debug("IndexCache HIT: MapId " + mapId + " found"); } if (info.mapSpillRecord.size() == 0 || info.mapSpillRecord.size() < reduce) { throw new IOException("Invalid request " + " Map Id = " + mapId + " Reducer = " + reduce + " Index Info Length = " + info.mapSpillRecord.size()); } return info.mapSpillRecord.getIndex(reduce); }
[ "public", "IndexRecord", "getIndexInformation", "(", "String", "mapId", ",", "int", "reduce", ",", "Path", "fileName", ")", "throws", "IOException", "{", "IndexInformation", "info", "=", "cache", ".", "get", "(", "mapId", ")", ";", "if", "(", "info", "==", "null", ")", "{", "info", "=", "readIndexFileToCache", "(", "fileName", ",", "mapId", ")", ";", "}", "else", "{", "synchronized", "(", "info", ")", "{", "while", "(", "null", "==", "info", ".", "mapSpillRecord", ")", "{", "try", "{", "info", ".", "wait", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "IOException", "(", "\"Interrupted waiting for construction\"", ",", "e", ")", ";", "}", "}", "}", "LOG", ".", "debug", "(", "\"IndexCache HIT: MapId \"", "+", "mapId", "+", "\" found\"", ")", ";", "}", "if", "(", "info", ".", "mapSpillRecord", ".", "size", "(", ")", "==", "0", "||", "info", ".", "mapSpillRecord", ".", "size", "(", ")", "<", "reduce", ")", "{", "throw", "new", "IOException", "(", "\"Invalid request \"", "+", "\" Map Id = \"", "+", "mapId", "+", "\" Reducer = \"", "+", "reduce", "+", "\" Index Info Length = \"", "+", "info", ".", "mapSpillRecord", ".", "size", "(", ")", ")", ";", "}", "return", "info", ".", "mapSpillRecord", ".", "getIndex", "(", "reduce", ")", ";", "}" ]
This method gets the index information for the given mapId and reduce. It reads the index file into cache if it is not already present. @param mapId @param reduce @param fileName The file to read the index information from if it is not already present in the cache @return The Index Information @throws IOException
[ "This", "method", "gets", "the", "index", "information", "for", "the", "given", "mapId", "and", "reduce", ".", "It", "reads", "the", "index", "file", "into", "cache", "if", "it", "is", "not", "already", "present", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/IndexCache.java#L59-L86
Impetus/Kundera
src/kundera-spark/spark-core/src/main/java/com/impetus/spark/datahandler/SparkDataHandler.java
SparkDataHandler.loadDataAndPopulateResults
public List<?> loadDataAndPopulateResults(DataFrame dataFrame, EntityMetadata m, KunderaQuery kunderaQuery) { """ Load data and populate results. @param dataFrame the data frame @param m the m @param kunderaQuery the kundera query @return the list """ if (kunderaQuery != null && kunderaQuery.isAggregated()) { return dataFrame.collectAsList(); } // TODO: handle the case of specific field selection else { return populateEntityObjectsList(dataFrame, m); } }
java
public List<?> loadDataAndPopulateResults(DataFrame dataFrame, EntityMetadata m, KunderaQuery kunderaQuery) { if (kunderaQuery != null && kunderaQuery.isAggregated()) { return dataFrame.collectAsList(); } // TODO: handle the case of specific field selection else { return populateEntityObjectsList(dataFrame, m); } }
[ "public", "List", "<", "?", ">", "loadDataAndPopulateResults", "(", "DataFrame", "dataFrame", ",", "EntityMetadata", "m", ",", "KunderaQuery", "kunderaQuery", ")", "{", "if", "(", "kunderaQuery", "!=", "null", "&&", "kunderaQuery", ".", "isAggregated", "(", ")", ")", "{", "return", "dataFrame", ".", "collectAsList", "(", ")", ";", "}", "// TODO: handle the case of specific field selection", "else", "{", "return", "populateEntityObjectsList", "(", "dataFrame", ",", "m", ")", ";", "}", "}" ]
Load data and populate results. @param dataFrame the data frame @param m the m @param kunderaQuery the kundera query @return the list
[ "Load", "data", "and", "populate", "results", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-spark/spark-core/src/main/java/com/impetus/spark/datahandler/SparkDataHandler.java#L75-L86
alkacon/opencms-core
src/org/opencms/staticexport/CmsLinkManager.java
CmsLinkManager.substituteLink
public String substituteLink(CmsObject cms, CmsResource resource) { """ Returns a link <i>from</i> the URI stored in the provided OpenCms user context <i>to</i> the given VFS resource, for use on web pages.<p> The result will contain the configured context path and servlet name, and in the case of the "online" project it will also be rewritten according to to the configured static export settings.<p> Should the current site of the given OpenCms user context <code>cms</code> be different from the site root of the given resource, the result will contain the full server URL to the target resource.<p> Please note the above text describes the default behavior as implemented by {@link CmsDefaultLinkSubstitutionHandler}, which can be fully customized using the {@link I_CmsLinkSubstitutionHandler} interface.<p> @param cms the current OpenCms user context @param resource the VFS resource the link should point to @return a link <i>from</i> the URI stored in the provided OpenCms user context <i>to</i> the given VFS resource, for use on web pages """ return substituteLinkForRootPath(cms, resource.getRootPath()); }
java
public String substituteLink(CmsObject cms, CmsResource resource) { return substituteLinkForRootPath(cms, resource.getRootPath()); }
[ "public", "String", "substituteLink", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ")", "{", "return", "substituteLinkForRootPath", "(", "cms", ",", "resource", ".", "getRootPath", "(", ")", ")", ";", "}" ]
Returns a link <i>from</i> the URI stored in the provided OpenCms user context <i>to</i> the given VFS resource, for use on web pages.<p> The result will contain the configured context path and servlet name, and in the case of the "online" project it will also be rewritten according to to the configured static export settings.<p> Should the current site of the given OpenCms user context <code>cms</code> be different from the site root of the given resource, the result will contain the full server URL to the target resource.<p> Please note the above text describes the default behavior as implemented by {@link CmsDefaultLinkSubstitutionHandler}, which can be fully customized using the {@link I_CmsLinkSubstitutionHandler} interface.<p> @param cms the current OpenCms user context @param resource the VFS resource the link should point to @return a link <i>from</i> the URI stored in the provided OpenCms user context <i>to</i> the given VFS resource, for use on web pages
[ "Returns", "a", "link", "<i", ">", "from<", "/", "i", ">", "the", "URI", "stored", "in", "the", "provided", "OpenCms", "user", "context", "<i", ">", "to<", "/", "i", ">", "the", "given", "VFS", "resource", "for", "use", "on", "web", "pages", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsLinkManager.java#L652-L655
groovy/groovy-core
src/main/org/codehaus/groovy/classgen/asm/OperandStack.java
OperandStack.primitive2b
private void primitive2b(MethodVisitor mv, ClassNode type) { """ convert primitive (not boolean) to boolean or byte. type needs to be a primitive type (not checked) """ Label trueLabel = new Label(); Label falseLabel = new Label(); // for the various types we make first a // kind of conversion to int using a compare // operation and then handle the result common // for all cases. In case of long that is LCMP, // for int nothing is to be done if (type==ClassHelper.double_TYPE) { mv.visitInsn(DCONST_0); mv.visitInsn(DCMPL); } else if (type==ClassHelper.long_TYPE) { mv.visitInsn(LCONST_0); mv.visitInsn(LCMP); } else if (type==ClassHelper.float_TYPE) { mv.visitInsn(FCONST_0); mv.visitInsn(FCMPL); } else if (type==ClassHelper.int_TYPE) { // nothing, see comment above } mv.visitJumpInsn(IFEQ, falseLabel); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, trueLabel); mv.visitLabel(falseLabel); mv.visitInsn(ICONST_0); mv.visitLabel(trueLabel); // other cases can be used directly }
java
private void primitive2b(MethodVisitor mv, ClassNode type) { Label trueLabel = new Label(); Label falseLabel = new Label(); // for the various types we make first a // kind of conversion to int using a compare // operation and then handle the result common // for all cases. In case of long that is LCMP, // for int nothing is to be done if (type==ClassHelper.double_TYPE) { mv.visitInsn(DCONST_0); mv.visitInsn(DCMPL); } else if (type==ClassHelper.long_TYPE) { mv.visitInsn(LCONST_0); mv.visitInsn(LCMP); } else if (type==ClassHelper.float_TYPE) { mv.visitInsn(FCONST_0); mv.visitInsn(FCMPL); } else if (type==ClassHelper.int_TYPE) { // nothing, see comment above } mv.visitJumpInsn(IFEQ, falseLabel); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, trueLabel); mv.visitLabel(falseLabel); mv.visitInsn(ICONST_0); mv.visitLabel(trueLabel); // other cases can be used directly }
[ "private", "void", "primitive2b", "(", "MethodVisitor", "mv", ",", "ClassNode", "type", ")", "{", "Label", "trueLabel", "=", "new", "Label", "(", ")", ";", "Label", "falseLabel", "=", "new", "Label", "(", ")", ";", "// for the various types we make first a ", "// kind of conversion to int using a compare", "// operation and then handle the result common", "// for all cases. In case of long that is LCMP,", "// for int nothing is to be done", "if", "(", "type", "==", "ClassHelper", ".", "double_TYPE", ")", "{", "mv", ".", "visitInsn", "(", "DCONST_0", ")", ";", "mv", ".", "visitInsn", "(", "DCMPL", ")", ";", "}", "else", "if", "(", "type", "==", "ClassHelper", ".", "long_TYPE", ")", "{", "mv", ".", "visitInsn", "(", "LCONST_0", ")", ";", "mv", ".", "visitInsn", "(", "LCMP", ")", ";", "}", "else", "if", "(", "type", "==", "ClassHelper", ".", "float_TYPE", ")", "{", "mv", ".", "visitInsn", "(", "FCONST_0", ")", ";", "mv", ".", "visitInsn", "(", "FCMPL", ")", ";", "}", "else", "if", "(", "type", "==", "ClassHelper", ".", "int_TYPE", ")", "{", "// nothing, see comment above", "}", "mv", ".", "visitJumpInsn", "(", "IFEQ", ",", "falseLabel", ")", ";", "mv", ".", "visitInsn", "(", "ICONST_1", ")", ";", "mv", ".", "visitJumpInsn", "(", "GOTO", ",", "trueLabel", ")", ";", "mv", ".", "visitLabel", "(", "falseLabel", ")", ";", "mv", ".", "visitInsn", "(", "ICONST_0", ")", ";", "mv", ".", "visitLabel", "(", "trueLabel", ")", ";", "// other cases can be used directly", "}" ]
convert primitive (not boolean) to boolean or byte. type needs to be a primitive type (not checked)
[ "convert", "primitive", "(", "not", "boolean", ")", "to", "boolean", "or", "byte", ".", "type", "needs", "to", "be", "a", "primitive", "type", "(", "not", "checked", ")" ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/classgen/asm/OperandStack.java#L125-L152
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/document/json/JsonObject.java
JsonObject.getAndDecryptBigDecimal
public BigDecimal getAndDecryptBigDecimal(String name, String providerName) throws Exception { """ Retrieves the decrypted value from the field name and casts it to {@link BigDecimal}. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the field. @param providerName crypto provider for decryption @return the result or null if it does not exist. """ Object found = getAndDecrypt(name, providerName); if (found == null) { return null; } else if (found instanceof Double) { return new BigDecimal((Double) found); } return (BigDecimal) found; }
java
public BigDecimal getAndDecryptBigDecimal(String name, String providerName) throws Exception { Object found = getAndDecrypt(name, providerName); if (found == null) { return null; } else if (found instanceof Double) { return new BigDecimal((Double) found); } return (BigDecimal) found; }
[ "public", "BigDecimal", "getAndDecryptBigDecimal", "(", "String", "name", ",", "String", "providerName", ")", "throws", "Exception", "{", "Object", "found", "=", "getAndDecrypt", "(", "name", ",", "providerName", ")", ";", "if", "(", "found", "==", "null", ")", "{", "return", "null", ";", "}", "else", "if", "(", "found", "instanceof", "Double", ")", "{", "return", "new", "BigDecimal", "(", "(", "Double", ")", "found", ")", ";", "}", "return", "(", "BigDecimal", ")", "found", ";", "}" ]
Retrieves the decrypted value from the field name and casts it to {@link BigDecimal}. Note: Use of the Field Level Encryption functionality provided in the com.couchbase.client.encryption namespace provided by Couchbase is subject to the Couchbase Inc. Enterprise Subscription License Agreement at https://www.couchbase.com/ESLA-11132015. @param name the name of the field. @param providerName crypto provider for decryption @return the result or null if it does not exist.
[ "Retrieves", "the", "decrypted", "value", "from", "the", "field", "name", "and", "casts", "it", "to", "{", "@link", "BigDecimal", "}", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/document/json/JsonObject.java#L944-L952
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java
QrCodeUtil.encode
public static BitMatrix encode(String content, int width, int height) { """ 将文本内容编码为二维码 @param content 文本内容 @param width 宽度 @param height 高度 @return {@link BitMatrix} """ return encode(content, BarcodeFormat.QR_CODE, width, height); }
java
public static BitMatrix encode(String content, int width, int height) { return encode(content, BarcodeFormat.QR_CODE, width, height); }
[ "public", "static", "BitMatrix", "encode", "(", "String", "content", ",", "int", "width", ",", "int", "height", ")", "{", "return", "encode", "(", "content", ",", "BarcodeFormat", ".", "QR_CODE", ",", "width", ",", "height", ")", ";", "}" ]
将文本内容编码为二维码 @param content 文本内容 @param width 宽度 @param height 高度 @return {@link BitMatrix}
[ "将文本内容编码为二维码" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/qrcode/QrCodeUtil.java#L209-L211
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.flip
public static void flip(Image image, File outFile) throws IORuntimeException { """ 水平翻转图像 @param image 图像 @param outFile 输出文件 @throws IORuntimeException IO异常 @since 3.2.2 """ write(flip(image), outFile); }
java
public static void flip(Image image, File outFile) throws IORuntimeException { write(flip(image), outFile); }
[ "public", "static", "void", "flip", "(", "Image", "image", ",", "File", "outFile", ")", "throws", "IORuntimeException", "{", "write", "(", "flip", "(", "image", ")", ",", "outFile", ")", ";", "}" ]
水平翻转图像 @param image 图像 @param outFile 输出文件 @throws IORuntimeException IO异常 @since 3.2.2
[ "水平翻转图像" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L1082-L1084
m-m-m/util
version/src/main/java/net/sf/mmm/util/version/impl/VersionUtilImpl.java
VersionUtilImpl.putPhase
protected void putPhase(Map<String, DevelopmentPhase> map, String key, DevelopmentPhase phase) { """ This method puts the given {@code phase} in the given {@code map} using normalized variants of the given {@code key}. @param map is the {@link #getPhaseMap()}. @param key is the key. @param phase is the {@link DevelopmentPhase} to put. """ String newKey = key.toLowerCase(Locale.US); while (newKey != null) { DevelopmentPhase existingPhase = map.get(newKey); if ((existingPhase != null) && (existingPhase != phase)) { throw new IllegalStateException("Development phase '" + phase + "' has key '" + newKey + "' that is already mapped to '" + existingPhase + "'."); } map.put(newKey, phase); if (newKey.contains("-")) { newKey = newKey.replace("-", ""); } else { newKey = null; } } }
java
protected void putPhase(Map<String, DevelopmentPhase> map, String key, DevelopmentPhase phase) { String newKey = key.toLowerCase(Locale.US); while (newKey != null) { DevelopmentPhase existingPhase = map.get(newKey); if ((existingPhase != null) && (existingPhase != phase)) { throw new IllegalStateException("Development phase '" + phase + "' has key '" + newKey + "' that is already mapped to '" + existingPhase + "'."); } map.put(newKey, phase); if (newKey.contains("-")) { newKey = newKey.replace("-", ""); } else { newKey = null; } } }
[ "protected", "void", "putPhase", "(", "Map", "<", "String", ",", "DevelopmentPhase", ">", "map", ",", "String", "key", ",", "DevelopmentPhase", "phase", ")", "{", "String", "newKey", "=", "key", ".", "toLowerCase", "(", "Locale", ".", "US", ")", ";", "while", "(", "newKey", "!=", "null", ")", "{", "DevelopmentPhase", "existingPhase", "=", "map", ".", "get", "(", "newKey", ")", ";", "if", "(", "(", "existingPhase", "!=", "null", ")", "&&", "(", "existingPhase", "!=", "phase", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Development phase '\"", "+", "phase", "+", "\"' has key '\"", "+", "newKey", "+", "\"' that is already mapped to '\"", "+", "existingPhase", "+", "\"'.\"", ")", ";", "}", "map", ".", "put", "(", "newKey", ",", "phase", ")", ";", "if", "(", "newKey", ".", "contains", "(", "\"-\"", ")", ")", "{", "newKey", "=", "newKey", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", ";", "}", "else", "{", "newKey", "=", "null", ";", "}", "}", "}" ]
This method puts the given {@code phase} in the given {@code map} using normalized variants of the given {@code key}. @param map is the {@link #getPhaseMap()}. @param key is the key. @param phase is the {@link DevelopmentPhase} to put.
[ "This", "method", "puts", "the", "given", "{", "@code", "phase", "}", "in", "the", "given", "{", "@code", "map", "}", "using", "normalized", "variants", "of", "the", "given", "{", "@code", "key", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/version/src/main/java/net/sf/mmm/util/version/impl/VersionUtilImpl.java#L204-L219
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java
Http2FrameCodec.userEventTriggered
@Override public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { """ Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2 on stream 1 (the stream specifically reserved for cleartext HTTP upgrade). """ if (evt == Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE) { // The user event implies that we are on the client. tryExpandConnectionFlowControlWindow(connection()); } else if (evt instanceof UpgradeEvent) { UpgradeEvent upgrade = (UpgradeEvent) evt; try { onUpgradeEvent(ctx, upgrade.retain()); Http2Stream stream = connection().stream(HTTP_UPGRADE_STREAM_ID); if (stream.getProperty(streamKey) == null) { // TODO: improve handler/stream lifecycle so that stream isn't active before handler added. // The stream was already made active, but ctx may have been null so it wasn't initialized. // https://github.com/netty/netty/issues/4942 onStreamActive0(stream); } upgrade.upgradeRequest().headers().setInt( HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), HTTP_UPGRADE_STREAM_ID); stream.setProperty(upgradeKey, true); InboundHttpToHttp2Adapter.handle( ctx, connection(), decoder().frameListener(), upgrade.upgradeRequest().retain()); } finally { upgrade.release(); } return; } super.userEventTriggered(ctx, evt); }
java
@Override public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE) { // The user event implies that we are on the client. tryExpandConnectionFlowControlWindow(connection()); } else if (evt instanceof UpgradeEvent) { UpgradeEvent upgrade = (UpgradeEvent) evt; try { onUpgradeEvent(ctx, upgrade.retain()); Http2Stream stream = connection().stream(HTTP_UPGRADE_STREAM_ID); if (stream.getProperty(streamKey) == null) { // TODO: improve handler/stream lifecycle so that stream isn't active before handler added. // The stream was already made active, but ctx may have been null so it wasn't initialized. // https://github.com/netty/netty/issues/4942 onStreamActive0(stream); } upgrade.upgradeRequest().headers().setInt( HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), HTTP_UPGRADE_STREAM_ID); stream.setProperty(upgradeKey, true); InboundHttpToHttp2Adapter.handle( ctx, connection(), decoder().frameListener(), upgrade.upgradeRequest().retain()); } finally { upgrade.release(); } return; } super.userEventTriggered(ctx, evt); }
[ "@", "Override", "public", "final", "void", "userEventTriggered", "(", "ChannelHandlerContext", "ctx", ",", "Object", "evt", ")", "throws", "Exception", "{", "if", "(", "evt", "==", "Http2ConnectionPrefaceAndSettingsFrameWrittenEvent", ".", "INSTANCE", ")", "{", "// The user event implies that we are on the client.", "tryExpandConnectionFlowControlWindow", "(", "connection", "(", ")", ")", ";", "}", "else", "if", "(", "evt", "instanceof", "UpgradeEvent", ")", "{", "UpgradeEvent", "upgrade", "=", "(", "UpgradeEvent", ")", "evt", ";", "try", "{", "onUpgradeEvent", "(", "ctx", ",", "upgrade", ".", "retain", "(", ")", ")", ";", "Http2Stream", "stream", "=", "connection", "(", ")", ".", "stream", "(", "HTTP_UPGRADE_STREAM_ID", ")", ";", "if", "(", "stream", ".", "getProperty", "(", "streamKey", ")", "==", "null", ")", "{", "// TODO: improve handler/stream lifecycle so that stream isn't active before handler added.", "// The stream was already made active, but ctx may have been null so it wasn't initialized.", "// https://github.com/netty/netty/issues/4942", "onStreamActive0", "(", "stream", ")", ";", "}", "upgrade", ".", "upgradeRequest", "(", ")", ".", "headers", "(", ")", ".", "setInt", "(", "HttpConversionUtil", ".", "ExtensionHeaderNames", ".", "STREAM_ID", ".", "text", "(", ")", ",", "HTTP_UPGRADE_STREAM_ID", ")", ";", "stream", ".", "setProperty", "(", "upgradeKey", ",", "true", ")", ";", "InboundHttpToHttp2Adapter", ".", "handle", "(", "ctx", ",", "connection", "(", ")", ",", "decoder", "(", ")", ".", "frameListener", "(", ")", ",", "upgrade", ".", "upgradeRequest", "(", ")", ".", "retain", "(", ")", ")", ";", "}", "finally", "{", "upgrade", ".", "release", "(", ")", ";", "}", "return", ";", "}", "super", ".", "userEventTriggered", "(", "ctx", ",", "evt", ")", ";", "}" ]
Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2 on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
[ "Handles", "the", "cleartext", "HTTP", "upgrade", "event", ".", "If", "an", "upgrade", "occurred", "sends", "a", "simple", "response", "via", "HTTP", "/", "2", "on", "stream", "1", "(", "the", "stream", "specifically", "reserved", "for", "cleartext", "HTTP", "upgrade", ")", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java#L239-L266
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/util/ArgUtils.java
ArgUtils.notMin
@SuppressWarnings( { """ 引数が {@literal 'arg' >= 'min'} の関係か検証する。 @param arg 検証対象の値 @param min 最小値 @param name 検証対象の引数の名前 @throws IllegalArgumentException {@literal arg == null || arg < min.} """"unchecked", "rawtypes"}) public static <T extends Comparable> void notMin(final T arg, final T min, final String name) { if(arg == null) { throw new IllegalArgumentException(String.format("%s should not be null.", name)); } if(arg.compareTo(min) < 0) { throw new IllegalArgumentException(String.format("%s cannot be smaller than %s", name, min.toString())); } }
java
@SuppressWarnings({"unchecked", "rawtypes"}) public static <T extends Comparable> void notMin(final T arg, final T min, final String name) { if(arg == null) { throw new IllegalArgumentException(String.format("%s should not be null.", name)); } if(arg.compareTo(min) < 0) { throw new IllegalArgumentException(String.format("%s cannot be smaller than %s", name, min.toString())); } }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "static", "<", "T", "extends", "Comparable", ">", "void", "notMin", "(", "final", "T", "arg", ",", "final", "T", "min", ",", "final", "String", "name", ")", "{", "if", "(", "arg", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"%s should not be null.\"", ",", "name", ")", ")", ";", "}", "if", "(", "arg", ".", "compareTo", "(", "min", ")", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"%s cannot be smaller than %s\"", ",", "name", ",", "min", ".", "toString", "(", ")", ")", ")", ";", "}", "}" ]
引数が {@literal 'arg' >= 'min'} の関係か検証する。 @param arg 検証対象の値 @param min 最小値 @param name 検証対象の引数の名前 @throws IllegalArgumentException {@literal arg == null || arg < min.}
[ "引数が", "{" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/ArgUtils.java#L95-L106
graphhopper/map-matching
matching-core/src/main/java/com/graphhopper/matching/util/Distributions.java
Distributions.logNormalDistribution
public static double logNormalDistribution(double sigma, double x) { """ Use this function instead of Math.log(normalDistribution(sigma, x)) to avoid an arithmetic underflow for very small probabilities. """ return Math.log(1.0 / (sqrt(2.0 * PI) * sigma)) + (-0.5 * pow(x / sigma, 2)); }
java
public static double logNormalDistribution(double sigma, double x) { return Math.log(1.0 / (sqrt(2.0 * PI) * sigma)) + (-0.5 * pow(x / sigma, 2)); }
[ "public", "static", "double", "logNormalDistribution", "(", "double", "sigma", ",", "double", "x", ")", "{", "return", "Math", ".", "log", "(", "1.0", "/", "(", "sqrt", "(", "2.0", "*", "PI", ")", "*", "sigma", ")", ")", "+", "(", "-", "0.5", "*", "pow", "(", "x", "/", "sigma", ",", "2", ")", ")", ";", "}" ]
Use this function instead of Math.log(normalDistribution(sigma, x)) to avoid an arithmetic underflow for very small probabilities.
[ "Use", "this", "function", "instead", "of", "Math", ".", "log", "(", "normalDistribution", "(", "sigma", "x", "))", "to", "avoid", "an", "arithmetic", "underflow", "for", "very", "small", "probabilities", "." ]
train
https://github.com/graphhopper/map-matching/blob/32cd83f14cb990c2be83c8781f22dfb59e0dbeb4/matching-core/src/main/java/com/graphhopper/matching/util/Distributions.java#L38-L40
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/UtilReflection.java
UtilReflection.getDeclaredFieldSuper
private static Field getDeclaredFieldSuper(Class<?> clazz, String name) throws NoSuchFieldException { """ Get the field by reflection searching in super class if needed. @param clazz The class to use. @param name The field name. @return The field found. @throws NoSuchFieldException If field not found. """ try { return clazz.getDeclaredField(name); } catch (final NoSuchFieldException exception) { if (clazz.getSuperclass() == null) { throw exception; } return getDeclaredFieldSuper(clazz.getSuperclass(), name); } }
java
private static Field getDeclaredFieldSuper(Class<?> clazz, String name) throws NoSuchFieldException { try { return clazz.getDeclaredField(name); } catch (final NoSuchFieldException exception) { if (clazz.getSuperclass() == null) { throw exception; } return getDeclaredFieldSuper(clazz.getSuperclass(), name); } }
[ "private", "static", "Field", "getDeclaredFieldSuper", "(", "Class", "<", "?", ">", "clazz", ",", "String", "name", ")", "throws", "NoSuchFieldException", "{", "try", "{", "return", "clazz", ".", "getDeclaredField", "(", "name", ")", ";", "}", "catch", "(", "final", "NoSuchFieldException", "exception", ")", "{", "if", "(", "clazz", ".", "getSuperclass", "(", ")", "==", "null", ")", "{", "throw", "exception", ";", "}", "return", "getDeclaredFieldSuper", "(", "clazz", ".", "getSuperclass", "(", ")", ",", "name", ")", ";", "}", "}" ]
Get the field by reflection searching in super class if needed. @param clazz The class to use. @param name The field name. @return The field found. @throws NoSuchFieldException If field not found.
[ "Get", "the", "field", "by", "reflection", "searching", "in", "super", "class", "if", "needed", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/UtilReflection.java#L373-L387
app55/app55-java
src/support/java/com/googlecode/openbeans/Encoder.java
Encoder.writeExpression
public void writeExpression(Expression oldExp) { """ Write an expression of old objects. <p> The implementation first check the return value of the expression. If there exists a new version of the object, simply return. </p> <p> A new expression is created using the new versions of the target and the arguments. If any of the old objects do not have its new version yet, <code>writeObject()</code> is called to create the new version. </p> <p> The new expression is then executed to obtained a new copy of the old return value. </p> <p> Call <code>writeObject()</code> with the old return value, so that more statements will be executed on its new version to change it into the same state as the old value. </p> @param oldExp the expression to write. The target, arguments, and return value of the expression are all old objects. """ if (oldExp == null) { throw new NullPointerException(); } try { // if oldValue exists, no operation Object oldValue = expressionValue(oldExp); if (oldValue == null || get(oldValue) != null) { return; } // copy to newExp Expression newExp = (Expression) createNewStatement(oldExp); // relate oldValue to newValue try { oldNewMap.put(oldValue, newExp.getValue()); } catch (IndexOutOfBoundsException e) { // container does not have any component, set newVal null } // force same state writeObject(oldValue); } catch (Exception e) { listener.exceptionThrown(new Exception("failed to write expression: " + oldExp, e)); //$NON-NLS-1$ } }
java
public void writeExpression(Expression oldExp) { if (oldExp == null) { throw new NullPointerException(); } try { // if oldValue exists, no operation Object oldValue = expressionValue(oldExp); if (oldValue == null || get(oldValue) != null) { return; } // copy to newExp Expression newExp = (Expression) createNewStatement(oldExp); // relate oldValue to newValue try { oldNewMap.put(oldValue, newExp.getValue()); } catch (IndexOutOfBoundsException e) { // container does not have any component, set newVal null } // force same state writeObject(oldValue); } catch (Exception e) { listener.exceptionThrown(new Exception("failed to write expression: " + oldExp, e)); //$NON-NLS-1$ } }
[ "public", "void", "writeExpression", "(", "Expression", "oldExp", ")", "{", "if", "(", "oldExp", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "try", "{", "// if oldValue exists, no operation", "Object", "oldValue", "=", "expressionValue", "(", "oldExp", ")", ";", "if", "(", "oldValue", "==", "null", "||", "get", "(", "oldValue", ")", "!=", "null", ")", "{", "return", ";", "}", "// copy to newExp", "Expression", "newExp", "=", "(", "Expression", ")", "createNewStatement", "(", "oldExp", ")", ";", "// relate oldValue to newValue", "try", "{", "oldNewMap", ".", "put", "(", "oldValue", ",", "newExp", ".", "getValue", "(", ")", ")", ";", "}", "catch", "(", "IndexOutOfBoundsException", "e", ")", "{", "// container does not have any component, set newVal null", "}", "// force same state", "writeObject", "(", "oldValue", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "listener", ".", "exceptionThrown", "(", "new", "Exception", "(", "\"failed to write expression: \"", "+", "oldExp", ",", "e", ")", ")", ";", "//$NON-NLS-1$", "}", "}" ]
Write an expression of old objects. <p> The implementation first check the return value of the expression. If there exists a new version of the object, simply return. </p> <p> A new expression is created using the new versions of the target and the arguments. If any of the old objects do not have its new version yet, <code>writeObject()</code> is called to create the new version. </p> <p> The new expression is then executed to obtained a new copy of the old return value. </p> <p> Call <code>writeObject()</code> with the old return value, so that more statements will be executed on its new version to change it into the same state as the old value. </p> @param oldExp the expression to write. The target, arguments, and return value of the expression are all old objects.
[ "Write", "an", "expression", "of", "old", "objects", ".", "<p", ">", "The", "implementation", "first", "check", "the", "return", "value", "of", "the", "expression", ".", "If", "there", "exists", "a", "new", "version", "of", "the", "object", "simply", "return", ".", "<", "/", "p", ">", "<p", ">", "A", "new", "expression", "is", "created", "using", "the", "new", "versions", "of", "the", "target", "and", "the", "arguments", ".", "If", "any", "of", "the", "old", "objects", "do", "not", "have", "its", "new", "version", "yet", "<code", ">", "writeObject", "()", "<", "/", "code", ">", "is", "called", "to", "create", "the", "new", "version", ".", "<", "/", "p", ">", "<p", ">", "The", "new", "expression", "is", "then", "executed", "to", "obtained", "a", "new", "copy", "of", "the", "old", "return", "value", ".", "<", "/", "p", ">", "<p", ">", "Call", "<code", ">", "writeObject", "()", "<", "/", "code", ">", "with", "the", "old", "return", "value", "so", "that", "more", "statements", "will", "be", "executed", "on", "its", "new", "version", "to", "change", "it", "into", "the", "same", "state", "as", "the", "old", "value", ".", "<", "/", "p", ">" ]
train
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Encoder.java#L373-L407
BrunoEberhard/minimal-j
src/main/java/org/minimalj/frontend/form/Form.java
Form.addDependecy
public void addDependecy(Object from, Object... to) { """ Declares that if the <i>from</i> property changes all the properties with <i>to</i> could change. This is normally used if the to <i>to</i> property is a getter that calculates something that depends on the <i>from</i> in some way. @param from the key or property of the field triggering the update @param to the field possible changed its value implicitly """ PropertyInterface fromProperty = Keys.getProperty(from); if (!dependencies.containsKey(fromProperty.getPath())) { dependencies.put(fromProperty.getPath(), new ArrayList<PropertyInterface>()); } List<PropertyInterface> list = dependencies.get(fromProperty.getPath()); for (Object key : to) { list.add(Keys.getProperty(key)); } }
java
public void addDependecy(Object from, Object... to) { PropertyInterface fromProperty = Keys.getProperty(from); if (!dependencies.containsKey(fromProperty.getPath())) { dependencies.put(fromProperty.getPath(), new ArrayList<PropertyInterface>()); } List<PropertyInterface> list = dependencies.get(fromProperty.getPath()); for (Object key : to) { list.add(Keys.getProperty(key)); } }
[ "public", "void", "addDependecy", "(", "Object", "from", ",", "Object", "...", "to", ")", "{", "PropertyInterface", "fromProperty", "=", "Keys", ".", "getProperty", "(", "from", ")", ";", "if", "(", "!", "dependencies", ".", "containsKey", "(", "fromProperty", ".", "getPath", "(", ")", ")", ")", "{", "dependencies", ".", "put", "(", "fromProperty", ".", "getPath", "(", ")", ",", "new", "ArrayList", "<", "PropertyInterface", ">", "(", ")", ")", ";", "}", "List", "<", "PropertyInterface", ">", "list", "=", "dependencies", ".", "get", "(", "fromProperty", ".", "getPath", "(", ")", ")", ";", "for", "(", "Object", "key", ":", "to", ")", "{", "list", ".", "add", "(", "Keys", ".", "getProperty", "(", "key", ")", ")", ";", "}", "}" ]
Declares that if the <i>from</i> property changes all the properties with <i>to</i> could change. This is normally used if the to <i>to</i> property is a getter that calculates something that depends on the <i>from</i> in some way. @param from the key or property of the field triggering the update @param to the field possible changed its value implicitly
[ "Declares", "that", "if", "the", "<i", ">", "from<", "/", "i", ">", "property", "changes", "all", "the", "properties", "with", "<i", ">", "to<", "/", "i", ">", "could", "change", ".", "This", "is", "normally", "used", "if", "the", "to", "<i", ">", "to<", "/", "i", ">", "property", "is", "a", "getter", "that", "calculates", "something", "that", "depends", "on", "the", "<i", ">", "from<", "/", "i", ">", "in", "some", "way", "." ]
train
https://github.com/BrunoEberhard/minimal-j/blob/f7c5461b2b47a10b383aee1e2f1f150f6773703b/src/main/java/org/minimalj/frontend/form/Form.java#L240-L249
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeSetStringSpan.java
UnicodeSetStringSpan.spanOne
static int spanOne(final UnicodeSet set, CharSequence s, int start, int length) { """ Does the set contain the next code point? If so, return its length; otherwise return its negative length. """ char c = s.charAt(start); if (c >= 0xd800 && c <= 0xdbff && length >= 2) { char c2 = s.charAt(start + 1); if (android.icu.text.UTF16.isTrailSurrogate(c2)) { int supplementary = Character.toCodePoint(c, c2); return set.contains(supplementary) ? 2 : -2; } } return set.contains(c) ? 1 : -1; }
java
static int spanOne(final UnicodeSet set, CharSequence s, int start, int length) { char c = s.charAt(start); if (c >= 0xd800 && c <= 0xdbff && length >= 2) { char c2 = s.charAt(start + 1); if (android.icu.text.UTF16.isTrailSurrogate(c2)) { int supplementary = Character.toCodePoint(c, c2); return set.contains(supplementary) ? 2 : -2; } } return set.contains(c) ? 1 : -1; }
[ "static", "int", "spanOne", "(", "final", "UnicodeSet", "set", ",", "CharSequence", "s", ",", "int", "start", ",", "int", "length", ")", "{", "char", "c", "=", "s", ".", "charAt", "(", "start", ")", ";", "if", "(", "c", ">=", "0xd800", "&&", "c", "<=", "0xdbff", "&&", "length", ">=", "2", ")", "{", "char", "c2", "=", "s", ".", "charAt", "(", "start", "+", "1", ")", ";", "if", "(", "android", ".", "icu", ".", "text", ".", "UTF16", ".", "isTrailSurrogate", "(", "c2", ")", ")", "{", "int", "supplementary", "=", "Character", ".", "toCodePoint", "(", "c", ",", "c2", ")", ";", "return", "set", ".", "contains", "(", "supplementary", ")", "?", "2", ":", "-", "2", ";", "}", "}", "return", "set", ".", "contains", "(", "c", ")", "?", "1", ":", "-", "1", ";", "}" ]
Does the set contain the next code point? If so, return its length; otherwise return its negative length.
[ "Does", "the", "set", "contain", "the", "next", "code", "point?", "If", "so", "return", "its", "length", ";", "otherwise", "return", "its", "negative", "length", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UnicodeSetStringSpan.java#L976-L986
dita-ot/dita-ot
src/main/java/org/dita/dost/writer/ConrefPushParser.java
ConrefPushParser.isPushedTypeMatch
private boolean isPushedTypeMatch(final DitaClass targetClassAttribute, final DocumentFragment content) { """ The function is to judge if the pushed content type march the type of content being pushed/replaced @param targetClassAttribute the class attribute of target element which is being pushed @param content pushedContent @return boolean: if type match, return true, else return false """ DitaClass clazz = null; if (content.hasChildNodes()) { final NodeList nodeList = content.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { final Element elem = (Element) node; clazz = new DitaClass(elem.getAttribute(ATTRIBUTE_NAME_CLASS)); break; // get type of the target element } } } return targetClassAttribute.matches(clazz); }
java
private boolean isPushedTypeMatch(final DitaClass targetClassAttribute, final DocumentFragment content) { DitaClass clazz = null; if (content.hasChildNodes()) { final NodeList nodeList = content.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { final Element elem = (Element) node; clazz = new DitaClass(elem.getAttribute(ATTRIBUTE_NAME_CLASS)); break; // get type of the target element } } } return targetClassAttribute.matches(clazz); }
[ "private", "boolean", "isPushedTypeMatch", "(", "final", "DitaClass", "targetClassAttribute", ",", "final", "DocumentFragment", "content", ")", "{", "DitaClass", "clazz", "=", "null", ";", "if", "(", "content", ".", "hasChildNodes", "(", ")", ")", "{", "final", "NodeList", "nodeList", "=", "content", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodeList", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "final", "Node", "node", "=", "nodeList", ".", "item", "(", "i", ")", ";", "if", "(", "node", ".", "getNodeType", "(", ")", "==", "Node", ".", "ELEMENT_NODE", ")", "{", "final", "Element", "elem", "=", "(", "Element", ")", "node", ";", "clazz", "=", "new", "DitaClass", "(", "elem", ".", "getAttribute", "(", "ATTRIBUTE_NAME_CLASS", ")", ")", ";", "break", ";", "// get type of the target element", "}", "}", "}", "return", "targetClassAttribute", ".", "matches", "(", "clazz", ")", ";", "}" ]
The function is to judge if the pushed content type march the type of content being pushed/replaced @param targetClassAttribute the class attribute of target element which is being pushed @param content pushedContent @return boolean: if type match, return true, else return false
[ "The", "function", "is", "to", "judge", "if", "the", "pushed", "content", "type", "march", "the", "type", "of", "content", "being", "pushed", "/", "replaced" ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/writer/ConrefPushParser.java#L261-L278
elki-project/elki
elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/strategies/split/MSTSplit.java
MSTSplit.omitEdge
private static void omitEdge(int[] edges, int[] idx, int[] sizes, int omit) { """ Partition the data by omitting one edge. @param edges Edges list @param idx Partition index storage @param sizes Partition sizes @param omit Edge number to omit """ for(int i = 0; i < idx.length; i++) { idx[i] = i; } Arrays.fill(sizes, 1); for(int i = 0, j = 0, e = edges.length - 1; j < e; i++, j += 2) { if(i == omit) { continue; } int ea = edges[j + 1], eb = edges[j]; if(eb < ea) { // Swap int tmp = eb; eb = ea; ea = tmp; } final int pa = follow(ea, idx), pb = follow(eb, idx); assert (pa != pb) : "Must be disjoint - MST inconsistent."; sizes[idx[pa]] += sizes[idx[pb]]; idx[pb] = idx[pa]; } }
java
private static void omitEdge(int[] edges, int[] idx, int[] sizes, int omit) { for(int i = 0; i < idx.length; i++) { idx[i] = i; } Arrays.fill(sizes, 1); for(int i = 0, j = 0, e = edges.length - 1; j < e; i++, j += 2) { if(i == omit) { continue; } int ea = edges[j + 1], eb = edges[j]; if(eb < ea) { // Swap int tmp = eb; eb = ea; ea = tmp; } final int pa = follow(ea, idx), pb = follow(eb, idx); assert (pa != pb) : "Must be disjoint - MST inconsistent."; sizes[idx[pa]] += sizes[idx[pb]]; idx[pb] = idx[pa]; } }
[ "private", "static", "void", "omitEdge", "(", "int", "[", "]", "edges", ",", "int", "[", "]", "idx", ",", "int", "[", "]", "sizes", ",", "int", "omit", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "idx", ".", "length", ";", "i", "++", ")", "{", "idx", "[", "i", "]", "=", "i", ";", "}", "Arrays", ".", "fill", "(", "sizes", ",", "1", ")", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "0", ",", "e", "=", "edges", ".", "length", "-", "1", ";", "j", "<", "e", ";", "i", "++", ",", "j", "+=", "2", ")", "{", "if", "(", "i", "==", "omit", ")", "{", "continue", ";", "}", "int", "ea", "=", "edges", "[", "j", "+", "1", "]", ",", "eb", "=", "edges", "[", "j", "]", ";", "if", "(", "eb", "<", "ea", ")", "{", "// Swap", "int", "tmp", "=", "eb", ";", "eb", "=", "ea", ";", "ea", "=", "tmp", ";", "}", "final", "int", "pa", "=", "follow", "(", "ea", ",", "idx", ")", ",", "pb", "=", "follow", "(", "eb", ",", "idx", ")", ";", "assert", "(", "pa", "!=", "pb", ")", ":", "\"Must be disjoint - MST inconsistent.\"", ";", "sizes", "[", "idx", "[", "pa", "]", "]", "+=", "sizes", "[", "idx", "[", "pb", "]", "]", ";", "idx", "[", "pb", "]", "=", "idx", "[", "pa", "]", ";", "}", "}" ]
Partition the data by omitting one edge. @param edges Edges list @param idx Partition index storage @param sizes Partition sizes @param omit Edge number to omit
[ "Partition", "the", "data", "by", "omitting", "one", "edge", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/strategies/split/MSTSplit.java#L196-L216
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslContext.java
SslContext.newClientContext
@Deprecated public static SslContext newClientContext(TrustManagerFactory trustManagerFactory) throws SSLException { """ Creates a new client-side {@link SslContext}. @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s that verifies the certificates sent from servers. {@code null} to use the default. @return a new client-side {@link SslContext} @deprecated Replaced by {@link SslContextBuilder} """ return newClientContext(null, null, trustManagerFactory); }
java
@Deprecated public static SslContext newClientContext(TrustManagerFactory trustManagerFactory) throws SSLException { return newClientContext(null, null, trustManagerFactory); }
[ "@", "Deprecated", "public", "static", "SslContext", "newClientContext", "(", "TrustManagerFactory", "trustManagerFactory", ")", "throws", "SSLException", "{", "return", "newClientContext", "(", "null", ",", "null", ",", "trustManagerFactory", ")", ";", "}" ]
Creates a new client-side {@link SslContext}. @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s that verifies the certificates sent from servers. {@code null} to use the default. @return a new client-side {@link SslContext} @deprecated Replaced by {@link SslContextBuilder}
[ "Creates", "a", "new", "client", "-", "side", "{", "@link", "SslContext", "}", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslContext.java#L478-L481
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java
Utils.findClassInPackageElement
public TypeElement findClassInPackageElement(PackageElement pkg, String className) { """ Lookup for a class within this package. @return TypeElement of found class, or null if not found. """ for (TypeElement c : getAllClasses(pkg)) { if (getSimpleName(c).equals(className)) { return c; } } return null; }
java
public TypeElement findClassInPackageElement(PackageElement pkg, String className) { for (TypeElement c : getAllClasses(pkg)) { if (getSimpleName(c).equals(className)) { return c; } } return null; }
[ "public", "TypeElement", "findClassInPackageElement", "(", "PackageElement", "pkg", ",", "String", "className", ")", "{", "for", "(", "TypeElement", "c", ":", "getAllClasses", "(", "pkg", ")", ")", "{", "if", "(", "getSimpleName", "(", "c", ")", ".", "equals", "(", "className", ")", ")", "{", "return", "c", ";", "}", "}", "return", "null", ";", "}" ]
Lookup for a class within this package. @return TypeElement of found class, or null if not found.
[ "Lookup", "for", "a", "class", "within", "this", "package", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java#L1046-L1053
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java
VirtualMachineScaleSetsInner.beginRestartAsync
public Observable<OperationStatusResponseInner> beginRestartAsync(String resourceGroupName, String vmScaleSetName) { """ Restarts one or more virtual machines in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatusResponseInner object """ return beginRestartWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
java
public Observable<OperationStatusResponseInner> beginRestartAsync(String resourceGroupName, String vmScaleSetName) { return beginRestartWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatusResponseInner", ">", "beginRestartAsync", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ")", "{", "return", "beginRestartWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "OperationStatusResponseInner", ">", ",", "OperationStatusResponseInner", ">", "(", ")", "{", "@", "Override", "public", "OperationStatusResponseInner", "call", "(", "ServiceResponse", "<", "OperationStatusResponseInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Restarts one or more virtual machines in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatusResponseInner object
[ "Restarts", "one", "or", "more", "virtual", "machines", "in", "a", "VM", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java#L2230-L2237
knowm/XChange
xchange-anx/src/main/java/org/knowm/xchange/anx/v2/ANXAdapters.java
ANXAdapters.adaptTrades
public static Trades adaptTrades(List<ANXTrade> anxTrades) { """ Adapts ANXTrade's to a Trades Object @param anxTrades @return """ List<Trade> tradesList = new ArrayList<>(); long latestTid = 0; for (ANXTrade anxTrade : anxTrades) { long tid = anxTrade.getTid(); if (tid > latestTid) { latestTid = tid; } tradesList.add(adaptTrade(anxTrade)); } return new Trades(tradesList, latestTid, TradeSortType.SortByID); }
java
public static Trades adaptTrades(List<ANXTrade> anxTrades) { List<Trade> tradesList = new ArrayList<>(); long latestTid = 0; for (ANXTrade anxTrade : anxTrades) { long tid = anxTrade.getTid(); if (tid > latestTid) { latestTid = tid; } tradesList.add(adaptTrade(anxTrade)); } return new Trades(tradesList, latestTid, TradeSortType.SortByID); }
[ "public", "static", "Trades", "adaptTrades", "(", "List", "<", "ANXTrade", ">", "anxTrades", ")", "{", "List", "<", "Trade", ">", "tradesList", "=", "new", "ArrayList", "<>", "(", ")", ";", "long", "latestTid", "=", "0", ";", "for", "(", "ANXTrade", "anxTrade", ":", "anxTrades", ")", "{", "long", "tid", "=", "anxTrade", ".", "getTid", "(", ")", ";", "if", "(", "tid", ">", "latestTid", ")", "{", "latestTid", "=", "tid", ";", "}", "tradesList", ".", "add", "(", "adaptTrade", "(", "anxTrade", ")", ")", ";", "}", "return", "new", "Trades", "(", "tradesList", ",", "latestTid", ",", "TradeSortType", ".", "SortByID", ")", ";", "}" ]
Adapts ANXTrade's to a Trades Object @param anxTrades @return
[ "Adapts", "ANXTrade", "s", "to", "a", "Trades", "Object" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-anx/src/main/java/org/knowm/xchange/anx/v2/ANXAdapters.java#L207-L219
apereo/cas
support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/PasswordManagementWebflowUtils.java
PasswordManagementWebflowUtils.putPasswordResetPasswordPolicyPattern
public static String putPasswordResetPasswordPolicyPattern(final RequestContext requestContext, final String policyPattern) { """ Put password reset password policy pattern string. @param requestContext the request context @param policyPattern the policy pattern @return the string """ val flowScope = requestContext.getFlowScope(); return flowScope.getString("policyPattern"); }
java
public static String putPasswordResetPasswordPolicyPattern(final RequestContext requestContext, final String policyPattern) { val flowScope = requestContext.getFlowScope(); return flowScope.getString("policyPattern"); }
[ "public", "static", "String", "putPasswordResetPasswordPolicyPattern", "(", "final", "RequestContext", "requestContext", ",", "final", "String", "policyPattern", ")", "{", "val", "flowScope", "=", "requestContext", ".", "getFlowScope", "(", ")", ";", "return", "flowScope", ".", "getString", "(", "\"policyPattern\"", ")", ";", "}" ]
Put password reset password policy pattern string. @param requestContext the request context @param policyPattern the policy pattern @return the string
[ "Put", "password", "reset", "password", "policy", "pattern", "string", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/PasswordManagementWebflowUtils.java#L124-L127
OpenLiberty/open-liberty
dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java
RepositoryResolver.createInstallList
List<RepositoryResource> createInstallList(SampleResource resource) { """ Create a list of resources which should be installed in order to install the given sample. <p> The install list consists of all the dependencies which are needed by {@code resource}, ordered so that each resource in the list comes after its dependencies. @param resource the resource which is to be installed @return the ordered list of resources to install """ Map<String, Integer> maxDistanceMap = new HashMap<>(); List<MissingRequirement> missingRequirements = new ArrayList<>(); boolean allDependenciesResolved = true; if (resource.getRequireFeature() != null) { for (String featureName : resource.getRequireFeature()) { // Check that the sample actually exists ProvisioningFeatureDefinition feature = resolverRepository.getFeature(featureName); if (feature == null) { allDependenciesResolved = false; // Unless we know it exists but applies to another product, note the missing requirement as well if (!requirementsFoundForOtherProducts.contains(featureName)) { missingRequirements.add(new MissingRequirement(featureName, resource)); } } // Build distance map and check dependencies allDependenciesResolved &= populateMaxDistanceMap(maxDistanceMap, featureName, 1, new HashSet<ProvisioningFeatureDefinition>(), missingRequirements); } } if (!allDependenciesResolved) { missingTopLevelRequirements.add(resource.getShortName()); this.missingRequirements.addAll(missingRequirements); } ArrayList<RepositoryResource> installList = new ArrayList<>(); installList.addAll(convertFeatureNamesToResources(maxDistanceMap.keySet())); Collections.sort(installList, byMaxDistance(maxDistanceMap)); installList.add(resource); return installList; }
java
List<RepositoryResource> createInstallList(SampleResource resource) { Map<String, Integer> maxDistanceMap = new HashMap<>(); List<MissingRequirement> missingRequirements = new ArrayList<>(); boolean allDependenciesResolved = true; if (resource.getRequireFeature() != null) { for (String featureName : resource.getRequireFeature()) { // Check that the sample actually exists ProvisioningFeatureDefinition feature = resolverRepository.getFeature(featureName); if (feature == null) { allDependenciesResolved = false; // Unless we know it exists but applies to another product, note the missing requirement as well if (!requirementsFoundForOtherProducts.contains(featureName)) { missingRequirements.add(new MissingRequirement(featureName, resource)); } } // Build distance map and check dependencies allDependenciesResolved &= populateMaxDistanceMap(maxDistanceMap, featureName, 1, new HashSet<ProvisioningFeatureDefinition>(), missingRequirements); } } if (!allDependenciesResolved) { missingTopLevelRequirements.add(resource.getShortName()); this.missingRequirements.addAll(missingRequirements); } ArrayList<RepositoryResource> installList = new ArrayList<>(); installList.addAll(convertFeatureNamesToResources(maxDistanceMap.keySet())); Collections.sort(installList, byMaxDistance(maxDistanceMap)); installList.add(resource); return installList; }
[ "List", "<", "RepositoryResource", ">", "createInstallList", "(", "SampleResource", "resource", ")", "{", "Map", "<", "String", ",", "Integer", ">", "maxDistanceMap", "=", "new", "HashMap", "<>", "(", ")", ";", "List", "<", "MissingRequirement", ">", "missingRequirements", "=", "new", "ArrayList", "<>", "(", ")", ";", "boolean", "allDependenciesResolved", "=", "true", ";", "if", "(", "resource", ".", "getRequireFeature", "(", ")", "!=", "null", ")", "{", "for", "(", "String", "featureName", ":", "resource", ".", "getRequireFeature", "(", ")", ")", "{", "// Check that the sample actually exists", "ProvisioningFeatureDefinition", "feature", "=", "resolverRepository", ".", "getFeature", "(", "featureName", ")", ";", "if", "(", "feature", "==", "null", ")", "{", "allDependenciesResolved", "=", "false", ";", "// Unless we know it exists but applies to another product, note the missing requirement as well", "if", "(", "!", "requirementsFoundForOtherProducts", ".", "contains", "(", "featureName", ")", ")", "{", "missingRequirements", ".", "add", "(", "new", "MissingRequirement", "(", "featureName", ",", "resource", ")", ")", ";", "}", "}", "// Build distance map and check dependencies", "allDependenciesResolved", "&=", "populateMaxDistanceMap", "(", "maxDistanceMap", ",", "featureName", ",", "1", ",", "new", "HashSet", "<", "ProvisioningFeatureDefinition", ">", "(", ")", ",", "missingRequirements", ")", ";", "}", "}", "if", "(", "!", "allDependenciesResolved", ")", "{", "missingTopLevelRequirements", ".", "add", "(", "resource", ".", "getShortName", "(", ")", ")", ";", "this", ".", "missingRequirements", ".", "addAll", "(", "missingRequirements", ")", ";", "}", "ArrayList", "<", "RepositoryResource", ">", "installList", "=", "new", "ArrayList", "<>", "(", ")", ";", "installList", ".", "addAll", "(", "convertFeatureNamesToResources", "(", "maxDistanceMap", ".", "keySet", "(", ")", ")", ")", ";", "Collections", ".", "sort", "(", "installList", ",", "byMaxDistance", "(", "maxDistanceMap", ")", ")", ";", "installList", ".", "add", "(", "resource", ")", ";", "return", "installList", ";", "}" ]
Create a list of resources which should be installed in order to install the given sample. <p> The install list consists of all the dependencies which are needed by {@code resource}, ordered so that each resource in the list comes after its dependencies. @param resource the resource which is to be installed @return the ordered list of resources to install
[ "Create", "a", "list", "of", "resources", "which", "should", "be", "installed", "in", "order", "to", "install", "the", "given", "sample", ".", "<p", ">", "The", "install", "list", "consists", "of", "all", "the", "dependencies", "which", "are", "needed", "by", "{", "@code", "resource", "}", "ordered", "so", "that", "each", "resource", "in", "the", "list", "comes", "after", "its", "dependencies", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.repository.resolver/src/com/ibm/ws/repository/resolver/RepositoryResolver.java#L499-L535
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java
PaymentProtocol.createPaymentRequest
public static Protos.PaymentRequest.Builder createPaymentRequest(NetworkParameters params, @Nullable Coin amount, Address toAddress, @Nullable String memo, @Nullable String paymentUrl, @Nullable byte[] merchantData) { """ Create a payment request with one standard pay to address output. You may want to sign the request using {@link #signPaymentRequest}. Use {@link Protos.PaymentRequest.Builder#build} to get the actual payment request. @param params network parameters @param amount amount of coins to request, or null @param toAddress address to request coins to @param memo arbitrary, user readable memo, or null if none @param paymentUrl URL to send payment message to, or null if none @param merchantData arbitrary merchant data, or null if none @return created payment request, in its builder form """ return createPaymentRequest(params, ImmutableList.of(createPayToAddressOutput(amount, toAddress)), memo, paymentUrl, merchantData); }
java
public static Protos.PaymentRequest.Builder createPaymentRequest(NetworkParameters params, @Nullable Coin amount, Address toAddress, @Nullable String memo, @Nullable String paymentUrl, @Nullable byte[] merchantData) { return createPaymentRequest(params, ImmutableList.of(createPayToAddressOutput(amount, toAddress)), memo, paymentUrl, merchantData); }
[ "public", "static", "Protos", ".", "PaymentRequest", ".", "Builder", "createPaymentRequest", "(", "NetworkParameters", "params", ",", "@", "Nullable", "Coin", "amount", ",", "Address", "toAddress", ",", "@", "Nullable", "String", "memo", ",", "@", "Nullable", "String", "paymentUrl", ",", "@", "Nullable", "byte", "[", "]", "merchantData", ")", "{", "return", "createPaymentRequest", "(", "params", ",", "ImmutableList", ".", "of", "(", "createPayToAddressOutput", "(", "amount", ",", "toAddress", ")", ")", ",", "memo", ",", "paymentUrl", ",", "merchantData", ")", ";", "}" ]
Create a payment request with one standard pay to address output. You may want to sign the request using {@link #signPaymentRequest}. Use {@link Protos.PaymentRequest.Builder#build} to get the actual payment request. @param params network parameters @param amount amount of coins to request, or null @param toAddress address to request coins to @param memo arbitrary, user readable memo, or null if none @param paymentUrl URL to send payment message to, or null if none @param merchantData arbitrary merchant data, or null if none @return created payment request, in its builder form
[ "Create", "a", "payment", "request", "with", "one", "standard", "pay", "to", "address", "output", ".", "You", "may", "want", "to", "sign", "the", "request", "using", "{", "@link", "#signPaymentRequest", "}", ".", "Use", "{", "@link", "Protos", ".", "PaymentRequest", ".", "Builder#build", "}", "to", "get", "the", "actual", "payment", "request", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java#L68-L73
ops4j/org.ops4j.pax.logging
pax-logging-service/src/main/java/org/apache/log4j/rule/InequalityRule.java
InequalityRule.getRule
public static Rule getRule(final String inequalitySymbol, final Stack stack) { """ Create new instance from top two elements on stack. @param inequalitySymbol inequality symbol. @param stack stack. @return rule. """ if (stack.size() < 2) { throw new IllegalArgumentException("Invalid " + inequalitySymbol + " rule - expected two parameters but received " + stack.size()); } String p2 = stack.pop().toString(); String p1 = stack.pop().toString(); return getRule(inequalitySymbol, p1, p2); }
java
public static Rule getRule(final String inequalitySymbol, final Stack stack) { if (stack.size() < 2) { throw new IllegalArgumentException("Invalid " + inequalitySymbol + " rule - expected two parameters but received " + stack.size()); } String p2 = stack.pop().toString(); String p1 = stack.pop().toString(); return getRule(inequalitySymbol, p1, p2); }
[ "public", "static", "Rule", "getRule", "(", "final", "String", "inequalitySymbol", ",", "final", "Stack", "stack", ")", "{", "if", "(", "stack", ".", "size", "(", ")", "<", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid \"", "+", "inequalitySymbol", "+", "\" rule - expected two parameters but received \"", "+", "stack", ".", "size", "(", ")", ")", ";", "}", "String", "p2", "=", "stack", ".", "pop", "(", ")", ".", "toString", "(", ")", ";", "String", "p1", "=", "stack", ".", "pop", "(", ")", ".", "toString", "(", ")", ";", "return", "getRule", "(", "inequalitySymbol", ",", "p1", ",", "p2", ")", ";", "}" ]
Create new instance from top two elements on stack. @param inequalitySymbol inequality symbol. @param stack stack. @return rule.
[ "Create", "new", "instance", "from", "top", "two", "elements", "on", "stack", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/rule/InequalityRule.java#L89-L100
rundeck/rundeck
core/src/main/java/com/dtolabs/shared/resources/ResourceXMLParser.java
ResourceXMLParser.parseEntProperties
private void parseEntProperties(final Entity ent, final Node node) throws ResourceXMLParserException { """ Parse the DOM attributes as properties for the particular entity node type @param ent Entity object @param node entity DOM node @throws ResourceXMLParserException if the DOM node is an unexpected tag name """ if (null == entityProperties.get(node.getName())) { throw new ResourceXMLParserException( "Unexpected entity declaration: " + node.getName() + ": " + reportNodeErrorLocation(node)); } final Element node1 = (Element) node; //load all element attributes as properties for (final Object o : node1.attributes()) { final Attribute attr = (Attribute) o; ent.properties.setProperty(attr.getName(), attr.getStringValue()); } }
java
private void parseEntProperties(final Entity ent, final Node node) throws ResourceXMLParserException { if (null == entityProperties.get(node.getName())) { throw new ResourceXMLParserException( "Unexpected entity declaration: " + node.getName() + ": " + reportNodeErrorLocation(node)); } final Element node1 = (Element) node; //load all element attributes as properties for (final Object o : node1.attributes()) { final Attribute attr = (Attribute) o; ent.properties.setProperty(attr.getName(), attr.getStringValue()); } }
[ "private", "void", "parseEntProperties", "(", "final", "Entity", "ent", ",", "final", "Node", "node", ")", "throws", "ResourceXMLParserException", "{", "if", "(", "null", "==", "entityProperties", ".", "get", "(", "node", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "ResourceXMLParserException", "(", "\"Unexpected entity declaration: \"", "+", "node", ".", "getName", "(", ")", "+", "\": \"", "+", "reportNodeErrorLocation", "(", "node", ")", ")", ";", "}", "final", "Element", "node1", "=", "(", "Element", ")", "node", ";", "//load all element attributes as properties", "for", "(", "final", "Object", "o", ":", "node1", ".", "attributes", "(", ")", ")", "{", "final", "Attribute", "attr", "=", "(", "Attribute", ")", "o", ";", "ent", ".", "properties", ".", "setProperty", "(", "attr", ".", "getName", "(", ")", ",", "attr", ".", "getStringValue", "(", ")", ")", ";", "}", "}" ]
Parse the DOM attributes as properties for the particular entity node type @param ent Entity object @param node entity DOM node @throws ResourceXMLParserException if the DOM node is an unexpected tag name
[ "Parse", "the", "DOM", "attributes", "as", "properties", "for", "the", "particular", "entity", "node", "type" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/shared/resources/ResourceXMLParser.java#L225-L236
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.validIndex
public static <T extends CharSequence> T validIndex(final T chars, final int index) { """ <p>Validates that the index is within the bounds of the argument character sequence; otherwise throwing an exception.</p> <pre>Validate.validIndex(myStr, 2);</pre> <p>If the character sequence is {@code null}, then the message of the exception is &quot;The validated object is null&quot;.</p> <p>If the index is invalid, then the message of the exception is &quot;The validated character sequence index is invalid: &quot; followed by the index.</p> @param <T> the character sequence type @param chars the character sequence to check, validated not null by this method @param index the index to check @return the validated character sequence (never {@code null} for method chaining) @throws NullPointerException if the character sequence is {@code null} @throws IndexOutOfBoundsException if the index is invalid @see #validIndex(CharSequence, int, String, Object...) @since 3.0 """ return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index)); }
java
public static <T extends CharSequence> T validIndex(final T chars, final int index) { return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index)); }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "validIndex", "(", "final", "T", "chars", ",", "final", "int", "index", ")", "{", "return", "validIndex", "(", "chars", ",", "index", ",", "DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE", ",", "Integer", ".", "valueOf", "(", "index", ")", ")", ";", "}" ]
<p>Validates that the index is within the bounds of the argument character sequence; otherwise throwing an exception.</p> <pre>Validate.validIndex(myStr, 2);</pre> <p>If the character sequence is {@code null}, then the message of the exception is &quot;The validated object is null&quot;.</p> <p>If the index is invalid, then the message of the exception is &quot;The validated character sequence index is invalid: &quot; followed by the index.</p> @param <T> the character sequence type @param chars the character sequence to check, validated not null by this method @param index the index to check @return the validated character sequence (never {@code null} for method chaining) @throws NullPointerException if the character sequence is {@code null} @throws IndexOutOfBoundsException if the index is invalid @see #validIndex(CharSequence, int, String, Object...) @since 3.0
[ "<p", ">", "Validates", "that", "the", "index", "is", "within", "the", "bounds", "of", "the", "argument", "character", "sequence", ";", "otherwise", "throwing", "an", "exception", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L785-L787
ArcBees/gwtquery
gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/MousePlugin.java
MousePlugin.mouseMove
protected boolean mouseMove(Element element, GqEvent event) { """ Method called on MouseMove event. You should not override this method. Instead, override {@link #mouseMove(Element, GqEvent)} method """ if (started) { event.getOriginalEvent().preventDefault(); return mouseDrag(element, event); } if (delayConditionMet() && distanceConditionMet(event)) { started = mouseStart(element, startEvent); if (started) { mouseDrag(element, event); } else { mouseUp(element, event); } } return !started; }
java
protected boolean mouseMove(Element element, GqEvent event) { if (started) { event.getOriginalEvent().preventDefault(); return mouseDrag(element, event); } if (delayConditionMet() && distanceConditionMet(event)) { started = mouseStart(element, startEvent); if (started) { mouseDrag(element, event); } else { mouseUp(element, event); } } return !started; }
[ "protected", "boolean", "mouseMove", "(", "Element", "element", ",", "GqEvent", "event", ")", "{", "if", "(", "started", ")", "{", "event", ".", "getOriginalEvent", "(", ")", ".", "preventDefault", "(", ")", ";", "return", "mouseDrag", "(", "element", ",", "event", ")", ";", "}", "if", "(", "delayConditionMet", "(", ")", "&&", "distanceConditionMet", "(", "event", ")", ")", "{", "started", "=", "mouseStart", "(", "element", ",", "startEvent", ")", ";", "if", "(", "started", ")", "{", "mouseDrag", "(", "element", ",", "event", ")", ";", "}", "else", "{", "mouseUp", "(", "element", ",", "event", ")", ";", "}", "}", "return", "!", "started", ";", "}" ]
Method called on MouseMove event. You should not override this method. Instead, override {@link #mouseMove(Element, GqEvent)} method
[ "Method", "called", "on", "MouseMove", "event", "." ]
train
https://github.com/ArcBees/gwtquery/blob/93e02bc8eb030081061c56134ebee1f585981107/gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/MousePlugin.java#L168-L185
santhosh-tekuri/jlibs
core/src/main/java/jlibs/core/lang/ArrayUtil.java
ArrayUtil.endsWith
public static boolean endsWith(Object array1[], Object array2[]) { """ Returns true if <code>array1</code> ends with <code>array2</code> """ return equals(array1, array1.length-array2.length, array2, 0, array2.length); }
java
public static boolean endsWith(Object array1[], Object array2[]){ return equals(array1, array1.length-array2.length, array2, 0, array2.length); }
[ "public", "static", "boolean", "endsWith", "(", "Object", "array1", "[", "]", ",", "Object", "array2", "[", "]", ")", "{", "return", "equals", "(", "array1", ",", "array1", ".", "length", "-", "array2", ".", "length", ",", "array2", ",", "0", ",", "array2", ".", "length", ")", ";", "}" ]
Returns true if <code>array1</code> ends with <code>array2</code>
[ "Returns", "true", "if", "<code", ">", "array1<", "/", "code", ">", "ends", "with", "<code", ">", "array2<", "/", "code", ">" ]
train
https://github.com/santhosh-tekuri/jlibs/blob/59c28719f054123cf778278154e1b92e943ad232/core/src/main/java/jlibs/core/lang/ArrayUtil.java#L124-L126
dkmfbk/knowledgestore
ks-server-hbase/src/main/java/eu/fbk/knowledgestore/datastore/hbase/utils/TephraHBaseUtils.java
TephraHBaseUtils.getScanner
@Override public ResultScanner getScanner(final String tableName, final Scan scan) { """ Gets a scanner for a specific table @param tableName to get the scanner from @param scan for the specific table @param conf object to get a hold of an HBase table """ logger.debug("TEPHRA Begin of getScanner(" + tableName + ", " + scan + ")"); final TransactionAwareHTable txTable = (TransactionAwareHTable) getTable(tableName); ResultScanner resScanner = null; try { resScanner = txTable.getScanner(scan); } catch (final IOException e) { logger.error("Error while trying to obtain a ResultScanner: " + tableName); logger.error(e.getMessage()); } return resScanner; }
java
@Override public ResultScanner getScanner(final String tableName, final Scan scan) { logger.debug("TEPHRA Begin of getScanner(" + tableName + ", " + scan + ")"); final TransactionAwareHTable txTable = (TransactionAwareHTable) getTable(tableName); ResultScanner resScanner = null; try { resScanner = txTable.getScanner(scan); } catch (final IOException e) { logger.error("Error while trying to obtain a ResultScanner: " + tableName); logger.error(e.getMessage()); } return resScanner; }
[ "@", "Override", "public", "ResultScanner", "getScanner", "(", "final", "String", "tableName", ",", "final", "Scan", "scan", ")", "{", "logger", ".", "debug", "(", "\"TEPHRA Begin of getScanner(\"", "+", "tableName", "+", "\", \"", "+", "scan", "+", "\")\"", ")", ";", "final", "TransactionAwareHTable", "txTable", "=", "(", "TransactionAwareHTable", ")", "getTable", "(", "tableName", ")", ";", "ResultScanner", "resScanner", "=", "null", ";", "try", "{", "resScanner", "=", "txTable", ".", "getScanner", "(", "scan", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Error while trying to obtain a ResultScanner: \"", "+", "tableName", ")", ";", "logger", ".", "error", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "return", "resScanner", ";", "}" ]
Gets a scanner for a specific table @param tableName to get the scanner from @param scan for the specific table @param conf object to get a hold of an HBase table
[ "Gets", "a", "scanner", "for", "a", "specific", "table" ]
train
https://github.com/dkmfbk/knowledgestore/blob/a548101b1dd67fcf72a1ec6f838ea7539bdbbe7a/ks-server-hbase/src/main/java/eu/fbk/knowledgestore/datastore/hbase/utils/TephraHBaseUtils.java#L298-L311
ysc/QuestionAnsweringSystem
deep-qa-web/src/main/java/org/apdplat/qa/api/AskServlet.java
AskServlet.processRequest
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { """ Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. @param request servlet request @param response servlet response @throws ServletException if a servlet-specific error occurs @throws IOException if an I/O error occurs """ response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); String questionStr = request.getParameter("q"); String n = request.getParameter("n"); int topN = -1; if(n != null && StringUtils.isNumeric(n)){ topN = Integer.parseInt(n); } Question question = null; List<CandidateAnswer> candidateAnswers = null; if (questionStr != null && questionStr.trim().length() > 3) { question = SharedQuestionAnsweringSystem.getInstance().answerQuestion(questionStr); if (question != null) { candidateAnswers = question.getAllCandidateAnswer(); } } LOG.info("问题:"+questionStr); try (PrintWriter out = response.getWriter()) { String json = JsonGenerator.generate(candidateAnswers, topN); out.println(json); LOG.info("答案:"+json); } }
java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); String questionStr = request.getParameter("q"); String n = request.getParameter("n"); int topN = -1; if(n != null && StringUtils.isNumeric(n)){ topN = Integer.parseInt(n); } Question question = null; List<CandidateAnswer> candidateAnswers = null; if (questionStr != null && questionStr.trim().length() > 3) { question = SharedQuestionAnsweringSystem.getInstance().answerQuestion(questionStr); if (question != null) { candidateAnswers = question.getAllCandidateAnswer(); } } LOG.info("问题:"+questionStr); try (PrintWriter out = response.getWriter()) { String json = JsonGenerator.generate(candidateAnswers, topN); out.println(json); LOG.info("答案:"+json); } }
[ "protected", "void", "processRequest", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "response", ".", "setContentType", "(", "\"application/json;charset=UTF-8\"", ")", ";", "response", ".", "setCharacterEncoding", "(", "\"UTF-8\"", ")", ";", "request", ".", "setCharacterEncoding", "(", "\"UTF-8\"", ")", ";", "String", "questionStr", "=", "request", ".", "getParameter", "(", "\"q\"", ")", ";", "String", "n", "=", "request", ".", "getParameter", "(", "\"n\"", ")", ";", "int", "topN", "=", "-", "1", ";", "if", "(", "n", "!=", "null", "&&", "StringUtils", ".", "isNumeric", "(", "n", ")", ")", "{", "topN", "=", "Integer", ".", "parseInt", "(", "n", ")", ";", "}", "Question", "question", "=", "null", ";", "List", "<", "CandidateAnswer", ">", "candidateAnswers", "=", "null", ";", "if", "(", "questionStr", "!=", "null", "&&", "questionStr", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "3", ")", "{", "question", "=", "SharedQuestionAnsweringSystem", ".", "getInstance", "(", ")", ".", "answerQuestion", "(", "questionStr", ")", ";", "if", "(", "question", "!=", "null", ")", "{", "candidateAnswers", "=", "question", ".", "getAllCandidateAnswer", "(", ")", ";", "}", "}", "LOG", ".", "info", "(", "\"问题:\"+quest", "i", "onStr); \r", "", "", "try", "(", "PrintWriter", "out", "=", "response", ".", "getWriter", "(", ")", ")", "{", "String", "json", "=", "JsonGenerator", ".", "generate", "(", "candidateAnswers", ",", "topN", ")", ";", "out", ".", "println", "(", "json", ")", ";", "LOG", ".", "info", "(", "\"答案:\"+json)", ";", "\r", "", "", "}", "}" ]
Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. @param request servlet request @param response servlet response @throws ServletException if a servlet-specific error occurs @throws IOException if an I/O error occurs
[ "Processes", "requests", "for", "both", "HTTP", "<code", ">", "GET<", "/", "code", ">", "and", "<code", ">", "POST<", "/", "code", ">", "methods", "." ]
train
https://github.com/ysc/QuestionAnsweringSystem/blob/83f43625f1e0c2f4b72ebca7b0d8282fdf77c997/deep-qa-web/src/main/java/org/apdplat/qa/api/AskServlet.java#L55-L81
deeplearning4j/deeplearning4j
arbiter/arbiter-ui/src/main/java/org/deeplearning4j/arbiter/ui/misc/UIUtils.java
UIUtils.graphNiceRange
public static double[] graphNiceRange(double max, double min, int nTick) { """ Convert the "messy" min/max values on a dataset to something clean. For example, 0.895732 becomes 1.0 @param max Maximum data point value @param min Minimum data point value @param nTick Number of tick marks desired on chart (good setting: 5) @return double[] of length 2 - with new minimum and maximum """ if(max == min || !Double.isFinite(max)){ if(max == 0.0 || !Double.isFinite(max)){ return new double[]{0.0, 1.0}; } return graphNiceRange(1.5 * max, 0.5 * max, nTick); } double range = niceNum(max-min, false); double d = niceNum(range / (nTick-1), true ); double graphMin = Math.floor(min/d)*d; double graphMax = Math.ceil(max/d)*d; return new double[]{graphMin, graphMax}; }
java
public static double[] graphNiceRange(double max, double min, int nTick){ if(max == min || !Double.isFinite(max)){ if(max == 0.0 || !Double.isFinite(max)){ return new double[]{0.0, 1.0}; } return graphNiceRange(1.5 * max, 0.5 * max, nTick); } double range = niceNum(max-min, false); double d = niceNum(range / (nTick-1), true ); double graphMin = Math.floor(min/d)*d; double graphMax = Math.ceil(max/d)*d; return new double[]{graphMin, graphMax}; }
[ "public", "static", "double", "[", "]", "graphNiceRange", "(", "double", "max", ",", "double", "min", ",", "int", "nTick", ")", "{", "if", "(", "max", "==", "min", "||", "!", "Double", ".", "isFinite", "(", "max", ")", ")", "{", "if", "(", "max", "==", "0.0", "||", "!", "Double", ".", "isFinite", "(", "max", ")", ")", "{", "return", "new", "double", "[", "]", "{", "0.0", ",", "1.0", "}", ";", "}", "return", "graphNiceRange", "(", "1.5", "*", "max", ",", "0.5", "*", "max", ",", "nTick", ")", ";", "}", "double", "range", "=", "niceNum", "(", "max", "-", "min", ",", "false", ")", ";", "double", "d", "=", "niceNum", "(", "range", "/", "(", "nTick", "-", "1", ")", ",", "true", ")", ";", "double", "graphMin", "=", "Math", ".", "floor", "(", "min", "/", "d", ")", "*", "d", ";", "double", "graphMax", "=", "Math", ".", "ceil", "(", "max", "/", "d", ")", "*", "d", ";", "return", "new", "double", "[", "]", "{", "graphMin", ",", "graphMax", "}", ";", "}" ]
Convert the "messy" min/max values on a dataset to something clean. For example, 0.895732 becomes 1.0 @param max Maximum data point value @param min Minimum data point value @param nTick Number of tick marks desired on chart (good setting: 5) @return double[] of length 2 - with new minimum and maximum
[ "Convert", "the", "messy", "min", "/", "max", "values", "on", "a", "dataset", "to", "something", "clean", ".", "For", "example", "0", ".", "895732", "becomes", "1", ".", "0" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/arbiter/arbiter-ui/src/main/java/org/deeplearning4j/arbiter/ui/misc/UIUtils.java#L37-L53
HiddenStage/divide
Client/java-client/src/main/java/io/divide/client/BackendUser.java
BackendUser.signInInBackground
public static Observable<BackendUser> signInInBackground(String email, String password) { """ Perform asyncronously login attempt. @param email user email address @param password user password @return login results as observable. """ return getAM().loginASync(new LoginCredentials(email, password)); }
java
public static Observable<BackendUser> signInInBackground(String email, String password){ return getAM().loginASync(new LoginCredentials(email, password)); }
[ "public", "static", "Observable", "<", "BackendUser", ">", "signInInBackground", "(", "String", "email", ",", "String", "password", ")", "{", "return", "getAM", "(", ")", ".", "loginASync", "(", "new", "LoginCredentials", "(", "email", ",", "password", ")", ")", ";", "}" ]
Perform asyncronously login attempt. @param email user email address @param password user password @return login results as observable.
[ "Perform", "asyncronously", "login", "attempt", "." ]
train
https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/java-client/src/main/java/io/divide/client/BackendUser.java#L182-L184
diirt/util
src/main/java/org/epics/util/time/Timestamp.java
Timestamp.of
public static Timestamp of(Date date) { """ Converts a {@link java.util.Date} to a timestamp. Date is accurate to milliseconds, so the last 6 digits are always going to be zeros. @param date the date to convert @return a new timestamp """ if (date == null) return null; long time = date.getTime(); int nanoSec = (int) (time % 1000) * 1000000; long epochSec = (time / 1000); return createWithCarry(epochSec, nanoSec); }
java
public static Timestamp of(Date date) { if (date == null) return null; long time = date.getTime(); int nanoSec = (int) (time % 1000) * 1000000; long epochSec = (time / 1000); return createWithCarry(epochSec, nanoSec); }
[ "public", "static", "Timestamp", "of", "(", "Date", "date", ")", "{", "if", "(", "date", "==", "null", ")", "return", "null", ";", "long", "time", "=", "date", ".", "getTime", "(", ")", ";", "int", "nanoSec", "=", "(", "int", ")", "(", "time", "%", "1000", ")", "*", "1000000", ";", "long", "epochSec", "=", "(", "time", "/", "1000", ")", ";", "return", "createWithCarry", "(", "epochSec", ",", "nanoSec", ")", ";", "}" ]
Converts a {@link java.util.Date} to a timestamp. Date is accurate to milliseconds, so the last 6 digits are always going to be zeros. @param date the date to convert @return a new timestamp
[ "Converts", "a", "{", "@link", "java", ".", "util", ".", "Date", "}", "to", "a", "timestamp", ".", "Date", "is", "accurate", "to", "milliseconds", "so", "the", "last", "6", "digits", "are", "always", "going", "to", "be", "zeros", "." ]
train
https://github.com/diirt/util/blob/24aca0a173a635aaf0b78d213a3fee8d4f91c077/src/main/java/org/epics/util/time/Timestamp.java#L89-L96
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/BufferedFileWriter.java
BufferedFileWriter.getWriter
private static Writer getWriter(final File aFile) throws FileNotFoundException { """ Gets a writer that can write to the supplied file using the UTF-8 charset. @param aFile A file to which to write @return A writer that writes to the supplied file @throws FileNotFoundException If the supplied file cannot be found """ try { return new OutputStreamWriter(new FileOutputStream(aFile), StandardCharsets.UTF_8.name()); } catch (final java.io.UnsupportedEncodingException details) { throw new UnsupportedEncodingException(details, StandardCharsets.UTF_8.name()); } }
java
private static Writer getWriter(final File aFile) throws FileNotFoundException { try { return new OutputStreamWriter(new FileOutputStream(aFile), StandardCharsets.UTF_8.name()); } catch (final java.io.UnsupportedEncodingException details) { throw new UnsupportedEncodingException(details, StandardCharsets.UTF_8.name()); } }
[ "private", "static", "Writer", "getWriter", "(", "final", "File", "aFile", ")", "throws", "FileNotFoundException", "{", "try", "{", "return", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "aFile", ")", ",", "StandardCharsets", ".", "UTF_8", ".", "name", "(", ")", ")", ";", "}", "catch", "(", "final", "java", ".", "io", ".", "UnsupportedEncodingException", "details", ")", "{", "throw", "new", "UnsupportedEncodingException", "(", "details", ",", "StandardCharsets", ".", "UTF_8", ".", "name", "(", ")", ")", ";", "}", "}" ]
Gets a writer that can write to the supplied file using the UTF-8 charset. @param aFile A file to which to write @return A writer that writes to the supplied file @throws FileNotFoundException If the supplied file cannot be found
[ "Gets", "a", "writer", "that", "can", "write", "to", "the", "supplied", "file", "using", "the", "UTF", "-", "8", "charset", "." ]
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/BufferedFileWriter.java#L47-L53
jbundle/jbundle
thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TaskProxy.java
TaskProxy.createRemoteReceiveQueue
public RemoteReceiveQueue createRemoteReceiveQueue(String strQueueName, String strQueueType) throws RemoteException { """ Create a new remote receive queue. @param strQueueName The queue name. @param strQueueType The queue type (see MessageConstants). """ BaseTransport transport = this.createProxyTransport(CREATE_REMOTE_RECEIVE_QUEUE); transport.addParam(MessageConstants.QUEUE_NAME, strQueueName); transport.addParam(MessageConstants.QUEUE_TYPE, strQueueType); String strID = (String)transport.sendMessageAndGetReply(); return new ReceiveQueueProxy(this, strID); }
java
public RemoteReceiveQueue createRemoteReceiveQueue(String strQueueName, String strQueueType) throws RemoteException { BaseTransport transport = this.createProxyTransport(CREATE_REMOTE_RECEIVE_QUEUE); transport.addParam(MessageConstants.QUEUE_NAME, strQueueName); transport.addParam(MessageConstants.QUEUE_TYPE, strQueueType); String strID = (String)transport.sendMessageAndGetReply(); return new ReceiveQueueProxy(this, strID); }
[ "public", "RemoteReceiveQueue", "createRemoteReceiveQueue", "(", "String", "strQueueName", ",", "String", "strQueueType", ")", "throws", "RemoteException", "{", "BaseTransport", "transport", "=", "this", ".", "createProxyTransport", "(", "CREATE_REMOTE_RECEIVE_QUEUE", ")", ";", "transport", ".", "addParam", "(", "MessageConstants", ".", "QUEUE_NAME", ",", "strQueueName", ")", ";", "transport", ".", "addParam", "(", "MessageConstants", ".", "QUEUE_TYPE", ",", "strQueueType", ")", ";", "String", "strID", "=", "(", "String", ")", "transport", ".", "sendMessageAndGetReply", "(", ")", ";", "return", "new", "ReceiveQueueProxy", "(", "this", ",", "strID", ")", ";", "}" ]
Create a new remote receive queue. @param strQueueName The queue name. @param strQueueType The queue type (see MessageConstants).
[ "Create", "a", "new", "remote", "receive", "queue", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/remote/src/main/java/org/jbundle/thin/base/remote/proxy/TaskProxy.java#L129-L136
tvesalainen/util
util/src/main/java/org/vesalainen/util/Recycler.java
Recycler.get
public static final <T extends Recyclable> T get(Class<T> cls) { """ Returns new or recycled uninitialized object. @param <T> @param cls @return """ return get(cls, null); }
java
public static final <T extends Recyclable> T get(Class<T> cls) { return get(cls, null); }
[ "public", "static", "final", "<", "T", "extends", "Recyclable", ">", "T", "get", "(", "Class", "<", "T", ">", "cls", ")", "{", "return", "get", "(", "cls", ",", "null", ")", ";", "}" ]
Returns new or recycled uninitialized object. @param <T> @param cls @return
[ "Returns", "new", "or", "recycled", "uninitialized", "object", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/Recycler.java#L59-L62
Hygieia/Hygieia
api/src/main/java/com/capitalone/dashboard/service/DashboardRemoteServiceImpl.java
DashboardRemoteServiceImpl.getOwners
private List<Owner> getOwners(DashboardRemoteRequest request) throws HygieiaException { """ Creates a list of unique owners from the owner and owners requests @param request @return List<Owner> list of owners to be added to the dashboard @throws HygieiaException """ DashboardRemoteRequest.DashboardMetaData metaData = request.getMetaData(); Owner owner = metaData.getOwner(); List<Owner> owners = metaData.getOwners(); if (owner == null && CollectionUtils.isEmpty(owners)) { throw new HygieiaException("There are no owner/owners field in the request", HygieiaException.INVALID_CONFIGURATION); } if (owners == null) { owners = new ArrayList<Owner>(); owners.add(owner); } else if (owner != null) { owners.add(owner); } Set<Owner> uniqueOwners = new HashSet<Owner>(owners); return new ArrayList<Owner>(uniqueOwners); }
java
private List<Owner> getOwners(DashboardRemoteRequest request) throws HygieiaException { DashboardRemoteRequest.DashboardMetaData metaData = request.getMetaData(); Owner owner = metaData.getOwner(); List<Owner> owners = metaData.getOwners(); if (owner == null && CollectionUtils.isEmpty(owners)) { throw new HygieiaException("There are no owner/owners field in the request", HygieiaException.INVALID_CONFIGURATION); } if (owners == null) { owners = new ArrayList<Owner>(); owners.add(owner); } else if (owner != null) { owners.add(owner); } Set<Owner> uniqueOwners = new HashSet<Owner>(owners); return new ArrayList<Owner>(uniqueOwners); }
[ "private", "List", "<", "Owner", ">", "getOwners", "(", "DashboardRemoteRequest", "request", ")", "throws", "HygieiaException", "{", "DashboardRemoteRequest", ".", "DashboardMetaData", "metaData", "=", "request", ".", "getMetaData", "(", ")", ";", "Owner", "owner", "=", "metaData", ".", "getOwner", "(", ")", ";", "List", "<", "Owner", ">", "owners", "=", "metaData", ".", "getOwners", "(", ")", ";", "if", "(", "owner", "==", "null", "&&", "CollectionUtils", ".", "isEmpty", "(", "owners", ")", ")", "{", "throw", "new", "HygieiaException", "(", "\"There are no owner/owners field in the request\"", ",", "HygieiaException", ".", "INVALID_CONFIGURATION", ")", ";", "}", "if", "(", "owners", "==", "null", ")", "{", "owners", "=", "new", "ArrayList", "<", "Owner", ">", "(", ")", ";", "owners", ".", "add", "(", "owner", ")", ";", "}", "else", "if", "(", "owner", "!=", "null", ")", "{", "owners", ".", "add", "(", "owner", ")", ";", "}", "Set", "<", "Owner", ">", "uniqueOwners", "=", "new", "HashSet", "<", "Owner", ">", "(", "owners", ")", ";", "return", "new", "ArrayList", "<", "Owner", ">", "(", "uniqueOwners", ")", ";", "}" ]
Creates a list of unique owners from the owner and owners requests @param request @return List<Owner> list of owners to be added to the dashboard @throws HygieiaException
[ "Creates", "a", "list", "of", "unique", "owners", "from", "the", "owner", "and", "owners", "requests" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api/src/main/java/com/capitalone/dashboard/service/DashboardRemoteServiceImpl.java#L72-L90
Harium/keel
src/main/java/com/harium/keel/catalano/math/Tools.java
Tools.Scale
public static double Scale(double fromMin, double fromMax, double toMin, double toMax, double x) { """ Converts the value x (which is measured in the scale 'from') to another value measured in the scale 'to'. @param fromMin Scale min from. @param fromMax Scale max from. @param toMin Scale min to. @param toMax Scale max to. @param x Value. @return Result. """ if (fromMax - fromMin == 0) return 0; return (toMax - toMin) * (x - fromMin) / (fromMax - fromMin) + toMin; }
java
public static double Scale(double fromMin, double fromMax, double toMin, double toMax, double x) { if (fromMax - fromMin == 0) return 0; return (toMax - toMin) * (x - fromMin) / (fromMax - fromMin) + toMin; }
[ "public", "static", "double", "Scale", "(", "double", "fromMin", ",", "double", "fromMax", ",", "double", "toMin", ",", "double", "toMax", ",", "double", "x", ")", "{", "if", "(", "fromMax", "-", "fromMin", "==", "0", ")", "return", "0", ";", "return", "(", "toMax", "-", "toMin", ")", "*", "(", "x", "-", "fromMin", ")", "/", "(", "fromMax", "-", "fromMin", ")", "+", "toMin", ";", "}" ]
Converts the value x (which is measured in the scale 'from') to another value measured in the scale 'to'. @param fromMin Scale min from. @param fromMax Scale max from. @param toMin Scale min to. @param toMax Scale max to. @param x Value. @return Result.
[ "Converts", "the", "value", "x", "(", "which", "is", "measured", "in", "the", "scale", "from", ")", "to", "another", "value", "measured", "in", "the", "scale", "to", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/Tools.java#L463-L466
citrusframework/citrus
modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/functions/Functions.java
Functions.changeDate
public static String changeDate(String date, String dateOffset, String dateFormat, TestContext context) { """ Runs change date function with arguments. @param date @param dateOffset @param dateFormat @return """ return new ChangeDateFunction().execute(Arrays.asList(date, dateOffset, dateFormat), context); }
java
public static String changeDate(String date, String dateOffset, String dateFormat, TestContext context) { return new ChangeDateFunction().execute(Arrays.asList(date, dateOffset, dateFormat), context); }
[ "public", "static", "String", "changeDate", "(", "String", "date", ",", "String", "dateOffset", ",", "String", "dateFormat", ",", "TestContext", "context", ")", "{", "return", "new", "ChangeDateFunction", "(", ")", ".", "execute", "(", "Arrays", ".", "asList", "(", "date", ",", "dateOffset", ",", "dateFormat", ")", ",", "context", ")", ";", "}" ]
Runs change date function with arguments. @param date @param dateOffset @param dateFormat @return
[ "Runs", "change", "date", "function", "with", "arguments", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/functions/Functions.java#L61-L63
stephenc/redmine-java-api
src/main/java/org/redmine/ta/RedmineManager.java
RedmineManager.unwrapIO
private void unwrapIO(RedmineException orig, String tag) throws IOException { """ Unwraps an IO. @param e exception to unwrap. @param tag target tag. @throws IOException @throws RedmineException """ Throwable e = orig; while (e != null) { if (e instanceof MarkedIOException) { final MarkedIOException marked = (MarkedIOException) e; if (tag.equals(marked.getTag())) throw marked.getIOException(); } e = e.getCause(); } }
java
private void unwrapIO(RedmineException orig, String tag) throws IOException { Throwable e = orig; while (e != null) { if (e instanceof MarkedIOException) { final MarkedIOException marked = (MarkedIOException) e; if (tag.equals(marked.getTag())) throw marked.getIOException(); } e = e.getCause(); } }
[ "private", "void", "unwrapIO", "(", "RedmineException", "orig", ",", "String", "tag", ")", "throws", "IOException", "{", "Throwable", "e", "=", "orig", ";", "while", "(", "e", "!=", "null", ")", "{", "if", "(", "e", "instanceof", "MarkedIOException", ")", "{", "final", "MarkedIOException", "marked", "=", "(", "MarkedIOException", ")", "e", ";", "if", "(", "tag", ".", "equals", "(", "marked", ".", "getTag", "(", ")", ")", ")", "throw", "marked", ".", "getIOException", "(", ")", ";", "}", "e", "=", "e", ".", "getCause", "(", ")", ";", "}", "}" ]
Unwraps an IO. @param e exception to unwrap. @param tag target tag. @throws IOException @throws RedmineException
[ "Unwraps", "an", "IO", "." ]
train
https://github.com/stephenc/redmine-java-api/blob/7e5270c84aba32d74a506260ec47ff86ab6c9d84/src/main/java/org/redmine/ta/RedmineManager.java#L721-L731
hawkular/hawkular-commons
hawkular-bus/hawkular-bus-common/src/main/java/org/hawkular/bus/common/ConnectionContextFactory.java
ConnectionContextFactory.createOrReuseConnection
protected void createOrReuseConnection(ConnectionContext context, boolean start) throws JMSException { """ This method provides a way to cache and share a connection across multiple contexts. It combines the creation and setting of the connection. This also can optionally start the connection immediately. Use this if you want to reuse any connection that may already be stored in this processor object (i.e. {@link #getConnection()} is non-null). If there is no connection yet, one will be created. Whether the connection is created or reused, that connection will be stored in the given context. Note that if this object was told not to cache connections, this method will always create a new connection and store it in this object, overwriting any previously created connection (see {@link #cacheConnection}). @param context the connection will be stored in this context @param start if true, the created connection will be started. @throws JMSException any error """ Connection conn; if (isReuseConnection()) { conn = getConnection(); if (conn != null) { // already have a connection cached, give it to the context context.setConnection(conn); } else { // there is no connection yet; create it and cache it createConnection(context); conn = context.getConnection(); cacheConnection(conn, false); } } else { // we are not to cache connections - always create one createConnection(context); conn = context.getConnection(); cacheConnection(conn, false); } if (start) { // Calling start on started connection is ignored. // But if an exception is thrown, we need to throw away the connection try { conn.start(); } catch (JMSException e) { msglog.errorFailedToStartConnection(e); cacheConnection(null, true); throw e; } } }
java
protected void createOrReuseConnection(ConnectionContext context, boolean start) throws JMSException { Connection conn; if (isReuseConnection()) { conn = getConnection(); if (conn != null) { // already have a connection cached, give it to the context context.setConnection(conn); } else { // there is no connection yet; create it and cache it createConnection(context); conn = context.getConnection(); cacheConnection(conn, false); } } else { // we are not to cache connections - always create one createConnection(context); conn = context.getConnection(); cacheConnection(conn, false); } if (start) { // Calling start on started connection is ignored. // But if an exception is thrown, we need to throw away the connection try { conn.start(); } catch (JMSException e) { msglog.errorFailedToStartConnection(e); cacheConnection(null, true); throw e; } } }
[ "protected", "void", "createOrReuseConnection", "(", "ConnectionContext", "context", ",", "boolean", "start", ")", "throws", "JMSException", "{", "Connection", "conn", ";", "if", "(", "isReuseConnection", "(", ")", ")", "{", "conn", "=", "getConnection", "(", ")", ";", "if", "(", "conn", "!=", "null", ")", "{", "// already have a connection cached, give it to the context", "context", ".", "setConnection", "(", "conn", ")", ";", "}", "else", "{", "// there is no connection yet; create it and cache it", "createConnection", "(", "context", ")", ";", "conn", "=", "context", ".", "getConnection", "(", ")", ";", "cacheConnection", "(", "conn", ",", "false", ")", ";", "}", "}", "else", "{", "// we are not to cache connections - always create one", "createConnection", "(", "context", ")", ";", "conn", "=", "context", ".", "getConnection", "(", ")", ";", "cacheConnection", "(", "conn", ",", "false", ")", ";", "}", "if", "(", "start", ")", "{", "// Calling start on started connection is ignored.", "// But if an exception is thrown, we need to throw away the connection", "try", "{", "conn", ".", "start", "(", ")", ";", "}", "catch", "(", "JMSException", "e", ")", "{", "msglog", ".", "errorFailedToStartConnection", "(", "e", ")", ";", "cacheConnection", "(", "null", ",", "true", ")", ";", "throw", "e", ";", "}", "}", "}" ]
This method provides a way to cache and share a connection across multiple contexts. It combines the creation and setting of the connection. This also can optionally start the connection immediately. Use this if you want to reuse any connection that may already be stored in this processor object (i.e. {@link #getConnection()} is non-null). If there is no connection yet, one will be created. Whether the connection is created or reused, that connection will be stored in the given context. Note that if this object was told not to cache connections, this method will always create a new connection and store it in this object, overwriting any previously created connection (see {@link #cacheConnection}). @param context the connection will be stored in this context @param start if true, the created connection will be started. @throws JMSException any error
[ "This", "method", "provides", "a", "way", "to", "cache", "and", "share", "a", "connection", "across", "multiple", "contexts", ".", "It", "combines", "the", "creation", "and", "setting", "of", "the", "connection", ".", "This", "also", "can", "optionally", "start", "the", "connection", "immediately", ".", "Use", "this", "if", "you", "want", "to", "reuse", "any", "connection", "that", "may", "already", "be", "stored", "in", "this", "processor", "object", "(", "i", ".", "e", ".", "{", "@link", "#getConnection", "()", "}", "is", "non", "-", "null", ")", ".", "If", "there", "is", "no", "connection", "yet", "one", "will", "be", "created", ".", "Whether", "the", "connection", "is", "created", "or", "reused", "that", "connection", "will", "be", "stored", "in", "the", "given", "context", "." ]
train
https://github.com/hawkular/hawkular-commons/blob/e4a832862b3446d7f4d629bb05790f2df578e035/hawkular-bus/hawkular-bus-common/src/main/java/org/hawkular/bus/common/ConnectionContextFactory.java#L223-L255
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/registry/GlobalTransformerRegistry.java
GlobalTransformerRegistry.registerTransformer
public void registerTransformer(final PathAddress address, final ModelVersion version, String operationName, OperationTransformer transformer) { """ Register an operation transformer. @param address the operation handler address @param version the model version @param operationName the operation name @param transformer the operation transformer """ registerTransformer(address.iterator(), version, operationName, new OperationTransformerRegistry.OperationTransformerEntry(transformer, false)); }
java
public void registerTransformer(final PathAddress address, final ModelVersion version, String operationName, OperationTransformer transformer) { registerTransformer(address.iterator(), version, operationName, new OperationTransformerRegistry.OperationTransformerEntry(transformer, false)); }
[ "public", "void", "registerTransformer", "(", "final", "PathAddress", "address", ",", "final", "ModelVersion", "version", ",", "String", "operationName", ",", "OperationTransformer", "transformer", ")", "{", "registerTransformer", "(", "address", ".", "iterator", "(", ")", ",", "version", ",", "operationName", ",", "new", "OperationTransformerRegistry", ".", "OperationTransformerEntry", "(", "transformer", ",", "false", ")", ")", ";", "}" ]
Register an operation transformer. @param address the operation handler address @param version the model version @param operationName the operation name @param transformer the operation transformer
[ "Register", "an", "operation", "transformer", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/registry/GlobalTransformerRegistry.java#L136-L138
lessthanoptimal/ejml
main/ejml-simple/src/org/ejml/simple/SimpleBase.java
SimpleBase.set
public void set( int row , int col , double value ) { """ Assigns the element in the Matrix to the specified value. Performs a bounds check to make sure the requested element is part of the matrix. @param row The row of the element. @param col The column of the element. @param value The element's new value. """ ops.set(mat, row, col, value); }
java
public void set( int row , int col , double value ) { ops.set(mat, row, col, value); }
[ "public", "void", "set", "(", "int", "row", ",", "int", "col", ",", "double", "value", ")", "{", "ops", ".", "set", "(", "mat", ",", "row", ",", "col", ",", "value", ")", ";", "}" ]
Assigns the element in the Matrix to the specified value. Performs a bounds check to make sure the requested element is part of the matrix. @param row The row of the element. @param col The column of the element. @param value The element's new value.
[ "Assigns", "the", "element", "in", "the", "Matrix", "to", "the", "specified", "value", ".", "Performs", "a", "bounds", "check", "to", "make", "sure", "the", "requested", "element", "is", "part", "of", "the", "matrix", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-simple/src/org/ejml/simple/SimpleBase.java#L615-L617
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/serialize/write/XMLCharHelper.java
XMLCharHelper.isInvalidXMLTextChar
public static boolean isInvalidXMLTextChar (@Nonnull final EXMLSerializeVersion eXMLVersion, final int c) { """ Check if the passed character is invalid for a text node. @param eXMLVersion XML version to be used. May not be <code>null</code>. @param c char to check @return <code>true</code> if the char is invalid """ switch (eXMLVersion) { case XML_10: return INVALID_VALUE_CHAR_XML10.get (c); case XML_11: return INVALID_TEXT_VALUE_CHAR_XML11.get (c); case HTML: return INVALID_CHAR_HTML.get (c); default: throw new IllegalArgumentException ("Unsupported XML version " + eXMLVersion + "!"); } }
java
public static boolean isInvalidXMLTextChar (@Nonnull final EXMLSerializeVersion eXMLVersion, final int c) { switch (eXMLVersion) { case XML_10: return INVALID_VALUE_CHAR_XML10.get (c); case XML_11: return INVALID_TEXT_VALUE_CHAR_XML11.get (c); case HTML: return INVALID_CHAR_HTML.get (c); default: throw new IllegalArgumentException ("Unsupported XML version " + eXMLVersion + "!"); } }
[ "public", "static", "boolean", "isInvalidXMLTextChar", "(", "@", "Nonnull", "final", "EXMLSerializeVersion", "eXMLVersion", ",", "final", "int", "c", ")", "{", "switch", "(", "eXMLVersion", ")", "{", "case", "XML_10", ":", "return", "INVALID_VALUE_CHAR_XML10", ".", "get", "(", "c", ")", ";", "case", "XML_11", ":", "return", "INVALID_TEXT_VALUE_CHAR_XML11", ".", "get", "(", "c", ")", ";", "case", "HTML", ":", "return", "INVALID_CHAR_HTML", ".", "get", "(", "c", ")", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported XML version \"", "+", "eXMLVersion", "+", "\"!\"", ")", ";", "}", "}" ]
Check if the passed character is invalid for a text node. @param eXMLVersion XML version to be used. May not be <code>null</code>. @param c char to check @return <code>true</code> if the char is invalid
[ "Check", "if", "the", "passed", "character", "is", "invalid", "for", "a", "text", "node", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/serialize/write/XMLCharHelper.java#L778-L791
hawkular/hawkular-alerts
engine/src/main/java/org/hawkular/alerts/engine/impl/AlertsEngineCache.java
AlertsEngineCache.isDataIdActive
public boolean isDataIdActive(String tenantId, String dataId) { """ Check if a specific dataId is active on this node @param tenantId to check if has triggers deployed on this node @param dataId to check if it has triggers deployed on this node @return true if it is active false otherwise """ return tenantId != null && dataId != null && activeDataIds.contains(new DataId(tenantId, dataId)); }
java
public boolean isDataIdActive(String tenantId, String dataId) { return tenantId != null && dataId != null && activeDataIds.contains(new DataId(tenantId, dataId)); }
[ "public", "boolean", "isDataIdActive", "(", "String", "tenantId", ",", "String", "dataId", ")", "{", "return", "tenantId", "!=", "null", "&&", "dataId", "!=", "null", "&&", "activeDataIds", ".", "contains", "(", "new", "DataId", "(", "tenantId", ",", "dataId", ")", ")", ";", "}" ]
Check if a specific dataId is active on this node @param tenantId to check if has triggers deployed on this node @param dataId to check if it has triggers deployed on this node @return true if it is active false otherwise
[ "Check", "if", "a", "specific", "dataId", "is", "active", "on", "this", "node" ]
train
https://github.com/hawkular/hawkular-alerts/blob/b4a0c2909b38e03e72cc1828219562ee8fcbf426/engine/src/main/java/org/hawkular/alerts/engine/impl/AlertsEngineCache.java#L60-L62
hankcs/HanLP
src/main/java/com/hankcs/hanlp/dependency/nnparser/Matrix.java
Matrix.getMatrix
public Matrix getMatrix(int i0, int i1, int j0, int j1) { """ Get a submatrix. @param i0 Initial row index @param i1 Final row index @param j0 Initial column index @param j1 Final column index @return A(i0:i1, j0:j1) @throws ArrayIndexOutOfBoundsException Submatrix indices """ Matrix X = new Matrix(i1 - i0 + 1, j1 - j0 + 1); double[][] B = X.getArray(); try { for (int i = i0; i <= i1; i++) { for (int j = j0; j <= j1; j++) { B[i - i0][j - j0] = A[i][j]; } } } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } return X; }
java
public Matrix getMatrix(int i0, int i1, int j0, int j1) { Matrix X = new Matrix(i1 - i0 + 1, j1 - j0 + 1); double[][] B = X.getArray(); try { for (int i = i0; i <= i1; i++) { for (int j = j0; j <= j1; j++) { B[i - i0][j - j0] = A[i][j]; } } } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); } return X; }
[ "public", "Matrix", "getMatrix", "(", "int", "i0", ",", "int", "i1", ",", "int", "j0", ",", "int", "j1", ")", "{", "Matrix", "X", "=", "new", "Matrix", "(", "i1", "-", "i0", "+", "1", ",", "j1", "-", "j0", "+", "1", ")", ";", "double", "[", "]", "[", "]", "B", "=", "X", ".", "getArray", "(", ")", ";", "try", "{", "for", "(", "int", "i", "=", "i0", ";", "i", "<=", "i1", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "j0", ";", "j", "<=", "j1", ";", "j", "++", ")", "{", "B", "[", "i", "-", "i0", "]", "[", "j", "-", "j0", "]", "=", "A", "[", "i", "]", "[", "j", "]", ";", "}", "}", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "e", ")", "{", "throw", "new", "ArrayIndexOutOfBoundsException", "(", "\"Submatrix indices\"", ")", ";", "}", "return", "X", ";", "}" ]
Get a submatrix. @param i0 Initial row index @param i1 Final row index @param j0 Initial column index @param j1 Final column index @return A(i0:i1, j0:j1) @throws ArrayIndexOutOfBoundsException Submatrix indices
[ "Get", "a", "submatrix", "." ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/dependency/nnparser/Matrix.java#L362-L381
moparisthebest/beehive
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletBeanContext.java
ServletBeanContext.getResource
public URL getResource(String name, BeanContextChild bcc) throws IllegalArgumentException { """ Override BeanContext.getResource() so it delegates to the current ServletContext. @param name the resource name @param bcc the specified child @return a <code>URL</code> for the named resource for the specified child @throws IllegalArgumentException <code>IllegalArgumentException</code> if the resource is not valid """ ServletContext sc = getServletContext(); if ( sc != null ) { try { return sc.getResource( name ); } catch ( MalformedURLException mue ) { throw new IllegalArgumentException( mue.getMessage() ); } } return null; }
java
public URL getResource(String name, BeanContextChild bcc) throws IllegalArgumentException { ServletContext sc = getServletContext(); if ( sc != null ) { try { return sc.getResource( name ); } catch ( MalformedURLException mue ) { throw new IllegalArgumentException( mue.getMessage() ); } } return null; }
[ "public", "URL", "getResource", "(", "String", "name", ",", "BeanContextChild", "bcc", ")", "throws", "IllegalArgumentException", "{", "ServletContext", "sc", "=", "getServletContext", "(", ")", ";", "if", "(", "sc", "!=", "null", ")", "{", "try", "{", "return", "sc", ".", "getResource", "(", "name", ")", ";", "}", "catch", "(", "MalformedURLException", "mue", ")", "{", "throw", "new", "IllegalArgumentException", "(", "mue", ".", "getMessage", "(", ")", ")", ";", "}", "}", "return", "null", ";", "}" ]
Override BeanContext.getResource() so it delegates to the current ServletContext. @param name the resource name @param bcc the specified child @return a <code>URL</code> for the named resource for the specified child @throws IllegalArgumentException <code>IllegalArgumentException</code> if the resource is not valid
[ "Override", "BeanContext", ".", "getResource", "()", "so", "it", "delegates", "to", "the", "current", "ServletContext", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/servlet/ServletBeanContext.java#L210-L227
LearnLib/learnlib
algorithms/active/adt/src/main/java/de/learnlib/algorithms/adt/learner/ADTLearner.java
ADTLearner.ensureConsistency
private void ensureConsistency(final ADTNode<ADTState<I, O>, I, O> leaf) { """ Ensure that the output behavior of a hypothesis state matches the observed output behavior recorded in the ADT. Any differences in output behavior yields new counterexamples. @param leaf the leaf whose hypothesis state should be checked """ final ADTState<I, O> state = leaf.getHypothesisState(); final Word<I> as = state.getAccessSequence(); final Word<O> asOut = this.hypothesis.computeOutput(as); ADTNode<ADTState<I, O>, I, O> iter = leaf; while (iter != null) { final Pair<Word<I>, Word<O>> trace = ADTUtil.buildTraceForNode(iter); final Word<I> input = trace.getFirst(); final Word<O> output = trace.getSecond(); final Word<O> hypOut = this.hypothesis.computeStateOutput(state, input); if (!hypOut.equals(output)) { this.openCounterExamples.add(new DefaultQuery<>(as.concat(input), asOut.concat(output))); } iter = ADTUtil.getStartOfADS(iter).getParent(); } }
java
private void ensureConsistency(final ADTNode<ADTState<I, O>, I, O> leaf) { final ADTState<I, O> state = leaf.getHypothesisState(); final Word<I> as = state.getAccessSequence(); final Word<O> asOut = this.hypothesis.computeOutput(as); ADTNode<ADTState<I, O>, I, O> iter = leaf; while (iter != null) { final Pair<Word<I>, Word<O>> trace = ADTUtil.buildTraceForNode(iter); final Word<I> input = trace.getFirst(); final Word<O> output = trace.getSecond(); final Word<O> hypOut = this.hypothesis.computeStateOutput(state, input); if (!hypOut.equals(output)) { this.openCounterExamples.add(new DefaultQuery<>(as.concat(input), asOut.concat(output))); } iter = ADTUtil.getStartOfADS(iter).getParent(); } }
[ "private", "void", "ensureConsistency", "(", "final", "ADTNode", "<", "ADTState", "<", "I", ",", "O", ">", ",", "I", ",", "O", ">", "leaf", ")", "{", "final", "ADTState", "<", "I", ",", "O", ">", "state", "=", "leaf", ".", "getHypothesisState", "(", ")", ";", "final", "Word", "<", "I", ">", "as", "=", "state", ".", "getAccessSequence", "(", ")", ";", "final", "Word", "<", "O", ">", "asOut", "=", "this", ".", "hypothesis", ".", "computeOutput", "(", "as", ")", ";", "ADTNode", "<", "ADTState", "<", "I", ",", "O", ">", ",", "I", ",", "O", ">", "iter", "=", "leaf", ";", "while", "(", "iter", "!=", "null", ")", "{", "final", "Pair", "<", "Word", "<", "I", ">", ",", "Word", "<", "O", ">", ">", "trace", "=", "ADTUtil", ".", "buildTraceForNode", "(", "iter", ")", ";", "final", "Word", "<", "I", ">", "input", "=", "trace", ".", "getFirst", "(", ")", ";", "final", "Word", "<", "O", ">", "output", "=", "trace", ".", "getSecond", "(", ")", ";", "final", "Word", "<", "O", ">", "hypOut", "=", "this", ".", "hypothesis", ".", "computeStateOutput", "(", "state", ",", "input", ")", ";", "if", "(", "!", "hypOut", ".", "equals", "(", "output", ")", ")", "{", "this", ".", "openCounterExamples", ".", "add", "(", "new", "DefaultQuery", "<>", "(", "as", ".", "concat", "(", "input", ")", ",", "asOut", ".", "concat", "(", "output", ")", ")", ")", ";", "}", "iter", "=", "ADTUtil", ".", "getStartOfADS", "(", "iter", ")", ".", "getParent", "(", ")", ";", "}", "}" ]
Ensure that the output behavior of a hypothesis state matches the observed output behavior recorded in the ADT. Any differences in output behavior yields new counterexamples. @param leaf the leaf whose hypothesis state should be checked
[ "Ensure", "that", "the", "output", "behavior", "of", "a", "hypothesis", "state", "matches", "the", "observed", "output", "behavior", "recorded", "in", "the", "ADT", ".", "Any", "differences", "in", "output", "behavior", "yields", "new", "counterexamples", "." ]
train
https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/adt/src/main/java/de/learnlib/algorithms/adt/learner/ADTLearner.java#L427-L449
mcxiaoke/Android-Next
core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java
IOUtils.writeStream
public static boolean writeStream(File file, InputStream stream, boolean append) throws IOException { """ write file @param file the file to be opened for writing. @param stream the input stream @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning @return return true @throws IOException if an error occurs while operator FileOutputStream """ OutputStream o = null; try { makeDirs(file.getAbsolutePath()); o = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = stream.read(data)) != -1) { o.write(data, 0, length); } o.flush(); return true; } finally { closeQuietly(o); closeQuietly(stream); } }
java
public static boolean writeStream(File file, InputStream stream, boolean append) throws IOException { OutputStream o = null; try { makeDirs(file.getAbsolutePath()); o = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = stream.read(data)) != -1) { o.write(data, 0, length); } o.flush(); return true; } finally { closeQuietly(o); closeQuietly(stream); } }
[ "public", "static", "boolean", "writeStream", "(", "File", "file", ",", "InputStream", "stream", ",", "boolean", "append", ")", "throws", "IOException", "{", "OutputStream", "o", "=", "null", ";", "try", "{", "makeDirs", "(", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "o", "=", "new", "FileOutputStream", "(", "file", ",", "append", ")", ";", "byte", "data", "[", "]", "=", "new", "byte", "[", "1024", "]", ";", "int", "length", "=", "-", "1", ";", "while", "(", "(", "length", "=", "stream", ".", "read", "(", "data", ")", ")", "!=", "-", "1", ")", "{", "o", ".", "write", "(", "data", ",", "0", ",", "length", ")", ";", "}", "o", ".", "flush", "(", ")", ";", "return", "true", ";", "}", "finally", "{", "closeQuietly", "(", "o", ")", ";", "closeQuietly", "(", "stream", ")", ";", "}", "}" ]
write file @param file the file to be opened for writing. @param stream the input stream @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning @return return true @throws IOException if an error occurs while operator FileOutputStream
[ "write", "file" ]
train
https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/core/src/main/java/com/mcxiaoke/next/utils/IOUtils.java#L1224-L1240
aws/aws-sdk-java
aws-java-sdk-workdocs/src/main/java/com/amazonaws/services/workdocs/model/UploadMetadata.java
UploadMetadata.withSignedHeaders
public UploadMetadata withSignedHeaders(java.util.Map<String, String> signedHeaders) { """ <p> The signed headers. </p> @param signedHeaders The signed headers. @return Returns a reference to this object so that method calls can be chained together. """ setSignedHeaders(signedHeaders); return this; }
java
public UploadMetadata withSignedHeaders(java.util.Map<String, String> signedHeaders) { setSignedHeaders(signedHeaders); return this; }
[ "public", "UploadMetadata", "withSignedHeaders", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "signedHeaders", ")", "{", "setSignedHeaders", "(", "signedHeaders", ")", ";", "return", "this", ";", "}" ]
<p> The signed headers. </p> @param signedHeaders The signed headers. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "signed", "headers", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-workdocs/src/main/java/com/amazonaws/services/workdocs/model/UploadMetadata.java#L119-L122
aoindustries/aoweb-framework
src/main/java/com/aoindustries/website/framework/ErrorReportingServlet.java
ErrorReportingServlet.doPost
@Override final protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { """ Any error that occurs during a <code>doPost</code> is caught and reported here. """ resp.setBufferSize(BUFFER_SIZE); postCount.incrementAndGet(); try { reportingDoPost(req, resp); } catch (ThreadDeath t) { throw t; } catch (RuntimeException | ServletException | IOException e) { getLogger().log(Level.SEVERE, null, e); throw e; } catch (SQLException t) { getLogger().log(Level.SEVERE, null, t); throw new ServletException(t); } }
java
@Override final protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setBufferSize(BUFFER_SIZE); postCount.incrementAndGet(); try { reportingDoPost(req, resp); } catch (ThreadDeath t) { throw t; } catch (RuntimeException | ServletException | IOException e) { getLogger().log(Level.SEVERE, null, e); throw e; } catch (SQLException t) { getLogger().log(Level.SEVERE, null, t); throw new ServletException(t); } }
[ "@", "Override", "final", "protected", "void", "doPost", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "resp", ")", "throws", "ServletException", ",", "IOException", "{", "resp", ".", "setBufferSize", "(", "BUFFER_SIZE", ")", ";", "postCount", ".", "incrementAndGet", "(", ")", ";", "try", "{", "reportingDoPost", "(", "req", ",", "resp", ")", ";", "}", "catch", "(", "ThreadDeath", "t", ")", "{", "throw", "t", ";", "}", "catch", "(", "RuntimeException", "|", "ServletException", "|", "IOException", "e", ")", "{", "getLogger", "(", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "null", ",", "e", ")", ";", "throw", "e", ";", "}", "catch", "(", "SQLException", "t", ")", "{", "getLogger", "(", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "null", ",", "t", ")", ";", "throw", "new", "ServletException", "(", "t", ")", ";", "}", "}" ]
Any error that occurs during a <code>doPost</code> is caught and reported here.
[ "Any", "error", "that", "occurs", "during", "a", "<code", ">", "doPost<", "/", "code", ">", "is", "caught", "and", "reported", "here", "." ]
train
https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/ErrorReportingServlet.java#L135-L150
audit4j/audit4j-core
src/main/java/org/audit4j/core/util/ReflectUtil.java
ReflectUtil.getNewInstance
@SuppressWarnings("unchecked") public I getNewInstance(String className) { """ Gets the new instance. @param className the class name @return the new instance """ try { return getNewInstance((Class<I>) Class.forName(className)); } catch (ClassNotFoundException e) { throw new InitializationException("Given class not found", e); } }
java
@SuppressWarnings("unchecked") public I getNewInstance(String className) { try { return getNewInstance((Class<I>) Class.forName(className)); } catch (ClassNotFoundException e) { throw new InitializationException("Given class not found", e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "I", "getNewInstance", "(", "String", "className", ")", "{", "try", "{", "return", "getNewInstance", "(", "(", "Class", "<", "I", ">", ")", "Class", ".", "forName", "(", "className", ")", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "throw", "new", "InitializationException", "(", "\"Given class not found\"", ",", "e", ")", ";", "}", "}" ]
Gets the new instance. @param className the class name @return the new instance
[ "Gets", "the", "new", "instance", "." ]
train
https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/util/ReflectUtil.java#L61-L68
mapbox/mapbox-java
services-geojson/src/main/java/com/mapbox/geojson/GeometryCollection.java
GeometryCollection.fromGeometries
public static GeometryCollection fromGeometries(@NonNull List<Geometry> geometries, @Nullable BoundingBox bbox) { """ Create a new instance of this class by giving the collection a list of {@link Geometry}. @param geometries a non-null list of geometry which makes up this collection @param bbox optionally include a bbox definition as a double array @return a new instance of this class defined by the values passed inside this static factory method @since 1.0.0 """ return new GeometryCollection(TYPE, bbox, geometries); }
java
public static GeometryCollection fromGeometries(@NonNull List<Geometry> geometries, @Nullable BoundingBox bbox) { return new GeometryCollection(TYPE, bbox, geometries); }
[ "public", "static", "GeometryCollection", "fromGeometries", "(", "@", "NonNull", "List", "<", "Geometry", ">", "geometries", ",", "@", "Nullable", "BoundingBox", "bbox", ")", "{", "return", "new", "GeometryCollection", "(", "TYPE", ",", "bbox", ",", "geometries", ")", ";", "}" ]
Create a new instance of this class by giving the collection a list of {@link Geometry}. @param geometries a non-null list of geometry which makes up this collection @param bbox optionally include a bbox definition as a double array @return a new instance of this class defined by the values passed inside this static factory method @since 1.0.0
[ "Create", "a", "new", "instance", "of", "this", "class", "by", "giving", "the", "collection", "a", "list", "of", "{", "@link", "Geometry", "}", "." ]
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/GeometryCollection.java#L113-L116
mabe02/lanterna
src/main/java/com/googlecode/lanterna/gui2/ActionListBox.java
ActionListBox.addItem
public ActionListBox addItem(final String label, final Runnable action) { """ Adds a new item to the list, which is displayed in the list using a supplied label. @param label Label to use in the list for the new item @param action Runnable to invoke when this action is selected and then triggered @return Itself """ return addItem(new Runnable() { @Override public void run() { action.run(); } @Override public String toString() { return label; } }); }
java
public ActionListBox addItem(final String label, final Runnable action) { return addItem(new Runnable() { @Override public void run() { action.run(); } @Override public String toString() { return label; } }); }
[ "public", "ActionListBox", "addItem", "(", "final", "String", "label", ",", "final", "Runnable", "action", ")", "{", "return", "addItem", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "action", ".", "run", "(", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "label", ";", "}", "}", ")", ";", "}" ]
Adds a new item to the list, which is displayed in the list using a supplied label. @param label Label to use in the list for the new item @param action Runnable to invoke when this action is selected and then triggered @return Itself
[ "Adds", "a", "new", "item", "to", "the", "list", "which", "is", "displayed", "in", "the", "list", "using", "a", "supplied", "label", "." ]
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/gui2/ActionListBox.java#L74-L86
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java
GenericMultiBoJdbcDao.addDelegateDao
public <T> GenericMultiBoJdbcDao addDelegateDao(Class<T> clazz, IGenericBoDao<T> dao) { """ Add a delegate dao to mapping list. @param clazz @param dao @return """ delegateDaos.put(clazz, dao); return this; }
java
public <T> GenericMultiBoJdbcDao addDelegateDao(Class<T> clazz, IGenericBoDao<T> dao) { delegateDaos.put(clazz, dao); return this; }
[ "public", "<", "T", ">", "GenericMultiBoJdbcDao", "addDelegateDao", "(", "Class", "<", "T", ">", "clazz", ",", "IGenericBoDao", "<", "T", ">", "dao", ")", "{", "delegateDaos", ".", "put", "(", "clazz", ",", "dao", ")", ";", "return", "this", ";", "}" ]
Add a delegate dao to mapping list. @param clazz @param dao @return
[ "Add", "a", "delegate", "dao", "to", "mapping", "list", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java#L75-L78
florent37/DaVinci
davinci/src/main/java/com/github/florent37/davinci/DaVinci.java
DaVinci.returnBitmapInto
private static void returnBitmapInto(final Bitmap bitmap, final String path, final Object into) { """ When the bitmap has been downloaded, load it into the [into] object @param bitmap the downloaded bitmap @param path the image source path (path or url) @param into the destination object """ new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (into != null && path != null && bitmap != null) { if (into instanceof ImageView) { Log.d(TAG, "return bitmap " + path + " into ImageView"); ((ImageView) into).setImageBitmap(bitmap); } else if (into instanceof Callback) { Log.d(TAG, "return bitmap " + path + " into Callback"); ((Callback) into).onBitmapLoaded(path, bitmap); } } } }); }
java
private static void returnBitmapInto(final Bitmap bitmap, final String path, final Object into) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (into != null && path != null && bitmap != null) { if (into instanceof ImageView) { Log.d(TAG, "return bitmap " + path + " into ImageView"); ((ImageView) into).setImageBitmap(bitmap); } else if (into instanceof Callback) { Log.d(TAG, "return bitmap " + path + " into Callback"); ((Callback) into).onBitmapLoaded(path, bitmap); } } } }); }
[ "private", "static", "void", "returnBitmapInto", "(", "final", "Bitmap", "bitmap", ",", "final", "String", "path", ",", "final", "Object", "into", ")", "{", "new", "Handler", "(", "Looper", ".", "getMainLooper", "(", ")", ")", ".", "post", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "into", "!=", "null", "&&", "path", "!=", "null", "&&", "bitmap", "!=", "null", ")", "{", "if", "(", "into", "instanceof", "ImageView", ")", "{", "Log", ".", "d", "(", "TAG", ",", "\"return bitmap \"", "+", "path", "+", "\" into ImageView\"", ")", ";", "(", "(", "ImageView", ")", "into", ")", ".", "setImageBitmap", "(", "bitmap", ")", ";", "}", "else", "if", "(", "into", "instanceof", "Callback", ")", "{", "Log", ".", "d", "(", "TAG", ",", "\"return bitmap \"", "+", "path", "+", "\" into Callback\"", ")", ";", "(", "(", "Callback", ")", "into", ")", ".", "onBitmapLoaded", "(", "path", ",", "bitmap", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
When the bitmap has been downloaded, load it into the [into] object @param bitmap the downloaded bitmap @param path the image source path (path or url) @param into the destination object
[ "When", "the", "bitmap", "has", "been", "downloaded", "load", "it", "into", "the", "[", "into", "]", "object" ]
train
https://github.com/florent37/DaVinci/blob/9c6ce4aa2df8e2288cd6ee8b57d9091b1b770a7a/davinci/src/main/java/com/github/florent37/davinci/DaVinci.java#L326-L341
lukas-krecan/JsonUnit
json-unit-spring/src/main/java/net/javacrumbs/jsonunit/spring/JsonUnitResultMatchers.java
JsonUnitResultMatchers.isString
public ResultMatcher isString() { """ Fails if the selected JSON is not a String or is not present. """ return new AbstractResultMatcher(path, configuration) { public void doMatch(Object actual) { isString(actual); } }; }
java
public ResultMatcher isString() { return new AbstractResultMatcher(path, configuration) { public void doMatch(Object actual) { isString(actual); } }; }
[ "public", "ResultMatcher", "isString", "(", ")", "{", "return", "new", "AbstractResultMatcher", "(", "path", ",", "configuration", ")", "{", "public", "void", "doMatch", "(", "Object", "actual", ")", "{", "isString", "(", "actual", ")", ";", "}", "}", ";", "}" ]
Fails if the selected JSON is not a String or is not present.
[ "Fails", "if", "the", "selected", "JSON", "is", "not", "a", "String", "or", "is", "not", "present", "." ]
train
https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit-spring/src/main/java/net/javacrumbs/jsonunit/spring/JsonUnitResultMatchers.java#L198-L204
looly/hutool
hutool-db/src/main/java/cn/hutool/db/SqlConnRunner.java
SqlConnRunner.insert
public int[] insert(Connection conn, Collection<Entity> records) throws SQLException { """ 批量插入数据<br> 需要注意的是,批量插入每一条数据结构必须一致。批量插入数据时会获取第一条数据的字段结构,之后的数据会按照这个格式插入。<br> 也就是说假如第一条数据只有2个字段,后边数据多于这两个字段的部分将被抛弃。 此方法不会关闭Connection @param conn 数据库连接 @param records 记录列表,记录KV必须严格一致 @return 插入行数 @throws SQLException SQL执行异常 """ return insert(conn, records.toArray(new Entity[records.size()])); }
java
public int[] insert(Connection conn, Collection<Entity> records) throws SQLException { return insert(conn, records.toArray(new Entity[records.size()])); }
[ "public", "int", "[", "]", "insert", "(", "Connection", "conn", ",", "Collection", "<", "Entity", ">", "records", ")", "throws", "SQLException", "{", "return", "insert", "(", "conn", ",", "records", ".", "toArray", "(", "new", "Entity", "[", "records", ".", "size", "(", ")", "]", ")", ")", ";", "}" ]
批量插入数据<br> 需要注意的是,批量插入每一条数据结构必须一致。批量插入数据时会获取第一条数据的字段结构,之后的数据会按照这个格式插入。<br> 也就是说假如第一条数据只有2个字段,后边数据多于这两个字段的部分将被抛弃。 此方法不会关闭Connection @param conn 数据库连接 @param records 记录列表,记录KV必须严格一致 @return 插入行数 @throws SQLException SQL执行异常
[ "批量插入数据<br", ">", "需要注意的是,批量插入每一条数据结构必须一致。批量插入数据时会获取第一条数据的字段结构,之后的数据会按照这个格式插入。<br", ">", "也就是说假如第一条数据只有2个字段,后边数据多于这两个字段的部分将被抛弃。", "此方法不会关闭Connection" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/SqlConnRunner.java#L141-L143
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2019_01_01/src/main/java/com/microsoft/azure/management/eventgrid/v2019_01_01/implementation/TopicsInner.java
TopicsInner.createOrUpdateAsync
public Observable<TopicInner> createOrUpdateAsync(String resourceGroupName, String topicName, TopicInner topicInfo) { """ Create a topic. Asynchronously creates a new topic with the specified parameters. @param resourceGroupName The name of the resource group within the user's subscription. @param topicName Name of the topic @param topicInfo Topic information @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, topicName, topicInfo).map(new Func1<ServiceResponse<TopicInner>, TopicInner>() { @Override public TopicInner call(ServiceResponse<TopicInner> response) { return response.body(); } }); }
java
public Observable<TopicInner> createOrUpdateAsync(String resourceGroupName, String topicName, TopicInner topicInfo) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, topicName, topicInfo).map(new Func1<ServiceResponse<TopicInner>, TopicInner>() { @Override public TopicInner call(ServiceResponse<TopicInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "TopicInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "topicName", ",", "TopicInner", "topicInfo", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "topicName", ",", "topicInfo", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "TopicInner", ">", ",", "TopicInner", ">", "(", ")", "{", "@", "Override", "public", "TopicInner", "call", "(", "ServiceResponse", "<", "TopicInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create a topic. Asynchronously creates a new topic with the specified parameters. @param resourceGroupName The name of the resource group within the user's subscription. @param topicName Name of the topic @param topicInfo Topic information @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "a", "topic", ".", "Asynchronously", "creates", "a", "new", "topic", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2019_01_01/src/main/java/com/microsoft/azure/management/eventgrid/v2019_01_01/implementation/TopicsInner.java#L250-L257
rzwitserloot/lombok
src/core/lombok/core/AST.java
AST.replaceStatementInNode
protected boolean replaceStatementInNode(N statement, N oldN, N newN) { """ Uses reflection to find the given direct child on the given statement, and replace it with a new child. """ for (FieldAccess fa : fieldsOf(statement.getClass())) { if (replaceStatementInField(fa, statement, oldN, newN)) return true; } return false; }
java
protected boolean replaceStatementInNode(N statement, N oldN, N newN) { for (FieldAccess fa : fieldsOf(statement.getClass())) { if (replaceStatementInField(fa, statement, oldN, newN)) return true; } return false; }
[ "protected", "boolean", "replaceStatementInNode", "(", "N", "statement", ",", "N", "oldN", ",", "N", "newN", ")", "{", "for", "(", "FieldAccess", "fa", ":", "fieldsOf", "(", "statement", ".", "getClass", "(", ")", ")", ")", "{", "if", "(", "replaceStatementInField", "(", "fa", ",", "statement", ",", "oldN", ",", "newN", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Uses reflection to find the given direct child on the given statement, and replace it with a new child.
[ "Uses", "reflection", "to", "find", "the", "given", "direct", "child", "on", "the", "given", "statement", "and", "replace", "it", "with", "a", "new", "child", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/core/AST.java#L299-L305
alkacon/opencms-core
src/org/opencms/ui/util/table/CmsBeanTableBuilder.java
CmsBeanTableBuilder.getDefaultCellStyleGenerator
public CellStyleGenerator getDefaultCellStyleGenerator() { """ Creates a default cell style generator which just returns the value of the styleName attribute in a Column annotation for cells in that column.<p> @return the default cell style generator """ return new CellStyleGenerator() { private static final long serialVersionUID = 1L; @SuppressWarnings("synthetic-access") public String getStyle(Table source, Object itemId, Object propertyId) { for (ColumnBean colBean : m_columns) { if (colBean.getProperty().getName().equals(propertyId)) { return colBean.getInfo().styleName(); } } return ""; } }; }
java
public CellStyleGenerator getDefaultCellStyleGenerator() { return new CellStyleGenerator() { private static final long serialVersionUID = 1L; @SuppressWarnings("synthetic-access") public String getStyle(Table source, Object itemId, Object propertyId) { for (ColumnBean colBean : m_columns) { if (colBean.getProperty().getName().equals(propertyId)) { return colBean.getInfo().styleName(); } } return ""; } }; }
[ "public", "CellStyleGenerator", "getDefaultCellStyleGenerator", "(", ")", "{", "return", "new", "CellStyleGenerator", "(", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "SuppressWarnings", "(", "\"synthetic-access\"", ")", "public", "String", "getStyle", "(", "Table", "source", ",", "Object", "itemId", ",", "Object", "propertyId", ")", "{", "for", "(", "ColumnBean", "colBean", ":", "m_columns", ")", "{", "if", "(", "colBean", ".", "getProperty", "(", ")", ".", "getName", "(", ")", ".", "equals", "(", "propertyId", ")", ")", "{", "return", "colBean", ".", "getInfo", "(", ")", ".", "styleName", "(", ")", ";", "}", "}", "return", "\"\"", ";", "}", "}", ";", "}" ]
Creates a default cell style generator which just returns the value of the styleName attribute in a Column annotation for cells in that column.<p> @return the default cell style generator
[ "Creates", "a", "default", "cell", "style", "generator", "which", "just", "returns", "the", "value", "of", "the", "styleName", "attribute", "in", "a", "Column", "annotation", "for", "cells", "in", "that", "column", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/util/table/CmsBeanTableBuilder.java#L267-L284
ehcache/ehcache3
core/src/main/java/org/ehcache/core/config/DefaultConfiguration.java
DefaultConfiguration.addCacheConfiguration
public void addCacheConfiguration(final String alias, final CacheConfiguration<?, ?> config) { """ Adds a {@link CacheConfiguration} tied to the provided alias. @param alias the alias of the cache @param config the configuration of the cache """ if (caches.put(alias, config) != null) { throw new IllegalStateException("Cache '" + alias + "' already present!"); } }
java
public void addCacheConfiguration(final String alias, final CacheConfiguration<?, ?> config) { if (caches.put(alias, config) != null) { throw new IllegalStateException("Cache '" + alias + "' already present!"); } }
[ "public", "void", "addCacheConfiguration", "(", "final", "String", "alias", ",", "final", "CacheConfiguration", "<", "?", ",", "?", ">", "config", ")", "{", "if", "(", "caches", ".", "put", "(", "alias", ",", "config", ")", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cache '\"", "+", "alias", "+", "\"' already present!\"", ")", ";", "}", "}" ]
Adds a {@link CacheConfiguration} tied to the provided alias. @param alias the alias of the cache @param config the configuration of the cache
[ "Adds", "a", "{", "@link", "CacheConfiguration", "}", "tied", "to", "the", "provided", "alias", "." ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/config/DefaultConfiguration.java#L121-L125
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/PackedSpriteSheet.java
PackedSpriteSheet.loadDefinition
private void loadDefinition(String def, Color trans) throws SlickException { """ Load the definition file and parse each of the sections @param def The location of the definitions file @param trans The color to be treated as transparent @throws SlickException Indicates a failure to read or parse the definitions file or referenced image. """ BufferedReader reader = new BufferedReader(new InputStreamReader(ResourceLoader.getResourceAsStream(def))); try { image = new Image(basePath+reader.readLine(), false, filter, trans); while (reader.ready()) { if (reader.readLine() == null) { break; } Section sect = new Section(reader); sections.put(sect.name, sect); if (reader.readLine() == null) { break; } } } catch (Exception e) { Log.error(e); throw new SlickException("Failed to process definitions file - invalid format?", e); } }
java
private void loadDefinition(String def, Color trans) throws SlickException { BufferedReader reader = new BufferedReader(new InputStreamReader(ResourceLoader.getResourceAsStream(def))); try { image = new Image(basePath+reader.readLine(), false, filter, trans); while (reader.ready()) { if (reader.readLine() == null) { break; } Section sect = new Section(reader); sections.put(sect.name, sect); if (reader.readLine() == null) { break; } } } catch (Exception e) { Log.error(e); throw new SlickException("Failed to process definitions file - invalid format?", e); } }
[ "private", "void", "loadDefinition", "(", "String", "def", ",", "Color", "trans", ")", "throws", "SlickException", "{", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "ResourceLoader", ".", "getResourceAsStream", "(", "def", ")", ")", ")", ";", "try", "{", "image", "=", "new", "Image", "(", "basePath", "+", "reader", ".", "readLine", "(", ")", ",", "false", ",", "filter", ",", "trans", ")", ";", "while", "(", "reader", ".", "ready", "(", ")", ")", "{", "if", "(", "reader", ".", "readLine", "(", ")", "==", "null", ")", "{", "break", ";", "}", "Section", "sect", "=", "new", "Section", "(", "reader", ")", ";", "sections", ".", "put", "(", "sect", ".", "name", ",", "sect", ")", ";", "if", "(", "reader", ".", "readLine", "(", ")", "==", "null", ")", "{", "break", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "error", "(", "e", ")", ";", "throw", "new", "SlickException", "(", "\"Failed to process definitions file - invalid format?\"", ",", "e", ")", ";", "}", "}" ]
Load the definition file and parse each of the sections @param def The location of the definitions file @param trans The color to be treated as transparent @throws SlickException Indicates a failure to read or parse the definitions file or referenced image.
[ "Load", "the", "definition", "file", "and", "parse", "each", "of", "the", "sections" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/PackedSpriteSheet.java#L127-L148
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/RowReaderDefaultImpl.java
RowReaderDefaultImpl.readObjectArrayFrom
public void readObjectArrayFrom(ResultSetAndStatement rs_stmt, Map row) { """ materialize a single object, described by cld, from the first row of the ResultSet rs. There are two possible strategies: 1. The persistent class defines a public constructor with arguments matching the persistent primitive attributes of the class. In this case we build an array args of arguments from rs and call Constructor.newInstance(args) to build an object. 2. The persistent class does not provide such a constructor, but only a public default constructor. In this case we create an empty instance with Class.newInstance(). This empty instance is then filled by calling Field::set(obj,getObject(matchingColumn)) for each attribute. The second strategy needs n calls to Field::set() which are much more expensive than the filling of the args array in the first strategy. client applications should therefore define adequate constructors to benefit from performance gain of the first strategy. @throws PersistenceBrokerException if there is an error accessing the access layer """ FieldDescriptor[] fields; /* arminw: TODO: this feature doesn't work, so remove this in future */ if (m_cld.getSuperClass() != null) { /** * treeder * append super class fields if exist */ fields = m_cld.getFieldDescriptorsInHeirarchy(); } else { String ojbConcreteClass = extractOjbConcreteClass(m_cld, rs_stmt.m_rs, row); /* arminw: if multiple classes were mapped to the same table, lookup the concrete class and use these fields, attach ojbConcreteClass in row map for later use */ if(ojbConcreteClass != null) { ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(ojbConcreteClass); row.put(OJB_CONCRETE_CLASS_KEY, cld.getClassOfObject()); fields = cld.getFieldDescriptor(true); } else { String ojbClass = SqlHelper.getOjbClassName(rs_stmt.m_rs); if (ojbClass != null) { ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(ojbClass); row.put(OJB_CONCRETE_CLASS_KEY, cld.getClassOfObject()); fields = cld.getFieldDescriptor(true); } else { fields = m_cld.getFieldDescriptor(true); } } } readValuesFrom(rs_stmt, row, fields); }
java
public void readObjectArrayFrom(ResultSetAndStatement rs_stmt, Map row) { FieldDescriptor[] fields; /* arminw: TODO: this feature doesn't work, so remove this in future */ if (m_cld.getSuperClass() != null) { /** * treeder * append super class fields if exist */ fields = m_cld.getFieldDescriptorsInHeirarchy(); } else { String ojbConcreteClass = extractOjbConcreteClass(m_cld, rs_stmt.m_rs, row); /* arminw: if multiple classes were mapped to the same table, lookup the concrete class and use these fields, attach ojbConcreteClass in row map for later use */ if(ojbConcreteClass != null) { ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(ojbConcreteClass); row.put(OJB_CONCRETE_CLASS_KEY, cld.getClassOfObject()); fields = cld.getFieldDescriptor(true); } else { String ojbClass = SqlHelper.getOjbClassName(rs_stmt.m_rs); if (ojbClass != null) { ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(ojbClass); row.put(OJB_CONCRETE_CLASS_KEY, cld.getClassOfObject()); fields = cld.getFieldDescriptor(true); } else { fields = m_cld.getFieldDescriptor(true); } } } readValuesFrom(rs_stmt, row, fields); }
[ "public", "void", "readObjectArrayFrom", "(", "ResultSetAndStatement", "rs_stmt", ",", "Map", "row", ")", "{", "FieldDescriptor", "[", "]", "fields", ";", "/*\r\narminw:\r\nTODO: this feature doesn't work, so remove this in future\r\n*/", "if", "(", "m_cld", ".", "getSuperClass", "(", ")", "!=", "null", ")", "{", "/**\r\n * treeder\r\n * append super class fields if exist\r\n */", "fields", "=", "m_cld", ".", "getFieldDescriptorsInHeirarchy", "(", ")", ";", "}", "else", "{", "String", "ojbConcreteClass", "=", "extractOjbConcreteClass", "(", "m_cld", ",", "rs_stmt", ".", "m_rs", ",", "row", ")", ";", "/*\r\n arminw:\r\n if multiple classes were mapped to the same table, lookup the concrete\r\n class and use these fields, attach ojbConcreteClass in row map for later use\r\n */", "if", "(", "ojbConcreteClass", "!=", "null", ")", "{", "ClassDescriptor", "cld", "=", "m_cld", ".", "getRepository", "(", ")", ".", "getDescriptorFor", "(", "ojbConcreteClass", ")", ";", "row", ".", "put", "(", "OJB_CONCRETE_CLASS_KEY", ",", "cld", ".", "getClassOfObject", "(", ")", ")", ";", "fields", "=", "cld", ".", "getFieldDescriptor", "(", "true", ")", ";", "}", "else", "{", "String", "ojbClass", "=", "SqlHelper", ".", "getOjbClassName", "(", "rs_stmt", ".", "m_rs", ")", ";", "if", "(", "ojbClass", "!=", "null", ")", "{", "ClassDescriptor", "cld", "=", "m_cld", ".", "getRepository", "(", ")", ".", "getDescriptorFor", "(", "ojbClass", ")", ";", "row", ".", "put", "(", "OJB_CONCRETE_CLASS_KEY", ",", "cld", ".", "getClassOfObject", "(", ")", ")", ";", "fields", "=", "cld", ".", "getFieldDescriptor", "(", "true", ")", ";", "}", "else", "{", "fields", "=", "m_cld", ".", "getFieldDescriptor", "(", "true", ")", ";", "}", "}", "}", "readValuesFrom", "(", "rs_stmt", ",", "row", ",", "fields", ")", ";", "}" ]
materialize a single object, described by cld, from the first row of the ResultSet rs. There are two possible strategies: 1. The persistent class defines a public constructor with arguments matching the persistent primitive attributes of the class. In this case we build an array args of arguments from rs and call Constructor.newInstance(args) to build an object. 2. The persistent class does not provide such a constructor, but only a public default constructor. In this case we create an empty instance with Class.newInstance(). This empty instance is then filled by calling Field::set(obj,getObject(matchingColumn)) for each attribute. The second strategy needs n calls to Field::set() which are much more expensive than the filling of the args array in the first strategy. client applications should therefore define adequate constructors to benefit from performance gain of the first strategy. @throws PersistenceBrokerException if there is an error accessing the access layer
[ "materialize", "a", "single", "object", "described", "by", "cld", "from", "the", "first", "row", "of", "the", "ResultSet", "rs", ".", "There", "are", "two", "possible", "strategies", ":", "1", ".", "The", "persistent", "class", "defines", "a", "public", "constructor", "with", "arguments", "matching", "the", "persistent", "primitive", "attributes", "of", "the", "class", ".", "In", "this", "case", "we", "build", "an", "array", "args", "of", "arguments", "from", "rs", "and", "call", "Constructor", ".", "newInstance", "(", "args", ")", "to", "build", "an", "object", ".", "2", ".", "The", "persistent", "class", "does", "not", "provide", "such", "a", "constructor", "but", "only", "a", "public", "default", "constructor", ".", "In", "this", "case", "we", "create", "an", "empty", "instance", "with", "Class", ".", "newInstance", "()", ".", "This", "empty", "instance", "is", "then", "filled", "by", "calling", "Field", "::", "set", "(", "obj", "getObject", "(", "matchingColumn", "))", "for", "each", "attribute", ".", "The", "second", "strategy", "needs", "n", "calls", "to", "Field", "::", "set", "()", "which", "are", "much", "more", "expensive", "than", "the", "filling", "of", "the", "args", "array", "in", "the", "first", "strategy", ".", "client", "applications", "should", "therefore", "define", "adequate", "constructors", "to", "benefit", "from", "performance", "gain", "of", "the", "first", "strategy", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/RowReaderDefaultImpl.java#L164-L209
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.setPerspectiveRect
public Matrix4d setPerspectiveRect(double width, double height, double zNear, double zFar) { """ Set this matrix to be a symmetric perspective projection frustum transformation for a right-handed coordinate system using OpenGL's NDC z range of <code>[-1..+1]</code>. <p> In order to apply the perspective projection transformation to an existing transformation, use {@link #perspectiveRect(double, double, double, double) perspectiveRect()}. @see #perspectiveRect(double, double, double, double) @param width the width of the near frustum plane @param height the height of the near frustum plane @param zNear near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. @param zFar far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. @return this """ return setPerspectiveRect(width, height, zNear, zFar, false); }
java
public Matrix4d setPerspectiveRect(double width, double height, double zNear, double zFar) { return setPerspectiveRect(width, height, zNear, zFar, false); }
[ "public", "Matrix4d", "setPerspectiveRect", "(", "double", "width", ",", "double", "height", ",", "double", "zNear", ",", "double", "zFar", ")", "{", "return", "setPerspectiveRect", "(", "width", ",", "height", ",", "zNear", ",", "zFar", ",", "false", ")", ";", "}" ]
Set this matrix to be a symmetric perspective projection frustum transformation for a right-handed coordinate system using OpenGL's NDC z range of <code>[-1..+1]</code>. <p> In order to apply the perspective projection transformation to an existing transformation, use {@link #perspectiveRect(double, double, double, double) perspectiveRect()}. @see #perspectiveRect(double, double, double, double) @param width the width of the near frustum plane @param height the height of the near frustum plane @param zNear near clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the near clipping plane will be at positive infinity. In that case, <code>zFar</code> may not also be {@link Float#POSITIVE_INFINITY}. @param zFar far clipping plane distance. If the special value {@link Float#POSITIVE_INFINITY} is used, the far clipping plane will be at positive infinity. In that case, <code>zNear</code> may not also be {@link Float#POSITIVE_INFINITY}. @return this
[ "Set", "this", "matrix", "to", "be", "a", "symmetric", "perspective", "projection", "frustum", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "using", "OpenGL", "s", "NDC", "z", "range", "of", "<code", ">", "[", "-", "1", "..", "+", "1", "]", "<", "/", "code", ">", ".", "<p", ">", "In", "order", "to", "apply", "the", "perspective", "projection", "transformation", "to", "an", "existing", "transformation", "use", "{", "@link", "#perspectiveRect", "(", "double", "double", "double", "double", ")", "perspectiveRect", "()", "}", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L12701-L12703
BlueBrain/bluima
modules/bluima_typesystem/src/main/java/de/julielab/jules/types/Token.java
Token.setPosTag
public void setPosTag(int i, POSTag v) { """ indexed setter for posTag - sets an indexed value - List contains part-of-speech tags of different part-of-speech tagsets (see also POSTag and subtypes), O @generated @param i index in the array to set @param v value to set into the array """ if (Token_Type.featOkTst && ((Token_Type)jcasType).casFeat_posTag == null) jcasType.jcas.throwFeatMissing("posTag", "de.julielab.jules.types.Token"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Token_Type)jcasType).casFeatCode_posTag), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Token_Type)jcasType).casFeatCode_posTag), i, jcasType.ll_cas.ll_getFSRef(v));}
java
public void setPosTag(int i, POSTag v) { if (Token_Type.featOkTst && ((Token_Type)jcasType).casFeat_posTag == null) jcasType.jcas.throwFeatMissing("posTag", "de.julielab.jules.types.Token"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Token_Type)jcasType).casFeatCode_posTag), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Token_Type)jcasType).casFeatCode_posTag), i, jcasType.ll_cas.ll_getFSRef(v));}
[ "public", "void", "setPosTag", "(", "int", "i", ",", "POSTag", "v", ")", "{", "if", "(", "Token_Type", ".", "featOkTst", "&&", "(", "(", "Token_Type", ")", "jcasType", ")", ".", "casFeat_posTag", "==", "null", ")", "jcasType", ".", "jcas", ".", "throwFeatMissing", "(", "\"posTag\"", ",", "\"de.julielab.jules.types.Token\"", ")", ";", "jcasType", ".", "jcas", ".", "checkArrayBounds", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Token_Type", ")", "jcasType", ")", ".", "casFeatCode_posTag", ")", ",", "i", ")", ";", "jcasType", ".", "ll_cas", ".", "ll_setRefArrayValue", "(", "jcasType", ".", "ll_cas", ".", "ll_getRefValue", "(", "addr", ",", "(", "(", "Token_Type", ")", "jcasType", ")", ".", "casFeatCode_posTag", ")", ",", "i", ",", "jcasType", ".", "ll_cas", ".", "ll_getFSRef", "(", "v", ")", ")", ";", "}" ]
indexed setter for posTag - sets an indexed value - List contains part-of-speech tags of different part-of-speech tagsets (see also POSTag and subtypes), O @generated @param i index in the array to set @param v value to set into the array
[ "indexed", "setter", "for", "posTag", "-", "sets", "an", "indexed", "value", "-", "List", "contains", "part", "-", "of", "-", "speech", "tags", "of", "different", "part", "-", "of", "-", "speech", "tagsets", "(", "see", "also", "POSTag", "and", "subtypes", ")", "O" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/Token.java#L138-L142
CloudSlang/cs-actions
cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java
AwsSignatureV4.getSignature
public String getSignature(String stringToSign, byte[] derivedSigningKey) throws SignatureException { """ Calculates the AWS Signature Version 4 by signing (calculates the HmacSHA256) the string-to-sign with the derived key. @param stringToSign String-to-sign the includes meta information about the request. @param derivedSigningKey Signing key derived from the AWS secret access key. @return AWS Signature Version 4. """ try { return new String(Hex.encode(calculateHmacSHA256(stringToSign, derivedSigningKey)), ENCODING); } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { throw new SignatureException(SIGNATURE_ERROR + e.getMessage()); } }
java
public String getSignature(String stringToSign, byte[] derivedSigningKey) throws SignatureException { try { return new String(Hex.encode(calculateHmacSHA256(stringToSign, derivedSigningKey)), ENCODING); } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { throw new SignatureException(SIGNATURE_ERROR + e.getMessage()); } }
[ "public", "String", "getSignature", "(", "String", "stringToSign", ",", "byte", "[", "]", "derivedSigningKey", ")", "throws", "SignatureException", "{", "try", "{", "return", "new", "String", "(", "Hex", ".", "encode", "(", "calculateHmacSHA256", "(", "stringToSign", ",", "derivedSigningKey", ")", ")", ",", "ENCODING", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "|", "InvalidKeyException", "|", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "SignatureException", "(", "SIGNATURE_ERROR", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Calculates the AWS Signature Version 4 by signing (calculates the HmacSHA256) the string-to-sign with the derived key. @param stringToSign String-to-sign the includes meta information about the request. @param derivedSigningKey Signing key derived from the AWS secret access key. @return AWS Signature Version 4.
[ "Calculates", "the", "AWS", "Signature", "Version", "4", "by", "signing", "(", "calculates", "the", "HmacSHA256", ")", "the", "string", "-", "to", "-", "sign", "with", "the", "derived", "key", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureV4.java#L120-L126
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/moladb/model/BatchGetItemResponse.java
BatchGetItemResponse.setResponses
public void setResponses(Map<String, List<Map<String, AttributeValue>>> responses) { """ Set the processed items' content for this BatchGetItem request. @param responses The processed items' content for this BatchGetItem request. """ this.responses = responses; }
java
public void setResponses(Map<String, List<Map<String, AttributeValue>>> responses) { this.responses = responses; }
[ "public", "void", "setResponses", "(", "Map", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "AttributeValue", ">", ">", ">", "responses", ")", "{", "this", ".", "responses", "=", "responses", ";", "}" ]
Set the processed items' content for this BatchGetItem request. @param responses The processed items' content for this BatchGetItem request.
[ "Set", "the", "processed", "items", "content", "for", "this", "BatchGetItem", "request", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/moladb/model/BatchGetItemResponse.java#L75-L77
EasyinnovaSL/Tiff-Library-4J
src/main/java/com/easyinnova/tiff/profiles/TiffITProfile.java
TiffITProfile.validateIfdBL
private void validateIfdBL(IFD ifd, int p) { """ Validate Binary Lineart. @param ifd the ifd @param p the profile (default = 0, P1 = 1) """ IfdTags metadata = ifd.getMetadata(); if (p == 1) { checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0}); } checkRequiredTag(metadata, "ImageLength", 1); checkRequiredTag(metadata, "ImageWidth", 1); checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{1}); checkRequiredTag(metadata, "Compression", 1, new long[]{32898}); if (p == 0) { checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0, 1}); } else { checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0}); } checkRequiredTag(metadata, "StripOffsets", 1); if (p == 0) { checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8}); } else { checkRequiredTag(metadata, "Orientation", 1, new long[]{1}); } checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1}); checkRequiredTag(metadata, "StripBYTECount", 1); checkRequiredTag(metadata, "XResolution", 1); checkRequiredTag(metadata, "YResolution", 1); if (p == 1) { checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3}); checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255}); } checkRequiredTag(metadata, "ImageColorIndicator", 1, new long[]{0, 1, 2}); checkRequiredTag(metadata, "BackgroundColorIndicator", 1, new long[]{0, 1, 2}); }
java
private void validateIfdBL(IFD ifd, int p) { IfdTags metadata = ifd.getMetadata(); if (p == 1) { checkRequiredTag(metadata, "NewSubfileType", 1, new long[]{0}); } checkRequiredTag(metadata, "ImageLength", 1); checkRequiredTag(metadata, "ImageWidth", 1); checkRequiredTag(metadata, "BitsPerSample", 1, new long[]{1}); checkRequiredTag(metadata, "Compression", 1, new long[]{32898}); if (p == 0) { checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0, 1}); } else { checkRequiredTag(metadata, "PhotometricInterpretation", 1, new long[] {0}); } checkRequiredTag(metadata, "StripOffsets", 1); if (p == 0) { checkRequiredTag(metadata, "Orientation", 1, new long[]{1,4,5,8}); } else { checkRequiredTag(metadata, "Orientation", 1, new long[]{1}); } checkRequiredTag(metadata, "SamplesPerPixel", 1, new long[]{1}); checkRequiredTag(metadata, "StripBYTECount", 1); checkRequiredTag(metadata, "XResolution", 1); checkRequiredTag(metadata, "YResolution", 1); if (p == 1) { checkRequiredTag(metadata, "ResolutionUnit", 1, new long[]{2, 3}); checkRequiredTag(metadata, "DotRange", 2, new long[]{0, 255}); } checkRequiredTag(metadata, "ImageColorIndicator", 1, new long[]{0, 1, 2}); checkRequiredTag(metadata, "BackgroundColorIndicator", 1, new long[]{0, 1, 2}); }
[ "private", "void", "validateIfdBL", "(", "IFD", "ifd", ",", "int", "p", ")", "{", "IfdTags", "metadata", "=", "ifd", ".", "getMetadata", "(", ")", ";", "if", "(", "p", "==", "1", ")", "{", "checkRequiredTag", "(", "metadata", ",", "\"NewSubfileType\"", ",", "1", ",", "new", "long", "[", "]", "{", "0", "}", ")", ";", "}", "checkRequiredTag", "(", "metadata", ",", "\"ImageLength\"", ",", "1", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"ImageWidth\"", ",", "1", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"BitsPerSample\"", ",", "1", ",", "new", "long", "[", "]", "{", "1", "}", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"Compression\"", ",", "1", ",", "new", "long", "[", "]", "{", "32898", "}", ")", ";", "if", "(", "p", "==", "0", ")", "{", "checkRequiredTag", "(", "metadata", ",", "\"PhotometricInterpretation\"", ",", "1", ",", "new", "long", "[", "]", "{", "0", ",", "1", "}", ")", ";", "}", "else", "{", "checkRequiredTag", "(", "metadata", ",", "\"PhotometricInterpretation\"", ",", "1", ",", "new", "long", "[", "]", "{", "0", "}", ")", ";", "}", "checkRequiredTag", "(", "metadata", ",", "\"StripOffsets\"", ",", "1", ")", ";", "if", "(", "p", "==", "0", ")", "{", "checkRequiredTag", "(", "metadata", ",", "\"Orientation\"", ",", "1", ",", "new", "long", "[", "]", "{", "1", ",", "4", ",", "5", ",", "8", "}", ")", ";", "}", "else", "{", "checkRequiredTag", "(", "metadata", ",", "\"Orientation\"", ",", "1", ",", "new", "long", "[", "]", "{", "1", "}", ")", ";", "}", "checkRequiredTag", "(", "metadata", ",", "\"SamplesPerPixel\"", ",", "1", ",", "new", "long", "[", "]", "{", "1", "}", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"StripBYTECount\"", ",", "1", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"XResolution\"", ",", "1", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"YResolution\"", ",", "1", ")", ";", "if", "(", "p", "==", "1", ")", "{", "checkRequiredTag", "(", "metadata", ",", "\"ResolutionUnit\"", ",", "1", ",", "new", "long", "[", "]", "{", "2", ",", "3", "}", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"DotRange\"", ",", "2", ",", "new", "long", "[", "]", "{", "0", ",", "255", "}", ")", ";", "}", "checkRequiredTag", "(", "metadata", ",", "\"ImageColorIndicator\"", ",", "1", ",", "new", "long", "[", "]", "{", "0", ",", "1", ",", "2", "}", ")", ";", "checkRequiredTag", "(", "metadata", ",", "\"BackgroundColorIndicator\"", ",", "1", ",", "new", "long", "[", "]", "{", "0", ",", "1", ",", "2", "}", ")", ";", "}" ]
Validate Binary Lineart. @param ifd the ifd @param p the profile (default = 0, P1 = 1)
[ "Validate", "Binary", "Lineart", "." ]
train
https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/profiles/TiffITProfile.java#L512-L543
jglobus/JGlobus
gridftp/src/main/java/org/globus/ftp/FTPClient.java
FTPClient.getLastModified
public Date getLastModified(String filename) throws IOException, ServerException { """ Returns last modification time of the specifed file. @param filename filename get the last modification time for. @return the time and date of the last modification. @exception ServerException if the file does not exist or an error occured. """ if (filename == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("MDTM", filename); Reply reply = null; try { reply = controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing transfer mode"); } if (dateFormat == null) { dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } try { return dateFormat.parse(reply.getMessage()); } catch (ParseException e) { throw ServerException.embedFTPReplyParseException( new FTPReplyParseException( 0, "Invalid file modification time reply: " + reply)); } }
java
public Date getLastModified(String filename) throws IOException, ServerException { if (filename == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("MDTM", filename); Reply reply = null; try { reply = controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused changing transfer mode"); } if (dateFormat == null) { dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } try { return dateFormat.parse(reply.getMessage()); } catch (ParseException e) { throw ServerException.embedFTPReplyParseException( new FTPReplyParseException( 0, "Invalid file modification time reply: " + reply)); } }
[ "public", "Date", "getLastModified", "(", "String", "filename", ")", "throws", "IOException", ",", "ServerException", "{", "if", "(", "filename", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Required argument missing\"", ")", ";", "}", "Command", "cmd", "=", "new", "Command", "(", "\"MDTM\"", ",", "filename", ")", ";", "Reply", "reply", "=", "null", ";", "try", "{", "reply", "=", "controlChannel", ".", "execute", "(", "cmd", ")", ";", "}", "catch", "(", "FTPReplyParseException", "rpe", ")", "{", "throw", "ServerException", ".", "embedFTPReplyParseException", "(", "rpe", ")", ";", "}", "catch", "(", "UnexpectedReplyCodeException", "urce", ")", "{", "throw", "ServerException", ".", "embedUnexpectedReplyCodeException", "(", "urce", ",", "\"Server refused changing transfer mode\"", ")", ";", "}", "if", "(", "dateFormat", "==", "null", ")", "{", "dateFormat", "=", "new", "SimpleDateFormat", "(", "\"yyyyMMddHHmmss\"", ")", ";", "dateFormat", ".", "setTimeZone", "(", "TimeZone", ".", "getTimeZone", "(", "\"GMT\"", ")", ")", ";", "}", "try", "{", "return", "dateFormat", ".", "parse", "(", "reply", ".", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "ParseException", "e", ")", "{", "throw", "ServerException", ".", "embedFTPReplyParseException", "(", "new", "FTPReplyParseException", "(", "0", ",", "\"Invalid file modification time reply: \"", "+", "reply", ")", ")", ";", "}", "}" ]
Returns last modification time of the specifed file. @param filename filename get the last modification time for. @return the time and date of the last modification. @exception ServerException if the file does not exist or an error occured.
[ "Returns", "last", "modification", "time", "of", "the", "specifed", "file", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/FTPClient.java#L171-L201
linkedin/dexmaker
dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/StaticMockMethodAdvice.java
StaticMockMethodAdvice.tryInvoke
private static Object tryInvoke(Method origin, Object[] arguments) throws Throwable { """ Try to invoke the method {@code origin}. @param origin method to invoke @param arguments arguments to the method @return result of the method @throws Throwable Exception if thrown by the method """ try { return origin.invoke(null, arguments); } catch (InvocationTargetException exception) { throw exception.getCause(); } }
java
private static Object tryInvoke(Method origin, Object[] arguments) throws Throwable { try { return origin.invoke(null, arguments); } catch (InvocationTargetException exception) { throw exception.getCause(); } }
[ "private", "static", "Object", "tryInvoke", "(", "Method", "origin", ",", "Object", "[", "]", "arguments", ")", "throws", "Throwable", "{", "try", "{", "return", "origin", ".", "invoke", "(", "null", ",", "arguments", ")", ";", "}", "catch", "(", "InvocationTargetException", "exception", ")", "{", "throw", "exception", ".", "getCause", "(", ")", ";", "}", "}" ]
Try to invoke the method {@code origin}. @param origin method to invoke @param arguments arguments to the method @return result of the method @throws Throwable Exception if thrown by the method
[ "Try", "to", "invoke", "the", "method", "{", "@code", "origin", "}", "." ]
train
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/StaticMockMethodAdvice.java#L52-L59
dain/leveldb
leveldb/src/main/java/org/iq80/leveldb/util/Slice.java
Slice.setBytes
public int setBytes(int index, InputStream in, int length) throws IOException { """ Transfers the content of the specified source stream to this buffer starting at the specified absolute {@code index}. @param length the number of bytes to transfer @return the actual number of bytes read in from the specified channel. {@code -1} if the specified channel is closed. @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or if {@code index + length} is greater than {@code this.capacity} @throws java.io.IOException if the specified stream threw an exception during I/O """ checkPositionIndexes(index, index + length, this.length); index += offset; int readBytes = 0; do { int localReadBytes = in.read(data, index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); return readBytes; }
java
public int setBytes(int index, InputStream in, int length) throws IOException { checkPositionIndexes(index, index + length, this.length); index += offset; int readBytes = 0; do { int localReadBytes = in.read(data, index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); return readBytes; }
[ "public", "int", "setBytes", "(", "int", "index", ",", "InputStream", "in", ",", "int", "length", ")", "throws", "IOException", "{", "checkPositionIndexes", "(", "index", ",", "index", "+", "length", ",", "this", ".", "length", ")", ";", "index", "+=", "offset", ";", "int", "readBytes", "=", "0", ";", "do", "{", "int", "localReadBytes", "=", "in", ".", "read", "(", "data", ",", "index", ",", "length", ")", ";", "if", "(", "localReadBytes", "<", "0", ")", "{", "if", "(", "readBytes", "==", "0", ")", "{", "return", "-", "1", ";", "}", "else", "{", "break", ";", "}", "}", "readBytes", "+=", "localReadBytes", ";", "index", "+=", "localReadBytes", ";", "length", "-=", "localReadBytes", ";", "}", "while", "(", "length", ">", "0", ")", ";", "return", "readBytes", ";", "}" ]
Transfers the content of the specified source stream to this buffer starting at the specified absolute {@code index}. @param length the number of bytes to transfer @return the actual number of bytes read in from the specified channel. {@code -1} if the specified channel is closed. @throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or if {@code index + length} is greater than {@code this.capacity} @throws java.io.IOException if the specified stream threw an exception during I/O
[ "Transfers", "the", "content", "of", "the", "specified", "source", "stream", "to", "this", "buffer", "starting", "at", "the", "specified", "absolute", "{", "@code", "index", "}", "." ]
train
https://github.com/dain/leveldb/blob/7994065b48eada2ef29e7fefd172c2ad1e0110eb/leveldb/src/main/java/org/iq80/leveldb/util/Slice.java#L417-L439
skjolber/3d-bin-container-packing
src/main/java/com/github/skjolberg/packing/Packager.java
Packager.packList
public List<Container> packList(List<BoxItem> boxes, int limit, long deadline, AtomicBoolean interrupt) { """ Return a list of containers which holds all the boxes in the argument @param boxes list of boxes to fit in a container @param limit maximum number of containers @param deadline the system time in milliseconds at which the search should be aborted @param interrupt When true, the computation is interrupted as soon as possible. @return index of container if match, -1 if not """ return packList(boxes, limit, () -> deadlineReached(deadline) || interrupt.get()); }
java
public List<Container> packList(List<BoxItem> boxes, int limit, long deadline, AtomicBoolean interrupt) { return packList(boxes, limit, () -> deadlineReached(deadline) || interrupt.get()); }
[ "public", "List", "<", "Container", ">", "packList", "(", "List", "<", "BoxItem", ">", "boxes", ",", "int", "limit", ",", "long", "deadline", ",", "AtomicBoolean", "interrupt", ")", "{", "return", "packList", "(", "boxes", ",", "limit", ",", "(", ")", "->", "deadlineReached", "(", "deadline", ")", "||", "interrupt", ".", "get", "(", ")", ")", ";", "}" ]
Return a list of containers which holds all the boxes in the argument @param boxes list of boxes to fit in a container @param limit maximum number of containers @param deadline the system time in milliseconds at which the search should be aborted @param interrupt When true, the computation is interrupted as soon as possible. @return index of container if match, -1 if not
[ "Return", "a", "list", "of", "containers", "which", "holds", "all", "the", "boxes", "in", "the", "argument" ]
train
https://github.com/skjolber/3d-bin-container-packing/blob/9609bc7515322b2de2cad0dfb3d2f72607e71aae/src/main/java/com/github/skjolberg/packing/Packager.java#L249-L251
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/graph/EdmondsMaximumMatching.java
EdmondsMaximumMatching.blossomSupports
private int[] blossomSupports(int v, int w, int base) { """ Creates the blossom 'supports' for the specified blossom 'bridge' edge (v, w). We travel down each side to the base of the blossom ('base') collapsing vertices and point any 'odd' vertices to the correct 'bridge' edge. We do this by indexing the birdie to each vertex in the 'bridges' map. @param v an endpoint of the blossom bridge @param w another endpoint of the blossom bridge @param base the base of the blossom """ int n = 0; path[n++] = dsf.getRoot(v); Tuple b = new Tuple(v, w); while (path[n - 1] != base) { int u = even[path[n - 1]]; path[n++] = u; this.bridges.put(u, b); // contracting the blossom allows us to continue searching from odd // vertices (any odd vertices are now even - part of the blossom set) queue.add(u); path[n++] = dsf.getRoot(odd[u]); } return Arrays.copyOf(path, n); }
java
private int[] blossomSupports(int v, int w, int base) { int n = 0; path[n++] = dsf.getRoot(v); Tuple b = new Tuple(v, w); while (path[n - 1] != base) { int u = even[path[n - 1]]; path[n++] = u; this.bridges.put(u, b); // contracting the blossom allows us to continue searching from odd // vertices (any odd vertices are now even - part of the blossom set) queue.add(u); path[n++] = dsf.getRoot(odd[u]); } return Arrays.copyOf(path, n); }
[ "private", "int", "[", "]", "blossomSupports", "(", "int", "v", ",", "int", "w", ",", "int", "base", ")", "{", "int", "n", "=", "0", ";", "path", "[", "n", "++", "]", "=", "dsf", ".", "getRoot", "(", "v", ")", ";", "Tuple", "b", "=", "new", "Tuple", "(", "v", ",", "w", ")", ";", "while", "(", "path", "[", "n", "-", "1", "]", "!=", "base", ")", "{", "int", "u", "=", "even", "[", "path", "[", "n", "-", "1", "]", "]", ";", "path", "[", "n", "++", "]", "=", "u", ";", "this", ".", "bridges", ".", "put", "(", "u", ",", "b", ")", ";", "// contracting the blossom allows us to continue searching from odd", "// vertices (any odd vertices are now even - part of the blossom set)", "queue", ".", "add", "(", "u", ")", ";", "path", "[", "n", "++", "]", "=", "dsf", ".", "getRoot", "(", "odd", "[", "u", "]", ")", ";", "}", "return", "Arrays", ".", "copyOf", "(", "path", ",", "n", ")", ";", "}" ]
Creates the blossom 'supports' for the specified blossom 'bridge' edge (v, w). We travel down each side to the base of the blossom ('base') collapsing vertices and point any 'odd' vertices to the correct 'bridge' edge. We do this by indexing the birdie to each vertex in the 'bridges' map. @param v an endpoint of the blossom bridge @param w another endpoint of the blossom bridge @param base the base of the blossom
[ "Creates", "the", "blossom", "supports", "for", "the", "specified", "blossom", "bridge", "edge", "(", "v", "w", ")", ".", "We", "travel", "down", "each", "side", "to", "the", "base", "of", "the", "blossom", "(", "base", ")", "collapsing", "vertices", "and", "point", "any", "odd", "vertices", "to", "the", "correct", "bridge", "edge", ".", "We", "do", "this", "by", "indexing", "the", "birdie", "to", "each", "vertex", "in", "the", "bridges", "map", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/graph/EdmondsMaximumMatching.java#L292-L308
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/windowing/Window.java
Window.addListener
public void addListener(WindowListener<K,R,P> listener) { """ Adds a new WindowListener if and only if it isn't already present. @param listener The listener to add """ this.listeners.addIfAbsent(new UnwrappedWeakReference<WindowListener<K,R,P>>(listener)); }
java
public void addListener(WindowListener<K,R,P> listener) { this.listeners.addIfAbsent(new UnwrappedWeakReference<WindowListener<K,R,P>>(listener)); }
[ "public", "void", "addListener", "(", "WindowListener", "<", "K", ",", "R", ",", "P", ">", "listener", ")", "{", "this", ".", "listeners", ".", "addIfAbsent", "(", "new", "UnwrappedWeakReference", "<", "WindowListener", "<", "K", ",", "R", ",", "P", ">", ">", "(", "listener", ")", ")", ";", "}" ]
Adds a new WindowListener if and only if it isn't already present. @param listener The listener to add
[ "Adds", "a", "new", "WindowListener", "if", "and", "only", "if", "it", "isn", "t", "already", "present", "." ]
train
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/windowing/Window.java#L206-L208
landawn/AbacusUtil
src/com/landawn/abacus/util/StringUtil.java
StringUtil.toUpperCase
public static String toUpperCase(final String str, final Locale locale) { """ <p> Converts a String to upper case as per {@link String#toUpperCase(Locale)} . </p> <p> A {@code null} input String returns {@code null}. </p> <pre> N.toUpperCase(null, Locale.ENGLISH) = null N.toUpperCase("", Locale.ENGLISH) = "" N.toUpperCase("aBc", Locale.ENGLISH) = "ABC" </pre> @param str the String to upper case, may be null @param locale the locale that defines the case transformation rules, must not be null @return the upper cased String, {@code null} if null String input @since 2.5 """ if (N.isNullOrEmpty(str)) { return str; } return str.toUpperCase(locale); }
java
public static String toUpperCase(final String str, final Locale locale) { if (N.isNullOrEmpty(str)) { return str; } return str.toUpperCase(locale); }
[ "public", "static", "String", "toUpperCase", "(", "final", "String", "str", ",", "final", "Locale", "locale", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "str", ")", ")", "{", "return", "str", ";", "}", "return", "str", ".", "toUpperCase", "(", "locale", ")", ";", "}" ]
<p> Converts a String to upper case as per {@link String#toUpperCase(Locale)} . </p> <p> A {@code null} input String returns {@code null}. </p> <pre> N.toUpperCase(null, Locale.ENGLISH) = null N.toUpperCase("", Locale.ENGLISH) = "" N.toUpperCase("aBc", Locale.ENGLISH) = "ABC" </pre> @param str the String to upper case, may be null @param locale the locale that defines the case transformation rules, must not be null @return the upper cased String, {@code null} if null String input @since 2.5
[ "<p", ">", "Converts", "a", "String", "to", "upper", "case", "as", "per", "{", "@link", "String#toUpperCase", "(", "Locale", ")", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L632-L638
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
ClassName.bestGuess
public static ClassName bestGuess(String classNameString) { """ Returns a new {@link ClassName} instance for the given fully-qualified class name string. This method assumes that the input is ASCII and follows typical Java style (lowercase package names, UpperCamelCase class names) and may produce incorrect results or throw {@link IllegalArgumentException} otherwise. For that reason, {@link #get(Class)} and {@link #get(Class)} should be preferred as they can correctly create {@link ClassName} instances without such restrictions. """ // Add the package name, like "java.util.concurrent", or "" for no package. int p = 0; while (p < classNameString.length() && Character.isLowerCase(classNameString.codePointAt(p))) { p = classNameString.indexOf('.', p) + 1; checkArgument(p != 0, "couldn't make a guess for %s", classNameString); } String packageName = p == 0 ? "" : classNameString.substring(0, p - 1); // Add class names like "Map" and "Entry". ClassName className = null; for (String simpleName : classNameString.substring(p).split("\\.", -1)) { checkArgument(!simpleName.isEmpty() && Character.isUpperCase(simpleName.codePointAt(0)), "couldn't make a guess for %s", classNameString); className = new ClassName(packageName, className, simpleName); } return className; }
java
public static ClassName bestGuess(String classNameString) { // Add the package name, like "java.util.concurrent", or "" for no package. int p = 0; while (p < classNameString.length() && Character.isLowerCase(classNameString.codePointAt(p))) { p = classNameString.indexOf('.', p) + 1; checkArgument(p != 0, "couldn't make a guess for %s", classNameString); } String packageName = p == 0 ? "" : classNameString.substring(0, p - 1); // Add class names like "Map" and "Entry". ClassName className = null; for (String simpleName : classNameString.substring(p).split("\\.", -1)) { checkArgument(!simpleName.isEmpty() && Character.isUpperCase(simpleName.codePointAt(0)), "couldn't make a guess for %s", classNameString); className = new ClassName(packageName, className, simpleName); } return className; }
[ "public", "static", "ClassName", "bestGuess", "(", "String", "classNameString", ")", "{", "// Add the package name, like \"java.util.concurrent\", or \"\" for no package.", "int", "p", "=", "0", ";", "while", "(", "p", "<", "classNameString", ".", "length", "(", ")", "&&", "Character", ".", "isLowerCase", "(", "classNameString", ".", "codePointAt", "(", "p", ")", ")", ")", "{", "p", "=", "classNameString", ".", "indexOf", "(", "'", "'", ",", "p", ")", "+", "1", ";", "checkArgument", "(", "p", "!=", "0", ",", "\"couldn't make a guess for %s\"", ",", "classNameString", ")", ";", "}", "String", "packageName", "=", "p", "==", "0", "?", "\"\"", ":", "classNameString", ".", "substring", "(", "0", ",", "p", "-", "1", ")", ";", "// Add class names like \"Map\" and \"Entry\".", "ClassName", "className", "=", "null", ";", "for", "(", "String", "simpleName", ":", "classNameString", ".", "substring", "(", "p", ")", ".", "split", "(", "\"\\\\.\"", ",", "-", "1", ")", ")", "{", "checkArgument", "(", "!", "simpleName", ".", "isEmpty", "(", ")", "&&", "Character", ".", "isUpperCase", "(", "simpleName", ".", "codePointAt", "(", "0", ")", ")", ",", "\"couldn't make a guess for %s\"", ",", "classNameString", ")", ";", "className", "=", "new", "ClassName", "(", "packageName", ",", "className", ",", "simpleName", ")", ";", "}", "return", "className", ";", "}" ]
Returns a new {@link ClassName} instance for the given fully-qualified class name string. This method assumes that the input is ASCII and follows typical Java style (lowercase package names, UpperCamelCase class names) and may produce incorrect results or throw {@link IllegalArgumentException} otherwise. For that reason, {@link #get(Class)} and {@link #get(Class)} should be preferred as they can correctly create {@link ClassName} instances without such restrictions.
[ "Returns", "a", "new", "{" ]
train
https://github.com/square/javapoet/blob/0f93da9a3d9a1da8d29fc993409fcf83d40452bc/src/main/java/com/squareup/javapoet/ClassName.java#L190-L208
michael-rapp/AndroidMaterialValidation
library/src/main/java/de/mrapp/android/validation/AbstractValidateableView.java
AbstractValidateableView.setEnabledOnViewGroup
private void setEnabledOnViewGroup(@NonNull final ViewGroup viewGroup, final boolean enabled) { """ Adapts the enable state of all children of a specific view group. @param viewGroup The view group, whose children's enabled states should be adapted, as an instance of the class {@link ViewGroup}. The view group may not be null @param enabled True, if the children should be enabled, false otherwise """ viewGroup.setEnabled(enabled); for (int i = 0; i < viewGroup.getChildCount(); i++) { View child = viewGroup.getChildAt(i); if (child instanceof ViewGroup) { setEnabledOnViewGroup((ViewGroup) child, enabled); } else { child.setEnabled(enabled); } } }
java
private void setEnabledOnViewGroup(@NonNull final ViewGroup viewGroup, final boolean enabled) { viewGroup.setEnabled(enabled); for (int i = 0; i < viewGroup.getChildCount(); i++) { View child = viewGroup.getChildAt(i); if (child instanceof ViewGroup) { setEnabledOnViewGroup((ViewGroup) child, enabled); } else { child.setEnabled(enabled); } } }
[ "private", "void", "setEnabledOnViewGroup", "(", "@", "NonNull", "final", "ViewGroup", "viewGroup", ",", "final", "boolean", "enabled", ")", "{", "viewGroup", ".", "setEnabled", "(", "enabled", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "viewGroup", ".", "getChildCount", "(", ")", ";", "i", "++", ")", "{", "View", "child", "=", "viewGroup", ".", "getChildAt", "(", "i", ")", ";", "if", "(", "child", "instanceof", "ViewGroup", ")", "{", "setEnabledOnViewGroup", "(", "(", "ViewGroup", ")", "child", ",", "enabled", ")", ";", "}", "else", "{", "child", ".", "setEnabled", "(", "enabled", ")", ";", "}", "}", "}" ]
Adapts the enable state of all children of a specific view group. @param viewGroup The view group, whose children's enabled states should be adapted, as an instance of the class {@link ViewGroup}. The view group may not be null @param enabled True, if the children should be enabled, false otherwise
[ "Adapts", "the", "enable", "state", "of", "all", "children", "of", "a", "specific", "view", "group", "." ]
train
https://github.com/michael-rapp/AndroidMaterialValidation/blob/ac8693baeac7abddf2e38a47da4c1849d4661a8b/library/src/main/java/de/mrapp/android/validation/AbstractValidateableView.java#L470-L482
SeleniumHQ/selenium
java/server/src/org/openqa/grid/internal/DefaultGridRegistry.java
DefaultGridRegistry._release
private void _release(TestSlot testSlot, SessionTerminationReason reason) { """ Release the test slot. Free the resource on the slot itself and the registry. If also invokes the {@link org.openqa.grid.internal.listeners.TestSessionListener#afterSession(TestSession)} if applicable. @param testSlot The slot to release """ if (!testSlot.startReleaseProcess()) { return; } if (!testSlot.performAfterSessionEvent()) { return; } final String internalKey = testSlot.getInternalKey(); try { lock.lock(); testSlot.finishReleaseProcess(); release(internalKey, reason); } finally { lock.unlock(); } }
java
private void _release(TestSlot testSlot, SessionTerminationReason reason) { if (!testSlot.startReleaseProcess()) { return; } if (!testSlot.performAfterSessionEvent()) { return; } final String internalKey = testSlot.getInternalKey(); try { lock.lock(); testSlot.finishReleaseProcess(); release(internalKey, reason); } finally { lock.unlock(); } }
[ "private", "void", "_release", "(", "TestSlot", "testSlot", ",", "SessionTerminationReason", "reason", ")", "{", "if", "(", "!", "testSlot", ".", "startReleaseProcess", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", "testSlot", ".", "performAfterSessionEvent", "(", ")", ")", "{", "return", ";", "}", "final", "String", "internalKey", "=", "testSlot", ".", "getInternalKey", "(", ")", ";", "try", "{", "lock", ".", "lock", "(", ")", ";", "testSlot", ".", "finishReleaseProcess", "(", ")", ";", "release", "(", "internalKey", ",", "reason", ")", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Release the test slot. Free the resource on the slot itself and the registry. If also invokes the {@link org.openqa.grid.internal.listeners.TestSessionListener#afterSession(TestSession)} if applicable. @param testSlot The slot to release
[ "Release", "the", "test", "slot", ".", "Free", "the", "resource", "on", "the", "slot", "itself", "and", "the", "registry", ".", "If", "also", "invokes", "the", "{", "@link", "org", ".", "openqa", ".", "grid", ".", "internal", ".", "listeners", ".", "TestSessionListener#afterSession", "(", "TestSession", ")", "}", "if", "applicable", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/server/src/org/openqa/grid/internal/DefaultGridRegistry.java#L126-L144
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BThreadSyncSnapshot.java
BThreadSyncSnapshot.copyWith
public BThreadSyncSnapshot copyWith(Object aContinuation, SyncStatement aStatement) { """ Creates the next snapshot of the BThread in a given run. @param aContinuation The BThread's continuation for the next sync. @param aStatement The BThread's statement for the next sync. @return a copy of {@code this} with updated continuation and statement. """ BThreadSyncSnapshot retVal = new BThreadSyncSnapshot(name, entryPoint); retVal.continuation = aContinuation; retVal.setInterruptHandler(interruptHandler); retVal.syncStatement = aStatement; aStatement.setBthread(retVal); return retVal; }
java
public BThreadSyncSnapshot copyWith(Object aContinuation, SyncStatement aStatement) { BThreadSyncSnapshot retVal = new BThreadSyncSnapshot(name, entryPoint); retVal.continuation = aContinuation; retVal.setInterruptHandler(interruptHandler); retVal.syncStatement = aStatement; aStatement.setBthread(retVal); return retVal; }
[ "public", "BThreadSyncSnapshot", "copyWith", "(", "Object", "aContinuation", ",", "SyncStatement", "aStatement", ")", "{", "BThreadSyncSnapshot", "retVal", "=", "new", "BThreadSyncSnapshot", "(", "name", ",", "entryPoint", ")", ";", "retVal", ".", "continuation", "=", "aContinuation", ";", "retVal", ".", "setInterruptHandler", "(", "interruptHandler", ")", ";", "retVal", ".", "syncStatement", "=", "aStatement", ";", "aStatement", ".", "setBthread", "(", "retVal", ")", ";", "return", "retVal", ";", "}" ]
Creates the next snapshot of the BThread in a given run. @param aContinuation The BThread's continuation for the next sync. @param aStatement The BThread's statement for the next sync. @return a copy of {@code this} with updated continuation and statement.
[ "Creates", "the", "next", "snapshot", "of", "the", "BThread", "in", "a", "given", "run", "." ]
train
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BThreadSyncSnapshot.java#L81-L89
alkacon/opencms-core
src/org/opencms/workplace/editors/CmsWorkplaceEditorManager.java
CmsWorkplaceEditorManager.checkAcaciaEditorAvailable
public static boolean checkAcaciaEditorAvailable(CmsObject cms, CmsResource resource) { """ Checks whether GWT widgets are available for all fields of a content.<p> @param cms the current CMS context @param resource the resource to check @return false if for some fields the new Acacia widgets are not available @throws CmsException if something goes wrong """ if (resource == null) { try { // we want a stack trace throw new Exception(); } catch (Exception e) { LOG.error("Can't check widget availability because resource is null!", e); } return false; } try { CmsFile file = (resource instanceof CmsFile) ? (CmsFile)resource : cms.readFile(resource); CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file); if (content.getContentDefinition().getContentHandler().isAcaciaEditorDisabled()) { return false; } CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(cms, file, cms.getRequestContext().getLocale()); return visitor.isEditorCompatible(content.getContentDefinition()); } catch (CmsException e) { LOG.info("error thrown in checkAcaciaEditorAvailable for " + resource + " : " + e.getLocalizedMessage(), e); return true; } }
java
public static boolean checkAcaciaEditorAvailable(CmsObject cms, CmsResource resource) { if (resource == null) { try { // we want a stack trace throw new Exception(); } catch (Exception e) { LOG.error("Can't check widget availability because resource is null!", e); } return false; } try { CmsFile file = (resource instanceof CmsFile) ? (CmsFile)resource : cms.readFile(resource); CmsXmlContent content = CmsXmlContentFactory.unmarshal(cms, file); if (content.getContentDefinition().getContentHandler().isAcaciaEditorDisabled()) { return false; } CmsContentTypeVisitor visitor = new CmsContentTypeVisitor(cms, file, cms.getRequestContext().getLocale()); return visitor.isEditorCompatible(content.getContentDefinition()); } catch (CmsException e) { LOG.info("error thrown in checkAcaciaEditorAvailable for " + resource + " : " + e.getLocalizedMessage(), e); return true; } }
[ "public", "static", "boolean", "checkAcaciaEditorAvailable", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ")", "{", "if", "(", "resource", "==", "null", ")", "{", "try", "{", "// we want a stack trace", "throw", "new", "Exception", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Can't check widget availability because resource is null!\"", ",", "e", ")", ";", "}", "return", "false", ";", "}", "try", "{", "CmsFile", "file", "=", "(", "resource", "instanceof", "CmsFile", ")", "?", "(", "CmsFile", ")", "resource", ":", "cms", ".", "readFile", "(", "resource", ")", ";", "CmsXmlContent", "content", "=", "CmsXmlContentFactory", ".", "unmarshal", "(", "cms", ",", "file", ")", ";", "if", "(", "content", ".", "getContentDefinition", "(", ")", ".", "getContentHandler", "(", ")", ".", "isAcaciaEditorDisabled", "(", ")", ")", "{", "return", "false", ";", "}", "CmsContentTypeVisitor", "visitor", "=", "new", "CmsContentTypeVisitor", "(", "cms", ",", "file", ",", "cms", ".", "getRequestContext", "(", ")", ".", "getLocale", "(", ")", ")", ";", "return", "visitor", ".", "isEditorCompatible", "(", "content", ".", "getContentDefinition", "(", ")", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "LOG", ".", "info", "(", "\"error thrown in checkAcaciaEditorAvailable for \"", "+", "resource", "+", "\" : \"", "+", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "return", "true", ";", "}", "}" ]
Checks whether GWT widgets are available for all fields of a content.<p> @param cms the current CMS context @param resource the resource to check @return false if for some fields the new Acacia widgets are not available @throws CmsException if something goes wrong
[ "Checks", "whether", "GWT", "widgets", "are", "available", "for", "all", "fields", "of", "a", "content", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/editors/CmsWorkplaceEditorManager.java#L154-L177
mojohaus/jaxb2-maven-plugin
src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java
Validate.notNull
public static void notNull(final Object object, final String argumentName) { """ Validates that the supplied object is not null, and throws a NullPointerException otherwise. @param object The object to validate for {@code null}-ness. @param argumentName The argument name of the object to validate. If supplied (i.e. non-{@code null}), this value is used in composing a better exception message. """ if (object == null) { throw new NullPointerException(getMessage("null", argumentName)); } }
java
public static void notNull(final Object object, final String argumentName) { if (object == null) { throw new NullPointerException(getMessage("null", argumentName)); } }
[ "public", "static", "void", "notNull", "(", "final", "Object", "object", ",", "final", "String", "argumentName", ")", "{", "if", "(", "object", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "getMessage", "(", "\"null\"", ",", "argumentName", ")", ")", ";", "}", "}" ]
Validates that the supplied object is not null, and throws a NullPointerException otherwise. @param object The object to validate for {@code null}-ness. @param argumentName The argument name of the object to validate. If supplied (i.e. non-{@code null}), this value is used in composing a better exception message.
[ "Validates", "that", "the", "supplied", "object", "is", "not", "null", "and", "throws", "a", "NullPointerException", "otherwise", "." ]
train
https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java#L43-L47
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/borland/BorlandLibrarian.java
BorlandLibrarian.quoteFilename
@Override protected String quoteFilename(final StringBuffer buf, final String filename) { """ Encloses problematic file names within quotes. @param buf string buffer @param filename source file name @return filename potentially enclosed in quotes. """ buf.setLength(0); BorlandProcessor.quoteFile(buf, filename); return buf.toString(); }
java
@Override protected String quoteFilename(final StringBuffer buf, final String filename) { buf.setLength(0); BorlandProcessor.quoteFile(buf, filename); return buf.toString(); }
[ "@", "Override", "protected", "String", "quoteFilename", "(", "final", "StringBuffer", "buf", ",", "final", "String", "filename", ")", "{", "buf", ".", "setLength", "(", "0", ")", ";", "BorlandProcessor", ".", "quoteFile", "(", "buf", ",", "filename", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Encloses problematic file names within quotes. @param buf string buffer @param filename source file name @return filename potentially enclosed in quotes.
[ "Encloses", "problematic", "file", "names", "within", "quotes", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/borland/BorlandLibrarian.java#L218-L223
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/model/messaging/ConversationEventsResponse.java
ConversationEventsResponse.parseEvent
private void parseEvent(JsonObject event, Parser parser, int i) { """ Parse event and add to appropriate list. @param event Json object to parse. @param parser Parser interface. @param i Number of event in the json array. """ JsonElement nameJE = event.get(Event.KEY_NAME); if (nameJE != null) { String name = nameJE.getAsString(); if (MessageSentEvent.TYPE.equals(name)) { MessageSentEvent parsed = parser.parse(event, MessageSentEvent.class); messageSent.add(parsed); map.put(i, parsed); } else if (MessageDeliveredEvent.TYPE.equals(name)) { MessageDeliveredEvent parsed = parser.parse(event, MessageDeliveredEvent.class); messageDelivered.add(parsed); map.put(i, parsed); } else if (MessageReadEvent.TYPE.equals(name)) { MessageReadEvent parsed = parser.parse(event, MessageReadEvent.class); messageRead.add(parsed); map.put(i, parsed); } } }
java
private void parseEvent(JsonObject event, Parser parser, int i) { JsonElement nameJE = event.get(Event.KEY_NAME); if (nameJE != null) { String name = nameJE.getAsString(); if (MessageSentEvent.TYPE.equals(name)) { MessageSentEvent parsed = parser.parse(event, MessageSentEvent.class); messageSent.add(parsed); map.put(i, parsed); } else if (MessageDeliveredEvent.TYPE.equals(name)) { MessageDeliveredEvent parsed = parser.parse(event, MessageDeliveredEvent.class); messageDelivered.add(parsed); map.put(i, parsed); } else if (MessageReadEvent.TYPE.equals(name)) { MessageReadEvent parsed = parser.parse(event, MessageReadEvent.class); messageRead.add(parsed); map.put(i, parsed); } } }
[ "private", "void", "parseEvent", "(", "JsonObject", "event", ",", "Parser", "parser", ",", "int", "i", ")", "{", "JsonElement", "nameJE", "=", "event", ".", "get", "(", "Event", ".", "KEY_NAME", ")", ";", "if", "(", "nameJE", "!=", "null", ")", "{", "String", "name", "=", "nameJE", ".", "getAsString", "(", ")", ";", "if", "(", "MessageSentEvent", ".", "TYPE", ".", "equals", "(", "name", ")", ")", "{", "MessageSentEvent", "parsed", "=", "parser", ".", "parse", "(", "event", ",", "MessageSentEvent", ".", "class", ")", ";", "messageSent", ".", "add", "(", "parsed", ")", ";", "map", ".", "put", "(", "i", ",", "parsed", ")", ";", "}", "else", "if", "(", "MessageDeliveredEvent", ".", "TYPE", ".", "equals", "(", "name", ")", ")", "{", "MessageDeliveredEvent", "parsed", "=", "parser", ".", "parse", "(", "event", ",", "MessageDeliveredEvent", ".", "class", ")", ";", "messageDelivered", ".", "add", "(", "parsed", ")", ";", "map", ".", "put", "(", "i", ",", "parsed", ")", ";", "}", "else", "if", "(", "MessageReadEvent", ".", "TYPE", ".", "equals", "(", "name", ")", ")", "{", "MessageReadEvent", "parsed", "=", "parser", ".", "parse", "(", "event", ",", "MessageReadEvent", ".", "class", ")", ";", "messageRead", ".", "add", "(", "parsed", ")", ";", "map", ".", "put", "(", "i", ",", "parsed", ")", ";", "}", "}", "}" ]
Parse event and add to appropriate list. @param event Json object to parse. @param parser Parser interface. @param i Number of event in the json array.
[ "Parse", "event", "and", "add", "to", "appropriate", "list", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/model/messaging/ConversationEventsResponse.java#L69-L91
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/form/RadioChoicesListView.java
RadioChoicesListView.newLabel
protected Label newLabel(final String id, final String 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}. @param id the id @param label the string for the label @return the new {@link Label} """ return ComponentFactory.newLabel(id, label); }
java
protected Label newLabel(final String id, final String label) { return ComponentFactory.newLabel(id, label); }
[ "protected", "Label", "newLabel", "(", "final", "String", "id", ",", "final", "String", "label", ")", "{", "return", "ComponentFactory", ".", "newLabel", "(", "id", ",", "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}. @param id the id @param label the string for the label @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/form/RadioChoicesListView.java#L103-L106
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/TagsApi.java
TagsApi.createTag
public Tag createTag(Object projectIdOrPath, String tagName, String ref) throws GitLabApiException { """ Creates a tag on a particular ref of the given project. <pre><code>GitLab Endpoint: POST /projects/:id/repository/tags</code></pre> @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path @param tagName The name of the tag Must be unique for the project @param ref the git ref to place the tag on @return a Tag instance containing info on the newly created tag @throws GitLabApiException if any exception occurs """ return (createTag(projectIdOrPath, tagName, ref, null, (String)null)); }
java
public Tag createTag(Object projectIdOrPath, String tagName, String ref) throws GitLabApiException { return (createTag(projectIdOrPath, tagName, ref, null, (String)null)); }
[ "public", "Tag", "createTag", "(", "Object", "projectIdOrPath", ",", "String", "tagName", ",", "String", "ref", ")", "throws", "GitLabApiException", "{", "return", "(", "createTag", "(", "projectIdOrPath", ",", "tagName", ",", "ref", ",", "null", ",", "(", "String", ")", "null", ")", ")", ";", "}" ]
Creates a tag on a particular ref of the given project. <pre><code>GitLab Endpoint: POST /projects/:id/repository/tags</code></pre> @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path @param tagName The name of the tag Must be unique for the project @param ref the git ref to place the tag on @return a Tag instance containing info on the newly created tag @throws GitLabApiException if any exception occurs
[ "Creates", "a", "tag", "on", "a", "particular", "ref", "of", "the", "given", "project", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/TagsApi.java#L130-L132
pressgang-ccms/PressGangCCMSZanataInterface
src/main/java/org/jboss/pressgang/ccms/zanata/ZanataInterface.java
ZanataInterface.deleteTranslation
public boolean deleteTranslation(final String id, final LocaleId locale) { """ Delete the translations for a Document from Zanata. <p/> Note: This method should be used with extreme care. @param id The ID of the document in Zanata to be deleted. @param locale The locale of the translation to be deleted. @return True if the document was successfully deleted, otherwise false. """ performZanataRESTCallWaiting(); ClientResponse<String> response = null; try { final ITranslatedDocResource client = proxyFactory.getTranslatedDocResource(details.getProject(), details.getVersion()); response = client.deleteTranslations(id, locale); final Status status = Response.Status.fromStatusCode(response.getStatus()); if (status == Response.Status.OK) { final String entity = response.getEntity(); if (entity.trim().length() != 0) log.info(entity); return true; } else { log.error("REST call to deleteResource() did not complete successfully. HTTP response code was " + status.getStatusCode() + ". Reason was " + status.getReasonPhrase()); } } catch (final Exception ex) { log.error("Failed to delete the Zanata Translation", ex); } finally { /* * If you are using RESTEasy client framework, and returning a Response from your service method, you will * explicitly need to release the connection. */ if (response != null) response.releaseConnection(); } return false; }
java
public boolean deleteTranslation(final String id, final LocaleId locale) { performZanataRESTCallWaiting(); ClientResponse<String> response = null; try { final ITranslatedDocResource client = proxyFactory.getTranslatedDocResource(details.getProject(), details.getVersion()); response = client.deleteTranslations(id, locale); final Status status = Response.Status.fromStatusCode(response.getStatus()); if (status == Response.Status.OK) { final String entity = response.getEntity(); if (entity.trim().length() != 0) log.info(entity); return true; } else { log.error("REST call to deleteResource() did not complete successfully. HTTP response code was " + status.getStatusCode() + ". Reason was " + status.getReasonPhrase()); } } catch (final Exception ex) { log.error("Failed to delete the Zanata Translation", ex); } finally { /* * If you are using RESTEasy client framework, and returning a Response from your service method, you will * explicitly need to release the connection. */ if (response != null) response.releaseConnection(); } return false; }
[ "public", "boolean", "deleteTranslation", "(", "final", "String", "id", ",", "final", "LocaleId", "locale", ")", "{", "performZanataRESTCallWaiting", "(", ")", ";", "ClientResponse", "<", "String", ">", "response", "=", "null", ";", "try", "{", "final", "ITranslatedDocResource", "client", "=", "proxyFactory", ".", "getTranslatedDocResource", "(", "details", ".", "getProject", "(", ")", ",", "details", ".", "getVersion", "(", ")", ")", ";", "response", "=", "client", ".", "deleteTranslations", "(", "id", ",", "locale", ")", ";", "final", "Status", "status", "=", "Response", ".", "Status", ".", "fromStatusCode", "(", "response", ".", "getStatus", "(", ")", ")", ";", "if", "(", "status", "==", "Response", ".", "Status", ".", "OK", ")", "{", "final", "String", "entity", "=", "response", ".", "getEntity", "(", ")", ";", "if", "(", "entity", ".", "trim", "(", ")", ".", "length", "(", ")", "!=", "0", ")", "log", ".", "info", "(", "entity", ")", ";", "return", "true", ";", "}", "else", "{", "log", ".", "error", "(", "\"REST call to deleteResource() did not complete successfully. HTTP response code was \"", "+", "status", ".", "getStatusCode", "(", ")", "+", "\". Reason was \"", "+", "status", ".", "getReasonPhrase", "(", ")", ")", ";", "}", "}", "catch", "(", "final", "Exception", "ex", ")", "{", "log", ".", "error", "(", "\"Failed to delete the Zanata Translation\"", ",", "ex", ")", ";", "}", "finally", "{", "/*\n * If you are using RESTEasy client framework, and returning a Response from your service method, you will\n * explicitly need to release the connection.\n */", "if", "(", "response", "!=", "null", ")", "response", ".", "releaseConnection", "(", ")", ";", "}", "return", "false", ";", "}" ]
Delete the translations for a Document from Zanata. <p/> Note: This method should be used with extreme care. @param id The ID of the document in Zanata to be deleted. @param locale The locale of the translation to be deleted. @return True if the document was successfully deleted, otherwise false.
[ "Delete", "the", "translations", "for", "a", "Document", "from", "Zanata", ".", "<p", "/", ">", "Note", ":", "This", "method", "should", "be", "used", "with", "extreme", "care", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSZanataInterface/blob/0fed2480fec2cca2c578d08724288ae8268ee4d9/src/main/java/org/jboss/pressgang/ccms/zanata/ZanataInterface.java#L475-L503
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.getFullName
public static String getFullName(final ZoneId self, Locale locale) { """ Returns the name of this zone formatted according to the {@link java.time.format.TextStyle#FULL} text style for the provided {@link java.util.Locale}. @param self a ZoneId @param locale a Locale @return the full display name of the ZoneId @since 2.5.0 """ return self.getDisplayName(TextStyle.FULL, locale); }
java
public static String getFullName(final ZoneId self, Locale locale) { return self.getDisplayName(TextStyle.FULL, locale); }
[ "public", "static", "String", "getFullName", "(", "final", "ZoneId", "self", ",", "Locale", "locale", ")", "{", "return", "self", ".", "getDisplayName", "(", "TextStyle", ".", "FULL", ",", "locale", ")", ";", "}" ]
Returns the name of this zone formatted according to the {@link java.time.format.TextStyle#FULL} text style for the provided {@link java.util.Locale}. @param self a ZoneId @param locale a Locale @return the full display name of the ZoneId @since 2.5.0
[ "Returns", "the", "name", "of", "this", "zone", "formatted", "according", "to", "the", "{", "@link", "java", ".", "time", ".", "format", ".", "TextStyle#FULL", "}", "text", "style", "for", "the", "provided", "{", "@link", "java", ".", "util", ".", "Locale", "}", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L1798-L1800
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/util/Name.java
Name.subName
public Name subName(int start, int end) { """ Returns the sub-name starting at position start, up to and excluding position end. """ if (end < start) end = start; return table.fromUtf(getByteArray(), getByteOffset() + start, end - start); }
java
public Name subName(int start, int end) { if (end < start) end = start; return table.fromUtf(getByteArray(), getByteOffset() + start, end - start); }
[ "public", "Name", "subName", "(", "int", "start", ",", "int", "end", ")", "{", "if", "(", "end", "<", "start", ")", "end", "=", "start", ";", "return", "table", ".", "fromUtf", "(", "getByteArray", "(", ")", ",", "getByteOffset", "(", ")", "+", "start", ",", "end", "-", "start", ")", ";", "}" ]
Returns the sub-name starting at position start, up to and excluding position end.
[ "Returns", "the", "sub", "-", "name", "starting", "at", "position", "start", "up", "to", "and", "excluding", "position", "end", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Name.java#L143-L146
jankotek/mapdb
src/main/java/org/mapdb/io/DataIO.java
DataIO.packInt
static public void packInt(DataOutput out, int value) throws IOException { """ Pack int into an output stream. It will occupy 1-5 bytes depending on value (lower values occupy smaller space) @param out DataOutput to put value into @param value to be serialized, must be non-negative @throws java.io.IOException in case of IO error """ // Optimize for the common case where value is small. This is particular important where our caller // is SerializerBase.SER_STRING.serialize because most chars will be ASCII characters and hence in this range. // credit Max Bolingbroke https://github.com/jankotek/MapDB/pull/489 int shift = (value & ~0x7F); //reuse variable if (shift != 0) { //$DELAY$ shift = 31-Integer.numberOfLeadingZeros(value); shift -= shift%7; // round down to nearest multiple of 7 while(shift!=0){ out.writeByte((byte) ((value>>>shift) & 0x7F)); //$DELAY$ shift-=7; } } //$DELAY$ out.writeByte((byte) ((value & 0x7F)|0x80)); }
java
static public void packInt(DataOutput out, int value) throws IOException { // Optimize for the common case where value is small. This is particular important where our caller // is SerializerBase.SER_STRING.serialize because most chars will be ASCII characters and hence in this range. // credit Max Bolingbroke https://github.com/jankotek/MapDB/pull/489 int shift = (value & ~0x7F); //reuse variable if (shift != 0) { //$DELAY$ shift = 31-Integer.numberOfLeadingZeros(value); shift -= shift%7; // round down to nearest multiple of 7 while(shift!=0){ out.writeByte((byte) ((value>>>shift) & 0x7F)); //$DELAY$ shift-=7; } } //$DELAY$ out.writeByte((byte) ((value & 0x7F)|0x80)); }
[ "static", "public", "void", "packInt", "(", "DataOutput", "out", ",", "int", "value", ")", "throws", "IOException", "{", "// Optimize for the common case where value is small. This is particular important where our caller", "// is SerializerBase.SER_STRING.serialize because most chars will be ASCII characters and hence in this range.", "// credit Max Bolingbroke https://github.com/jankotek/MapDB/pull/489", "int", "shift", "=", "(", "value", "&", "~", "0x7F", ")", ";", "//reuse variable", "if", "(", "shift", "!=", "0", ")", "{", "//$DELAY$", "shift", "=", "31", "-", "Integer", ".", "numberOfLeadingZeros", "(", "value", ")", ";", "shift", "-=", "shift", "%", "7", ";", "// round down to nearest multiple of 7", "while", "(", "shift", "!=", "0", ")", "{", "out", ".", "writeByte", "(", "(", "byte", ")", "(", "(", "value", ">>>", "shift", ")", "&", "0x7F", ")", ")", ";", "//$DELAY$", "shift", "-=", "7", ";", "}", "}", "//$DELAY$", "out", ".", "writeByte", "(", "(", "byte", ")", "(", "(", "value", "&", "0x7F", ")", "|", "0x80", ")", ")", ";", "}" ]
Pack int into an output stream. It will occupy 1-5 bytes depending on value (lower values occupy smaller space) @param out DataOutput to put value into @param value to be serialized, must be non-negative @throws java.io.IOException in case of IO error
[ "Pack", "int", "into", "an", "output", "stream", ".", "It", "will", "occupy", "1", "-", "5", "bytes", "depending", "on", "value", "(", "lower", "values", "occupy", "smaller", "space", ")" ]
train
https://github.com/jankotek/mapdb/blob/dfd873b2b9cc4e299228839c100adf93a98f1903/src/main/java/org/mapdb/io/DataIO.java#L201-L219
spring-projects/spring-security-oauth
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/store/jwk/JwkSetConverter.java
JwkSetConverter.createRsaJwkDefinition
private JwkDefinition createRsaJwkDefinition(Map<String, String> attributes) { """ Creates a {@link RsaJwkDefinition} based on the supplied attributes. @param attributes the attributes used to create the {@link RsaJwkDefinition} @return a {@link JwkDefinition} representation of a RSA Key @throws JwkException if at least one attribute value is missing or invalid for a RSA Key """ // kid String keyId = attributes.get(KEY_ID); if (!StringUtils.hasText(keyId)) { throw new JwkException(KEY_ID + " is a required attribute for a JWK."); } // use JwkDefinition.PublicKeyUse publicKeyUse = JwkDefinition.PublicKeyUse.fromValue(attributes.get(PUBLIC_KEY_USE)); if (!JwkDefinition.PublicKeyUse.SIG.equals(publicKeyUse)) { throw new JwkException((publicKeyUse != null ? publicKeyUse.value() : "unknown") + " (" + PUBLIC_KEY_USE + ") is currently not supported."); } // alg JwkDefinition.CryptoAlgorithm algorithm = JwkDefinition.CryptoAlgorithm.fromHeaderParamValue(attributes.get(ALGORITHM)); if (algorithm != null && !JwkDefinition.CryptoAlgorithm.RS256.equals(algorithm) && !JwkDefinition.CryptoAlgorithm.RS384.equals(algorithm) && !JwkDefinition.CryptoAlgorithm.RS512.equals(algorithm)) { throw new JwkException(algorithm.standardName() + " (" + ALGORITHM + ") is currently not supported."); } // n String modulus = attributes.get(RSA_PUBLIC_KEY_MODULUS); if (!StringUtils.hasText(modulus)) { throw new JwkException(RSA_PUBLIC_KEY_MODULUS + " is a required attribute for a RSA JWK."); } // e String exponent = attributes.get(RSA_PUBLIC_KEY_EXPONENT); if (!StringUtils.hasText(exponent)) { throw new JwkException(RSA_PUBLIC_KEY_EXPONENT + " is a required attribute for a RSA JWK."); } RsaJwkDefinition jwkDefinition = new RsaJwkDefinition( keyId, publicKeyUse, algorithm, modulus, exponent); return jwkDefinition; }
java
private JwkDefinition createRsaJwkDefinition(Map<String, String> attributes) { // kid String keyId = attributes.get(KEY_ID); if (!StringUtils.hasText(keyId)) { throw new JwkException(KEY_ID + " is a required attribute for a JWK."); } // use JwkDefinition.PublicKeyUse publicKeyUse = JwkDefinition.PublicKeyUse.fromValue(attributes.get(PUBLIC_KEY_USE)); if (!JwkDefinition.PublicKeyUse.SIG.equals(publicKeyUse)) { throw new JwkException((publicKeyUse != null ? publicKeyUse.value() : "unknown") + " (" + PUBLIC_KEY_USE + ") is currently not supported."); } // alg JwkDefinition.CryptoAlgorithm algorithm = JwkDefinition.CryptoAlgorithm.fromHeaderParamValue(attributes.get(ALGORITHM)); if (algorithm != null && !JwkDefinition.CryptoAlgorithm.RS256.equals(algorithm) && !JwkDefinition.CryptoAlgorithm.RS384.equals(algorithm) && !JwkDefinition.CryptoAlgorithm.RS512.equals(algorithm)) { throw new JwkException(algorithm.standardName() + " (" + ALGORITHM + ") is currently not supported."); } // n String modulus = attributes.get(RSA_PUBLIC_KEY_MODULUS); if (!StringUtils.hasText(modulus)) { throw new JwkException(RSA_PUBLIC_KEY_MODULUS + " is a required attribute for a RSA JWK."); } // e String exponent = attributes.get(RSA_PUBLIC_KEY_EXPONENT); if (!StringUtils.hasText(exponent)) { throw new JwkException(RSA_PUBLIC_KEY_EXPONENT + " is a required attribute for a RSA JWK."); } RsaJwkDefinition jwkDefinition = new RsaJwkDefinition( keyId, publicKeyUse, algorithm, modulus, exponent); return jwkDefinition; }
[ "private", "JwkDefinition", "createRsaJwkDefinition", "(", "Map", "<", "String", ",", "String", ">", "attributes", ")", "{", "// kid", "String", "keyId", "=", "attributes", ".", "get", "(", "KEY_ID", ")", ";", "if", "(", "!", "StringUtils", ".", "hasText", "(", "keyId", ")", ")", "{", "throw", "new", "JwkException", "(", "KEY_ID", "+", "\" is a required attribute for a JWK.\"", ")", ";", "}", "// use", "JwkDefinition", ".", "PublicKeyUse", "publicKeyUse", "=", "JwkDefinition", ".", "PublicKeyUse", ".", "fromValue", "(", "attributes", ".", "get", "(", "PUBLIC_KEY_USE", ")", ")", ";", "if", "(", "!", "JwkDefinition", ".", "PublicKeyUse", ".", "SIG", ".", "equals", "(", "publicKeyUse", ")", ")", "{", "throw", "new", "JwkException", "(", "(", "publicKeyUse", "!=", "null", "?", "publicKeyUse", ".", "value", "(", ")", ":", "\"unknown\"", ")", "+", "\" (\"", "+", "PUBLIC_KEY_USE", "+", "\") is currently not supported.\"", ")", ";", "}", "// alg", "JwkDefinition", ".", "CryptoAlgorithm", "algorithm", "=", "JwkDefinition", ".", "CryptoAlgorithm", ".", "fromHeaderParamValue", "(", "attributes", ".", "get", "(", "ALGORITHM", ")", ")", ";", "if", "(", "algorithm", "!=", "null", "&&", "!", "JwkDefinition", ".", "CryptoAlgorithm", ".", "RS256", ".", "equals", "(", "algorithm", ")", "&&", "!", "JwkDefinition", ".", "CryptoAlgorithm", ".", "RS384", ".", "equals", "(", "algorithm", ")", "&&", "!", "JwkDefinition", ".", "CryptoAlgorithm", ".", "RS512", ".", "equals", "(", "algorithm", ")", ")", "{", "throw", "new", "JwkException", "(", "algorithm", ".", "standardName", "(", ")", "+", "\" (\"", "+", "ALGORITHM", "+", "\") is currently not supported.\"", ")", ";", "}", "// n", "String", "modulus", "=", "attributes", ".", "get", "(", "RSA_PUBLIC_KEY_MODULUS", ")", ";", "if", "(", "!", "StringUtils", ".", "hasText", "(", "modulus", ")", ")", "{", "throw", "new", "JwkException", "(", "RSA_PUBLIC_KEY_MODULUS", "+", "\" is a required attribute for a RSA JWK.\"", ")", ";", "}", "// e", "String", "exponent", "=", "attributes", ".", "get", "(", "RSA_PUBLIC_KEY_EXPONENT", ")", ";", "if", "(", "!", "StringUtils", ".", "hasText", "(", "exponent", ")", ")", "{", "throw", "new", "JwkException", "(", "RSA_PUBLIC_KEY_EXPONENT", "+", "\" is a required attribute for a RSA JWK.\"", ")", ";", "}", "RsaJwkDefinition", "jwkDefinition", "=", "new", "RsaJwkDefinition", "(", "keyId", ",", "publicKeyUse", ",", "algorithm", ",", "modulus", ",", "exponent", ")", ";", "return", "jwkDefinition", ";", "}" ]
Creates a {@link RsaJwkDefinition} based on the supplied attributes. @param attributes the attributes used to create the {@link RsaJwkDefinition} @return a {@link JwkDefinition} representation of a RSA Key @throws JwkException if at least one attribute value is missing or invalid for a RSA Key
[ "Creates", "a", "{", "@link", "RsaJwkDefinition", "}", "based", "on", "the", "supplied", "attributes", "." ]
train
https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/store/jwk/JwkSetConverter.java#L139-L180
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java
ExpectedConditions.attributeContains
public static ExpectedCondition<Boolean> attributeContains(final WebElement element, final String attribute, final String value) { """ An expectation for checking WebElement with given locator has attribute which contains specific value @param element used to check its parameters @param attribute used to define css or html attribute @param value used as expected attribute value @return Boolean true when element has css or html attribute which contains the value """ return new ExpectedCondition<Boolean>() { private String currentValue = null; @Override public Boolean apply(WebDriver driver) { return getAttributeOrCssValue(element, attribute) .map(seen -> seen.contains(value)) .orElse(false); } @Override public String toString() { return String.format("value to contain \"%s\". Current value: \"%s\"", value, currentValue); } }; }
java
public static ExpectedCondition<Boolean> attributeContains(final WebElement element, final String attribute, final String value) { return new ExpectedCondition<Boolean>() { private String currentValue = null; @Override public Boolean apply(WebDriver driver) { return getAttributeOrCssValue(element, attribute) .map(seen -> seen.contains(value)) .orElse(false); } @Override public String toString() { return String.format("value to contain \"%s\". Current value: \"%s\"", value, currentValue); } }; }
[ "public", "static", "ExpectedCondition", "<", "Boolean", ">", "attributeContains", "(", "final", "WebElement", "element", ",", "final", "String", "attribute", ",", "final", "String", "value", ")", "{", "return", "new", "ExpectedCondition", "<", "Boolean", ">", "(", ")", "{", "private", "String", "currentValue", "=", "null", ";", "@", "Override", "public", "Boolean", "apply", "(", "WebDriver", "driver", ")", "{", "return", "getAttributeOrCssValue", "(", "element", ",", "attribute", ")", ".", "map", "(", "seen", "->", "seen", ".", "contains", "(", "value", ")", ")", ".", "orElse", "(", "false", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "String", ".", "format", "(", "\"value to contain \\\"%s\\\". Current value: \\\"%s\\\"\"", ",", "value", ",", "currentValue", ")", ";", "}", "}", ";", "}" ]
An expectation for checking WebElement with given locator has attribute which contains specific value @param element used to check its parameters @param attribute used to define css or html attribute @param value used as expected attribute value @return Boolean true when element has css or html attribute which contains the value
[ "An", "expectation", "for", "checking", "WebElement", "with", "given", "locator", "has", "attribute", "which", "contains", "specific", "value" ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java#L1076-L1094
cdk/cdk
tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java
ModelBuilder3D.getRingSetOfAtom
private IRingSet getRingSetOfAtom(List ringSystems, IAtom atom) { """ Gets the ringSetOfAtom attribute of the ModelBuilder3D object. @return The ringSetOfAtom value """ IRingSet ringSetOfAtom = null; for (int i = 0; i < ringSystems.size(); i++) { if (((IRingSet) ringSystems.get(i)).contains(atom)) { return (IRingSet) ringSystems.get(i); } } return ringSetOfAtom; }
java
private IRingSet getRingSetOfAtom(List ringSystems, IAtom atom) { IRingSet ringSetOfAtom = null; for (int i = 0; i < ringSystems.size(); i++) { if (((IRingSet) ringSystems.get(i)).contains(atom)) { return (IRingSet) ringSystems.get(i); } } return ringSetOfAtom; }
[ "private", "IRingSet", "getRingSetOfAtom", "(", "List", "ringSystems", ",", "IAtom", "atom", ")", "{", "IRingSet", "ringSetOfAtom", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ringSystems", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "(", "(", "IRingSet", ")", "ringSystems", ".", "get", "(", "i", ")", ")", ".", "contains", "(", "atom", ")", ")", "{", "return", "(", "IRingSet", ")", "ringSystems", ".", "get", "(", "i", ")", ";", "}", "}", "return", "ringSetOfAtom", ";", "}" ]
Gets the ringSetOfAtom attribute of the ModelBuilder3D object. @return The ringSetOfAtom value
[ "Gets", "the", "ringSetOfAtom", "attribute", "of", "the", "ModelBuilder3D", "object", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java#L250-L258
ReactiveX/RxJavaAsyncUtil
src/main/java/rx/util/async/Async.java
Async.toAsync
public static <T1, T2> Func2<T1, T2, Observable<Void>> toAsync(Action2<? super T1, ? super T2> action) { """ Convert a synchronous action call into an asynchronous function call through an Observable. <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.an.png" alt=""> @param <T1> the first parameter type @param <T2> the second parameter type @param action the action to convert @return a function that returns an Observable that executes the {@code action} and emits {@code null} @see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a> @see <a href="http://msdn.microsoft.com/en-us/library/hh211875.aspx">MSDN: Observable.ToAsync</a> """ return toAsync(action, Schedulers.computation()); }
java
public static <T1, T2> Func2<T1, T2, Observable<Void>> toAsync(Action2<? super T1, ? super T2> action) { return toAsync(action, Schedulers.computation()); }
[ "public", "static", "<", "T1", ",", "T2", ">", "Func2", "<", "T1", ",", "T2", ",", "Observable", "<", "Void", ">", ">", "toAsync", "(", "Action2", "<", "?", "super", "T1", ",", "?", "super", "T2", ">", "action", ")", "{", "return", "toAsync", "(", "action", ",", "Schedulers", ".", "computation", "(", ")", ")", ";", "}" ]
Convert a synchronous action call into an asynchronous function call through an Observable. <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toAsync.an.png" alt=""> @param <T1> the first parameter type @param <T2> the second parameter type @param action the action to convert @return a function that returns an Observable that executes the {@code action} and emits {@code null} @see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc">RxJava Wiki: toAsync()</a> @see <a href="http://msdn.microsoft.com/en-us/library/hh211875.aspx">MSDN: Observable.ToAsync</a>
[ "Convert", "a", "synchronous", "action", "call", "into", "an", "asynchronous", "function", "call", "through", "an", "Observable", ".", "<p", ">", "<img", "width", "=", "640", "src", "=", "https", ":", "//", "raw", ".", "github", ".", "com", "/", "wiki", "/", "ReactiveX", "/", "RxJava", "/", "images", "/", "rx", "-", "operators", "/", "toAsync", ".", "an", ".", "png", "alt", "=", ">" ]
train
https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L239-L241
infinispan/infinispan
lucene/lucene-directory/src/main/java/org/infinispan/lucene/cacheloader/DirectoryLoaderAdaptor.java
DirectoryLoaderAdaptor.figureChunksNumber
public static int figureChunksNumber(final String fileName, final long fileLength, int chunkSize) { """ Index segment files might be larger than 2GB; so it's possible to have an autoChunksize which is too low to contain all bytes in a single array (overkill anyway). In this case we ramp up and try splitting with larger chunkSize values. """ if (chunkSize < 0) { throw new IllegalStateException("Overflow in rescaling chunkSize. File way too large?"); } final long numChunks = (fileLength % chunkSize == 0) ? (fileLength / chunkSize) : (fileLength / chunkSize) + 1; if (numChunks > Integer.MAX_VALUE) { log.rescalingChunksize(fileName, fileLength, chunkSize); chunkSize = 32 * chunkSize; return figureChunksNumber(fileName, fileLength, chunkSize); } else { return (int)numChunks; } }
java
public static int figureChunksNumber(final String fileName, final long fileLength, int chunkSize) { if (chunkSize < 0) { throw new IllegalStateException("Overflow in rescaling chunkSize. File way too large?"); } final long numChunks = (fileLength % chunkSize == 0) ? (fileLength / chunkSize) : (fileLength / chunkSize) + 1; if (numChunks > Integer.MAX_VALUE) { log.rescalingChunksize(fileName, fileLength, chunkSize); chunkSize = 32 * chunkSize; return figureChunksNumber(fileName, fileLength, chunkSize); } else { return (int)numChunks; } }
[ "public", "static", "int", "figureChunksNumber", "(", "final", "String", "fileName", ",", "final", "long", "fileLength", ",", "int", "chunkSize", ")", "{", "if", "(", "chunkSize", "<", "0", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Overflow in rescaling chunkSize. File way too large?\"", ")", ";", "}", "final", "long", "numChunks", "=", "(", "fileLength", "%", "chunkSize", "==", "0", ")", "?", "(", "fileLength", "/", "chunkSize", ")", ":", "(", "fileLength", "/", "chunkSize", ")", "+", "1", ";", "if", "(", "numChunks", ">", "Integer", ".", "MAX_VALUE", ")", "{", "log", ".", "rescalingChunksize", "(", "fileName", ",", "fileLength", ",", "chunkSize", ")", ";", "chunkSize", "=", "32", "*", "chunkSize", ";", "return", "figureChunksNumber", "(", "fileName", ",", "fileLength", ",", "chunkSize", ")", ";", "}", "else", "{", "return", "(", "int", ")", "numChunks", ";", "}", "}" ]
Index segment files might be larger than 2GB; so it's possible to have an autoChunksize which is too low to contain all bytes in a single array (overkill anyway). In this case we ramp up and try splitting with larger chunkSize values.
[ "Index", "segment", "files", "might", "be", "larger", "than", "2GB", ";", "so", "it", "s", "possible", "to", "have", "an", "autoChunksize", "which", "is", "too", "low", "to", "contain", "all", "bytes", "in", "a", "single", "array", "(", "overkill", "anyway", ")", ".", "In", "this", "case", "we", "ramp", "up", "and", "try", "splitting", "with", "larger", "chunkSize", "values", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/lucene/lucene-directory/src/main/java/org/infinispan/lucene/cacheloader/DirectoryLoaderAdaptor.java#L147-L160
OpenLiberty/open-liberty
dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/internal/jaas/modules/ServerCommonLoginModule.java
ServerCommonLoginModule.getSecurityName
protected String getSecurityName(String loginName, String urAuthenticatedId) throws EntryNotFoundException, RegistryException { """ Common method called by all login modules that use the UserRegistry (UsernameAndPasswordLoginModule, CertificateLoginModule, HashtableLoginModule and TokenLoginModule). Determines the securityName to use for the login. @param loginName The username passed to the login @param urAuthenticatedId The id returned by UserRegistry checkPassword or mapCertificate. @return The securityName to use for the WSPrincipal. @throws EntryNotFoundException @throws RegistryException """ UserRegistry ur = getUserRegistry(); if (ur != null && ur.getType() != "CUSTOM") { // Preserve the existing behavior for CUSTOM user registries String securityName = ur.getUserSecurityName(urAuthenticatedId); if (securityName != null) { return securityName; } } // If a loginName was provided, use it. if (loginName != null) { return loginName; } if (ur != null) { return ur.getUserSecurityName(urAuthenticatedId); } else { throw new NullPointerException("No user registry"); } }
java
protected String getSecurityName(String loginName, String urAuthenticatedId) throws EntryNotFoundException, RegistryException { UserRegistry ur = getUserRegistry(); if (ur != null && ur.getType() != "CUSTOM") { // Preserve the existing behavior for CUSTOM user registries String securityName = ur.getUserSecurityName(urAuthenticatedId); if (securityName != null) { return securityName; } } // If a loginName was provided, use it. if (loginName != null) { return loginName; } if (ur != null) { return ur.getUserSecurityName(urAuthenticatedId); } else { throw new NullPointerException("No user registry"); } }
[ "protected", "String", "getSecurityName", "(", "String", "loginName", ",", "String", "urAuthenticatedId", ")", "throws", "EntryNotFoundException", ",", "RegistryException", "{", "UserRegistry", "ur", "=", "getUserRegistry", "(", ")", ";", "if", "(", "ur", "!=", "null", "&&", "ur", ".", "getType", "(", ")", "!=", "\"CUSTOM\"", ")", "{", "// Preserve the existing behavior for CUSTOM user registries", "String", "securityName", "=", "ur", ".", "getUserSecurityName", "(", "urAuthenticatedId", ")", ";", "if", "(", "securityName", "!=", "null", ")", "{", "return", "securityName", ";", "}", "}", "// If a loginName was provided, use it.", "if", "(", "loginName", "!=", "null", ")", "{", "return", "loginName", ";", "}", "if", "(", "ur", "!=", "null", ")", "{", "return", "ur", ".", "getUserSecurityName", "(", "urAuthenticatedId", ")", ";", "}", "else", "{", "throw", "new", "NullPointerException", "(", "\"No user registry\"", ")", ";", "}", "}" ]
Common method called by all login modules that use the UserRegistry (UsernameAndPasswordLoginModule, CertificateLoginModule, HashtableLoginModule and TokenLoginModule). Determines the securityName to use for the login. @param loginName The username passed to the login @param urAuthenticatedId The id returned by UserRegistry checkPassword or mapCertificate. @return The securityName to use for the WSPrincipal. @throws EntryNotFoundException @throws RegistryException
[ "Common", "method", "called", "by", "all", "login", "modules", "that", "use", "the", "UserRegistry", "(", "UsernameAndPasswordLoginModule", "CertificateLoginModule", "HashtableLoginModule", "and", "TokenLoginModule", ")", ".", "Determines", "the", "securityName", "to", "use", "for", "the", "login", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.authentication.builtin/src/com/ibm/ws/security/authentication/internal/jaas/modules/ServerCommonLoginModule.java#L109-L129
deeplearning4j/deeplearning4j
datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/ResizeImageTransform.java
ResizeImageTransform.doTransform
@Override protected ImageWritable doTransform(ImageWritable image, Random random) { """ Takes an image and returns a transformed image. Uses the random object in the case of random transformations. @param image to transform, null == end of stream @param random object to use (or null for deterministic) @return transformed image """ if (image == null) { return null; } Mat mat = converter.convert(image.getFrame()); Mat result = new Mat(); srch = mat.rows(); srcw = mat.cols(); resize(mat, result, new Size(newWidth, newHeight)); return new ImageWritable(converter.convert(result)); }
java
@Override protected ImageWritable doTransform(ImageWritable image, Random random) { if (image == null) { return null; } Mat mat = converter.convert(image.getFrame()); Mat result = new Mat(); srch = mat.rows(); srcw = mat.cols(); resize(mat, result, new Size(newWidth, newHeight)); return new ImageWritable(converter.convert(result)); }
[ "@", "Override", "protected", "ImageWritable", "doTransform", "(", "ImageWritable", "image", ",", "Random", "random", ")", "{", "if", "(", "image", "==", "null", ")", "{", "return", "null", ";", "}", "Mat", "mat", "=", "converter", ".", "convert", "(", "image", ".", "getFrame", "(", ")", ")", ";", "Mat", "result", "=", "new", "Mat", "(", ")", ";", "srch", "=", "mat", ".", "rows", "(", ")", ";", "srcw", "=", "mat", ".", "cols", "(", ")", ";", "resize", "(", "mat", ",", "result", ",", "new", "Size", "(", "newWidth", ",", "newHeight", ")", ")", ";", "return", "new", "ImageWritable", "(", "converter", ".", "convert", "(", "result", ")", ")", ";", "}" ]
Takes an image and returns a transformed image. Uses the random object in the case of random transformations. @param image to transform, null == end of stream @param random object to use (or null for deterministic) @return transformed image
[ "Takes", "an", "image", "and", "returns", "a", "transformed", "image", ".", "Uses", "the", "random", "object", "in", "the", "case", "of", "random", "transformations", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/transform/ResizeImageTransform.java#L84-L95
MorphiaOrg/morphia
morphia/src/main/java/dev/morphia/mapping/DefaultCreator.java
DefaultCreator.newInstance
private <T> T newInstance(final Constructor<T> tryMe, final Class<T> fallbackType) { """ creates an instance of testType (if it isn't Object.class or null) or fallbackType """ if (tryMe != null) { tryMe.setAccessible(true); try { return tryMe.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } return createInstance(fallbackType); }
java
private <T> T newInstance(final Constructor<T> tryMe, final Class<T> fallbackType) { if (tryMe != null) { tryMe.setAccessible(true); try { return tryMe.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } return createInstance(fallbackType); }
[ "private", "<", "T", ">", "T", "newInstance", "(", "final", "Constructor", "<", "T", ">", "tryMe", ",", "final", "Class", "<", "T", ">", "fallbackType", ")", "{", "if", "(", "tryMe", "!=", "null", ")", "{", "tryMe", ".", "setAccessible", "(", "true", ")", ";", "try", "{", "return", "tryMe", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "return", "createInstance", "(", "fallbackType", ")", ";", "}" ]
creates an instance of testType (if it isn't Object.class or null) or fallbackType
[ "creates", "an", "instance", "of", "testType", "(", "if", "it", "isn", "t", "Object", ".", "class", "or", "null", ")", "or", "fallbackType" ]
train
https://github.com/MorphiaOrg/morphia/blob/667c30bdc7c6f1d9f2e2eb8774835d6137b52d12/morphia/src/main/java/dev/morphia/mapping/DefaultCreator.java#L192-L202
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/util/zookeeper/ClientNode.java
ClientNode.createNode
public String createNode(final String path, final boolean watch, final boolean ephimeral) { """ Create a zookeeper node @param path The path of znode to create @param watch Whether to watch this node or not @param ephimeral Create ephemeral or permanent node @return The created node path """ String createdNodePath = null; try { final Stat nodeStat = zooKeeper.exists(path, watch); if(nodeStat == null) { createdNodePath = zooKeeper.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, (ephimeral ? CreateMode.EPHEMERAL_SEQUENTIAL : CreateMode.PERSISTENT)); } else { createdNodePath = path; } } catch (KeeperException | InterruptedException e) { throw new IllegalStateException(e); } return createdNodePath; }
java
public String createNode(final String path, final boolean watch, final boolean ephimeral) { String createdNodePath = null; try { final Stat nodeStat = zooKeeper.exists(path, watch); if(nodeStat == null) { createdNodePath = zooKeeper.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, (ephimeral ? CreateMode.EPHEMERAL_SEQUENTIAL : CreateMode.PERSISTENT)); } else { createdNodePath = path; } } catch (KeeperException | InterruptedException e) { throw new IllegalStateException(e); } return createdNodePath; }
[ "public", "String", "createNode", "(", "final", "String", "path", ",", "final", "boolean", "watch", ",", "final", "boolean", "ephimeral", ")", "{", "String", "createdNodePath", "=", "null", ";", "try", "{", "final", "Stat", "nodeStat", "=", "zooKeeper", ".", "exists", "(", "path", ",", "watch", ")", ";", "if", "(", "nodeStat", "==", "null", ")", "{", "createdNodePath", "=", "zooKeeper", ".", "create", "(", "path", ",", "new", "byte", "[", "0", "]", ",", "Ids", ".", "OPEN_ACL_UNSAFE", ",", "(", "ephimeral", "?", "CreateMode", ".", "EPHEMERAL_SEQUENTIAL", ":", "CreateMode", ".", "PERSISTENT", ")", ")", ";", "}", "else", "{", "createdNodePath", "=", "path", ";", "}", "}", "catch", "(", "KeeperException", "|", "InterruptedException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "return", "createdNodePath", ";", "}" ]
Create a zookeeper node @param path The path of znode to create @param watch Whether to watch this node or not @param ephimeral Create ephemeral or permanent node @return The created node path
[ "Create", "a", "zookeeper", "node" ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/util/zookeeper/ClientNode.java#L141-L158