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
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.common/src/com/ibm/ws/jaxws/metadata/builder/HandlerChainInfoBuilder.java
HandlerChainInfoBuilder.resolveHandlerChainFileName
protected URL resolveHandlerChainFileName(String clzName, String fileName) { """ Resolve handler chain configuration file associated with the given class @param clzName @param fileName @return A URL object or null if no resource with this name is found """ URL handlerFile = null; InputStream in = null; String handlerChainFileName = fileName; URL baseUrl = classLoader.getResource(getClassResourceName(clzName)); try { //if the filename start with '/', then find and return the resource under the web application home directory directory. if (handlerChainFileName.charAt(0) == '/') { return classLoader.getResource(handlerChainFileName.substring(1)); } //otherwise, create a new url instance according to the baseurl and the fileName handlerFile = new URL(baseUrl, handlerChainFileName); in = handlerFile.openStream(); } catch (Exception e) { // log the error msg } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } return handlerFile; }
java
protected URL resolveHandlerChainFileName(String clzName, String fileName) { URL handlerFile = null; InputStream in = null; String handlerChainFileName = fileName; URL baseUrl = classLoader.getResource(getClassResourceName(clzName)); try { //if the filename start with '/', then find and return the resource under the web application home directory directory. if (handlerChainFileName.charAt(0) == '/') { return classLoader.getResource(handlerChainFileName.substring(1)); } //otherwise, create a new url instance according to the baseurl and the fileName handlerFile = new URL(baseUrl, handlerChainFileName); in = handlerFile.openStream(); } catch (Exception e) { // log the error msg } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } return handlerFile; }
[ "protected", "URL", "resolveHandlerChainFileName", "(", "String", "clzName", ",", "String", "fileName", ")", "{", "URL", "handlerFile", "=", "null", ";", "InputStream", "in", "=", "null", ";", "String", "handlerChainFileName", "=", "fileName", ";", "URL", "baseUrl", "=", "classLoader", ".", "getResource", "(", "getClassResourceName", "(", "clzName", ")", ")", ";", "try", "{", "//if the filename start with '/', then find and return the resource under the web application home directory directory.", "if", "(", "handlerChainFileName", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "return", "classLoader", ".", "getResource", "(", "handlerChainFileName", ".", "substring", "(", "1", ")", ")", ";", "}", "//otherwise, create a new url instance according to the baseurl and the fileName", "handlerFile", "=", "new", "URL", "(", "baseUrl", ",", "handlerChainFileName", ")", ";", "in", "=", "handlerFile", ".", "openStream", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// log the error msg", "}", "finally", "{", "if", "(", "in", "!=", "null", ")", "{", "try", "{", "in", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "}", "return", "handlerFile", ";", "}" ]
Resolve handler chain configuration file associated with the given class @param clzName @param fileName @return A URL object or null if no resource with this name is found
[ "Resolve", "handler", "chain", "configuration", "file", "associated", "with", "the", "given", "class" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxws.common/src/com/ibm/ws/jaxws/metadata/builder/HandlerChainInfoBuilder.java#L356-L383
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java
GeometryUtilities.getAngleInTriangle
public static double getAngleInTriangle( double a, double b, double c ) { """ Uses the cosine rule to find an angle in radiants of a triangle defined by the length of its sides. <p>The calculated angle is the one between the two adjacent sides a and b.</p> @param a adjacent side 1 length. @param b adjacent side 2 length. @param c opposite side length. @return the angle in radiants. """ double angle = Math.acos((a * a + b * b - c * c) / (2.0 * a * b)); return angle; }
java
public static double getAngleInTriangle( double a, double b, double c ) { double angle = Math.acos((a * a + b * b - c * c) / (2.0 * a * b)); return angle; }
[ "public", "static", "double", "getAngleInTriangle", "(", "double", "a", ",", "double", "b", ",", "double", "c", ")", "{", "double", "angle", "=", "Math", ".", "acos", "(", "(", "a", "*", "a", "+", "b", "*", "b", "-", "c", "*", "c", ")", "/", "(", "2.0", "*", "a", "*", "b", ")", ")", ";", "return", "angle", ";", "}" ]
Uses the cosine rule to find an angle in radiants of a triangle defined by the length of its sides. <p>The calculated angle is the one between the two adjacent sides a and b.</p> @param a adjacent side 1 length. @param b adjacent side 2 length. @param c opposite side length. @return the angle in radiants.
[ "Uses", "the", "cosine", "rule", "to", "find", "an", "angle", "in", "radiants", "of", "a", "triangle", "defined", "by", "the", "length", "of", "its", "sides", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java#L837-L840
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsVfsSitemapService.java
CmsVfsSitemapService.readGalleryFolderEntry
private CmsGalleryFolderEntry readGalleryFolderEntry(CmsResource folder, String typeName) throws CmsException { """ Reads the gallery folder properties.<p> @param folder the folder resource @param typeName the resource type name @return the folder entry data @throws CmsException if the folder properties can not be read """ CmsObject cms = getCmsObject(); CmsGalleryFolderEntry folderEntry = new CmsGalleryFolderEntry(); folderEntry.setResourceType(typeName); folderEntry.setSitePath(cms.getSitePath(folder)); folderEntry.setStructureId(folder.getStructureId()); folderEntry.setOwnProperties(getClientProperties(cms, folder, false)); folderEntry.setIconClasses(CmsIconUtil.getIconClasses(typeName, null, false)); return folderEntry; }
java
private CmsGalleryFolderEntry readGalleryFolderEntry(CmsResource folder, String typeName) throws CmsException { CmsObject cms = getCmsObject(); CmsGalleryFolderEntry folderEntry = new CmsGalleryFolderEntry(); folderEntry.setResourceType(typeName); folderEntry.setSitePath(cms.getSitePath(folder)); folderEntry.setStructureId(folder.getStructureId()); folderEntry.setOwnProperties(getClientProperties(cms, folder, false)); folderEntry.setIconClasses(CmsIconUtil.getIconClasses(typeName, null, false)); return folderEntry; }
[ "private", "CmsGalleryFolderEntry", "readGalleryFolderEntry", "(", "CmsResource", "folder", ",", "String", "typeName", ")", "throws", "CmsException", "{", "CmsObject", "cms", "=", "getCmsObject", "(", ")", ";", "CmsGalleryFolderEntry", "folderEntry", "=", "new", "CmsGalleryFolderEntry", "(", ")", ";", "folderEntry", ".", "setResourceType", "(", "typeName", ")", ";", "folderEntry", ".", "setSitePath", "(", "cms", ".", "getSitePath", "(", "folder", ")", ")", ";", "folderEntry", ".", "setStructureId", "(", "folder", ".", "getStructureId", "(", ")", ")", ";", "folderEntry", ".", "setOwnProperties", "(", "getClientProperties", "(", "cms", ",", "folder", ",", "false", ")", ")", ";", "folderEntry", ".", "setIconClasses", "(", "CmsIconUtil", ".", "getIconClasses", "(", "typeName", ",", "null", ",", "false", ")", ")", ";", "return", "folderEntry", ";", "}" ]
Reads the gallery folder properties.<p> @param folder the folder resource @param typeName the resource type name @return the folder entry data @throws CmsException if the folder properties can not be read
[ "Reads", "the", "gallery", "folder", "properties", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L2943-L2953
sonyxperiadev/gerrit-events
src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritConnection.java
GerritConnection.getSubSequence
@IgnoreJRERequirement private CharSequence getSubSequence(CharBuffer cb, int start, int end) { """ Get sub sequence of buffer. This method avoids error in java-api-check. animal-sniffer is confused by the signature of CharBuffer.subSequence() due to declaration of this method has been changed since Java7. (abstract -> non-abstract) @param cb a buffer @param start start of sub sequence @param end end of sub sequence @return sub sequence. """ return cb.subSequence(start, end); }
java
@IgnoreJRERequirement private CharSequence getSubSequence(CharBuffer cb, int start, int end) { return cb.subSequence(start, end); }
[ "@", "IgnoreJRERequirement", "private", "CharSequence", "getSubSequence", "(", "CharBuffer", "cb", ",", "int", "start", ",", "int", "end", ")", "{", "return", "cb", ".", "subSequence", "(", "start", ",", "end", ")", ";", "}" ]
Get sub sequence of buffer. This method avoids error in java-api-check. animal-sniffer is confused by the signature of CharBuffer.subSequence() due to declaration of this method has been changed since Java7. (abstract -> non-abstract) @param cb a buffer @param start start of sub sequence @param end end of sub sequence @return sub sequence.
[ "Get", "sub", "sequence", "of", "buffer", "." ]
train
https://github.com/sonyxperiadev/gerrit-events/blob/9a443d13dded85cc4709136ac33989f2bbb34fe2/src/main/java/com/sonymobile/tools/gerrit/gerritevents/GerritConnection.java#L393-L396
baratine/baratine
framework/src/main/java/com/caucho/v5/javac/LineMap.java
LineMap.convertError
private void convertError(CharBuffer buf, int line) { """ Maps a destination line to an error location. @param buf CharBuffer to write the error location @param line generated source line to convert. """ String srcFilename = null; int destLine = 0; int srcLine = 0; int srcTailLine = Integer.MAX_VALUE; for (int i = 0; i < _lines.size(); i++) { Line map = (Line) _lines.get(i); if (map._dstLine <= line && line <= map.getLastDestinationLine()) { srcFilename = map._srcFilename; destLine = map._dstLine; srcLine = map.getSourceLine(line); break; } } if (srcFilename != null) { } else if (_lines.size() > 0) srcFilename = ((Line) _lines.get(0))._srcFilename; else srcFilename = ""; buf.append(srcFilename); if (line >= 0) { buf.append(":"); buf.append(srcLine + (line - destLine)); } }
java
private void convertError(CharBuffer buf, int line) { String srcFilename = null; int destLine = 0; int srcLine = 0; int srcTailLine = Integer.MAX_VALUE; for (int i = 0; i < _lines.size(); i++) { Line map = (Line) _lines.get(i); if (map._dstLine <= line && line <= map.getLastDestinationLine()) { srcFilename = map._srcFilename; destLine = map._dstLine; srcLine = map.getSourceLine(line); break; } } if (srcFilename != null) { } else if (_lines.size() > 0) srcFilename = ((Line) _lines.get(0))._srcFilename; else srcFilename = ""; buf.append(srcFilename); if (line >= 0) { buf.append(":"); buf.append(srcLine + (line - destLine)); } }
[ "private", "void", "convertError", "(", "CharBuffer", "buf", ",", "int", "line", ")", "{", "String", "srcFilename", "=", "null", ";", "int", "destLine", "=", "0", ";", "int", "srcLine", "=", "0", ";", "int", "srcTailLine", "=", "Integer", ".", "MAX_VALUE", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "_lines", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Line", "map", "=", "(", "Line", ")", "_lines", ".", "get", "(", "i", ")", ";", "if", "(", "map", ".", "_dstLine", "<=", "line", "&&", "line", "<=", "map", ".", "getLastDestinationLine", "(", ")", ")", "{", "srcFilename", "=", "map", ".", "_srcFilename", ";", "destLine", "=", "map", ".", "_dstLine", ";", "srcLine", "=", "map", ".", "getSourceLine", "(", "line", ")", ";", "break", ";", "}", "}", "if", "(", "srcFilename", "!=", "null", ")", "{", "}", "else", "if", "(", "_lines", ".", "size", "(", ")", ">", "0", ")", "srcFilename", "=", "(", "(", "Line", ")", "_lines", ".", "get", "(", "0", ")", ")", ".", "_srcFilename", ";", "else", "srcFilename", "=", "\"\"", ";", "buf", ".", "append", "(", "srcFilename", ")", ";", "if", "(", "line", ">=", "0", ")", "{", "buf", ".", "append", "(", "\":\"", ")", ";", "buf", ".", "append", "(", "srcLine", "+", "(", "line", "-", "destLine", ")", ")", ";", "}", "}" ]
Maps a destination line to an error location. @param buf CharBuffer to write the error location @param line generated source line to convert.
[ "Maps", "a", "destination", "line", "to", "an", "error", "location", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/javac/LineMap.java#L384-L414
esigate/esigate
esigate-core/src/main/java/org/esigate/http/OutgoingRequestContext.java
OutgoingRequestContext.removeAttribute
public Object removeAttribute(String id, boolean restore) { """ remove attribute and restore previous attribute value @param id attribute name @param restore restore previous attribute value @return attribute value """ Object value = removeAttribute(id); if (restore) { String historyAttribute = id + "history"; Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute); if (history != null && !history.isEmpty()) { Object previous = history.remove(); setAttribute(id, previous); } } return value; }
java
public Object removeAttribute(String id, boolean restore) { Object value = removeAttribute(id); if (restore) { String historyAttribute = id + "history"; Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute); if (history != null && !history.isEmpty()) { Object previous = history.remove(); setAttribute(id, previous); } } return value; }
[ "public", "Object", "removeAttribute", "(", "String", "id", ",", "boolean", "restore", ")", "{", "Object", "value", "=", "removeAttribute", "(", "id", ")", ";", "if", "(", "restore", ")", "{", "String", "historyAttribute", "=", "id", "+", "\"history\"", ";", "Queue", "<", "Object", ">", "history", "=", "(", "Queue", "<", "Object", ">", ")", "getAttribute", "(", "historyAttribute", ")", ";", "if", "(", "history", "!=", "null", "&&", "!", "history", ".", "isEmpty", "(", ")", ")", "{", "Object", "previous", "=", "history", ".", "remove", "(", ")", ";", "setAttribute", "(", "id", ",", "previous", ")", ";", "}", "}", "return", "value", ";", "}" ]
remove attribute and restore previous attribute value @param id attribute name @param restore restore previous attribute value @return attribute value
[ "remove", "attribute", "and", "restore", "previous", "attribute", "value" ]
train
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/OutgoingRequestContext.java#L116-L127
ops4j/org.ops4j.base
ops4j-base-lang/src/main/java/org/ops4j/lang/PreConditionException.java
PreConditionException.validateNotNull
public static void validateNotNull( Object object, String identifier ) throws PreConditionException { """ Validates that the object is not null. @param object The object to be validated. @param identifier The name of the object. @throws PreConditionException if the object is null. """ if( object == null ) { throw new PreConditionException( identifier + " was NULL." ); } }
java
public static void validateNotNull( Object object, String identifier ) throws PreConditionException { if( object == null ) { throw new PreConditionException( identifier + " was NULL." ); } }
[ "public", "static", "void", "validateNotNull", "(", "Object", "object", ",", "String", "identifier", ")", "throws", "PreConditionException", "{", "if", "(", "object", "==", "null", ")", "{", "throw", "new", "PreConditionException", "(", "identifier", "+", "\" was NULL.\"", ")", ";", "}", "}" ]
Validates that the object is not null. @param object The object to be validated. @param identifier The name of the object. @throws PreConditionException if the object is null.
[ "Validates", "that", "the", "object", "is", "not", "null", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-lang/src/main/java/org/ops4j/lang/PreConditionException.java#L47-L54
nguillaumin/slick2d-maven
slick2d-core/src/main/java/org/newdawn/slick/font/effects/EffectUtil.java
EffectUtil.floatValue
static public Value floatValue (String name, final float currentValue, final float min, final float max, final String description) { """ Prompts the user for float value @param name The name of the dialog to show @param currentValue The current value to be displayed @param description The help text to provide @param min The minimum value to allow @param max The maximum value to allow @return The value selected by the user """ return new DefaultValue(name, String.valueOf(currentValue)) { public void showDialog () { JSpinner spinner = new JSpinner(new SpinnerNumberModel(currentValue, min, max, 0.1f)); if (showValueDialog(spinner, description)) value = String.valueOf(((Double)spinner.getValue()).floatValue()); } public Object getObject () { return Float.valueOf(value); } }; }
java
static public Value floatValue (String name, final float currentValue, final float min, final float max, final String description) { return new DefaultValue(name, String.valueOf(currentValue)) { public void showDialog () { JSpinner spinner = new JSpinner(new SpinnerNumberModel(currentValue, min, max, 0.1f)); if (showValueDialog(spinner, description)) value = String.valueOf(((Double)spinner.getValue()).floatValue()); } public Object getObject () { return Float.valueOf(value); } }; }
[ "static", "public", "Value", "floatValue", "(", "String", "name", ",", "final", "float", "currentValue", ",", "final", "float", "min", ",", "final", "float", "max", ",", "final", "String", "description", ")", "{", "return", "new", "DefaultValue", "(", "name", ",", "String", ".", "valueOf", "(", "currentValue", ")", ")", "{", "public", "void", "showDialog", "(", ")", "{", "JSpinner", "spinner", "=", "new", "JSpinner", "(", "new", "SpinnerNumberModel", "(", "currentValue", ",", "min", ",", "max", ",", "0.1f", ")", ")", ";", "if", "(", "showValueDialog", "(", "spinner", ",", "description", ")", ")", "value", "=", "String", ".", "valueOf", "(", "(", "(", "Double", ")", "spinner", ".", "getValue", "(", ")", ")", ".", "floatValue", "(", ")", ")", ";", "}", "public", "Object", "getObject", "(", ")", "{", "return", "Float", ".", "valueOf", "(", "value", ")", ";", "}", "}", ";", "}" ]
Prompts the user for float value @param name The name of the dialog to show @param currentValue The current value to be displayed @param description The help text to provide @param min The minimum value to allow @param max The maximum value to allow @return The value selected by the user
[ "Prompts", "the", "user", "for", "float", "value" ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/font/effects/EffectUtil.java#L108-L120
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTreeRenderer.java
WTreeRenderer.handlePaintItems
protected void handlePaintItems(final WTree tree, final XmlStringBuilder xml) { """ Paint the tree items. @param tree the WTree to render @param xml the XML string builder """ TreeItemModel model = tree.getTreeModel(); int rows = model.getRowCount(); if (rows > 0) { Set<String> selectedRows = new HashSet(tree.getSelectedRows()); Set<String> expandedRows = new HashSet(tree.getExpandedRows()); WTree.ExpandMode mode = tree.getExpandMode(); for (int i = 0; i < rows; i++) { List<Integer> rowIndex = new ArrayList<>(); rowIndex.add(i); paintItem(tree, mode, model, rowIndex, xml, selectedRows, expandedRows); } } }
java
protected void handlePaintItems(final WTree tree, final XmlStringBuilder xml) { TreeItemModel model = tree.getTreeModel(); int rows = model.getRowCount(); if (rows > 0) { Set<String> selectedRows = new HashSet(tree.getSelectedRows()); Set<String> expandedRows = new HashSet(tree.getExpandedRows()); WTree.ExpandMode mode = tree.getExpandMode(); for (int i = 0; i < rows; i++) { List<Integer> rowIndex = new ArrayList<>(); rowIndex.add(i); paintItem(tree, mode, model, rowIndex, xml, selectedRows, expandedRows); } } }
[ "protected", "void", "handlePaintItems", "(", "final", "WTree", "tree", ",", "final", "XmlStringBuilder", "xml", ")", "{", "TreeItemModel", "model", "=", "tree", ".", "getTreeModel", "(", ")", ";", "int", "rows", "=", "model", ".", "getRowCount", "(", ")", ";", "if", "(", "rows", ">", "0", ")", "{", "Set", "<", "String", ">", "selectedRows", "=", "new", "HashSet", "(", "tree", ".", "getSelectedRows", "(", ")", ")", ";", "Set", "<", "String", ">", "expandedRows", "=", "new", "HashSet", "(", "tree", ".", "getExpandedRows", "(", ")", ")", ";", "WTree", ".", "ExpandMode", "mode", "=", "tree", ".", "getExpandMode", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "rows", ";", "i", "++", ")", "{", "List", "<", "Integer", ">", "rowIndex", "=", "new", "ArrayList", "<>", "(", ")", ";", "rowIndex", ".", "add", "(", "i", ")", ";", "paintItem", "(", "tree", ",", "mode", ",", "model", ",", "rowIndex", ",", "xml", ",", "selectedRows", ",", "expandedRows", ")", ";", "}", "}", "}" ]
Paint the tree items. @param tree the WTree to render @param xml the XML string builder
[ "Paint", "the", "tree", "items", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WTreeRenderer.java#L128-L143
Erudika/para
para-server/src/main/java/com/erudika/para/security/SecurityUtils.java
SecurityUtils.isValidJWToken
public static boolean isValidJWToken(String secret, SignedJWT jwt) { """ Validates a JWT token. @param secret secret used for generating the token @param jwt token to validate @return true if token is valid """ try { if (secret != null && jwt != null) { JWSVerifier verifier = new MACVerifier(secret); if (jwt.verify(verifier)) { Date referenceTime = new Date(); JWTClaimsSet claims = jwt.getJWTClaimsSet(); Date expirationTime = claims.getExpirationTime(); Date notBeforeTime = claims.getNotBeforeTime(); boolean expired = expirationTime == null || expirationTime.before(referenceTime); boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime); return !(expired || notYetValid); } } } catch (JOSEException e) { logger.warn(null, e); } catch (ParseException ex) { logger.warn(null, ex); } return false; }
java
public static boolean isValidJWToken(String secret, SignedJWT jwt) { try { if (secret != null && jwt != null) { JWSVerifier verifier = new MACVerifier(secret); if (jwt.verify(verifier)) { Date referenceTime = new Date(); JWTClaimsSet claims = jwt.getJWTClaimsSet(); Date expirationTime = claims.getExpirationTime(); Date notBeforeTime = claims.getNotBeforeTime(); boolean expired = expirationTime == null || expirationTime.before(referenceTime); boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime); return !(expired || notYetValid); } } } catch (JOSEException e) { logger.warn(null, e); } catch (ParseException ex) { logger.warn(null, ex); } return false; }
[ "public", "static", "boolean", "isValidJWToken", "(", "String", "secret", ",", "SignedJWT", "jwt", ")", "{", "try", "{", "if", "(", "secret", "!=", "null", "&&", "jwt", "!=", "null", ")", "{", "JWSVerifier", "verifier", "=", "new", "MACVerifier", "(", "secret", ")", ";", "if", "(", "jwt", ".", "verify", "(", "verifier", ")", ")", "{", "Date", "referenceTime", "=", "new", "Date", "(", ")", ";", "JWTClaimsSet", "claims", "=", "jwt", ".", "getJWTClaimsSet", "(", ")", ";", "Date", "expirationTime", "=", "claims", ".", "getExpirationTime", "(", ")", ";", "Date", "notBeforeTime", "=", "claims", ".", "getNotBeforeTime", "(", ")", ";", "boolean", "expired", "=", "expirationTime", "==", "null", "||", "expirationTime", ".", "before", "(", "referenceTime", ")", ";", "boolean", "notYetValid", "=", "notBeforeTime", "==", "null", "||", "notBeforeTime", ".", "after", "(", "referenceTime", ")", ";", "return", "!", "(", "expired", "||", "notYetValid", ")", ";", "}", "}", "}", "catch", "(", "JOSEException", "e", ")", "{", "logger", ".", "warn", "(", "null", ",", "e", ")", ";", "}", "catch", "(", "ParseException", "ex", ")", "{", "logger", ".", "warn", "(", "null", ",", "ex", ")", ";", "}", "return", "false", ";", "}" ]
Validates a JWT token. @param secret secret used for generating the token @param jwt token to validate @return true if token is valid
[ "Validates", "a", "JWT", "token", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/security/SecurityUtils.java#L230-L252
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrBinaryResourceRequestHandler.java
JawrBinaryResourceRequestHandler.getContentType
@Override protected String getContentType(String filePath, HttpServletRequest request) { """ Returns the content type for the image @param filePath the image file path @param request the request @return the content type of the image """ String requestUri = request.getRequestURI(); // Retrieve the extension String extension = getExtension(filePath); if (extension == null) { LOGGER.info("No extension found for the request URI : " + requestUri); return null; } String binContentType = (String) binaryMimeTypeMap.get(extension); if (binContentType == null) { LOGGER.info( "No binary extension match the extension '" + extension + "' for the request URI : " + requestUri); return null; } return binContentType; }
java
@Override protected String getContentType(String filePath, HttpServletRequest request) { String requestUri = request.getRequestURI(); // Retrieve the extension String extension = getExtension(filePath); if (extension == null) { LOGGER.info("No extension found for the request URI : " + requestUri); return null; } String binContentType = (String) binaryMimeTypeMap.get(extension); if (binContentType == null) { LOGGER.info( "No binary extension match the extension '" + extension + "' for the request URI : " + requestUri); return null; } return binContentType; }
[ "@", "Override", "protected", "String", "getContentType", "(", "String", "filePath", ",", "HttpServletRequest", "request", ")", "{", "String", "requestUri", "=", "request", ".", "getRequestURI", "(", ")", ";", "// Retrieve the extension", "String", "extension", "=", "getExtension", "(", "filePath", ")", ";", "if", "(", "extension", "==", "null", ")", "{", "LOGGER", ".", "info", "(", "\"No extension found for the request URI : \"", "+", "requestUri", ")", ";", "return", "null", ";", "}", "String", "binContentType", "=", "(", "String", ")", "binaryMimeTypeMap", ".", "get", "(", "extension", ")", ";", "if", "(", "binContentType", "==", "null", ")", "{", "LOGGER", ".", "info", "(", "\"No binary extension match the extension '\"", "+", "extension", "+", "\"' for the request URI : \"", "+", "requestUri", ")", ";", "return", "null", ";", "}", "return", "binContentType", ";", "}" ]
Returns the content type for the image @param filePath the image file path @param request the request @return the content type of the image
[ "Returns", "the", "content", "type", "for", "the", "image" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/servlet/JawrBinaryResourceRequestHandler.java#L532-L552
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java
SerializedFormBuilder.serialInclude
public static boolean serialInclude(Utils utils, Element element) { """ Returns true if the given Element should be included in the serialized form. @param utils the utils object @param element the Element object to check for serializability @return true if the element should be included in the serial form """ if (element == null) { return false; } return utils.isClass(element) ? serialClassInclude(utils, (TypeElement)element) : serialDocInclude(utils, element); }
java
public static boolean serialInclude(Utils utils, Element element) { if (element == null) { return false; } return utils.isClass(element) ? serialClassInclude(utils, (TypeElement)element) : serialDocInclude(utils, element); }
[ "public", "static", "boolean", "serialInclude", "(", "Utils", "utils", ",", "Element", "element", ")", "{", "if", "(", "element", "==", "null", ")", "{", "return", "false", ";", "}", "return", "utils", ".", "isClass", "(", "element", ")", "?", "serialClassInclude", "(", "utils", ",", "(", "TypeElement", ")", "element", ")", ":", "serialDocInclude", "(", "utils", ",", "element", ")", ";", "}" ]
Returns true if the given Element should be included in the serialized form. @param utils the utils object @param element the Element object to check for serializability @return true if the element should be included in the serial form
[ "Returns", "true", "if", "the", "given", "Element", "should", "be", "included", "in", "the", "serialized", "form", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/builders/SerializedFormBuilder.java#L555-L562
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/gen/CodeBuilderUtil.java
CodeBuilderUtil.defineCopyBridges
public static void defineCopyBridges(ClassFile cf, Class leaf) { """ Add copy bridge methods for all classes/interfaces between the leaf (genericised class) and the root (genericised baseclass). @param cf file to which to add the copy bridge @param leaf leaf class """ for (Class c : gatherAllBridgeTypes(new HashSet<Class>(), leaf)) { if (c != Object.class) { defineCopyBridge(cf, leaf, c); } } }
java
public static void defineCopyBridges(ClassFile cf, Class leaf) { for (Class c : gatherAllBridgeTypes(new HashSet<Class>(), leaf)) { if (c != Object.class) { defineCopyBridge(cf, leaf, c); } } }
[ "public", "static", "void", "defineCopyBridges", "(", "ClassFile", "cf", ",", "Class", "leaf", ")", "{", "for", "(", "Class", "c", ":", "gatherAllBridgeTypes", "(", "new", "HashSet", "<", "Class", ">", "(", ")", ",", "leaf", ")", ")", "{", "if", "(", "c", "!=", "Object", ".", "class", ")", "{", "defineCopyBridge", "(", "cf", ",", "leaf", ",", "c", ")", ";", "}", "}", "}" ]
Add copy bridge methods for all classes/interfaces between the leaf (genericised class) and the root (genericised baseclass). @param cf file to which to add the copy bridge @param leaf leaf class
[ "Add", "copy", "bridge", "methods", "for", "all", "classes", "/", "interfaces", "between", "the", "leaf", "(", "genericised", "class", ")", "and", "the", "root", "(", "genericised", "baseclass", ")", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/gen/CodeBuilderUtil.java#L169-L175
googleapis/google-http-java-client
google-http-client/src/main/java/com/google/api/client/util/escape/PercentEscaper.java
PercentEscaper.nextEscapeIndex
@Override protected int nextEscapeIndex(CharSequence csq, int index, int end) { """ /* Overridden for performance. For unescaped strings this improved the performance of the uri escaper from ~760ns to ~400ns as measured by {@link CharEscapersBenchmark}. """ for (; index < end; index++) { char c = csq.charAt(index); if (c >= safeOctets.length || !safeOctets[c]) { break; } } return index; }
java
@Override protected int nextEscapeIndex(CharSequence csq, int index, int end) { for (; index < end; index++) { char c = csq.charAt(index); if (c >= safeOctets.length || !safeOctets[c]) { break; } } return index; }
[ "@", "Override", "protected", "int", "nextEscapeIndex", "(", "CharSequence", "csq", ",", "int", "index", ",", "int", "end", ")", "{", "for", "(", ";", "index", "<", "end", ";", "index", "++", ")", "{", "char", "c", "=", "csq", ".", "charAt", "(", "index", ")", ";", "if", "(", "c", ">=", "safeOctets", ".", "length", "||", "!", "safeOctets", "[", "c", "]", ")", "{", "break", ";", "}", "}", "return", "index", ";", "}" ]
/* Overridden for performance. For unescaped strings this improved the performance of the uri escaper from ~760ns to ~400ns as measured by {@link CharEscapersBenchmark}.
[ "/", "*", "Overridden", "for", "performance", ".", "For", "unescaped", "strings", "this", "improved", "the", "performance", "of", "the", "uri", "escaper", "from", "~760ns", "to", "~400ns", "as", "measured", "by", "{" ]
train
https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/util/escape/PercentEscaper.java#L163-L172
google/closure-compiler
src/com/google/javascript/rhino/Node.java
Node.matchesQualifiedName
private boolean matchesQualifiedName(String qname, int endIndex) { """ Returns whether a node matches a simple or a qualified name, such as <code>x</code> or <code>a.b.c</code> or <code>this.a</code>. """ int start = qname.lastIndexOf('.', endIndex - 1) + 1; switch (this.getToken()) { case NAME: String name = getString(); return start == 0 && !name.isEmpty() && name.length() == endIndex && qname.startsWith(name); case THIS: return start == 0 && 4 == endIndex && qname.startsWith("this"); case SUPER: return start == 0 && 5 == endIndex && qname.startsWith("super"); case GETPROP: String prop = getLastChild().getString(); return start > 1 && prop.length() == endIndex - start && prop.regionMatches(0, qname, start, endIndex - start) && getFirstChild().matchesQualifiedName(qname, start - 1); case MEMBER_FUNCTION_DEF: // These are explicitly *not* qualified name components. default: return false; } }
java
private boolean matchesQualifiedName(String qname, int endIndex) { int start = qname.lastIndexOf('.', endIndex - 1) + 1; switch (this.getToken()) { case NAME: String name = getString(); return start == 0 && !name.isEmpty() && name.length() == endIndex && qname.startsWith(name); case THIS: return start == 0 && 4 == endIndex && qname.startsWith("this"); case SUPER: return start == 0 && 5 == endIndex && qname.startsWith("super"); case GETPROP: String prop = getLastChild().getString(); return start > 1 && prop.length() == endIndex - start && prop.regionMatches(0, qname, start, endIndex - start) && getFirstChild().matchesQualifiedName(qname, start - 1); case MEMBER_FUNCTION_DEF: // These are explicitly *not* qualified name components. default: return false; } }
[ "private", "boolean", "matchesQualifiedName", "(", "String", "qname", ",", "int", "endIndex", ")", "{", "int", "start", "=", "qname", ".", "lastIndexOf", "(", "'", "'", ",", "endIndex", "-", "1", ")", "+", "1", ";", "switch", "(", "this", ".", "getToken", "(", ")", ")", "{", "case", "NAME", ":", "String", "name", "=", "getString", "(", ")", ";", "return", "start", "==", "0", "&&", "!", "name", ".", "isEmpty", "(", ")", "&&", "name", ".", "length", "(", ")", "==", "endIndex", "&&", "qname", ".", "startsWith", "(", "name", ")", ";", "case", "THIS", ":", "return", "start", "==", "0", "&&", "4", "==", "endIndex", "&&", "qname", ".", "startsWith", "(", "\"this\"", ")", ";", "case", "SUPER", ":", "return", "start", "==", "0", "&&", "5", "==", "endIndex", "&&", "qname", ".", "startsWith", "(", "\"super\"", ")", ";", "case", "GETPROP", ":", "String", "prop", "=", "getLastChild", "(", ")", ".", "getString", "(", ")", ";", "return", "start", ">", "1", "&&", "prop", ".", "length", "(", ")", "==", "endIndex", "-", "start", "&&", "prop", ".", "regionMatches", "(", "0", ",", "qname", ",", "start", ",", "endIndex", "-", "start", ")", "&&", "getFirstChild", "(", ")", ".", "matchesQualifiedName", "(", "qname", ",", "start", "-", "1", ")", ";", "case", "MEMBER_FUNCTION_DEF", ":", "// These are explicitly *not* qualified name components.", "default", ":", "return", "false", ";", "}", "}" ]
Returns whether a node matches a simple or a qualified name, such as <code>x</code> or <code>a.b.c</code> or <code>this.a</code>.
[ "Returns", "whether", "a", "node", "matches", "a", "simple", "or", "a", "qualified", "name", "such", "as", "<code", ">", "x<", "/", "code", ">", "or", "<code", ">", "a", ".", "b", ".", "c<", "/", "code", ">", "or", "<code", ">", "this", ".", "a<", "/", "code", ">", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/Node.java#L2145-L2168
xdcrafts/flower
flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ListApi.java
ListApi.getString
public static Optional<String> getString(final List list, final Integer... path) { """ Get string value by path. @param list subject @param path nodes to walk in map @return value """ return get(list, String.class, path); }
java
public static Optional<String> getString(final List list, final Integer... path) { return get(list, String.class, path); }
[ "public", "static", "Optional", "<", "String", ">", "getString", "(", "final", "List", "list", ",", "final", "Integer", "...", "path", ")", "{", "return", "get", "(", "list", ",", "String", ".", "class", ",", "path", ")", ";", "}" ]
Get string value by path. @param list subject @param path nodes to walk in map @return value
[ "Get", "string", "value", "by", "path", "." ]
train
https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ListApi.java#L150-L152
OpenBEL/openbel-framework
org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/beldata/equivalence/EquivalenceHeaderParser.java
EquivalenceHeaderParser.parseEquivalence
public EquivalenceHeader parseEquivalence(String resourceLocation, File equivalenceFile) throws IOException, BELDataMissingPropertyException, BELDataConversionException { """ Parses the equivalence {@link File} into a {@link EquivalenceHeader} object. @param equivalenceFile {@link File}, the equivalence file, which cannot be null, must exist, and must be readable @return {@link NamespaceHeader}, the parsed equivalence header @throws IOException Thrown if an IO error occurred reading the <tt>equivalenceFile</tt> @throws BELDataHeaderParseException Thrown if a parsing error occurred when processing the <tt>equivalenceFile</tt> @throws BELDataConversionException @throws BELDataMissingPropertyException @throws InvalidArgument Thrown if the <tt>equivalenceFile</tt> is null, does not exist, or cannot be read """ if (equivalenceFile == null) { throw new InvalidArgument("namespaceFile", equivalenceFile); } if (!equivalenceFile.exists()) { throw new InvalidArgument("namespaceFile does not exist"); } if (!equivalenceFile.canRead()) { throw new InvalidArgument("namespaceFile cannot be read"); } Map<String, Properties> blockProperties = parse(equivalenceFile); EquivalenceBlock equivalenceBlock = EquivalenceBlock.create(resourceLocation, blockProperties.get(EquivalenceBlock.BLOCK_NAME)); NamespaceReferenceBlock namespaceReferenceBlock = NamespaceReferenceBlock .create(resourceLocation, blockProperties .get(NamespaceReferenceBlock.BLOCK_NAME)); AuthorBlock authorblock = AuthorBlock.create(resourceLocation, blockProperties.get(AuthorBlock.BLOCK_NAME)); CitationBlock citationBlock = CitationBlock.create(resourceLocation, blockProperties.get(CitationBlock.BLOCK_NAME)); ProcessingBlock processingBlock = ProcessingBlock.create( resourceLocation, blockProperties.get(ProcessingBlock.BLOCK_NAME)); return new EquivalenceHeader(equivalenceBlock, namespaceReferenceBlock, authorblock, citationBlock, processingBlock); }
java
public EquivalenceHeader parseEquivalence(String resourceLocation, File equivalenceFile) throws IOException, BELDataMissingPropertyException, BELDataConversionException { if (equivalenceFile == null) { throw new InvalidArgument("namespaceFile", equivalenceFile); } if (!equivalenceFile.exists()) { throw new InvalidArgument("namespaceFile does not exist"); } if (!equivalenceFile.canRead()) { throw new InvalidArgument("namespaceFile cannot be read"); } Map<String, Properties> blockProperties = parse(equivalenceFile); EquivalenceBlock equivalenceBlock = EquivalenceBlock.create(resourceLocation, blockProperties.get(EquivalenceBlock.BLOCK_NAME)); NamespaceReferenceBlock namespaceReferenceBlock = NamespaceReferenceBlock .create(resourceLocation, blockProperties .get(NamespaceReferenceBlock.BLOCK_NAME)); AuthorBlock authorblock = AuthorBlock.create(resourceLocation, blockProperties.get(AuthorBlock.BLOCK_NAME)); CitationBlock citationBlock = CitationBlock.create(resourceLocation, blockProperties.get(CitationBlock.BLOCK_NAME)); ProcessingBlock processingBlock = ProcessingBlock.create( resourceLocation, blockProperties.get(ProcessingBlock.BLOCK_NAME)); return new EquivalenceHeader(equivalenceBlock, namespaceReferenceBlock, authorblock, citationBlock, processingBlock); }
[ "public", "EquivalenceHeader", "parseEquivalence", "(", "String", "resourceLocation", ",", "File", "equivalenceFile", ")", "throws", "IOException", ",", "BELDataMissingPropertyException", ",", "BELDataConversionException", "{", "if", "(", "equivalenceFile", "==", "null", ")", "{", "throw", "new", "InvalidArgument", "(", "\"namespaceFile\"", ",", "equivalenceFile", ")", ";", "}", "if", "(", "!", "equivalenceFile", ".", "exists", "(", ")", ")", "{", "throw", "new", "InvalidArgument", "(", "\"namespaceFile does not exist\"", ")", ";", "}", "if", "(", "!", "equivalenceFile", ".", "canRead", "(", ")", ")", "{", "throw", "new", "InvalidArgument", "(", "\"namespaceFile cannot be read\"", ")", ";", "}", "Map", "<", "String", ",", "Properties", ">", "blockProperties", "=", "parse", "(", "equivalenceFile", ")", ";", "EquivalenceBlock", "equivalenceBlock", "=", "EquivalenceBlock", ".", "create", "(", "resourceLocation", ",", "blockProperties", ".", "get", "(", "EquivalenceBlock", ".", "BLOCK_NAME", ")", ")", ";", "NamespaceReferenceBlock", "namespaceReferenceBlock", "=", "NamespaceReferenceBlock", ".", "create", "(", "resourceLocation", ",", "blockProperties", ".", "get", "(", "NamespaceReferenceBlock", ".", "BLOCK_NAME", ")", ")", ";", "AuthorBlock", "authorblock", "=", "AuthorBlock", ".", "create", "(", "resourceLocation", ",", "blockProperties", ".", "get", "(", "AuthorBlock", ".", "BLOCK_NAME", ")", ")", ";", "CitationBlock", "citationBlock", "=", "CitationBlock", ".", "create", "(", "resourceLocation", ",", "blockProperties", ".", "get", "(", "CitationBlock", ".", "BLOCK_NAME", ")", ")", ";", "ProcessingBlock", "processingBlock", "=", "ProcessingBlock", ".", "create", "(", "resourceLocation", ",", "blockProperties", ".", "get", "(", "ProcessingBlock", ".", "BLOCK_NAME", ")", ")", ";", "return", "new", "EquivalenceHeader", "(", "equivalenceBlock", ",", "namespaceReferenceBlock", ",", "authorblock", ",", "citationBlock", ",", "processingBlock", ")", ";", "}" ]
Parses the equivalence {@link File} into a {@link EquivalenceHeader} object. @param equivalenceFile {@link File}, the equivalence file, which cannot be null, must exist, and must be readable @return {@link NamespaceHeader}, the parsed equivalence header @throws IOException Thrown if an IO error occurred reading the <tt>equivalenceFile</tt> @throws BELDataHeaderParseException Thrown if a parsing error occurred when processing the <tt>equivalenceFile</tt> @throws BELDataConversionException @throws BELDataMissingPropertyException @throws InvalidArgument Thrown if the <tt>equivalenceFile</tt> is null, does not exist, or cannot be read
[ "Parses", "the", "equivalence", "{", "@link", "File", "}", "into", "a", "{", "@link", "EquivalenceHeader", "}", "object", "." ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/beldata/equivalence/EquivalenceHeaderParser.java#L75-L115
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/ReadSecondIfCheckHandler.java
ReadSecondIfCheckHandler.fieldChanged
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { """ The Field has Changed. If the flag is true, do inherited (read secondary), otherwise do initRecord. @param bDisplayOption If true, display the change. @param iMoveMode The type of move being done (init/read/screen). @return The error code (or NORMAL_RETURN if okay). """ if (m_convFlag.getState()) return super.fieldChanged(bDisplayOption, iMoveMode); else { try { m_record.initRecord(bDisplayOption); // Clear the fields m_record.addNew(); } catch(DBException ex) { ex.printStackTrace(); // Never } } return DBConstants.NORMAL_RETURN; }
java
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { if (m_convFlag.getState()) return super.fieldChanged(bDisplayOption, iMoveMode); else { try { m_record.initRecord(bDisplayOption); // Clear the fields m_record.addNew(); } catch(DBException ex) { ex.printStackTrace(); // Never } } return DBConstants.NORMAL_RETURN; }
[ "public", "int", "fieldChanged", "(", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "if", "(", "m_convFlag", ".", "getState", "(", ")", ")", "return", "super", ".", "fieldChanged", "(", "bDisplayOption", ",", "iMoveMode", ")", ";", "else", "{", "try", "{", "m_record", ".", "initRecord", "(", "bDisplayOption", ")", ";", "// Clear the fields", "m_record", ".", "addNew", "(", ")", ";", "}", "catch", "(", "DBException", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "// Never", "}", "}", "return", "DBConstants", ".", "NORMAL_RETURN", ";", "}" ]
The Field has Changed. If the flag is true, do inherited (read secondary), otherwise do initRecord. @param bDisplayOption If true, display the change. @param iMoveMode The type of move being done (init/read/screen). @return The error code (or NORMAL_RETURN if okay).
[ "The", "Field", "has", "Changed", ".", "If", "the", "flag", "is", "true", "do", "inherited", "(", "read", "secondary", ")", "otherwise", "do", "initRecord", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/ReadSecondIfCheckHandler.java#L72-L89
lukas-krecan/JsonUnit
json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java
JsonAssert.assertJsonPartNotEquals
public static void assertJsonPartNotEquals(Object expected, Object fullJson, String path) { """ Compares part of the JSON and fails if they are equal. Path has this format "root.array[0].value". """ assertJsonPartNotEquals(expected, fullJson, path, configuration); }
java
public static void assertJsonPartNotEquals(Object expected, Object fullJson, String path) { assertJsonPartNotEquals(expected, fullJson, path, configuration); }
[ "public", "static", "void", "assertJsonPartNotEquals", "(", "Object", "expected", ",", "Object", "fullJson", ",", "String", "path", ")", "{", "assertJsonPartNotEquals", "(", "expected", ",", "fullJson", ",", "path", ",", "configuration", ")", ";", "}" ]
Compares part of the JSON and fails if they are equal. Path has this format "root.array[0].value".
[ "Compares", "part", "of", "the", "JSON", "and", "fails", "if", "they", "are", "equal", ".", "Path", "has", "this", "format", "root", ".", "array", "[", "0", "]", ".", "value", "." ]
train
https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit/src/main/java/net/javacrumbs/jsonunit/JsonAssert.java#L103-L105
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/model/BuildWithDetails.java
BuildWithDetails.updateDisplayName
public BuildWithDetails updateDisplayName(String displayName, boolean crumbFlag) throws IOException { """ Update <code>displayName</code> of a build. @param displayName The new displayName which should be set. @param crumbFlag <code>true</code> or <code>false</code>. @throws IOException in case of errors. """ Objects.requireNonNull(displayName, "displayName is not allowed to be null."); String description = getDescription() == null ? "" : getDescription(); Map<String, String> params = new HashMap<>(); params.put("displayName", displayName); params.put("description", description); // TODO: Check what the "core:apply" means? params.put("core:apply", ""); params.put("Submit", "Save"); client.post_form(this.getUrl() + "/configSubmit?", params, crumbFlag); return this; }
java
public BuildWithDetails updateDisplayName(String displayName, boolean crumbFlag) throws IOException { Objects.requireNonNull(displayName, "displayName is not allowed to be null."); String description = getDescription() == null ? "" : getDescription(); Map<String, String> params = new HashMap<>(); params.put("displayName", displayName); params.put("description", description); // TODO: Check what the "core:apply" means? params.put("core:apply", ""); params.put("Submit", "Save"); client.post_form(this.getUrl() + "/configSubmit?", params, crumbFlag); return this; }
[ "public", "BuildWithDetails", "updateDisplayName", "(", "String", "displayName", ",", "boolean", "crumbFlag", ")", "throws", "IOException", "{", "Objects", ".", "requireNonNull", "(", "displayName", ",", "\"displayName is not allowed to be null.\"", ")", ";", "String", "description", "=", "getDescription", "(", ")", "==", "null", "?", "\"\"", ":", "getDescription", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"displayName\"", ",", "displayName", ")", ";", "params", ".", "put", "(", "\"description\"", ",", "description", ")", ";", "// TODO: Check what the \"core:apply\" means?", "params", ".", "put", "(", "\"core:apply\"", ",", "\"\"", ")", ";", "params", ".", "put", "(", "\"Submit\"", ",", "\"Save\"", ")", ";", "client", ".", "post_form", "(", "this", ".", "getUrl", "(", ")", "+", "\"/configSubmit?\"", ",", "params", ",", "crumbFlag", ")", ";", "return", "this", ";", "}" ]
Update <code>displayName</code> of a build. @param displayName The new displayName which should be set. @param crumbFlag <code>true</code> or <code>false</code>. @throws IOException in case of errors.
[ "Update", "<code", ">", "displayName<", "/", "code", ">", "of", "a", "build", "." ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/model/BuildWithDetails.java#L215-L226
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/content/PublishSetSummaryUrl.java
PublishSetSummaryUrl.deletePublishSetUrl
public static MozuUrl deletePublishSetUrl(String code, String responseFields, Boolean shouldDiscard) { """ Get Resource Url for DeletePublishSet @param code User-defined code that uniqely identifies the channel group. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @param shouldDiscard Specifies whether to discard the pending content changes assigned to the content publish set when the publish set is deleted. @return String Resource Url """ UrlFormatter formatter = new UrlFormatter("/api/content/publishsets/{code}?shouldDiscard={shouldDiscard}&responseFields={responseFields}"); formatter.formatUrl("code", code); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("shouldDiscard", shouldDiscard); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl deletePublishSetUrl(String code, String responseFields, Boolean shouldDiscard) { UrlFormatter formatter = new UrlFormatter("/api/content/publishsets/{code}?shouldDiscard={shouldDiscard}&responseFields={responseFields}"); formatter.formatUrl("code", code); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("shouldDiscard", shouldDiscard); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "deletePublishSetUrl", "(", "String", "code", ",", "String", "responseFields", ",", "Boolean", "shouldDiscard", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/content/publishsets/{code}?shouldDiscard={shouldDiscard}&responseFields={responseFields}\"", ")", ";", "formatter", ".", "formatUrl", "(", "\"code\"", ",", "code", ")", ";", "formatter", ".", "formatUrl", "(", "\"responseFields\"", ",", "responseFields", ")", ";", "formatter", ".", "formatUrl", "(", "\"shouldDiscard\"", ",", "shouldDiscard", ")", ";", "return", "new", "MozuUrl", "(", "formatter", ".", "getResourceUrl", "(", ")", ",", "MozuUrl", ".", "UrlLocation", ".", "TENANT_POD", ")", ";", "}" ]
Get Resource Url for DeletePublishSet @param code User-defined code that uniqely identifies the channel group. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @param shouldDiscard Specifies whether to discard the pending content changes assigned to the content publish set when the publish set is deleted. @return String Resource Url
[ "Get", "Resource", "Url", "for", "DeletePublishSet" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/content/PublishSetSummaryUrl.java#L61-L68
Azure/azure-sdk-for-java
applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/APIKeysInner.java
APIKeysInner.createAsync
public Observable<ApplicationInsightsComponentAPIKeyInner> createAsync(String resourceGroupName, String resourceName, APIKeyRequest aPIKeyProperties) { """ Create an API Key of an Application Insights component. @param resourceGroupName The name of the resource group. @param resourceName The name of the Application Insights component resource. @param aPIKeyProperties Properties that need to be specified to create an API key of a Application Insights component. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ApplicationInsightsComponentAPIKeyInner object """ return createWithServiceResponseAsync(resourceGroupName, resourceName, aPIKeyProperties).map(new Func1<ServiceResponse<ApplicationInsightsComponentAPIKeyInner>, ApplicationInsightsComponentAPIKeyInner>() { @Override public ApplicationInsightsComponentAPIKeyInner call(ServiceResponse<ApplicationInsightsComponentAPIKeyInner> response) { return response.body(); } }); }
java
public Observable<ApplicationInsightsComponentAPIKeyInner> createAsync(String resourceGroupName, String resourceName, APIKeyRequest aPIKeyProperties) { return createWithServiceResponseAsync(resourceGroupName, resourceName, aPIKeyProperties).map(new Func1<ServiceResponse<ApplicationInsightsComponentAPIKeyInner>, ApplicationInsightsComponentAPIKeyInner>() { @Override public ApplicationInsightsComponentAPIKeyInner call(ServiceResponse<ApplicationInsightsComponentAPIKeyInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ApplicationInsightsComponentAPIKeyInner", ">", "createAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ",", "APIKeyRequest", "aPIKeyProperties", ")", "{", "return", "createWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ",", "aPIKeyProperties", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ApplicationInsightsComponentAPIKeyInner", ">", ",", "ApplicationInsightsComponentAPIKeyInner", ">", "(", ")", "{", "@", "Override", "public", "ApplicationInsightsComponentAPIKeyInner", "call", "(", "ServiceResponse", "<", "ApplicationInsightsComponentAPIKeyInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create an API Key of an Application Insights component. @param resourceGroupName The name of the resource group. @param resourceName The name of the Application Insights component resource. @param aPIKeyProperties Properties that need to be specified to create an API key of a Application Insights component. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ApplicationInsightsComponentAPIKeyInner object
[ "Create", "an", "API", "Key", "of", "an", "Application", "Insights", "component", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/APIKeysInner.java#L207-L214
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.setSlidingDrawer
@SuppressWarnings("deprecation") public void setSlidingDrawer(SlidingDrawer slidingDrawer, int status) { """ Sets the status of the specified SlidingDrawer. Examples of status are: {@code Solo.CLOSED} and {@code Solo.OPENED}. @param slidingDrawer the {@link SlidingDrawer} @param status the status to set the {@link SlidingDrawer} """ if(config.commandLogging){ Log.d(config.commandLoggingTag, "setSlidingDrawer("+slidingDrawer+", "+status+")"); } slidingDrawer = (SlidingDrawer) waiter.waitForView(slidingDrawer, Timeout.getSmallTimeout()); setter.setSlidingDrawer(slidingDrawer, status); }
java
@SuppressWarnings("deprecation") public void setSlidingDrawer(SlidingDrawer slidingDrawer, int status){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "setSlidingDrawer("+slidingDrawer+", "+status+")"); } slidingDrawer = (SlidingDrawer) waiter.waitForView(slidingDrawer, Timeout.getSmallTimeout()); setter.setSlidingDrawer(slidingDrawer, status); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "void", "setSlidingDrawer", "(", "SlidingDrawer", "slidingDrawer", ",", "int", "status", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"setSlidingDrawer(\"", "+", "slidingDrawer", "+", "\", \"", "+", "status", "+", "\")\"", ")", ";", "}", "slidingDrawer", "=", "(", "SlidingDrawer", ")", "waiter", ".", "waitForView", "(", "slidingDrawer", ",", "Timeout", ".", "getSmallTimeout", "(", ")", ")", ";", "setter", ".", "setSlidingDrawer", "(", "slidingDrawer", ",", "status", ")", ";", "}" ]
Sets the status of the specified SlidingDrawer. Examples of status are: {@code Solo.CLOSED} and {@code Solo.OPENED}. @param slidingDrawer the {@link SlidingDrawer} @param status the status to set the {@link SlidingDrawer}
[ "Sets", "the", "status", "of", "the", "specified", "SlidingDrawer", ".", "Examples", "of", "status", "are", ":", "{", "@code", "Solo", ".", "CLOSED", "}", "and", "{", "@code", "Solo", ".", "OPENED", "}", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L2647-L2655
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java
CPDefinitionPersistenceImpl.countByC_S
@Override public int countByC_S(long CProductId, int status) { """ Returns the number of cp definitions where CProductId = &#63; and status = &#63;. @param CProductId the c product ID @param status the status @return the number of matching cp definitions """ FinderPath finderPath = FINDER_PATH_COUNT_BY_C_S; Object[] finderArgs = new Object[] { CProductId, status }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(3); query.append(_SQL_COUNT_CPDEFINITION_WHERE); query.append(_FINDER_COLUMN_C_S_CPRODUCTID_2); query.append(_FINDER_COLUMN_C_S_STATUS_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(CProductId); qPos.add(status); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
java
@Override public int countByC_S(long CProductId, int status) { FinderPath finderPath = FINDER_PATH_COUNT_BY_C_S; Object[] finderArgs = new Object[] { CProductId, status }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(3); query.append(_SQL_COUNT_CPDEFINITION_WHERE); query.append(_FINDER_COLUMN_C_S_CPRODUCTID_2); query.append(_FINDER_COLUMN_C_S_STATUS_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(CProductId); qPos.add(status); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
[ "@", "Override", "public", "int", "countByC_S", "(", "long", "CProductId", ",", "int", "status", ")", "{", "FinderPath", "finderPath", "=", "FINDER_PATH_COUNT_BY_C_S", ";", "Object", "[", "]", "finderArgs", "=", "new", "Object", "[", "]", "{", "CProductId", ",", "status", "}", ";", "Long", "count", "=", "(", "Long", ")", "finderCache", ".", "getResult", "(", "finderPath", ",", "finderArgs", ",", "this", ")", ";", "if", "(", "count", "==", "null", ")", "{", "StringBundler", "query", "=", "new", "StringBundler", "(", "3", ")", ";", "query", ".", "append", "(", "_SQL_COUNT_CPDEFINITION_WHERE", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_C_S_CPRODUCTID_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_C_S_STATUS_2", ")", ";", "String", "sql", "=", "query", ".", "toString", "(", ")", ";", "Session", "session", "=", "null", ";", "try", "{", "session", "=", "openSession", "(", ")", ";", "Query", "q", "=", "session", ".", "createQuery", "(", "sql", ")", ";", "QueryPos", "qPos", "=", "QueryPos", ".", "getInstance", "(", "q", ")", ";", "qPos", ".", "add", "(", "CProductId", ")", ";", "qPos", ".", "add", "(", "status", ")", ";", "count", "=", "(", "Long", ")", "q", ".", "uniqueResult", "(", ")", ";", "finderCache", ".", "putResult", "(", "finderPath", ",", "finderArgs", ",", "count", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "finderCache", ".", "removeResult", "(", "finderPath", ",", "finderArgs", ")", ";", "throw", "processException", "(", "e", ")", ";", "}", "finally", "{", "closeSession", "(", "session", ")", ";", "}", "}", "return", "count", ".", "intValue", "(", ")", ";", "}" ]
Returns the number of cp definitions where CProductId = &#63; and status = &#63;. @param CProductId the c product ID @param status the status @return the number of matching cp definitions
[ "Returns", "the", "number", "of", "cp", "definitions", "where", "CProductId", "=", "&#63", ";", "and", "status", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionPersistenceImpl.java#L4563-L4610
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/iomanager/IOManager.java
IOManager.createBlockChannelReader
public BlockChannelReader createBlockChannelReader(Channel.ID channelID, LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException { """ Creates a block channel reader that reads blocks from the given channel. The reader reads asynchronously, such that a read request is accepted, carried out at some (close) point in time, and the full segment is pushed to the given queue. @param channelID The descriptor for the channel to write to. @param returnQueue The queue to put the full buffers into. @return A block channel reader that reads from the given channel. @throws IOException Thrown, if the channel for the reader could not be opened. """ if (this.isClosed) { throw new IllegalStateException("I/O-Manger is closed."); } return new BlockChannelReader(channelID, this.readers[channelID.getThreadNum()].requestQueue, returnQueue, 1); }
java
public BlockChannelReader createBlockChannelReader(Channel.ID channelID, LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException { if (this.isClosed) { throw new IllegalStateException("I/O-Manger is closed."); } return new BlockChannelReader(channelID, this.readers[channelID.getThreadNum()].requestQueue, returnQueue, 1); }
[ "public", "BlockChannelReader", "createBlockChannelReader", "(", "Channel", ".", "ID", "channelID", ",", "LinkedBlockingQueue", "<", "MemorySegment", ">", "returnQueue", ")", "throws", "IOException", "{", "if", "(", "this", ".", "isClosed", ")", "{", "throw", "new", "IllegalStateException", "(", "\"I/O-Manger is closed.\"", ")", ";", "}", "return", "new", "BlockChannelReader", "(", "channelID", ",", "this", ".", "readers", "[", "channelID", ".", "getThreadNum", "(", ")", "]", ".", "requestQueue", ",", "returnQueue", ",", "1", ")", ";", "}" ]
Creates a block channel reader that reads blocks from the given channel. The reader reads asynchronously, such that a read request is accepted, carried out at some (close) point in time, and the full segment is pushed to the given queue. @param channelID The descriptor for the channel to write to. @param returnQueue The queue to put the full buffers into. @return A block channel reader that reads from the given channel. @throws IOException Thrown, if the channel for the reader could not be opened.
[ "Creates", "a", "block", "channel", "reader", "that", "reads", "blocks", "from", "the", "given", "channel", ".", "The", "reader", "reads", "asynchronously", "such", "that", "a", "read", "request", "is", "accepted", "carried", "out", "at", "some", "(", "close", ")", "point", "in", "time", "and", "the", "full", "segment", "is", "pushed", "to", "the", "given", "queue", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/iomanager/IOManager.java#L339-L348
BlueBrain/bluima
modules/bluima_banner/src/main/java/banner/Sentence.java
Sentence.getTrainingText
public String getTrainingText(TagFormat format, boolean reverse) { """ Returns a text representation of the tagging for this {@link Sentence}, using the specified {@link TagFormat}. In other words, each token in the sentence is given a tag indicating its position in a mention or that the token is not a mention. Assumes that each token is tagged either 0 or 1 times. @param format The {@link TagFormat} to use @param reverse Whether to return the text in reverse order @return A text representation of the tagging for this {@link Sentence}, using the specified {@link TagFormat} """ List<TaggedToken> taggedTokens = new ArrayList<TaggedToken>(getTaggedTokens()); if (reverse) Collections.reverse(taggedTokens); StringBuffer trainingText = new StringBuffer(); for (TaggedToken token : taggedTokens) { trainingText.append(token.getText(format)); trainingText.append(" "); } return trainingText.toString().trim(); }
java
public String getTrainingText(TagFormat format, boolean reverse) { List<TaggedToken> taggedTokens = new ArrayList<TaggedToken>(getTaggedTokens()); if (reverse) Collections.reverse(taggedTokens); StringBuffer trainingText = new StringBuffer(); for (TaggedToken token : taggedTokens) { trainingText.append(token.getText(format)); trainingText.append(" "); } return trainingText.toString().trim(); }
[ "public", "String", "getTrainingText", "(", "TagFormat", "format", ",", "boolean", "reverse", ")", "{", "List", "<", "TaggedToken", ">", "taggedTokens", "=", "new", "ArrayList", "<", "TaggedToken", ">", "(", "getTaggedTokens", "(", ")", ")", ";", "if", "(", "reverse", ")", "Collections", ".", "reverse", "(", "taggedTokens", ")", ";", "StringBuffer", "trainingText", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "TaggedToken", "token", ":", "taggedTokens", ")", "{", "trainingText", ".", "append", "(", "token", ".", "getText", "(", "format", ")", ")", ";", "trainingText", ".", "append", "(", "\" \"", ")", ";", "}", "return", "trainingText", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}" ]
Returns a text representation of the tagging for this {@link Sentence}, using the specified {@link TagFormat}. In other words, each token in the sentence is given a tag indicating its position in a mention or that the token is not a mention. Assumes that each token is tagged either 0 or 1 times. @param format The {@link TagFormat} to use @param reverse Whether to return the text in reverse order @return A text representation of the tagging for this {@link Sentence}, using the specified {@link TagFormat}
[ "Returns", "a", "text", "representation", "of", "the", "tagging", "for", "this", "{", "@link", "Sentence", "}", "using", "the", "specified", "{", "@link", "TagFormat", "}", ".", "In", "other", "words", "each", "token", "in", "the", "sentence", "is", "given", "a", "tag", "indicating", "its", "position", "in", "a", "mention", "or", "that", "the", "token", "is", "not", "a", "mention", ".", "Assumes", "that", "each", "token", "is", "tagged", "either", "0", "or", "1", "times", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_banner/src/main/java/banner/Sentence.java#L390-L402
jenkinsci/jenkins
core/src/main/java/hudson/model/ViewDescriptor.java
ViewDescriptor.doAutoCompleteCopyNewItemFrom
@Restricted(DoNotUse.class) public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value, @AncestorInPath ItemGroup<?> container) { """ Auto-completion for the "copy from" field in the new job page. """ AutoCompletionCandidates candidates = AutoCompletionCandidates.ofJobNames(TopLevelItem.class, value, container); if (container instanceof DirectlyModifiableTopLevelItemGroup) { DirectlyModifiableTopLevelItemGroup modifiableContainer = (DirectlyModifiableTopLevelItemGroup) container; Iterator<String> it = candidates.getValues().iterator(); while (it.hasNext()) { TopLevelItem item = Jenkins.getInstance().getItem(it.next(), container, TopLevelItem.class); if (item == null) { continue; // ? } if (!modifiableContainer.canAdd(item)) { it.remove(); } } } return candidates; }
java
@Restricted(DoNotUse.class) public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value, @AncestorInPath ItemGroup<?> container) { AutoCompletionCandidates candidates = AutoCompletionCandidates.ofJobNames(TopLevelItem.class, value, container); if (container instanceof DirectlyModifiableTopLevelItemGroup) { DirectlyModifiableTopLevelItemGroup modifiableContainer = (DirectlyModifiableTopLevelItemGroup) container; Iterator<String> it = candidates.getValues().iterator(); while (it.hasNext()) { TopLevelItem item = Jenkins.getInstance().getItem(it.next(), container, TopLevelItem.class); if (item == null) { continue; // ? } if (!modifiableContainer.canAdd(item)) { it.remove(); } } } return candidates; }
[ "@", "Restricted", "(", "DoNotUse", ".", "class", ")", "public", "AutoCompletionCandidates", "doAutoCompleteCopyNewItemFrom", "(", "@", "QueryParameter", "final", "String", "value", ",", "@", "AncestorInPath", "ItemGroup", "<", "?", ">", "container", ")", "{", "AutoCompletionCandidates", "candidates", "=", "AutoCompletionCandidates", ".", "ofJobNames", "(", "TopLevelItem", ".", "class", ",", "value", ",", "container", ")", ";", "if", "(", "container", "instanceof", "DirectlyModifiableTopLevelItemGroup", ")", "{", "DirectlyModifiableTopLevelItemGroup", "modifiableContainer", "=", "(", "DirectlyModifiableTopLevelItemGroup", ")", "container", ";", "Iterator", "<", "String", ">", "it", "=", "candidates", ".", "getValues", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "TopLevelItem", "item", "=", "Jenkins", ".", "getInstance", "(", ")", ".", "getItem", "(", "it", ".", "next", "(", ")", ",", "container", ",", "TopLevelItem", ".", "class", ")", ";", "if", "(", "item", "==", "null", ")", "{", "continue", ";", "// ?", "}", "if", "(", "!", "modifiableContainer", ".", "canAdd", "(", "item", ")", ")", "{", "it", ".", "remove", "(", ")", ";", "}", "}", "}", "return", "candidates", ";", "}" ]
Auto-completion for the "copy from" field in the new job page.
[ "Auto", "-", "completion", "for", "the", "copy", "from", "field", "in", "the", "new", "job", "page", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/ViewDescriptor.java#L87-L104
Azure/azure-sdk-for-java
privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/PrivateZonesInner.java
PrivateZonesInner.beginCreateOrUpdate
public PrivateZoneInner beginCreateOrUpdate(String resourceGroupName, String privateZoneName, PrivateZoneInner parameters) { """ Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. @param resourceGroupName The name of the resource group. @param privateZoneName The name of the Private DNS zone (without a terminating dot). @param parameters Parameters supplied to the CreateOrUpdate operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PrivateZoneInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, privateZoneName, parameters).toBlocking().single().body(); }
java
public PrivateZoneInner beginCreateOrUpdate(String resourceGroupName, String privateZoneName, PrivateZoneInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, privateZoneName, parameters).toBlocking().single().body(); }
[ "public", "PrivateZoneInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "privateZoneName", ",", "PrivateZoneInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "privateZoneName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records within the zone. @param resourceGroupName The name of the resource group. @param privateZoneName The name of the Private DNS zone (without a terminating dot). @param parameters Parameters supplied to the CreateOrUpdate operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PrivateZoneInner object if successful.
[ "Creates", "or", "updates", "a", "Private", "DNS", "zone", ".", "Does", "not", "modify", "Links", "to", "virtual", "networks", "or", "DNS", "records", "within", "the", "zone", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/PrivateZonesInner.java#L288-L290
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/hashtable/BinaryHashPartition.java
BinaryHashPartition.finalizeBuildPhase
int finalizeBuildPhase(IOManager ioAccess, FileIOChannel.Enumerator probeChannelEnumerator) throws IOException { """ After build phase. @return build spill return buffer, if have spilled, it returns the current write buffer, because it was used all the time in build phase, so it can only be returned at this time. """ this.finalBufferLimit = this.buildSideWriteBuffer.getCurrentPositionInSegment(); this.partitionBuffers = this.buildSideWriteBuffer.close(); if (!isInMemory()) { // close the channel. this.buildSideChannel.close(); this.probeSideBuffer = FileChannelUtil.createOutputView( ioAccess, probeChannelEnumerator.next(), compressionEnable, compressionCodecFactory, compressionBlockSize, memorySegmentSize); return 1; } else { return 0; } }
java
int finalizeBuildPhase(IOManager ioAccess, FileIOChannel.Enumerator probeChannelEnumerator) throws IOException { this.finalBufferLimit = this.buildSideWriteBuffer.getCurrentPositionInSegment(); this.partitionBuffers = this.buildSideWriteBuffer.close(); if (!isInMemory()) { // close the channel. this.buildSideChannel.close(); this.probeSideBuffer = FileChannelUtil.createOutputView( ioAccess, probeChannelEnumerator.next(), compressionEnable, compressionCodecFactory, compressionBlockSize, memorySegmentSize); return 1; } else { return 0; } }
[ "int", "finalizeBuildPhase", "(", "IOManager", "ioAccess", ",", "FileIOChannel", ".", "Enumerator", "probeChannelEnumerator", ")", "throws", "IOException", "{", "this", ".", "finalBufferLimit", "=", "this", ".", "buildSideWriteBuffer", ".", "getCurrentPositionInSegment", "(", ")", ";", "this", ".", "partitionBuffers", "=", "this", ".", "buildSideWriteBuffer", ".", "close", "(", ")", ";", "if", "(", "!", "isInMemory", "(", ")", ")", "{", "// close the channel.", "this", ".", "buildSideChannel", ".", "close", "(", ")", ";", "this", ".", "probeSideBuffer", "=", "FileChannelUtil", ".", "createOutputView", "(", "ioAccess", ",", "probeChannelEnumerator", ".", "next", "(", ")", ",", "compressionEnable", ",", "compressionCodecFactory", ",", "compressionBlockSize", ",", "memorySegmentSize", ")", ";", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
After build phase. @return build spill return buffer, if have spilled, it returns the current write buffer, because it was used all the time in build phase, so it can only be returned at this time.
[ "After", "build", "phase", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/hashtable/BinaryHashPartition.java#L332-L351
JodaOrg/joda-time
src/main/java/org/joda/time/format/FormatUtils.java
FormatUtils.writeUnpaddedInteger
public static void writeUnpaddedInteger(Writer out, int value) throws IOException { """ Converts an integer to a string, and writes it to the given writer. <p>This method is optimized for converting small values to strings. @param out receives integer converted to a string @param value value to convert to a string """ if (value < 0) { out.write('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { out.write("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { out.write(value + '0'); } else if (value < 100) { // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; out.write(d + '0'); // Append remainder by calculating (value - d * 10). out.write(value - (d << 3) - (d << 1) + '0'); } else { out.write(Integer.toString(value)); } }
java
public static void writeUnpaddedInteger(Writer out, int value) throws IOException { if (value < 0) { out.write('-'); if (value != Integer.MIN_VALUE) { value = -value; } else { out.write("" + -(long)Integer.MIN_VALUE); return; } } if (value < 10) { out.write(value + '0'); } else if (value < 100) { // Calculate value div/mod by 10 without using two expensive // division operations. (2 ^ 27) / 10 = 13421772. Add one to // value to correct rounding error. int d = ((value + 1) * 13421772) >> 27; out.write(d + '0'); // Append remainder by calculating (value - d * 10). out.write(value - (d << 3) - (d << 1) + '0'); } else { out.write(Integer.toString(value)); } }
[ "public", "static", "void", "writeUnpaddedInteger", "(", "Writer", "out", ",", "int", "value", ")", "throws", "IOException", "{", "if", "(", "value", "<", "0", ")", "{", "out", ".", "write", "(", "'", "'", ")", ";", "if", "(", "value", "!=", "Integer", ".", "MIN_VALUE", ")", "{", "value", "=", "-", "value", ";", "}", "else", "{", "out", ".", "write", "(", "\"\"", "+", "-", "(", "long", ")", "Integer", ".", "MIN_VALUE", ")", ";", "return", ";", "}", "}", "if", "(", "value", "<", "10", ")", "{", "out", ".", "write", "(", "value", "+", "'", "'", ")", ";", "}", "else", "if", "(", "value", "<", "100", ")", "{", "// Calculate value div/mod by 10 without using two expensive", "// division operations. (2 ^ 27) / 10 = 13421772. Add one to", "// value to correct rounding error.", "int", "d", "=", "(", "(", "value", "+", "1", ")", "*", "13421772", ")", ">>", "27", ";", "out", ".", "write", "(", "d", "+", "'", "'", ")", ";", "// Append remainder by calculating (value - d * 10).", "out", ".", "write", "(", "value", "-", "(", "d", "<<", "3", ")", "-", "(", "d", "<<", "1", ")", "+", "'", "'", ")", ";", "}", "else", "{", "out", ".", "write", "(", "Integer", ".", "toString", "(", "value", ")", ")", ";", "}", "}" ]
Converts an integer to a string, and writes it to the given writer. <p>This method is optimized for converting small values to strings. @param out receives integer converted to a string @param value value to convert to a string
[ "Converts", "an", "integer", "to", "a", "string", "and", "writes", "it", "to", "the", "given", "writer", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/FormatUtils.java#L356-L381
google/closure-templates
java/src/com/google/template/soy/data/SanitizedContents.java
SanitizedContents.pretendValidateResource
@VisibleForTesting static void pretendValidateResource(String resourceName, ContentKind kind) { """ Very basic but strict validation that the resource's extension matches the content kind. <p>In practice, this may be unnecessary, but it's always good to start out strict. This list can either be expanded as needed, or removed if too onerous. """ int index = resourceName.lastIndexOf('.'); Preconditions.checkArgument( index >= 0, "Currently, we only validate resources with explicit extensions."); String fileExtension = resourceName.substring(index + 1).toLowerCase(); switch (kind) { case JS: Preconditions.checkArgument(fileExtension.equals("js")); break; case HTML: Preconditions.checkArgument(SAFE_HTML_FILE_EXTENSIONS.contains(fileExtension)); break; case CSS: Preconditions.checkArgument(fileExtension.equals("css")); break; default: throw new IllegalArgumentException("Don't know how to validate resources of kind " + kind); } }
java
@VisibleForTesting static void pretendValidateResource(String resourceName, ContentKind kind) { int index = resourceName.lastIndexOf('.'); Preconditions.checkArgument( index >= 0, "Currently, we only validate resources with explicit extensions."); String fileExtension = resourceName.substring(index + 1).toLowerCase(); switch (kind) { case JS: Preconditions.checkArgument(fileExtension.equals("js")); break; case HTML: Preconditions.checkArgument(SAFE_HTML_FILE_EXTENSIONS.contains(fileExtension)); break; case CSS: Preconditions.checkArgument(fileExtension.equals("css")); break; default: throw new IllegalArgumentException("Don't know how to validate resources of kind " + kind); } }
[ "@", "VisibleForTesting", "static", "void", "pretendValidateResource", "(", "String", "resourceName", ",", "ContentKind", "kind", ")", "{", "int", "index", "=", "resourceName", ".", "lastIndexOf", "(", "'", "'", ")", ";", "Preconditions", ".", "checkArgument", "(", "index", ">=", "0", ",", "\"Currently, we only validate resources with explicit extensions.\"", ")", ";", "String", "fileExtension", "=", "resourceName", ".", "substring", "(", "index", "+", "1", ")", ".", "toLowerCase", "(", ")", ";", "switch", "(", "kind", ")", "{", "case", "JS", ":", "Preconditions", ".", "checkArgument", "(", "fileExtension", ".", "equals", "(", "\"js\"", ")", ")", ";", "break", ";", "case", "HTML", ":", "Preconditions", ".", "checkArgument", "(", "SAFE_HTML_FILE_EXTENSIONS", ".", "contains", "(", "fileExtension", ")", ")", ";", "break", ";", "case", "CSS", ":", "Preconditions", ".", "checkArgument", "(", "fileExtension", ".", "equals", "(", "\"css\"", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Don't know how to validate resources of kind \"", "+", "kind", ")", ";", "}", "}" ]
Very basic but strict validation that the resource's extension matches the content kind. <p>In practice, this may be unnecessary, but it's always good to start out strict. This list can either be expanded as needed, or removed if too onerous.
[ "Very", "basic", "but", "strict", "validation", "that", "the", "resource", "s", "extension", "matches", "the", "content", "kind", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SanitizedContents.java#L352-L372
rzwitserloot/lombok
src/core/lombok/bytecode/ClassFileMetaData.java
ClassFileMetaData.usesField
public boolean usesField(String className, String fieldName) { """ Checks if the constant pool contains a reference to a given field, either for writing or reading. @param className must be provided JVM-style, such as {@code java/lang/String} """ int classIndex = findClass(className); if (classIndex == NOT_FOUND) return false; int fieldNameIndex = findUtf8(fieldName); if (fieldNameIndex == NOT_FOUND) return false; for (int i = 1; i < maxPoolSize; i++) { if (types[i] == FIELD && readValue(offsets[i]) == classIndex) { int nameAndTypeIndex = readValue(offsets[i] + 2); if (readValue(offsets[nameAndTypeIndex]) == fieldNameIndex) return true; } } return false; }
java
public boolean usesField(String className, String fieldName) { int classIndex = findClass(className); if (classIndex == NOT_FOUND) return false; int fieldNameIndex = findUtf8(fieldName); if (fieldNameIndex == NOT_FOUND) return false; for (int i = 1; i < maxPoolSize; i++) { if (types[i] == FIELD && readValue(offsets[i]) == classIndex) { int nameAndTypeIndex = readValue(offsets[i] + 2); if (readValue(offsets[nameAndTypeIndex]) == fieldNameIndex) return true; } } return false; }
[ "public", "boolean", "usesField", "(", "String", "className", ",", "String", "fieldName", ")", "{", "int", "classIndex", "=", "findClass", "(", "className", ")", ";", "if", "(", "classIndex", "==", "NOT_FOUND", ")", "return", "false", ";", "int", "fieldNameIndex", "=", "findUtf8", "(", "fieldName", ")", ";", "if", "(", "fieldNameIndex", "==", "NOT_FOUND", ")", "return", "false", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "maxPoolSize", ";", "i", "++", ")", "{", "if", "(", "types", "[", "i", "]", "==", "FIELD", "&&", "readValue", "(", "offsets", "[", "i", "]", ")", "==", "classIndex", ")", "{", "int", "nameAndTypeIndex", "=", "readValue", "(", "offsets", "[", "i", "]", "+", "2", ")", ";", "if", "(", "readValue", "(", "offsets", "[", "nameAndTypeIndex", "]", ")", "==", "fieldNameIndex", ")", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the constant pool contains a reference to a given field, either for writing or reading. @param className must be provided JVM-style, such as {@code java/lang/String}
[ "Checks", "if", "the", "constant", "pool", "contains", "a", "reference", "to", "a", "given", "field", "either", "for", "writing", "or", "reading", "." ]
train
https://github.com/rzwitserloot/lombok/blob/75601240760bd81ff95fcde7a1b8185769ce64e8/src/core/lombok/bytecode/ClassFileMetaData.java#L164-L177
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/user/UserCoreDao.java
UserCoreDao.queryForEq
public TResult queryForEq(String fieldName, Object value) { """ Query for the row where the field equals the value @param fieldName field name @param value value @return result """ return queryForEq(fieldName, value, null, null, null); }
java
public TResult queryForEq(String fieldName, Object value) { return queryForEq(fieldName, value, null, null, null); }
[ "public", "TResult", "queryForEq", "(", "String", "fieldName", ",", "Object", "value", ")", "{", "return", "queryForEq", "(", "fieldName", ",", "value", ",", "null", ",", "null", ",", "null", ")", ";", "}" ]
Query for the row where the field equals the value @param fieldName field name @param value value @return result
[ "Query", "for", "the", "row", "where", "the", "field", "equals", "the", "value" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/user/UserCoreDao.java#L240-L242
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/ClassFile.java
ClassFile.readFrom
public static ClassFile readFrom(DataInput din, ClassFileDataLoader loader, AttributeFactory attrFactory) throws IOException { """ Reads a ClassFile from the given DataInput. A {@link ClassFileDataLoader} may be provided, which allows inner class definitions to be loaded. Also, an {@link AttributeFactory} may be provided, which allows non-standard attributes to be read. All remaining unknown attribute types are captured, but are not decoded. @param din source of class file data @param loader optional loader for reading inner class definitions @param attrFactory optional factory for reading custom attributes @throws IOException for I/O error or if classfile is invalid. @throws ArrayIndexOutOfBoundsException if a constant pool index is out of range. @throws ClassCastException if a constant pool index references the wrong type. """ return readFrom(din, loader, attrFactory, new HashMap<String, ClassFile>(11), null); }
java
public static ClassFile readFrom(DataInput din, ClassFileDataLoader loader, AttributeFactory attrFactory) throws IOException { return readFrom(din, loader, attrFactory, new HashMap<String, ClassFile>(11), null); }
[ "public", "static", "ClassFile", "readFrom", "(", "DataInput", "din", ",", "ClassFileDataLoader", "loader", ",", "AttributeFactory", "attrFactory", ")", "throws", "IOException", "{", "return", "readFrom", "(", "din", ",", "loader", ",", "attrFactory", ",", "new", "HashMap", "<", "String", ",", "ClassFile", ">", "(", "11", ")", ",", "null", ")", ";", "}" ]
Reads a ClassFile from the given DataInput. A {@link ClassFileDataLoader} may be provided, which allows inner class definitions to be loaded. Also, an {@link AttributeFactory} may be provided, which allows non-standard attributes to be read. All remaining unknown attribute types are captured, but are not decoded. @param din source of class file data @param loader optional loader for reading inner class definitions @param attrFactory optional factory for reading custom attributes @throws IOException for I/O error or if classfile is invalid. @throws ArrayIndexOutOfBoundsException if a constant pool index is out of range. @throws ClassCastException if a constant pool index references the wrong type.
[ "Reads", "a", "ClassFile", "from", "the", "given", "DataInput", ".", "A", "{", "@link", "ClassFileDataLoader", "}", "may", "be", "provided", "which", "allows", "inner", "class", "definitions", "to", "be", "loaded", ".", "Also", "an", "{", "@link", "AttributeFactory", "}", "may", "be", "provided", "which", "allows", "non", "-", "standard", "attributes", "to", "be", "read", ".", "All", "remaining", "unknown", "attribute", "types", "are", "captured", "but", "are", "not", "decoded", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ClassFile.java#L1052-L1058
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/TrConfigurator.java
TrConfigurator.setTraceSpec
synchronized static TraceSpecification setTraceSpec(String spec) { """ Set the trace specification of the service to the input value. @param spec New string trace specification @return new TraceSpecification, or null if unchanged """ // If logger is used & configured by logger properties, // we're done as far as trace string processing is concerned if (WsLogManager.isConfiguredByLoggingProperties()) { return null; } // If the specified string is null, or it is equal to a string, // or the sensitive flag has not been toggled, // we've already parsed, skip it. if ((spec == null || spec.equals(traceString)) && Tr.activeTraceSpec.isSensitiveTraceSuppressed() == suppressSensitiveTrace) { return null; } traceString = spec; // Parse the trace specification string, this will gather // exceptions that occur for different elements of the string TraceSpecification newTs = new TraceSpecification(spec, safeLevelsIndex, suppressSensitiveTrace); TraceSpecificationException tex = newTs.getExceptions(); if (tex != null) { do { tex.warning(loggingConfig.get() != null); tex = tex.getPreviousException(); } while (tex != null); } Tr.setTraceSpec(newTs); // Return the new/updated TraceSpecification to the caller. The caller can // then determine whether or not all elements of the TraceSpecification // were known to the system or not. return newTs; }
java
synchronized static TraceSpecification setTraceSpec(String spec) { // If logger is used & configured by logger properties, // we're done as far as trace string processing is concerned if (WsLogManager.isConfiguredByLoggingProperties()) { return null; } // If the specified string is null, or it is equal to a string, // or the sensitive flag has not been toggled, // we've already parsed, skip it. if ((spec == null || spec.equals(traceString)) && Tr.activeTraceSpec.isSensitiveTraceSuppressed() == suppressSensitiveTrace) { return null; } traceString = spec; // Parse the trace specification string, this will gather // exceptions that occur for different elements of the string TraceSpecification newTs = new TraceSpecification(spec, safeLevelsIndex, suppressSensitiveTrace); TraceSpecificationException tex = newTs.getExceptions(); if (tex != null) { do { tex.warning(loggingConfig.get() != null); tex = tex.getPreviousException(); } while (tex != null); } Tr.setTraceSpec(newTs); // Return the new/updated TraceSpecification to the caller. The caller can // then determine whether or not all elements of the TraceSpecification // were known to the system or not. return newTs; }
[ "synchronized", "static", "TraceSpecification", "setTraceSpec", "(", "String", "spec", ")", "{", "// If logger is used & configured by logger properties, ", "// we're done as far as trace string processing is concerned", "if", "(", "WsLogManager", ".", "isConfiguredByLoggingProperties", "(", ")", ")", "{", "return", "null", ";", "}", "// If the specified string is null, or it is equal to a string,", "// or the sensitive flag has not been toggled,", "// we've already parsed, skip it.", "if", "(", "(", "spec", "==", "null", "||", "spec", ".", "equals", "(", "traceString", ")", ")", "&&", "Tr", ".", "activeTraceSpec", ".", "isSensitiveTraceSuppressed", "(", ")", "==", "suppressSensitiveTrace", ")", "{", "return", "null", ";", "}", "traceString", "=", "spec", ";", "// Parse the trace specification string, this will gather", "// exceptions that occur for different elements of the string", "TraceSpecification", "newTs", "=", "new", "TraceSpecification", "(", "spec", ",", "safeLevelsIndex", ",", "suppressSensitiveTrace", ")", ";", "TraceSpecificationException", "tex", "=", "newTs", ".", "getExceptions", "(", ")", ";", "if", "(", "tex", "!=", "null", ")", "{", "do", "{", "tex", ".", "warning", "(", "loggingConfig", ".", "get", "(", ")", "!=", "null", ")", ";", "tex", "=", "tex", ".", "getPreviousException", "(", ")", ";", "}", "while", "(", "tex", "!=", "null", ")", ";", "}", "Tr", ".", "setTraceSpec", "(", "newTs", ")", ";", "// Return the new/updated TraceSpecification to the caller. The caller can", "// then determine whether or not all elements of the TraceSpecification ", "// were known to the system or not.", "return", "newTs", ";", "}" ]
Set the trace specification of the service to the input value. @param spec New string trace specification @return new TraceSpecification, or null if unchanged
[ "Set", "the", "trace", "specification", "of", "the", "service", "to", "the", "input", "value", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.core/src/com/ibm/websphere/ras/TrConfigurator.java#L271-L305
RestComm/sipunit
src/main/java/org/cafesip/sipunit/ReferNotifySender.java
ReferNotifySender.processRefer
public void processRefer(long timeout, int statusCode, String reasonPhrase, int duration, EventHeader overrideEvent) { """ Same as the other processRefer() except allows for a couple of overrides for testing error handling by the far end outbound REFER side: (a) takes a duration for adding ExpiresHeader to the REFER response (the response shouldn't have an expires header), and (b) this method takes an EventHeader for overriding what would normally/correctly be sent back in the response (normally same as what was received in the request). """ setErrorMessage(""); PhoneB b = new PhoneB(timeout + 500, statusCode, reasonPhrase, duration, overrideEvent); b.start(); }
java
public void processRefer(long timeout, int statusCode, String reasonPhrase, int duration, EventHeader overrideEvent) { setErrorMessage(""); PhoneB b = new PhoneB(timeout + 500, statusCode, reasonPhrase, duration, overrideEvent); b.start(); }
[ "public", "void", "processRefer", "(", "long", "timeout", ",", "int", "statusCode", ",", "String", "reasonPhrase", ",", "int", "duration", ",", "EventHeader", "overrideEvent", ")", "{", "setErrorMessage", "(", "\"\"", ")", ";", "PhoneB", "b", "=", "new", "PhoneB", "(", "timeout", "+", "500", ",", "statusCode", ",", "reasonPhrase", ",", "duration", ",", "overrideEvent", ")", ";", "b", ".", "start", "(", ")", ";", "}" ]
Same as the other processRefer() except allows for a couple of overrides for testing error handling by the far end outbound REFER side: (a) takes a duration for adding ExpiresHeader to the REFER response (the response shouldn't have an expires header), and (b) this method takes an EventHeader for overriding what would normally/correctly be sent back in the response (normally same as what was received in the request).
[ "Same", "as", "the", "other", "processRefer", "()", "except", "allows", "for", "a", "couple", "of", "overrides", "for", "testing", "error", "handling", "by", "the", "far", "end", "outbound", "REFER", "side", ":", "(", "a", ")", "takes", "a", "duration", "for", "adding", "ExpiresHeader", "to", "the", "REFER", "response", "(", "the", "response", "shouldn", "t", "have", "an", "expires", "header", ")", "and", "(", "b", ")", "this", "method", "takes", "an", "EventHeader", "for", "overriding", "what", "would", "normally", "/", "correctly", "be", "sent", "back", "in", "the", "response", "(", "normally", "same", "as", "what", "was", "received", "in", "the", "request", ")", "." ]
train
https://github.com/RestComm/sipunit/blob/18a6be2e29be3fbdc14226e8c41b25e2d57378b1/src/main/java/org/cafesip/sipunit/ReferNotifySender.java#L95-L101
OpenLiberty/open-liberty
dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java
AuditEvent.setObserver
public void setObserver(Map<String, Object> observer) { """ Set the observer keys/values. The provided Map will completely replace the existing observer, i.e. all current observer keys/values will be removed and the new observer keys/values will be added. @param observer - Map of all the observer keys/values """ removeEntriesStartingWith(OBSERVER); eventMap.putAll(observer); }
java
public void setObserver(Map<String, Object> observer) { removeEntriesStartingWith(OBSERVER); eventMap.putAll(observer); }
[ "public", "void", "setObserver", "(", "Map", "<", "String", ",", "Object", ">", "observer", ")", "{", "removeEntriesStartingWith", "(", "OBSERVER", ")", ";", "eventMap", ".", "putAll", "(", "observer", ")", ";", "}" ]
Set the observer keys/values. The provided Map will completely replace the existing observer, i.e. all current observer keys/values will be removed and the new observer keys/values will be added. @param observer - Map of all the observer keys/values
[ "Set", "the", "observer", "keys", "/", "values", ".", "The", "provided", "Map", "will", "completely", "replace", "the", "existing", "observer", "i", ".", "e", ".", "all", "current", "observer", "keys", "/", "values", "will", "be", "removed", "and", "the", "new", "observer", "keys", "/", "values", "will", "be", "added", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java#L315-L318
aws/aws-cloudtrail-processing-library
src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/manager/SqsManager.java
SqsManager.deleteMessageFromQueue
public void deleteMessageFromQueue(Message sqsMessage, ProgressStatus progressStatus) { """ Delete a message from the SQS queue that you specified in the configuration file. @param sqsMessage the {@link Message} that you want to delete. @param progressStatus {@link ProgressStatus} tracks the start and end status. """ final Object reportObject = progressReporter.reportStart(progressStatus); boolean deleteMessageSuccess = false; try { sqsClient.deleteMessage(new DeleteMessageRequest(config.getSqsUrl(), sqsMessage.getReceiptHandle())); deleteMessageSuccess = true; } catch (AmazonServiceException e) { LibraryUtils.handleException(exceptionHandler, progressStatus, e, "Failed to delete sqs message."); } LibraryUtils.endToProcess(progressReporter, deleteMessageSuccess, progressStatus, reportObject); }
java
public void deleteMessageFromQueue(Message sqsMessage, ProgressStatus progressStatus) { final Object reportObject = progressReporter.reportStart(progressStatus); boolean deleteMessageSuccess = false; try { sqsClient.deleteMessage(new DeleteMessageRequest(config.getSqsUrl(), sqsMessage.getReceiptHandle())); deleteMessageSuccess = true; } catch (AmazonServiceException e) { LibraryUtils.handleException(exceptionHandler, progressStatus, e, "Failed to delete sqs message."); } LibraryUtils.endToProcess(progressReporter, deleteMessageSuccess, progressStatus, reportObject); }
[ "public", "void", "deleteMessageFromQueue", "(", "Message", "sqsMessage", ",", "ProgressStatus", "progressStatus", ")", "{", "final", "Object", "reportObject", "=", "progressReporter", ".", "reportStart", "(", "progressStatus", ")", ";", "boolean", "deleteMessageSuccess", "=", "false", ";", "try", "{", "sqsClient", ".", "deleteMessage", "(", "new", "DeleteMessageRequest", "(", "config", ".", "getSqsUrl", "(", ")", ",", "sqsMessage", ".", "getReceiptHandle", "(", ")", ")", ")", ";", "deleteMessageSuccess", "=", "true", ";", "}", "catch", "(", "AmazonServiceException", "e", ")", "{", "LibraryUtils", ".", "handleException", "(", "exceptionHandler", ",", "progressStatus", ",", "e", ",", "\"Failed to delete sqs message.\"", ")", ";", "}", "LibraryUtils", ".", "endToProcess", "(", "progressReporter", ",", "deleteMessageSuccess", ",", "progressStatus", ",", "reportObject", ")", ";", "}" ]
Delete a message from the SQS queue that you specified in the configuration file. @param sqsMessage the {@link Message} that you want to delete. @param progressStatus {@link ProgressStatus} tracks the start and end status.
[ "Delete", "a", "message", "from", "the", "SQS", "queue", "that", "you", "specified", "in", "the", "configuration", "file", "." ]
train
https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/manager/SqsManager.java#L185-L195
opsmatters/newrelic-api
src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java
HttpContext.PUT
public <T> Optional<T> PUT(String partialUrl, Object payload, Map<String, Object> headers, List<String> queryParams, GenericType<T> returnType) { """ Execute a PUT call against the partial URL. @param <T> The type parameter used for the return object @param partialUrl The partial URL to build @param payload The object to use for the PUT @param headers A set of headers to add to the request @param queryParams A set of query parameters to add to the request @param returnType The expected return type @return The return type """ URI uri = buildUri(partialUrl); return executePutRequest(uri, payload, headers, queryParams, returnType); }
java
public <T> Optional<T> PUT(String partialUrl, Object payload, Map<String, Object> headers, List<String> queryParams, GenericType<T> returnType) { URI uri = buildUri(partialUrl); return executePutRequest(uri, payload, headers, queryParams, returnType); }
[ "public", "<", "T", ">", "Optional", "<", "T", ">", "PUT", "(", "String", "partialUrl", ",", "Object", "payload", ",", "Map", "<", "String", ",", "Object", ">", "headers", ",", "List", "<", "String", ">", "queryParams", ",", "GenericType", "<", "T", ">", "returnType", ")", "{", "URI", "uri", "=", "buildUri", "(", "partialUrl", ")", ";", "return", "executePutRequest", "(", "uri", ",", "payload", ",", "headers", ",", "queryParams", ",", "returnType", ")", ";", "}" ]
Execute a PUT call against the partial URL. @param <T> The type parameter used for the return object @param partialUrl The partial URL to build @param payload The object to use for the PUT @param headers A set of headers to add to the request @param queryParams A set of query parameters to add to the request @param returnType The expected return type @return The return type
[ "Execute", "a", "PUT", "call", "against", "the", "partial", "URL", "." ]
train
https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java#L180-L185
opentable/otj-pg-embedded
src/main/java/com/opentable/db/postgres/embedded/PreparedDbProvider.java
PreparedDbProvider.createOrFindPreparer
private static synchronized PrepPipeline createOrFindPreparer(DatabasePreparer preparer, Iterable<Consumer<Builder>> customizers) throws IOException, SQLException { """ Each schema set has its own database cluster. The template1 database has the schema preloaded so that each test case need only create a new database and not re-invoke your preparer. """ final ClusterKey key = new ClusterKey(preparer, customizers); PrepPipeline result = CLUSTERS.get(key); if (result != null) { return result; } final Builder builder = EmbeddedPostgres.builder(); customizers.forEach(c -> c.accept(builder)); final EmbeddedPostgres pg = builder.start(); preparer.prepare(pg.getTemplateDatabase()); result = new PrepPipeline(pg).start(); CLUSTERS.put(key, result); return result; }
java
private static synchronized PrepPipeline createOrFindPreparer(DatabasePreparer preparer, Iterable<Consumer<Builder>> customizers) throws IOException, SQLException { final ClusterKey key = new ClusterKey(preparer, customizers); PrepPipeline result = CLUSTERS.get(key); if (result != null) { return result; } final Builder builder = EmbeddedPostgres.builder(); customizers.forEach(c -> c.accept(builder)); final EmbeddedPostgres pg = builder.start(); preparer.prepare(pg.getTemplateDatabase()); result = new PrepPipeline(pg).start(); CLUSTERS.put(key, result); return result; }
[ "private", "static", "synchronized", "PrepPipeline", "createOrFindPreparer", "(", "DatabasePreparer", "preparer", ",", "Iterable", "<", "Consumer", "<", "Builder", ">", ">", "customizers", ")", "throws", "IOException", ",", "SQLException", "{", "final", "ClusterKey", "key", "=", "new", "ClusterKey", "(", "preparer", ",", "customizers", ")", ";", "PrepPipeline", "result", "=", "CLUSTERS", ".", "get", "(", "key", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "return", "result", ";", "}", "final", "Builder", "builder", "=", "EmbeddedPostgres", ".", "builder", "(", ")", ";", "customizers", ".", "forEach", "(", "c", "->", "c", ".", "accept", "(", "builder", ")", ")", ";", "final", "EmbeddedPostgres", "pg", "=", "builder", ".", "start", "(", ")", ";", "preparer", ".", "prepare", "(", "pg", ".", "getTemplateDatabase", "(", ")", ")", ";", "result", "=", "new", "PrepPipeline", "(", "pg", ")", ".", "start", "(", ")", ";", "CLUSTERS", ".", "put", "(", "key", ",", "result", ")", ";", "return", "result", ";", "}" ]
Each schema set has its own database cluster. The template1 database has the schema preloaded so that each test case need only create a new database and not re-invoke your preparer.
[ "Each", "schema", "set", "has", "its", "own", "database", "cluster", ".", "The", "template1", "database", "has", "the", "schema", "preloaded", "so", "that", "each", "test", "case", "need", "only", "create", "a", "new", "database", "and", "not", "re", "-", "invoke", "your", "preparer", "." ]
train
https://github.com/opentable/otj-pg-embedded/blob/0f94ce9677f004959c23a7a4a825a606267d4aa9/src/main/java/com/opentable/db/postgres/embedded/PreparedDbProvider.java#L72-L88
elki-project/elki
addons/xtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/spatial/rstarvariants/xtree/util/XSplitter.java
XSplitter.topologicalSplit
public SplitSorting topologicalSplit() { """ Perform a topological (R*-Tree) split of a list of node entries. <p> Only distributions that have between <code>m</code> and <code>M-m+1</code> entries in the first group will be tested. @return chosen split distribution; note that this method returns null, if the minimum overlap split has a volume which is larger than the allowed <code>maxOverlap</code> ratio of #tree """ if(node.getNumEntries() < 2) { throw new IllegalArgumentException("Splitting less than two entries is pointless."); } int minEntries = (node.getEntry(0) instanceof LeafEntry ? tree.getLeafMinimum() : tree.getDirMinimum()); int maxEntries = (node.getEntry(0) instanceof LeafEntry ? tree.getLeafCapacity() - 1 : tree.getDirCapacity() - 1); if(node.getNumEntries() < maxEntries) { throw new IllegalArgumentException("This entry list has not yet reached the maximum limit: " + node.getNumEntries() + "<=" + maxEntries); } maxEntries = maxEntries + 1 - minEntries; chooseSplitAxis(new IntegerRangeIterator(0, node.getEntry(0).getDimensionality()), minEntries, maxEntries); return chooseMinimumOverlapSplit(splitAxis, minEntries, maxEntries, false); }
java
public SplitSorting topologicalSplit() { if(node.getNumEntries() < 2) { throw new IllegalArgumentException("Splitting less than two entries is pointless."); } int minEntries = (node.getEntry(0) instanceof LeafEntry ? tree.getLeafMinimum() : tree.getDirMinimum()); int maxEntries = (node.getEntry(0) instanceof LeafEntry ? tree.getLeafCapacity() - 1 : tree.getDirCapacity() - 1); if(node.getNumEntries() < maxEntries) { throw new IllegalArgumentException("This entry list has not yet reached the maximum limit: " + node.getNumEntries() + "<=" + maxEntries); } maxEntries = maxEntries + 1 - minEntries; chooseSplitAxis(new IntegerRangeIterator(0, node.getEntry(0).getDimensionality()), minEntries, maxEntries); return chooseMinimumOverlapSplit(splitAxis, minEntries, maxEntries, false); }
[ "public", "SplitSorting", "topologicalSplit", "(", ")", "{", "if", "(", "node", ".", "getNumEntries", "(", ")", "<", "2", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Splitting less than two entries is pointless.\"", ")", ";", "}", "int", "minEntries", "=", "(", "node", ".", "getEntry", "(", "0", ")", "instanceof", "LeafEntry", "?", "tree", ".", "getLeafMinimum", "(", ")", ":", "tree", ".", "getDirMinimum", "(", ")", ")", ";", "int", "maxEntries", "=", "(", "node", ".", "getEntry", "(", "0", ")", "instanceof", "LeafEntry", "?", "tree", ".", "getLeafCapacity", "(", ")", "-", "1", ":", "tree", ".", "getDirCapacity", "(", ")", "-", "1", ")", ";", "if", "(", "node", ".", "getNumEntries", "(", ")", "<", "maxEntries", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"This entry list has not yet reached the maximum limit: \"", "+", "node", ".", "getNumEntries", "(", ")", "+", "\"<=\"", "+", "maxEntries", ")", ";", "}", "maxEntries", "=", "maxEntries", "+", "1", "-", "minEntries", ";", "chooseSplitAxis", "(", "new", "IntegerRangeIterator", "(", "0", ",", "node", ".", "getEntry", "(", "0", ")", ".", "getDimensionality", "(", ")", ")", ",", "minEntries", ",", "maxEntries", ")", ";", "return", "chooseMinimumOverlapSplit", "(", "splitAxis", ",", "minEntries", ",", "maxEntries", ",", "false", ")", ";", "}" ]
Perform a topological (R*-Tree) split of a list of node entries. <p> Only distributions that have between <code>m</code> and <code>M-m+1</code> entries in the first group will be tested. @return chosen split distribution; note that this method returns null, if the minimum overlap split has a volume which is larger than the allowed <code>maxOverlap</code> ratio of #tree
[ "Perform", "a", "topological", "(", "R", "*", "-", "Tree", ")", "split", "of", "a", "list", "of", "node", "entries", ".", "<p", ">", "Only", "distributions", "that", "have", "between", "<code", ">", "m<", "/", "code", ">", "and", "<code", ">", "M", "-", "m", "+", "1<", "/", "code", ">", "entries", "in", "the", "first", "group", "will", "be", "tested", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/xtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/spatial/rstarvariants/xtree/util/XSplitter.java#L699-L713
apptik/jus
benchmark/src/perf/java/com/android/volley/VolleyLog.java
VolleyLog.buildMessage
private static String buildMessage(String format, Object... args) { """ Formats the caller's provided message and prepends useful info like calling thread ID and method name. """ String msg = (args == null) ? format : String.format(Locale.US, format, args); StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace(); String caller = "<unknown>"; // Walk up the stack looking for the first caller outside of VolleyLog. // It will be at least two frames up, so start there. for (int i = 2; i < trace.length; i++) { Class<?> clazz = trace[i].getClass(); if (!clazz.equals(VolleyLog.class)) { String callingClass = trace[i].getClassName(); callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1); callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1); caller = callingClass + "." + trace[i].getMethodName(); break; } } return String.format(Locale.US, "[%d] %s: %s", Thread.currentThread().getId(), caller, msg); }
java
private static String buildMessage(String format, Object... args) { String msg = (args == null) ? format : String.format(Locale.US, format, args); StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace(); String caller = "<unknown>"; // Walk up the stack looking for the first caller outside of VolleyLog. // It will be at least two frames up, so start there. for (int i = 2; i < trace.length; i++) { Class<?> clazz = trace[i].getClass(); if (!clazz.equals(VolleyLog.class)) { String callingClass = trace[i].getClassName(); callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1); callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1); caller = callingClass + "." + trace[i].getMethodName(); break; } } return String.format(Locale.US, "[%d] %s: %s", Thread.currentThread().getId(), caller, msg); }
[ "private", "static", "String", "buildMessage", "(", "String", "format", ",", "Object", "...", "args", ")", "{", "String", "msg", "=", "(", "args", "==", "null", ")", "?", "format", ":", "String", ".", "format", "(", "Locale", ".", "US", ",", "format", ",", "args", ")", ";", "StackTraceElement", "[", "]", "trace", "=", "new", "Throwable", "(", ")", ".", "fillInStackTrace", "(", ")", ".", "getStackTrace", "(", ")", ";", "String", "caller", "=", "\"<unknown>\"", ";", "// Walk up the stack looking for the first caller outside of VolleyLog.", "// It will be at least two frames up, so start there.", "for", "(", "int", "i", "=", "2", ";", "i", "<", "trace", ".", "length", ";", "i", "++", ")", "{", "Class", "<", "?", ">", "clazz", "=", "trace", "[", "i", "]", ".", "getClass", "(", ")", ";", "if", "(", "!", "clazz", ".", "equals", "(", "VolleyLog", ".", "class", ")", ")", "{", "String", "callingClass", "=", "trace", "[", "i", "]", ".", "getClassName", "(", ")", ";", "callingClass", "=", "callingClass", ".", "substring", "(", "callingClass", ".", "lastIndexOf", "(", "'", "'", ")", "+", "1", ")", ";", "callingClass", "=", "callingClass", ".", "substring", "(", "callingClass", ".", "lastIndexOf", "(", "'", "'", ")", "+", "1", ")", ";", "caller", "=", "callingClass", "+", "\".\"", "+", "trace", "[", "i", "]", ".", "getMethodName", "(", ")", ";", "break", ";", "}", "}", "return", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"[%d] %s: %s\"", ",", "Thread", ".", "currentThread", "(", ")", ".", "getId", "(", ")", ",", "caller", ",", "msg", ")", ";", "}" ]
Formats the caller's provided message and prepends useful info like calling thread ID and method name.
[ "Formats", "the", "caller", "s", "provided", "message", "and", "prepends", "useful", "info", "like", "calling", "thread", "ID", "and", "method", "name", "." ]
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/benchmark/src/perf/java/com/android/volley/VolleyLog.java#L80-L100
wcm-io/wcm-io-sling
commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java
RequestParam.getDouble
public static double getDouble(@NotNull ServletRequest request, @NotNull String param) { """ Returns a request parameter as double. @param request Request. @param param Parameter name. @return Parameter value or 0 if it does not exist or is not a number. """ return getDouble(request, param, 0d); }
java
public static double getDouble(@NotNull ServletRequest request, @NotNull String param) { return getDouble(request, param, 0d); }
[ "public", "static", "double", "getDouble", "(", "@", "NotNull", "ServletRequest", "request", ",", "@", "NotNull", "String", "param", ")", "{", "return", "getDouble", "(", "request", ",", "param", ",", "0d", ")", ";", "}" ]
Returns a request parameter as double. @param request Request. @param param Parameter name. @return Parameter value or 0 if it does not exist or is not a number.
[ "Returns", "a", "request", "parameter", "as", "double", "." ]
train
https://github.com/wcm-io/wcm-io-sling/blob/90adbe432469378794b5695c72e9cdfa2b7d36f1/commons/src/main/java/io/wcm/sling/commons/request/RequestParam.java#L211-L213
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/hash/MutableHashTable.java
MutableHashTable.buildBloomFilterForBucket
final void buildBloomFilterForBucket(int bucketInSegmentPos, MemorySegment bucket, HashPartition<BT, PT> p) { """ Set all the bucket memory except bucket header as the bit set of bloom filter, and use hash code of build records to build bloom filter. """ final int count = bucket.getShort(bucketInSegmentPos + HEADER_COUNT_OFFSET); if (count <= 0) { return; } int[] hashCodes = new int[count]; // As the hashcode and bloom filter occupy same bytes, so we read all hashcode out at first and then write back to bloom filter. for (int i = 0; i < count; i++) { hashCodes[i] = bucket.getInt(bucketInSegmentPos + BUCKET_HEADER_LENGTH + i * HASH_CODE_LEN); } this.bloomFilter.setBitsLocation(bucket, bucketInSegmentPos + BUCKET_HEADER_LENGTH); for (int hashCode : hashCodes) { this.bloomFilter.addHash(hashCode); } buildBloomFilterForExtraOverflowSegments(bucketInSegmentPos, bucket, p); }
java
final void buildBloomFilterForBucket(int bucketInSegmentPos, MemorySegment bucket, HashPartition<BT, PT> p) { final int count = bucket.getShort(bucketInSegmentPos + HEADER_COUNT_OFFSET); if (count <= 0) { return; } int[] hashCodes = new int[count]; // As the hashcode and bloom filter occupy same bytes, so we read all hashcode out at first and then write back to bloom filter. for (int i = 0; i < count; i++) { hashCodes[i] = bucket.getInt(bucketInSegmentPos + BUCKET_HEADER_LENGTH + i * HASH_CODE_LEN); } this.bloomFilter.setBitsLocation(bucket, bucketInSegmentPos + BUCKET_HEADER_LENGTH); for (int hashCode : hashCodes) { this.bloomFilter.addHash(hashCode); } buildBloomFilterForExtraOverflowSegments(bucketInSegmentPos, bucket, p); }
[ "final", "void", "buildBloomFilterForBucket", "(", "int", "bucketInSegmentPos", ",", "MemorySegment", "bucket", ",", "HashPartition", "<", "BT", ",", "PT", ">", "p", ")", "{", "final", "int", "count", "=", "bucket", ".", "getShort", "(", "bucketInSegmentPos", "+", "HEADER_COUNT_OFFSET", ")", ";", "if", "(", "count", "<=", "0", ")", "{", "return", ";", "}", "int", "[", "]", "hashCodes", "=", "new", "int", "[", "count", "]", ";", "// As the hashcode and bloom filter occupy same bytes, so we read all hashcode out at first and then write back to bloom filter.", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "hashCodes", "[", "i", "]", "=", "bucket", ".", "getInt", "(", "bucketInSegmentPos", "+", "BUCKET_HEADER_LENGTH", "+", "i", "*", "HASH_CODE_LEN", ")", ";", "}", "this", ".", "bloomFilter", ".", "setBitsLocation", "(", "bucket", ",", "bucketInSegmentPos", "+", "BUCKET_HEADER_LENGTH", ")", ";", "for", "(", "int", "hashCode", ":", "hashCodes", ")", "{", "this", ".", "bloomFilter", ".", "addHash", "(", "hashCode", ")", ";", "}", "buildBloomFilterForExtraOverflowSegments", "(", "bucketInSegmentPos", ",", "bucket", ",", "p", ")", ";", "}" ]
Set all the bucket memory except bucket header as the bit set of bloom filter, and use hash code of build records to build bloom filter.
[ "Set", "all", "the", "bucket", "memory", "except", "bucket", "header", "as", "the", "bit", "set", "of", "bloom", "filter", "and", "use", "hash", "code", "of", "build", "records", "to", "build", "bloom", "filter", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/operators/hash/MutableHashTable.java#L1269-L1285
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/destination/LocalQueue.java
LocalQueue.notifyConsumer
private void notifyConsumer( AbstractMessage message ) { """ Notify a consumer that a message is probably available for it to retrieve """ consumersLock.readLock().lock(); try { switch (localConsumers.size()) { case 0 : return; // Nobody's listening case 1 : notifySingleConsumer(localConsumers.get(0),message); break; default : // Multiple consumers notifyNextConsumer(localConsumers,message); break; } } finally { consumersLock.readLock().unlock(); } }
java
private void notifyConsumer( AbstractMessage message ) { consumersLock.readLock().lock(); try { switch (localConsumers.size()) { case 0 : return; // Nobody's listening case 1 : notifySingleConsumer(localConsumers.get(0),message); break; default : // Multiple consumers notifyNextConsumer(localConsumers,message); break; } } finally { consumersLock.readLock().unlock(); } }
[ "private", "void", "notifyConsumer", "(", "AbstractMessage", "message", ")", "{", "consumersLock", ".", "readLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "switch", "(", "localConsumers", ".", "size", "(", ")", ")", "{", "case", "0", ":", "return", ";", "// Nobody's listening", "case", "1", ":", "notifySingleConsumer", "(", "localConsumers", ".", "get", "(", "0", ")", ",", "message", ")", ";", "break", ";", "default", ":", "// Multiple consumers", "notifyNextConsumer", "(", "localConsumers", ",", "message", ")", ";", "break", ";", "}", "}", "finally", "{", "consumersLock", ".", "readLock", "(", ")", ".", "unlock", "(", ")", ";", "}", "}" ]
Notify a consumer that a message is probably available for it to retrieve
[ "Notify", "a", "consumer", "that", "a", "message", "is", "probably", "available", "for", "it", "to", "retrieve" ]
train
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/destination/LocalQueue.java#L706-L726
gallandarakhneorg/afc
advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/dfx/Sphere3dfx.java
Sphere3dfx.radiusProperty
@Pure public DoubleProperty radiusProperty() { """ Replies the property that is the radius of the circle. @return the radius property. """ if (this.radius == null) { this.radius = new SimpleDoubleProperty(this, MathFXAttributeNames.RADIUS) { @Override protected void invalidated() { if (get() < 0.) { set(0.); } } }; } return this.radius; }
java
@Pure public DoubleProperty radiusProperty() { if (this.radius == null) { this.radius = new SimpleDoubleProperty(this, MathFXAttributeNames.RADIUS) { @Override protected void invalidated() { if (get() < 0.) { set(0.); } } }; } return this.radius; }
[ "@", "Pure", "public", "DoubleProperty", "radiusProperty", "(", ")", "{", "if", "(", "this", ".", "radius", "==", "null", ")", "{", "this", ".", "radius", "=", "new", "SimpleDoubleProperty", "(", "this", ",", "MathFXAttributeNames", ".", "RADIUS", ")", "{", "@", "Override", "protected", "void", "invalidated", "(", ")", "{", "if", "(", "get", "(", ")", "<", "0.", ")", "{", "set", "(", "0.", ")", ";", "}", "}", "}", ";", "}", "return", "this", ".", "radius", ";", "}" ]
Replies the property that is the radius of the circle. @return the radius property.
[ "Replies", "the", "property", "that", "is", "the", "radius", "of", "the", "circle", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/dfx/Sphere3dfx.java#L216-L229
biojava/biojava
biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java
TranscriptSequence.addCDS
public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) throws Exception { """ Add a Coding Sequence region with phase to the transcript sequence @param accession @param begin @param end @param phase 0,1,2 @return """ if (cdsSequenceHashMap.containsKey(accession.getID())) { throw new Exception("Duplicate accesion id " + accession.getID()); } CDSSequence cdsSequence = new CDSSequence(this, begin, end, phase); //sense should be the same as parent cdsSequence.setAccession(accession); cdsSequenceList.add(cdsSequence); Collections.sort(cdsSequenceList, new CDSComparator()); cdsSequenceHashMap.put(accession.getID(), cdsSequence); return cdsSequence; }
java
public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) throws Exception { if (cdsSequenceHashMap.containsKey(accession.getID())) { throw new Exception("Duplicate accesion id " + accession.getID()); } CDSSequence cdsSequence = new CDSSequence(this, begin, end, phase); //sense should be the same as parent cdsSequence.setAccession(accession); cdsSequenceList.add(cdsSequence); Collections.sort(cdsSequenceList, new CDSComparator()); cdsSequenceHashMap.put(accession.getID(), cdsSequence); return cdsSequence; }
[ "public", "CDSSequence", "addCDS", "(", "AccessionID", "accession", ",", "int", "begin", ",", "int", "end", ",", "int", "phase", ")", "throws", "Exception", "{", "if", "(", "cdsSequenceHashMap", ".", "containsKey", "(", "accession", ".", "getID", "(", ")", ")", ")", "{", "throw", "new", "Exception", "(", "\"Duplicate accesion id \"", "+", "accession", ".", "getID", "(", ")", ")", ";", "}", "CDSSequence", "cdsSequence", "=", "new", "CDSSequence", "(", "this", ",", "begin", ",", "end", ",", "phase", ")", ";", "//sense should be the same as parent", "cdsSequence", ".", "setAccession", "(", "accession", ")", ";", "cdsSequenceList", ".", "add", "(", "cdsSequence", ")", ";", "Collections", ".", "sort", "(", "cdsSequenceList", ",", "new", "CDSComparator", "(", ")", ")", ";", "cdsSequenceHashMap", ".", "put", "(", "accession", ".", "getID", "(", ")", ",", "cdsSequence", ")", ";", "return", "cdsSequence", ";", "}" ]
Add a Coding Sequence region with phase to the transcript sequence @param accession @param begin @param end @param phase 0,1,2 @return
[ "Add", "a", "Coding", "Sequence", "region", "with", "phase", "to", "the", "transcript", "sequence" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java#L109-L119
jeremylong/DependencyCheck
utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java
Settings.getBoolean
public boolean getBoolean(@NotNull final String key, boolean defaultValue) throws InvalidSettingException { """ Returns a boolean value from the properties file. If the value was specified as a system property or passed in via the <code>-Dprop=value</code> argument this method will return the value from the system properties before the values in the contained configuration file. @param key the key to lookup within the properties file @param defaultValue the default value to return if the setting does not exist @return the property from the properties file @throws org.owasp.dependencycheck.utils.InvalidSettingException is thrown if there is an error retrieving the setting """ return Boolean.parseBoolean(getString(key, Boolean.toString(defaultValue))); }
java
public boolean getBoolean(@NotNull final String key, boolean defaultValue) throws InvalidSettingException { return Boolean.parseBoolean(getString(key, Boolean.toString(defaultValue))); }
[ "public", "boolean", "getBoolean", "(", "@", "NotNull", "final", "String", "key", ",", "boolean", "defaultValue", ")", "throws", "InvalidSettingException", "{", "return", "Boolean", ".", "parseBoolean", "(", "getString", "(", "key", ",", "Boolean", ".", "toString", "(", "defaultValue", ")", ")", ")", ";", "}" ]
Returns a boolean value from the properties file. If the value was specified as a system property or passed in via the <code>-Dprop=value</code> argument this method will return the value from the system properties before the values in the contained configuration file. @param key the key to lookup within the properties file @param defaultValue the default value to return if the setting does not exist @return the property from the properties file @throws org.owasp.dependencycheck.utils.InvalidSettingException is thrown if there is an error retrieving the setting
[ "Returns", "a", "boolean", "value", "from", "the", "properties", "file", ".", "If", "the", "value", "was", "specified", "as", "a", "system", "property", "or", "passed", "in", "via", "the", "<code", ">", "-", "Dprop", "=", "value<", "/", "code", ">", "argument", "this", "method", "will", "return", "the", "value", "from", "the", "system", "properties", "before", "the", "values", "in", "the", "contained", "configuration", "file", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java#L1056-L1058
Azure/azure-sdk-for-java
eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/EventGridSubscriber.java
EventGridSubscriber.putCustomEventMapping
@Beta public void putCustomEventMapping(final String eventType, final Type eventDataType) { """ Add a custom event mapping. If a mapping with same eventType exists then the old eventDataType is replaced by the specified eventDataType. @param eventType the event type name. @param eventDataType type of the Java model that the event type name mapped to. """ if (eventType == null || eventType.isEmpty()) { throw new IllegalArgumentException("eventType parameter is required and cannot be null or empty"); } if (eventDataType == null) { throw new IllegalArgumentException("eventDataType parameter is required and cannot be null"); } this.eventTypeToEventDataMapping.put(canonicalizeEventType(eventType), eventDataType); }
java
@Beta public void putCustomEventMapping(final String eventType, final Type eventDataType) { if (eventType == null || eventType.isEmpty()) { throw new IllegalArgumentException("eventType parameter is required and cannot be null or empty"); } if (eventDataType == null) { throw new IllegalArgumentException("eventDataType parameter is required and cannot be null"); } this.eventTypeToEventDataMapping.put(canonicalizeEventType(eventType), eventDataType); }
[ "@", "Beta", "public", "void", "putCustomEventMapping", "(", "final", "String", "eventType", ",", "final", "Type", "eventDataType", ")", "{", "if", "(", "eventType", "==", "null", "||", "eventType", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"eventType parameter is required and cannot be null or empty\"", ")", ";", "}", "if", "(", "eventDataType", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"eventDataType parameter is required and cannot be null\"", ")", ";", "}", "this", ".", "eventTypeToEventDataMapping", ".", "put", "(", "canonicalizeEventType", "(", "eventType", ")", ",", "eventDataType", ")", ";", "}" ]
Add a custom event mapping. If a mapping with same eventType exists then the old eventDataType is replaced by the specified eventDataType. @param eventType the event type name. @param eventDataType type of the Java model that the event type name mapped to.
[ "Add", "a", "custom", "event", "mapping", ".", "If", "a", "mapping", "with", "same", "eventType", "exists", "then", "the", "old", "eventDataType", "is", "replaced", "by", "the", "specified", "eventDataType", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/EventGridSubscriber.java#L52-L61
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/adapter/PropertyAdapter.java
PropertyAdapter.generateArrayExample
private static Object generateArrayExample(ArrayProperty property, MarkupDocBuilder markupDocBuilder) { """ Generate example for an ArrayProperty @param property ArrayProperty to generate example for @param markupDocBuilder MarkupDocBuilder containing all associated settings @return String example """ Property itemProperty = property.getItems(); List<Object> exampleArray = new ArrayList<>(); exampleArray.add(generateExample(itemProperty, markupDocBuilder)); return exampleArray; }
java
private static Object generateArrayExample(ArrayProperty property, MarkupDocBuilder markupDocBuilder) { Property itemProperty = property.getItems(); List<Object> exampleArray = new ArrayList<>(); exampleArray.add(generateExample(itemProperty, markupDocBuilder)); return exampleArray; }
[ "private", "static", "Object", "generateArrayExample", "(", "ArrayProperty", "property", ",", "MarkupDocBuilder", "markupDocBuilder", ")", "{", "Property", "itemProperty", "=", "property", ".", "getItems", "(", ")", ";", "List", "<", "Object", ">", "exampleArray", "=", "new", "ArrayList", "<>", "(", ")", ";", "exampleArray", ".", "add", "(", "generateExample", "(", "itemProperty", ",", "markupDocBuilder", ")", ")", ";", "return", "exampleArray", ";", "}" ]
Generate example for an ArrayProperty @param property ArrayProperty to generate example for @param markupDocBuilder MarkupDocBuilder containing all associated settings @return String example
[ "Generate", "example", "for", "an", "ArrayProperty" ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/adapter/PropertyAdapter.java#L114-L120
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_storage_containerId_publicUrl_POST
public OvhContainerObjectTempURL project_serviceName_storage_containerId_publicUrl_POST(String serviceName, String containerId, Date expirationDate, String objectName) throws IOException { """ Get a public temporary URL to access to one of your object REST: POST /cloud/project/{serviceName}/storage/{containerId}/publicUrl @param containerId [required] Container ID @param expirationDate [required] Temporary URL expiration @param objectName [required] Object name @param serviceName [required] Service name """ String qPath = "/cloud/project/{serviceName}/storage/{containerId}/publicUrl"; StringBuilder sb = path(qPath, serviceName, containerId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "expirationDate", expirationDate); addBody(o, "objectName", objectName); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhContainerObjectTempURL.class); }
java
public OvhContainerObjectTempURL project_serviceName_storage_containerId_publicUrl_POST(String serviceName, String containerId, Date expirationDate, String objectName) throws IOException { String qPath = "/cloud/project/{serviceName}/storage/{containerId}/publicUrl"; StringBuilder sb = path(qPath, serviceName, containerId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "expirationDate", expirationDate); addBody(o, "objectName", objectName); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhContainerObjectTempURL.class); }
[ "public", "OvhContainerObjectTempURL", "project_serviceName_storage_containerId_publicUrl_POST", "(", "String", "serviceName", ",", "String", "containerId", ",", "Date", "expirationDate", ",", "String", "objectName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/storage/{containerId}/publicUrl\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "containerId", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"expirationDate\"", ",", "expirationDate", ")", ";", "addBody", "(", "o", ",", "\"objectName\"", ",", "objectName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhContainerObjectTempURL", ".", "class", ")", ";", "}" ]
Get a public temporary URL to access to one of your object REST: POST /cloud/project/{serviceName}/storage/{containerId}/publicUrl @param containerId [required] Container ID @param expirationDate [required] Temporary URL expiration @param objectName [required] Object name @param serviceName [required] Service name
[ "Get", "a", "public", "temporary", "URL", "to", "access", "to", "one", "of", "your", "object" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L589-L597
OpenLiberty/open-liberty
dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/util/Util.java
Util.writeTokenLength
private static void writeTokenLength(ByteArrayOutputStream baos, int tokenLength) { """ /* Write the token length in the same way as in tWAS to ensure compatibility. """ if (tokenLength < 128) { baos.write((byte) tokenLength); } else if (tokenLength < (1 << 8)) { baos.write((byte) 0x081); baos.write((byte) tokenLength); } else if (tokenLength < (1 << 16)) { baos.write((byte) 0x082); baos.write((byte) (tokenLength >> 8)); baos.write((byte) tokenLength); } else if (tokenLength < (1 << 24)) { baos.write((byte) 0x083); baos.write((byte) (tokenLength >> 16)); baos.write((byte) (tokenLength >> 8)); baos.write((byte) tokenLength); } else { baos.write((byte) 0x084); baos.write((byte) (tokenLength >> 24)); baos.write((byte) (tokenLength >> 16)); baos.write((byte) (tokenLength >> 8)); baos.write((byte) tokenLength); } }
java
private static void writeTokenLength(ByteArrayOutputStream baos, int tokenLength) { if (tokenLength < 128) { baos.write((byte) tokenLength); } else if (tokenLength < (1 << 8)) { baos.write((byte) 0x081); baos.write((byte) tokenLength); } else if (tokenLength < (1 << 16)) { baos.write((byte) 0x082); baos.write((byte) (tokenLength >> 8)); baos.write((byte) tokenLength); } else if (tokenLength < (1 << 24)) { baos.write((byte) 0x083); baos.write((byte) (tokenLength >> 16)); baos.write((byte) (tokenLength >> 8)); baos.write((byte) tokenLength); } else { baos.write((byte) 0x084); baos.write((byte) (tokenLength >> 24)); baos.write((byte) (tokenLength >> 16)); baos.write((byte) (tokenLength >> 8)); baos.write((byte) tokenLength); } }
[ "private", "static", "void", "writeTokenLength", "(", "ByteArrayOutputStream", "baos", ",", "int", "tokenLength", ")", "{", "if", "(", "tokenLength", "<", "128", ")", "{", "baos", ".", "write", "(", "(", "byte", ")", "tokenLength", ")", ";", "}", "else", "if", "(", "tokenLength", "<", "(", "1", "<<", "8", ")", ")", "{", "baos", ".", "write", "(", "(", "byte", ")", "0x081", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "tokenLength", ")", ";", "}", "else", "if", "(", "tokenLength", "<", "(", "1", "<<", "16", ")", ")", "{", "baos", ".", "write", "(", "(", "byte", ")", "0x082", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "(", "tokenLength", ">>", "8", ")", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "tokenLength", ")", ";", "}", "else", "if", "(", "tokenLength", "<", "(", "1", "<<", "24", ")", ")", "{", "baos", ".", "write", "(", "(", "byte", ")", "0x083", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "(", "tokenLength", ">>", "16", ")", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "(", "tokenLength", ">>", "8", ")", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "tokenLength", ")", ";", "}", "else", "{", "baos", ".", "write", "(", "(", "byte", ")", "0x084", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "(", "tokenLength", ">>", "24", ")", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "(", "tokenLength", ">>", "16", ")", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "(", "tokenLength", ">>", "8", ")", ")", ";", "baos", ".", "write", "(", "(", "byte", ")", "tokenLength", ")", ";", "}", "}" ]
/* Write the token length in the same way as in tWAS to ensure compatibility.
[ "/", "*", "Write", "the", "token", "length", "in", "the", "same", "way", "as", "in", "tWAS", "to", "ensure", "compatibility", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/util/Util.java#L471-L493
eclipse/hawkbit
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java
RepositoryApplicationConfiguration.eventEntityManager
@Bean @ConditionalOnMissingBean EventEntityManager eventEntityManager(final TenantAware aware, final EntityManager entityManager) { """ {@link EventEntityManager} bean. @param aware the tenant aware @param entityManager the entitymanager @return a new {@link EventEntityManager} """ return new JpaEventEntityManager(aware, entityManager); }
java
@Bean @ConditionalOnMissingBean EventEntityManager eventEntityManager(final TenantAware aware, final EntityManager entityManager) { return new JpaEventEntityManager(aware, entityManager); }
[ "@", "Bean", "@", "ConditionalOnMissingBean", "EventEntityManager", "eventEntityManager", "(", "final", "TenantAware", "aware", ",", "final", "EntityManager", "entityManager", ")", "{", "return", "new", "JpaEventEntityManager", "(", "aware", ",", "entityManager", ")", ";", "}" ]
{@link EventEntityManager} bean. @param aware the tenant aware @param entityManager the entitymanager @return a new {@link EventEntityManager}
[ "{", "@link", "EventEntityManager", "}", "bean", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RepositoryApplicationConfiguration.java#L737-L741
elki-project/elki
elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/data/VectorUtil.java
VectorUtil.dotSparseDense
public static double dotSparseDense(SparseNumberVector v1, NumberVector v2) { """ Compute the dot product for a sparse and a dense vector. @param v1 Sparse first vector @param v2 Dense second vector @return dot product """ final int dim2 = v2.getDimensionality(); double dot = 0.; for(int i1 = v1.iter(); v1.iterValid(i1);) { final int d1 = v1.iterDim(i1); if(d1 >= dim2) { break; } dot += v1.iterDoubleValue(i1) * v2.doubleValue(d1); i1 = v1.iterAdvance(i1); } return dot; }
java
public static double dotSparseDense(SparseNumberVector v1, NumberVector v2) { final int dim2 = v2.getDimensionality(); double dot = 0.; for(int i1 = v1.iter(); v1.iterValid(i1);) { final int d1 = v1.iterDim(i1); if(d1 >= dim2) { break; } dot += v1.iterDoubleValue(i1) * v2.doubleValue(d1); i1 = v1.iterAdvance(i1); } return dot; }
[ "public", "static", "double", "dotSparseDense", "(", "SparseNumberVector", "v1", ",", "NumberVector", "v2", ")", "{", "final", "int", "dim2", "=", "v2", ".", "getDimensionality", "(", ")", ";", "double", "dot", "=", "0.", ";", "for", "(", "int", "i1", "=", "v1", ".", "iter", "(", ")", ";", "v1", ".", "iterValid", "(", "i1", ")", ";", ")", "{", "final", "int", "d1", "=", "v1", ".", "iterDim", "(", "i1", ")", ";", "if", "(", "d1", ">=", "dim2", ")", "{", "break", ";", "}", "dot", "+=", "v1", ".", "iterDoubleValue", "(", "i1", ")", "*", "v2", ".", "doubleValue", "(", "d1", ")", ";", "i1", "=", "v1", ".", "iterAdvance", "(", "i1", ")", ";", "}", "return", "dot", ";", "}" ]
Compute the dot product for a sparse and a dense vector. @param v1 Sparse first vector @param v2 Dense second vector @return dot product
[ "Compute", "the", "dot", "product", "for", "a", "sparse", "and", "a", "dense", "vector", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/data/VectorUtil.java#L392-L404
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/io/FileSupport.java
FileSupport.getDirectoriesInDirectoryTree
public static ArrayList<File> getDirectoriesInDirectoryTree(String path) { """ Retrieves all directories from a directory and its subdirectories. @param path path to directory @return A list containing the found directories """ File file = new File(path); return getContentsInDirectoryTree(file, "*", false, true); }
java
public static ArrayList<File> getDirectoriesInDirectoryTree(String path) { File file = new File(path); return getContentsInDirectoryTree(file, "*", false, true); }
[ "public", "static", "ArrayList", "<", "File", ">", "getDirectoriesInDirectoryTree", "(", "String", "path", ")", "{", "File", "file", "=", "new", "File", "(", "path", ")", ";", "return", "getContentsInDirectoryTree", "(", "file", ",", "\"*\"", ",", "false", ",", "true", ")", ";", "}" ]
Retrieves all directories from a directory and its subdirectories. @param path path to directory @return A list containing the found directories
[ "Retrieves", "all", "directories", "from", "a", "directory", "and", "its", "subdirectories", "." ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/io/FileSupport.java#L170-L173
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java
JDBC4PreparedStatement.setTime
@Override public void setTime(int parameterIndex, Time x) throws SQLException { """ Sets the designated parameter to the given java.sql.Time value. """ checkParameterBounds(parameterIndex); throw SQLError.noSupport(); }
java
@Override public void setTime(int parameterIndex, Time x) throws SQLException { checkParameterBounds(parameterIndex); throw SQLError.noSupport(); }
[ "@", "Override", "public", "void", "setTime", "(", "int", "parameterIndex", ",", "Time", "x", ")", "throws", "SQLException", "{", "checkParameterBounds", "(", "parameterIndex", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Sets the designated parameter to the given java.sql.Time value.
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "java", ".", "sql", ".", "Time", "value", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4PreparedStatement.java#L558-L563
phax/ph-schedule
ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java
DateBuilder.translateTime
public static Date translateTime (final Date date, final TimeZone aSrcTZ, final TimeZone aDestTZ) { """ Translate a date &amp; time from a users time zone to the another (probably server) time zone to assist in creating a simple trigger with the right date &amp; time. @param date the date to translate @param aSrcTZ the original time-zone @param aDestTZ the destination time-zone @return the translated date """ final Date newDate = new Date (); final int offset = aDestTZ.getOffset (date.getTime ()) - aSrcTZ.getOffset (date.getTime ()); newDate.setTime (date.getTime () - offset); return newDate; }
java
public static Date translateTime (final Date date, final TimeZone aSrcTZ, final TimeZone aDestTZ) { final Date newDate = new Date (); final int offset = aDestTZ.getOffset (date.getTime ()) - aSrcTZ.getOffset (date.getTime ()); newDate.setTime (date.getTime () - offset); return newDate; }
[ "public", "static", "Date", "translateTime", "(", "final", "Date", "date", ",", "final", "TimeZone", "aSrcTZ", ",", "final", "TimeZone", "aDestTZ", ")", "{", "final", "Date", "newDate", "=", "new", "Date", "(", ")", ";", "final", "int", "offset", "=", "aDestTZ", ".", "getOffset", "(", "date", ".", "getTime", "(", ")", ")", "-", "aSrcTZ", ".", "getOffset", "(", "date", ".", "getTime", "(", ")", ")", ";", "newDate", ".", "setTime", "(", "date", ".", "getTime", "(", ")", "-", "offset", ")", ";", "return", "newDate", ";", "}" ]
Translate a date &amp; time from a users time zone to the another (probably server) time zone to assist in creating a simple trigger with the right date &amp; time. @param date the date to translate @param aSrcTZ the original time-zone @param aDestTZ the destination time-zone @return the translated date
[ "Translate", "a", "date", "&amp", ";", "time", "from", "a", "users", "time", "zone", "to", "the", "another", "(", "probably", "server", ")", "time", "zone", "to", "assist", "in", "creating", "a", "simple", "trigger", "with", "the", "right", "date", "&amp", ";", "time", "." ]
train
https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java#L916-L922
kite-sdk/kite
kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/FileSystemMetadataProvider.java
FileSystemMetadataProvider.pathForMetadata
private Path pathForMetadata(String namespace, String name) { """ Returns the path where this MetadataProvider will store metadata. Note that this is not dependent on the actual storage location for the dataset, although they are usually co-located. This provider must be able to read metadata without a location for the Dataset when loading. @param name The {@link Dataset} name @return The directory {@link Path} where metadata files will be located """ return pathForMetadata(rootDirectory, namespace, name); }
java
private Path pathForMetadata(String namespace, String name) { return pathForMetadata(rootDirectory, namespace, name); }
[ "private", "Path", "pathForMetadata", "(", "String", "namespace", ",", "String", "name", ")", "{", "return", "pathForMetadata", "(", "rootDirectory", ",", "namespace", ",", "name", ")", ";", "}" ]
Returns the path where this MetadataProvider will store metadata. Note that this is not dependent on the actual storage location for the dataset, although they are usually co-located. This provider must be able to read metadata without a location for the Dataset when loading. @param name The {@link Dataset} name @return The directory {@link Path} where metadata files will be located
[ "Returns", "the", "path", "where", "this", "MetadataProvider", "will", "store", "metadata", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/filesystem/FileSystemMetadataProvider.java#L461-L463
looly/hutool
hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java
BeanUtil.getPropertyDescriptor
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, final String fieldName, boolean ignoreCase) throws BeanException { """ 获得Bean类属性描述 @param clazz Bean类 @param fieldName 字段名 @param ignoreCase 是否忽略大小写 @return PropertyDescriptor @throws BeanException 获取属性异常 """ final Map<String, PropertyDescriptor> map = getPropertyDescriptorMap(clazz, ignoreCase); return (null == map) ? null : map.get(fieldName); }
java
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, final String fieldName, boolean ignoreCase) throws BeanException { final Map<String, PropertyDescriptor> map = getPropertyDescriptorMap(clazz, ignoreCase); return (null == map) ? null : map.get(fieldName); }
[ "public", "static", "PropertyDescriptor", "getPropertyDescriptor", "(", "Class", "<", "?", ">", "clazz", ",", "final", "String", "fieldName", ",", "boolean", "ignoreCase", ")", "throws", "BeanException", "{", "final", "Map", "<", "String", ",", "PropertyDescriptor", ">", "map", "=", "getPropertyDescriptorMap", "(", "clazz", ",", "ignoreCase", ")", ";", "return", "(", "null", "==", "map", ")", "?", "null", ":", "map", ".", "get", "(", "fieldName", ")", ";", "}" ]
获得Bean类属性描述 @param clazz Bean类 @param fieldName 字段名 @param ignoreCase 是否忽略大小写 @return PropertyDescriptor @throws BeanException 获取属性异常
[ "获得Bean类属性描述" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java#L241-L244
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java
PerspectiveOps.renderPixel
public static Point2D_F64 renderPixel( DMatrixRMaj worldToCamera , Point3D_F64 X ) { """ Computes the image coordinate of a point given its 3D location and the camera matrix. @param worldToCamera 3x4 camera matrix for transforming a 3D point from world to image coordinates. @param X 3D Point in world reference frame.. @return 2D Render point on image plane. """ return renderPixel(worldToCamera,X,(Point2D_F64)null); }
java
public static Point2D_F64 renderPixel( DMatrixRMaj worldToCamera , Point3D_F64 X ) { return renderPixel(worldToCamera,X,(Point2D_F64)null); }
[ "public", "static", "Point2D_F64", "renderPixel", "(", "DMatrixRMaj", "worldToCamera", ",", "Point3D_F64", "X", ")", "{", "return", "renderPixel", "(", "worldToCamera", ",", "X", ",", "(", "Point2D_F64", ")", "null", ")", ";", "}" ]
Computes the image coordinate of a point given its 3D location and the camera matrix. @param worldToCamera 3x4 camera matrix for transforming a 3D point from world to image coordinates. @param X 3D Point in world reference frame.. @return 2D Render point on image plane.
[ "Computes", "the", "image", "coordinate", "of", "a", "point", "given", "its", "3D", "location", "and", "the", "camera", "matrix", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java#L550-L552
sgroschupf/zkclient
src/main/java/org/I0Itec/zkclient/ZkClient.java
ZkClient.setAcl
public void setAcl(final String path, final List<ACL> acl) throws ZkException { """ Sets the acl on path @param path @param acl List of ACL permissions to assign to the path. @throws ZkException if any ZooKeeper exception occurred @throws RuntimeException if any other exception occurs """ if (path == null) { throw new NullPointerException("Missing value for path"); } if (acl == null || acl.size() == 0) { throw new NullPointerException("Missing value for ACL"); } if (!exists(path)) { throw new RuntimeException("trying to set acls on non existing node " + path); } retryUntilConnected(new Callable<Void>() { @Override public Void call() throws Exception { Stat stat = new Stat(); _connection.readData(path, stat, false); _connection.setAcl(path, acl, stat.getAversion()); return null; } }); }
java
public void setAcl(final String path, final List<ACL> acl) throws ZkException { if (path == null) { throw new NullPointerException("Missing value for path"); } if (acl == null || acl.size() == 0) { throw new NullPointerException("Missing value for ACL"); } if (!exists(path)) { throw new RuntimeException("trying to set acls on non existing node " + path); } retryUntilConnected(new Callable<Void>() { @Override public Void call() throws Exception { Stat stat = new Stat(); _connection.readData(path, stat, false); _connection.setAcl(path, acl, stat.getAversion()); return null; } }); }
[ "public", "void", "setAcl", "(", "final", "String", "path", ",", "final", "List", "<", "ACL", ">", "acl", ")", "throws", "ZkException", "{", "if", "(", "path", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Missing value for path\"", ")", ";", "}", "if", "(", "acl", "==", "null", "||", "acl", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "NullPointerException", "(", "\"Missing value for ACL\"", ")", ";", "}", "if", "(", "!", "exists", "(", "path", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"trying to set acls on non existing node \"", "+", "path", ")", ";", "}", "retryUntilConnected", "(", "new", "Callable", "<", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", ")", "throws", "Exception", "{", "Stat", "stat", "=", "new", "Stat", "(", ")", ";", "_connection", ".", "readData", "(", "path", ",", "stat", ",", "false", ")", ";", "_connection", ".", "setAcl", "(", "path", ",", "acl", ",", "stat", ".", "getAversion", "(", ")", ")", ";", "return", "null", ";", "}", "}", ")", ";", "}" ]
Sets the acl on path @param path @param acl List of ACL permissions to assign to the path. @throws ZkException if any ZooKeeper exception occurred @throws RuntimeException if any other exception occurs
[ "Sets", "the", "acl", "on", "path" ]
train
https://github.com/sgroschupf/zkclient/blob/03ccf12c70aca2f771bfcd94d44dc7c4d4a1495e/src/main/java/org/I0Itec/zkclient/ZkClient.java#L320-L342
agmip/agmip-common-functions
src/main/java/org/agmip/common/Functions.java
Functions.formatAgmipDateString
public synchronized static String formatAgmipDateString(String agmipDate, String format) { """ Convert from AgMIP standard date string (YYMMDD) to a custom date string @param agmipDate AgMIP standard date string @param format Destination format @return a formatted date string or {@code null} """ try { SimpleDateFormat fmt = new SimpleDateFormat(format); Date d = dateFormatter.parse(agmipDate); return fmt.format(d); } catch (Exception ex) { return null; } }
java
public synchronized static String formatAgmipDateString(String agmipDate, String format) { try { SimpleDateFormat fmt = new SimpleDateFormat(format); Date d = dateFormatter.parse(agmipDate); return fmt.format(d); } catch (Exception ex) { return null; } }
[ "public", "synchronized", "static", "String", "formatAgmipDateString", "(", "String", "agmipDate", ",", "String", "format", ")", "{", "try", "{", "SimpleDateFormat", "fmt", "=", "new", "SimpleDateFormat", "(", "format", ")", ";", "Date", "d", "=", "dateFormatter", ".", "parse", "(", "agmipDate", ")", ";", "return", "fmt", ".", "format", "(", "d", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "return", "null", ";", "}", "}" ]
Convert from AgMIP standard date string (YYMMDD) to a custom date string @param agmipDate AgMIP standard date string @param format Destination format @return a formatted date string or {@code null}
[ "Convert", "from", "AgMIP", "standard", "date", "string", "(", "YYMMDD", ")", "to", "a", "custom", "date", "string" ]
train
https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/common/Functions.java#L118-L126
rwl/CSparseJ
src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_util.java
DZcs_util.cs_ndone
public static DZcsn cs_ndone (DZcsn N, DZcs C, int[] w, DZcsa x, boolean ok) { """ /* free workspace and return a numeric factorization (Cholesky, LU, or QR) """ // cs_spfree (C) ; /* free temporary matrix */ // cs_free (w) ; /* free workspace */ // cs_free (x) ; return (ok ? N : null) ; /* return result if OK, else free it */ }
java
public static DZcsn cs_ndone (DZcsn N, DZcs C, int[] w, DZcsa x, boolean ok) { // cs_spfree (C) ; /* free temporary matrix */ // cs_free (w) ; /* free workspace */ // cs_free (x) ; return (ok ? N : null) ; /* return result if OK, else free it */ }
[ "public", "static", "DZcsn", "cs_ndone", "(", "DZcsn", "N", ",", "DZcs", "C", ",", "int", "[", "]", "w", ",", "DZcsa", "x", ",", "boolean", "ok", ")", "{", "//\t cs_spfree (C) ; /* free temporary matrix */\r", "//\t cs_free (w) ; /* free workspace */\r", "//\t cs_free (x) ;\r", "return", "(", "ok", "?", "N", ":", "null", ")", ";", "/* return result if OK, else free it */", "}" ]
/* free workspace and return a numeric factorization (Cholesky, LU, or QR)
[ "/", "*", "free", "workspace", "and", "return", "a", "numeric", "factorization", "(", "Cholesky", "LU", "or", "QR", ")" ]
train
https://github.com/rwl/CSparseJ/blob/6a6f66bccce1558156a961494358952603b0ac84/src/main/java/edu/emory/mathcs/csparsej/tdcomplex/DZcs_util.java#L187-L193
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.asImmutable
public static <K, V> Map<K, V> asImmutable(Map<K, V> self) { """ A convenience method for creating an immutable Map. @param self a Map @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy @see #asImmutable(java.util.List) @see #asUnmodifiable(java.util.Map) @since 1.0 """ return asUnmodifiable(new LinkedHashMap<K, V>(self)); }
java
public static <K, V> Map<K, V> asImmutable(Map<K, V> self) { return asUnmodifiable(new LinkedHashMap<K, V>(self)); }
[ "public", "static", "<", "K", ",", "V", ">", "Map", "<", "K", ",", "V", ">", "asImmutable", "(", "Map", "<", "K", ",", "V", ">", "self", ")", "{", "return", "asUnmodifiable", "(", "new", "LinkedHashMap", "<", "K", ",", "V", ">", "(", "self", ")", ")", ";", "}" ]
A convenience method for creating an immutable Map. @param self a Map @return an unmodifiable view of a copy of the original, i.e. an effectively immutable copy @see #asImmutable(java.util.List) @see #asUnmodifiable(java.util.Map) @since 1.0
[ "A", "convenience", "method", "for", "creating", "an", "immutable", "Map", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L8252-L8254
spring-projects/spring-data-solr
src/main/java/org/springframework/data/solr/core/query/Criteria.java
Criteria.startsWith
public Criteria startsWith(String s) { """ Crates new {@link Predicate} with trailing wildcard <br/> <strong>NOTE: </strong>Strings will not be automatically split on whitespace. @param s @return @throws InvalidDataAccessApiUsageException for strings with whitespace """ assertNoBlankInWildcardedQuery(s, false, true); predicates.add(new Predicate(OperationKey.STARTS_WITH, s)); return this; }
java
public Criteria startsWith(String s) { assertNoBlankInWildcardedQuery(s, false, true); predicates.add(new Predicate(OperationKey.STARTS_WITH, s)); return this; }
[ "public", "Criteria", "startsWith", "(", "String", "s", ")", "{", "assertNoBlankInWildcardedQuery", "(", "s", ",", "false", ",", "true", ")", ";", "predicates", ".", "add", "(", "new", "Predicate", "(", "OperationKey", ".", "STARTS_WITH", ",", "s", ")", ")", ";", "return", "this", ";", "}" ]
Crates new {@link Predicate} with trailing wildcard <br/> <strong>NOTE: </strong>Strings will not be automatically split on whitespace. @param s @return @throws InvalidDataAccessApiUsageException for strings with whitespace
[ "Crates", "new", "{", "@link", "Predicate", "}", "with", "trailing", "wildcard", "<br", "/", ">", "<strong", ">", "NOTE", ":", "<", "/", "strong", ">", "Strings", "will", "not", "be", "automatically", "split", "on", "whitespace", "." ]
train
https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/core/query/Criteria.java#L220-L225
amaembo/streamex
src/main/java/one/util/streamex/IntStreamEx.java
IntStreamEx.of
public static IntStreamEx of(IntStream stream) { """ Returns an {@code IntStreamEx} object which wraps given {@link IntStream} . <p> The supplied stream must not be consumed or closed when this method is called. No operation must be performed on the supplied stream after it's wrapped. @param stream original stream @return the wrapped stream @since 0.0.8 """ return stream instanceof IntStreamEx ? (IntStreamEx) stream : new IntStreamEx(stream, StreamContext.of(stream)); }
java
public static IntStreamEx of(IntStream stream) { return stream instanceof IntStreamEx ? (IntStreamEx) stream : new IntStreamEx(stream, StreamContext.of(stream)); }
[ "public", "static", "IntStreamEx", "of", "(", "IntStream", "stream", ")", "{", "return", "stream", "instanceof", "IntStreamEx", "?", "(", "IntStreamEx", ")", "stream", ":", "new", "IntStreamEx", "(", "stream", ",", "StreamContext", ".", "of", "(", "stream", ")", ")", ";", "}" ]
Returns an {@code IntStreamEx} object which wraps given {@link IntStream} . <p> The supplied stream must not be consumed or closed when this method is called. No operation must be performed on the supplied stream after it's wrapped. @param stream original stream @return the wrapped stream @since 0.0.8
[ "Returns", "an", "{", "@code", "IntStreamEx", "}", "object", "which", "wraps", "given", "{", "@link", "IntStream", "}", "." ]
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/IntStreamEx.java#L2152-L2154
jbundle/jbundle
thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageFilter.java
BaseMessageFilter.updateFilterTree
public final void updateFilterTree(Map<String, Object> propTree) { """ Update this object's filter with this new tree information. @param propTree Changes to the current property tree. """ Object[][] mxProperties = this.cloneMatrix(this.getNameValueTree()); mxProperties = this.createNameValueTree(mxProperties, propTree); // Update these properties this.setFilterTree(mxProperties); // Update any remote copy of this. }
java
public final void updateFilterTree(Map<String, Object> propTree) { Object[][] mxProperties = this.cloneMatrix(this.getNameValueTree()); mxProperties = this.createNameValueTree(mxProperties, propTree); // Update these properties this.setFilterTree(mxProperties); // Update any remote copy of this. }
[ "public", "final", "void", "updateFilterTree", "(", "Map", "<", "String", ",", "Object", ">", "propTree", ")", "{", "Object", "[", "]", "[", "]", "mxProperties", "=", "this", ".", "cloneMatrix", "(", "this", ".", "getNameValueTree", "(", ")", ")", ";", "mxProperties", "=", "this", ".", "createNameValueTree", "(", "mxProperties", ",", "propTree", ")", ";", "// Update these properties", "this", ".", "setFilterTree", "(", "mxProperties", ")", ";", "// Update any remote copy of this.", "}" ]
Update this object's filter with this new tree information. @param propTree Changes to the current property tree.
[ "Update", "this", "object", "s", "filter", "with", "this", "new", "tree", "information", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/message/src/main/java/org/jbundle/thin/base/message/BaseMessageFilter.java#L446-L451
Azure/azure-sdk-for-java
authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleAssignmentsInner.java
RoleAssignmentsInner.listForScopeWithServiceResponseAsync
public Observable<ServiceResponse<Page<RoleAssignmentInner>>> listForScopeWithServiceResponseAsync(final String scope, final String filter) { """ Gets role assignments for a scope. @param scope The scope of the role assignments. @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RoleAssignmentInner&gt; object """ return listForScopeSinglePageAsync(scope, filter) .concatMap(new Func1<ServiceResponse<Page<RoleAssignmentInner>>, Observable<ServiceResponse<Page<RoleAssignmentInner>>>>() { @Override public Observable<ServiceResponse<Page<RoleAssignmentInner>>> call(ServiceResponse<Page<RoleAssignmentInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listForScopeNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<RoleAssignmentInner>>> listForScopeWithServiceResponseAsync(final String scope, final String filter) { return listForScopeSinglePageAsync(scope, filter) .concatMap(new Func1<ServiceResponse<Page<RoleAssignmentInner>>, Observable<ServiceResponse<Page<RoleAssignmentInner>>>>() { @Override public Observable<ServiceResponse<Page<RoleAssignmentInner>>> call(ServiceResponse<Page<RoleAssignmentInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listForScopeNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RoleAssignmentInner", ">", ">", ">", "listForScopeWithServiceResponseAsync", "(", "final", "String", "scope", ",", "final", "String", "filter", ")", "{", "return", "listForScopeSinglePageAsync", "(", "scope", ",", "filter", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "RoleAssignmentInner", ">", ">", ",", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RoleAssignmentInner", ">", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RoleAssignmentInner", ">", ">", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "RoleAssignmentInner", ">", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "listForScopeNextWithServiceResponseAsync", "(", "nextPageLink", ")", ")", ";", "}", "}", ")", ";", "}" ]
Gets role assignments for a scope. @param scope The scope of the role assignments. @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for the specified principal. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RoleAssignmentInner&gt; object
[ "Gets", "role", "assignments", "for", "a", "scope", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleAssignmentsInner.java#L1531-L1543
pravega/pravega
common/src/main/java/io/pravega/common/tracing/RequestTracker.java
RequestTracker.initializeAndTrackRequestTag
public RequestTag initializeAndTrackRequestTag(long requestId, String...requestInfo) { """ This method first attempts to load a {@link RequestTag} from a request that is assumed to exist. However, if we work with clients or channels that do not attach tags to requests, then we initialize and track the request at the server side. In the worst case, we will have the ability of tracking a request from the server entry point onwards. @param requestId Alternative request id in the case there is no request id in headers. @param requestInfo Alternative descriptor to identify the call in the case there is no descriptor in headers. @return Request tag formed either from request headers or from arguments given. """ RequestTag requestTag = getRequestTagFor(requestInfo); if (tracingEnabled && !requestTag.isTracked()) { log.debug("Tags not found for this request: requestId={}, descriptor={}. Create request tag at this point.", requestId, RequestTracker.buildRequestDescriptor(requestInfo)); requestTag = new RequestTag(RequestTracker.buildRequestDescriptor(requestInfo), requestId); trackRequest(requestTag); } return requestTag; }
java
public RequestTag initializeAndTrackRequestTag(long requestId, String...requestInfo) { RequestTag requestTag = getRequestTagFor(requestInfo); if (tracingEnabled && !requestTag.isTracked()) { log.debug("Tags not found for this request: requestId={}, descriptor={}. Create request tag at this point.", requestId, RequestTracker.buildRequestDescriptor(requestInfo)); requestTag = new RequestTag(RequestTracker.buildRequestDescriptor(requestInfo), requestId); trackRequest(requestTag); } return requestTag; }
[ "public", "RequestTag", "initializeAndTrackRequestTag", "(", "long", "requestId", ",", "String", "...", "requestInfo", ")", "{", "RequestTag", "requestTag", "=", "getRequestTagFor", "(", "requestInfo", ")", ";", "if", "(", "tracingEnabled", "&&", "!", "requestTag", ".", "isTracked", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Tags not found for this request: requestId={}, descriptor={}. Create request tag at this point.\"", ",", "requestId", ",", "RequestTracker", ".", "buildRequestDescriptor", "(", "requestInfo", ")", ")", ";", "requestTag", "=", "new", "RequestTag", "(", "RequestTracker", ".", "buildRequestDescriptor", "(", "requestInfo", ")", ",", "requestId", ")", ";", "trackRequest", "(", "requestTag", ")", ";", "}", "return", "requestTag", ";", "}" ]
This method first attempts to load a {@link RequestTag} from a request that is assumed to exist. However, if we work with clients or channels that do not attach tags to requests, then we initialize and track the request at the server side. In the worst case, we will have the ability of tracking a request from the server entry point onwards. @param requestId Alternative request id in the case there is no request id in headers. @param requestInfo Alternative descriptor to identify the call in the case there is no descriptor in headers. @return Request tag formed either from request headers or from arguments given.
[ "This", "method", "first", "attempts", "to", "load", "a", "{", "@link", "RequestTag", "}", "from", "a", "request", "that", "is", "assumed", "to", "exist", ".", "However", "if", "we", "work", "with", "clients", "or", "channels", "that", "do", "not", "attach", "tags", "to", "requests", "then", "we", "initialize", "and", "track", "the", "request", "at", "the", "server", "side", ".", "In", "the", "worst", "case", "we", "will", "have", "the", "ability", "of", "tracking", "a", "request", "from", "the", "server", "entry", "point", "onwards", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/tracing/RequestTracker.java#L233-L243
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java
TopologyAssign.mkAssignment
public Assignment mkAssignment(TopologyAssignEvent event) throws Exception { """ make assignments for a topology The nimbus core function, this function has been totally rewrite @throws Exception """ String topologyId = event.getTopologyId(); LOG.info("Determining assignment for " + topologyId); TopologyAssignContext context = prepareTopologyAssign(event); Set<ResourceWorkerSlot> assignments; if (!StormConfig.local_mode(nimbusData.getConf())) { IToplogyScheduler scheduler = schedulers.get(DEFAULT_SCHEDULER_NAME); assignments = scheduler.assignTasks(context); } else { assignments = mkLocalAssignment(context); } Assignment assignment = null; if (assignments != null && assignments.size() > 0) { Map<String, String> nodeHost = getTopologyNodeHost( context.getCluster(), context.getOldAssignment(), assignments); Map<Integer, Integer> startTimes = getTaskStartTimes( context, nimbusData, topologyId, context.getOldAssignment(), assignments); String codeDir = (String) nimbusData.getConf().get(Config.STORM_LOCAL_DIR); assignment = new Assignment(codeDir, assignments, nodeHost, startTimes); // the topology binary changed. if (event.isScaleTopology()) { assignment.setAssignmentType(Assignment.AssignmentType.ScaleTopology); } StormClusterState stormClusterState = nimbusData.getStormClusterState(); stormClusterState.set_assignment(topologyId, assignment); // update task heartbeat's start time NimbusUtils.updateTaskHbStartTime(nimbusData, assignment, topologyId); // Update metrics information in ZK when rebalance or reassignment // Only update metrics monitor status when creating topology // if (context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_REBALANCE // || context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_MONITOR) // NimbusUtils.updateMetricsInfo(nimbusData, topologyId, assignment); NimbusUtils.updateTopologyTaskTimeout(nimbusData, topologyId); LOG.info("Successfully make assignment for topology id " + topologyId + ": " + assignment); } return assignment; }
java
public Assignment mkAssignment(TopologyAssignEvent event) throws Exception { String topologyId = event.getTopologyId(); LOG.info("Determining assignment for " + topologyId); TopologyAssignContext context = prepareTopologyAssign(event); Set<ResourceWorkerSlot> assignments; if (!StormConfig.local_mode(nimbusData.getConf())) { IToplogyScheduler scheduler = schedulers.get(DEFAULT_SCHEDULER_NAME); assignments = scheduler.assignTasks(context); } else { assignments = mkLocalAssignment(context); } Assignment assignment = null; if (assignments != null && assignments.size() > 0) { Map<String, String> nodeHost = getTopologyNodeHost( context.getCluster(), context.getOldAssignment(), assignments); Map<Integer, Integer> startTimes = getTaskStartTimes( context, nimbusData, topologyId, context.getOldAssignment(), assignments); String codeDir = (String) nimbusData.getConf().get(Config.STORM_LOCAL_DIR); assignment = new Assignment(codeDir, assignments, nodeHost, startTimes); // the topology binary changed. if (event.isScaleTopology()) { assignment.setAssignmentType(Assignment.AssignmentType.ScaleTopology); } StormClusterState stormClusterState = nimbusData.getStormClusterState(); stormClusterState.set_assignment(topologyId, assignment); // update task heartbeat's start time NimbusUtils.updateTaskHbStartTime(nimbusData, assignment, topologyId); // Update metrics information in ZK when rebalance or reassignment // Only update metrics monitor status when creating topology // if (context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_REBALANCE // || context.getAssignType() == // TopologyAssignContext.ASSIGN_TYPE_MONITOR) // NimbusUtils.updateMetricsInfo(nimbusData, topologyId, assignment); NimbusUtils.updateTopologyTaskTimeout(nimbusData, topologyId); LOG.info("Successfully make assignment for topology id " + topologyId + ": " + assignment); } return assignment; }
[ "public", "Assignment", "mkAssignment", "(", "TopologyAssignEvent", "event", ")", "throws", "Exception", "{", "String", "topologyId", "=", "event", ".", "getTopologyId", "(", ")", ";", "LOG", ".", "info", "(", "\"Determining assignment for \"", "+", "topologyId", ")", ";", "TopologyAssignContext", "context", "=", "prepareTopologyAssign", "(", "event", ")", ";", "Set", "<", "ResourceWorkerSlot", ">", "assignments", ";", "if", "(", "!", "StormConfig", ".", "local_mode", "(", "nimbusData", ".", "getConf", "(", ")", ")", ")", "{", "IToplogyScheduler", "scheduler", "=", "schedulers", ".", "get", "(", "DEFAULT_SCHEDULER_NAME", ")", ";", "assignments", "=", "scheduler", ".", "assignTasks", "(", "context", ")", ";", "}", "else", "{", "assignments", "=", "mkLocalAssignment", "(", "context", ")", ";", "}", "Assignment", "assignment", "=", "null", ";", "if", "(", "assignments", "!=", "null", "&&", "assignments", ".", "size", "(", ")", ">", "0", ")", "{", "Map", "<", "String", ",", "String", ">", "nodeHost", "=", "getTopologyNodeHost", "(", "context", ".", "getCluster", "(", ")", ",", "context", ".", "getOldAssignment", "(", ")", ",", "assignments", ")", ";", "Map", "<", "Integer", ",", "Integer", ">", "startTimes", "=", "getTaskStartTimes", "(", "context", ",", "nimbusData", ",", "topologyId", ",", "context", ".", "getOldAssignment", "(", ")", ",", "assignments", ")", ";", "String", "codeDir", "=", "(", "String", ")", "nimbusData", ".", "getConf", "(", ")", ".", "get", "(", "Config", ".", "STORM_LOCAL_DIR", ")", ";", "assignment", "=", "new", "Assignment", "(", "codeDir", ",", "assignments", ",", "nodeHost", ",", "startTimes", ")", ";", "// the topology binary changed.", "if", "(", "event", ".", "isScaleTopology", "(", ")", ")", "{", "assignment", ".", "setAssignmentType", "(", "Assignment", ".", "AssignmentType", ".", "ScaleTopology", ")", ";", "}", "StormClusterState", "stormClusterState", "=", "nimbusData", ".", "getStormClusterState", "(", ")", ";", "stormClusterState", ".", "set_assignment", "(", "topologyId", ",", "assignment", ")", ";", "// update task heartbeat's start time", "NimbusUtils", ".", "updateTaskHbStartTime", "(", "nimbusData", ",", "assignment", ",", "topologyId", ")", ";", "// Update metrics information in ZK when rebalance or reassignment", "// Only update metrics monitor status when creating topology", "// if (context.getAssignType() ==", "// TopologyAssignContext.ASSIGN_TYPE_REBALANCE", "// || context.getAssignType() ==", "// TopologyAssignContext.ASSIGN_TYPE_MONITOR)", "// NimbusUtils.updateMetricsInfo(nimbusData, topologyId, assignment);", "NimbusUtils", ".", "updateTopologyTaskTimeout", "(", "nimbusData", ",", "topologyId", ")", ";", "LOG", ".", "info", "(", "\"Successfully make assignment for topology id \"", "+", "topologyId", "+", "\": \"", "+", "assignment", ")", ";", "}", "return", "assignment", ";", "}" ]
make assignments for a topology The nimbus core function, this function has been totally rewrite @throws Exception
[ "make", "assignments", "for", "a", "topology", "The", "nimbus", "core", "function", "this", "function", "has", "been", "totally", "rewrite" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/nimbus/TopologyAssign.java#L439-L486
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.updateCollapsedParent
@UiThread private void updateCollapsedParent(@NonNull ExpandableWrapper<P, C> parentWrapper, int flatParentPosition, boolean collapseTriggeredByListItemClick) { """ Collapses a specified parent item. Calls through to the ExpandCollapseListener and removes children of the specified parent from the flat list of items. @param parentWrapper The ExpandableWrapper of the parent to collapse @param flatParentPosition The index of the parent to collapse @param collapseTriggeredByListItemClick true if expansion was triggered by a click event, false otherwise. """ if (!parentWrapper.isExpanded()) { return; } parentWrapper.setExpanded(false); mExpansionStateMap.put(parentWrapper.getParent(), false); List<ExpandableWrapper<P, C>> wrappedChildList = parentWrapper.getWrappedChildList(); if (wrappedChildList != null) { int childCount = wrappedChildList.size(); for (int i = childCount - 1; i >= 0; i--) { mFlatItemList.remove(flatParentPosition + i + 1); } notifyItemRangeRemoved(flatParentPosition + 1, childCount); } if (collapseTriggeredByListItemClick && mExpandCollapseListener != null) { mExpandCollapseListener.onParentCollapsed(getNearestParentPosition(flatParentPosition)); } }
java
@UiThread private void updateCollapsedParent(@NonNull ExpandableWrapper<P, C> parentWrapper, int flatParentPosition, boolean collapseTriggeredByListItemClick) { if (!parentWrapper.isExpanded()) { return; } parentWrapper.setExpanded(false); mExpansionStateMap.put(parentWrapper.getParent(), false); List<ExpandableWrapper<P, C>> wrappedChildList = parentWrapper.getWrappedChildList(); if (wrappedChildList != null) { int childCount = wrappedChildList.size(); for (int i = childCount - 1; i >= 0; i--) { mFlatItemList.remove(flatParentPosition + i + 1); } notifyItemRangeRemoved(flatParentPosition + 1, childCount); } if (collapseTriggeredByListItemClick && mExpandCollapseListener != null) { mExpandCollapseListener.onParentCollapsed(getNearestParentPosition(flatParentPosition)); } }
[ "@", "UiThread", "private", "void", "updateCollapsedParent", "(", "@", "NonNull", "ExpandableWrapper", "<", "P", ",", "C", ">", "parentWrapper", ",", "int", "flatParentPosition", ",", "boolean", "collapseTriggeredByListItemClick", ")", "{", "if", "(", "!", "parentWrapper", ".", "isExpanded", "(", ")", ")", "{", "return", ";", "}", "parentWrapper", ".", "setExpanded", "(", "false", ")", ";", "mExpansionStateMap", ".", "put", "(", "parentWrapper", ".", "getParent", "(", ")", ",", "false", ")", ";", "List", "<", "ExpandableWrapper", "<", "P", ",", "C", ">", ">", "wrappedChildList", "=", "parentWrapper", ".", "getWrappedChildList", "(", ")", ";", "if", "(", "wrappedChildList", "!=", "null", ")", "{", "int", "childCount", "=", "wrappedChildList", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "childCount", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "mFlatItemList", ".", "remove", "(", "flatParentPosition", "+", "i", "+", "1", ")", ";", "}", "notifyItemRangeRemoved", "(", "flatParentPosition", "+", "1", ",", "childCount", ")", ";", "}", "if", "(", "collapseTriggeredByListItemClick", "&&", "mExpandCollapseListener", "!=", "null", ")", "{", "mExpandCollapseListener", ".", "onParentCollapsed", "(", "getNearestParentPosition", "(", "flatParentPosition", ")", ")", ";", "}", "}" ]
Collapses a specified parent item. Calls through to the ExpandCollapseListener and removes children of the specified parent from the flat list of items. @param parentWrapper The ExpandableWrapper of the parent to collapse @param flatParentPosition The index of the parent to collapse @param collapseTriggeredByListItemClick true if expansion was triggered by a click event, false otherwise.
[ "Collapses", "a", "specified", "parent", "item", ".", "Calls", "through", "to", "the", "ExpandCollapseListener", "and", "removes", "children", "of", "the", "specified", "parent", "from", "the", "flat", "list", "of", "items", "." ]
train
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L728-L750
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.withIndex
public static <E> Iterator<Tuple2<E, Integer>> withIndex(Iterator<E> self) { """ Zips an iterator with indices in (value, index) order. <p/> Example usage: <pre class="groovyTestCase"> assert [["a", 0], ["b", 1]] == ["a", "b"].iterator().withIndex().toList() assert ["0: a", "1: b"] == ["a", "b"].iterator().withIndex().collect { str, idx {@code ->} "$idx: $str" }.toList() </pre> @param self an iterator @return a zipped iterator with indices @see #indexed(Iterator) @since 2.4.0 """ return withIndex(self, 0); }
java
public static <E> Iterator<Tuple2<E, Integer>> withIndex(Iterator<E> self) { return withIndex(self, 0); }
[ "public", "static", "<", "E", ">", "Iterator", "<", "Tuple2", "<", "E", ",", "Integer", ">", ">", "withIndex", "(", "Iterator", "<", "E", ">", "self", ")", "{", "return", "withIndex", "(", "self", ",", "0", ")", ";", "}" ]
Zips an iterator with indices in (value, index) order. <p/> Example usage: <pre class="groovyTestCase"> assert [["a", 0], ["b", 1]] == ["a", "b"].iterator().withIndex().toList() assert ["0: a", "1: b"] == ["a", "b"].iterator().withIndex().collect { str, idx {@code ->} "$idx: $str" }.toList() </pre> @param self an iterator @return a zipped iterator with indices @see #indexed(Iterator) @since 2.4.0
[ "Zips", "an", "iterator", "with", "indices", "in", "(", "value", "index", ")", "order", ".", "<p", "/", ">", "Example", "usage", ":", "<pre", "class", "=", "groovyTestCase", ">", "assert", "[[", "a", "0", "]", "[", "b", "1", "]]", "==", "[", "a", "b", "]", ".", "iterator", "()", ".", "withIndex", "()", ".", "toList", "()", "assert", "[", "0", ":", "a", "1", ":", "b", "]", "==", "[", "a", "b", "]", ".", "iterator", "()", ".", "withIndex", "()", ".", "collect", "{", "str", "idx", "{", "@code", "-", ">", "}", "$idx", ":", "$str", "}", ".", "toList", "()", "<", "/", "pre", ">" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L8819-L8821
leancloud/java-sdk-all
core/src/main/java/cn/leancloud/upload/QiniuAccessor.java
QiniuAccessor.putFileBlocksToQiniu
public QiniuBlockResponseData putFileBlocksToQiniu(QiniuBlockResponseData lastChunk, final int blockOffset, final byte[] currentChunkData, int currentChunkSize, int retry) { """ REST API: POST /bput/<ctx>/<nextChunkOffset> HTTP/1.1 Host: <UpHost> Content-Type: application/octet-stream Content-Length: <nextChunkSize> Authorization: UpToken <UploadToken> <nextChunkBinary> Request Params: - ctx: 前一次上传返回的块级上传控制信息。 - nextChunkOffset: 当前片在整个块中的起始偏移。 - nextChunkSize: 当前片数据大小 - nextChunkBinary: 当前片数据 Response: { "ctx": "<Ctx string>", "checksum": "<Checksum string>", "crc32": <Crc32 int64>, "offset": <Offset int64>, "host": "<UpHost string>" } @param lastChunk @param blockOffset @param currentChunkData @param currentChunkSize @param retry @return """ try { String endPoint = String.format(QINIU_BRICK_UPLOAD_EP, this.uploadUrl, lastChunk.ctx, lastChunk.offset); Request.Builder builder = new Request.Builder(); builder.url(endPoint); builder.addHeader(HEAD_CONTENT_TYPE, DEFAULT_CONTENT_TYPE); builder.addHeader(HEAD_CONTENT_LENGTH, String.valueOf(currentChunkSize)); builder.addHeader(HEAD_AUTHORIZATION, "UpToken " + this.uploadToken); LOGGER.d("putFileBlocksToQiniu with uploadUrl: " + endPoint); RequestBody requestBody = RequestBody.create(MediaType.parse(DEFAULT_CONTENT_TYPE), currentChunkData, 0, currentChunkSize); builder = builder.post(requestBody); Response response = this.client.newCall(builder.build()).execute(); QiniuBlockResponseData respData = parseQiniuResponse(response, QiniuBlockResponseData.class); validateCrc32Value(respData, currentChunkData, 0, currentChunkSize); return respData; } catch (Exception e) { if (retry-- > 0) { return putFileBlocksToQiniu(lastChunk, blockOffset, currentChunkData, currentChunkSize, retry); } else { LOGGER.w(e); } } return null; }
java
public QiniuBlockResponseData putFileBlocksToQiniu(QiniuBlockResponseData lastChunk, final int blockOffset, final byte[] currentChunkData, int currentChunkSize, int retry) { try { String endPoint = String.format(QINIU_BRICK_UPLOAD_EP, this.uploadUrl, lastChunk.ctx, lastChunk.offset); Request.Builder builder = new Request.Builder(); builder.url(endPoint); builder.addHeader(HEAD_CONTENT_TYPE, DEFAULT_CONTENT_TYPE); builder.addHeader(HEAD_CONTENT_LENGTH, String.valueOf(currentChunkSize)); builder.addHeader(HEAD_AUTHORIZATION, "UpToken " + this.uploadToken); LOGGER.d("putFileBlocksToQiniu with uploadUrl: " + endPoint); RequestBody requestBody = RequestBody.create(MediaType.parse(DEFAULT_CONTENT_TYPE), currentChunkData, 0, currentChunkSize); builder = builder.post(requestBody); Response response = this.client.newCall(builder.build()).execute(); QiniuBlockResponseData respData = parseQiniuResponse(response, QiniuBlockResponseData.class); validateCrc32Value(respData, currentChunkData, 0, currentChunkSize); return respData; } catch (Exception e) { if (retry-- > 0) { return putFileBlocksToQiniu(lastChunk, blockOffset, currentChunkData, currentChunkSize, retry); } else { LOGGER.w(e); } } return null; }
[ "public", "QiniuBlockResponseData", "putFileBlocksToQiniu", "(", "QiniuBlockResponseData", "lastChunk", ",", "final", "int", "blockOffset", ",", "final", "byte", "[", "]", "currentChunkData", ",", "int", "currentChunkSize", ",", "int", "retry", ")", "{", "try", "{", "String", "endPoint", "=", "String", ".", "format", "(", "QINIU_BRICK_UPLOAD_EP", ",", "this", ".", "uploadUrl", ",", "lastChunk", ".", "ctx", ",", "lastChunk", ".", "offset", ")", ";", "Request", ".", "Builder", "builder", "=", "new", "Request", ".", "Builder", "(", ")", ";", "builder", ".", "url", "(", "endPoint", ")", ";", "builder", ".", "addHeader", "(", "HEAD_CONTENT_TYPE", ",", "DEFAULT_CONTENT_TYPE", ")", ";", "builder", ".", "addHeader", "(", "HEAD_CONTENT_LENGTH", ",", "String", ".", "valueOf", "(", "currentChunkSize", ")", ")", ";", "builder", ".", "addHeader", "(", "HEAD_AUTHORIZATION", ",", "\"UpToken \"", "+", "this", ".", "uploadToken", ")", ";", "LOGGER", ".", "d", "(", "\"putFileBlocksToQiniu with uploadUrl: \"", "+", "endPoint", ")", ";", "RequestBody", "requestBody", "=", "RequestBody", ".", "create", "(", "MediaType", ".", "parse", "(", "DEFAULT_CONTENT_TYPE", ")", ",", "currentChunkData", ",", "0", ",", "currentChunkSize", ")", ";", "builder", "=", "builder", ".", "post", "(", "requestBody", ")", ";", "Response", "response", "=", "this", ".", "client", ".", "newCall", "(", "builder", ".", "build", "(", ")", ")", ".", "execute", "(", ")", ";", "QiniuBlockResponseData", "respData", "=", "parseQiniuResponse", "(", "response", ",", "QiniuBlockResponseData", ".", "class", ")", ";", "validateCrc32Value", "(", "respData", ",", "currentChunkData", ",", "0", ",", "currentChunkSize", ")", ";", "return", "respData", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "retry", "--", ">", "0", ")", "{", "return", "putFileBlocksToQiniu", "(", "lastChunk", ",", "blockOffset", ",", "currentChunkData", ",", "currentChunkSize", ",", "retry", ")", ";", "}", "else", "{", "LOGGER", ".", "w", "(", "e", ")", ";", "}", "}", "return", "null", ";", "}" ]
REST API: POST /bput/<ctx>/<nextChunkOffset> HTTP/1.1 Host: <UpHost> Content-Type: application/octet-stream Content-Length: <nextChunkSize> Authorization: UpToken <UploadToken> <nextChunkBinary> Request Params: - ctx: 前一次上传返回的块级上传控制信息。 - nextChunkOffset: 当前片在整个块中的起始偏移。 - nextChunkSize: 当前片数据大小 - nextChunkBinary: 当前片数据 Response: { "ctx": "<Ctx string>", "checksum": "<Checksum string>", "crc32": <Crc32 int64>, "offset": <Offset int64>, "host": "<UpHost string>" } @param lastChunk @param blockOffset @param currentChunkData @param currentChunkSize @param retry @return
[ "REST", "API", ":", "POST", "/", "bput", "/", "<ctx", ">", "/", "<nextChunkOffset", ">", "HTTP", "/", "1", ".", "1", "Host", ":", "<UpHost", ">", "Content", "-", "Type", ":", "application", "/", "octet", "-", "stream", "Content", "-", "Length", ":", "<nextChunkSize", ">", "Authorization", ":", "UpToken", "<UploadToken", ">", "<nextChunkBinary", ">" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/core/src/main/java/cn/leancloud/upload/QiniuAccessor.java#L264-L293
StripesFramework/stripes-stuff
src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java
SessionStoreInterceptor.setAttribute
protected Object setAttribute(HttpSession session, String key, Object object, boolean serializable, int maxTime) { """ Saves an object in session for latter use. @param session Session in which to store object. @param key Key under which object is saved. @param object Object to save. @param serializable True if object is serializable. @param maxTime Maximum time to keep object in session. @return Object previously saved under key. """ if (object == null) { // If object is null, remove attribute. Object ret; synchronized (session) { ret = session.getAttribute(key); session.removeAttribute(key); } return ret; } else { // Set object in session. Object ret; synchronized (session) { ret = session.getAttribute(key); session.setAttribute(key, object); } SessionMapper mapper = (SessionMapper) session.getAttribute(MAPPER_ATTRIBUTE); if (mapper == null) { // Register mapper for session. mapper = new SessionMapper(); session.setAttribute(MAPPER_ATTRIBUTE, mapper); } synchronized (mapper) { // Update field mapper. SessionFieldMapper fieldMapper = mapper.get(key); if (fieldMapper == null) { fieldMapper = new SessionFieldMapper(serializable && object instanceof Serializable); mapper.put(key, fieldMapper); } if (maxTime > 0) { // Register runnable to remove attribute. if (fieldMapper.runnable != null) { // Cancel old runnable because a new one will be created. fieldMapper.runnable.cancel(); } // Register runnable. RemoveFieldRunnable runnable = new RemoveFieldRunnable(key, maxTime, session); fieldMapper.runnable = runnable; (new Thread(runnable)).start(); } } return ret; } }
java
protected Object setAttribute(HttpSession session, String key, Object object, boolean serializable, int maxTime) { if (object == null) { // If object is null, remove attribute. Object ret; synchronized (session) { ret = session.getAttribute(key); session.removeAttribute(key); } return ret; } else { // Set object in session. Object ret; synchronized (session) { ret = session.getAttribute(key); session.setAttribute(key, object); } SessionMapper mapper = (SessionMapper) session.getAttribute(MAPPER_ATTRIBUTE); if (mapper == null) { // Register mapper for session. mapper = new SessionMapper(); session.setAttribute(MAPPER_ATTRIBUTE, mapper); } synchronized (mapper) { // Update field mapper. SessionFieldMapper fieldMapper = mapper.get(key); if (fieldMapper == null) { fieldMapper = new SessionFieldMapper(serializable && object instanceof Serializable); mapper.put(key, fieldMapper); } if (maxTime > 0) { // Register runnable to remove attribute. if (fieldMapper.runnable != null) { // Cancel old runnable because a new one will be created. fieldMapper.runnable.cancel(); } // Register runnable. RemoveFieldRunnable runnable = new RemoveFieldRunnable(key, maxTime, session); fieldMapper.runnable = runnable; (new Thread(runnable)).start(); } } return ret; } }
[ "protected", "Object", "setAttribute", "(", "HttpSession", "session", ",", "String", "key", ",", "Object", "object", ",", "boolean", "serializable", ",", "int", "maxTime", ")", "{", "if", "(", "object", "==", "null", ")", "{", "// If object is null, remove attribute.\r", "Object", "ret", ";", "synchronized", "(", "session", ")", "{", "ret", "=", "session", ".", "getAttribute", "(", "key", ")", ";", "session", ".", "removeAttribute", "(", "key", ")", ";", "}", "return", "ret", ";", "}", "else", "{", "// Set object in session.\r", "Object", "ret", ";", "synchronized", "(", "session", ")", "{", "ret", "=", "session", ".", "getAttribute", "(", "key", ")", ";", "session", ".", "setAttribute", "(", "key", ",", "object", ")", ";", "}", "SessionMapper", "mapper", "=", "(", "SessionMapper", ")", "session", ".", "getAttribute", "(", "MAPPER_ATTRIBUTE", ")", ";", "if", "(", "mapper", "==", "null", ")", "{", "// Register mapper for session.\r", "mapper", "=", "new", "SessionMapper", "(", ")", ";", "session", ".", "setAttribute", "(", "MAPPER_ATTRIBUTE", ",", "mapper", ")", ";", "}", "synchronized", "(", "mapper", ")", "{", "// Update field mapper.\r", "SessionFieldMapper", "fieldMapper", "=", "mapper", ".", "get", "(", "key", ")", ";", "if", "(", "fieldMapper", "==", "null", ")", "{", "fieldMapper", "=", "new", "SessionFieldMapper", "(", "serializable", "&&", "object", "instanceof", "Serializable", ")", ";", "mapper", ".", "put", "(", "key", ",", "fieldMapper", ")", ";", "}", "if", "(", "maxTime", ">", "0", ")", "{", "// Register runnable to remove attribute.\r", "if", "(", "fieldMapper", ".", "runnable", "!=", "null", ")", "{", "// Cancel old runnable because a new one will be created.\r", "fieldMapper", ".", "runnable", ".", "cancel", "(", ")", ";", "}", "// Register runnable.\r", "RemoveFieldRunnable", "runnable", "=", "new", "RemoveFieldRunnable", "(", "key", ",", "maxTime", ",", "session", ")", ";", "fieldMapper", ".", "runnable", "=", "runnable", ";", "(", "new", "Thread", "(", "runnable", ")", ")", ".", "start", "(", ")", ";", "}", "}", "return", "ret", ";", "}", "}" ]
Saves an object in session for latter use. @param session Session in which to store object. @param key Key under which object is saved. @param object Object to save. @param serializable True if object is serializable. @param maxTime Maximum time to keep object in session. @return Object previously saved under key.
[ "Saves", "an", "object", "in", "session", "for", "latter", "use", "." ]
train
https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L192-L236
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/internal/InternalUtils.java
InternalUtils.setIgnoreIncludeServletPath
public static void setIgnoreIncludeServletPath( ServletRequest request, boolean ignore ) { """ Tell {@link #getDecodedServletPath} (and all that call it) to ignore the attribute that specifies the Servlet Include path, which is set when a Servlet include is done through RequestDispatcher. Normally, getDecodedServletPath tries the Servlet Include path before falling back to getServletPath() on the request. Note that this is basically a stack of instructions to ignore the include path, and this method expects each call with <code>ignore</code>==<code>true</code> to be balanced by a call with <code>ignore</code>==<code>false</code>. """ Integer depth = ( Integer ) request.getAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR ); if ( ignore ) { if ( depth == null ) depth = new Integer( 0 ); request.setAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR, new Integer( depth.intValue() + 1 ) ); } else { assert depth != null : "call to setIgnoreIncludeServletPath() was imbalanced"; depth = new Integer( depth.intValue() - 1 ); if ( depth.intValue() == 0 ) { request.removeAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR ); } else { request.setAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR, depth ); } } }
java
public static void setIgnoreIncludeServletPath( ServletRequest request, boolean ignore ) { Integer depth = ( Integer ) request.getAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR ); if ( ignore ) { if ( depth == null ) depth = new Integer( 0 ); request.setAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR, new Integer( depth.intValue() + 1 ) ); } else { assert depth != null : "call to setIgnoreIncludeServletPath() was imbalanced"; depth = new Integer( depth.intValue() - 1 ); if ( depth.intValue() == 0 ) { request.removeAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR ); } else { request.setAttribute( IGNORE_INCLUDE_SERVLET_PATH_ATTR, depth ); } } }
[ "public", "static", "void", "setIgnoreIncludeServletPath", "(", "ServletRequest", "request", ",", "boolean", "ignore", ")", "{", "Integer", "depth", "=", "(", "Integer", ")", "request", ".", "getAttribute", "(", "IGNORE_INCLUDE_SERVLET_PATH_ATTR", ")", ";", "if", "(", "ignore", ")", "{", "if", "(", "depth", "==", "null", ")", "depth", "=", "new", "Integer", "(", "0", ")", ";", "request", ".", "setAttribute", "(", "IGNORE_INCLUDE_SERVLET_PATH_ATTR", ",", "new", "Integer", "(", "depth", ".", "intValue", "(", ")", "+", "1", ")", ")", ";", "}", "else", "{", "assert", "depth", "!=", "null", ":", "\"call to setIgnoreIncludeServletPath() was imbalanced\"", ";", "depth", "=", "new", "Integer", "(", "depth", ".", "intValue", "(", ")", "-", "1", ")", ";", "if", "(", "depth", ".", "intValue", "(", ")", "==", "0", ")", "{", "request", ".", "removeAttribute", "(", "IGNORE_INCLUDE_SERVLET_PATH_ATTR", ")", ";", "}", "else", "{", "request", ".", "setAttribute", "(", "IGNORE_INCLUDE_SERVLET_PATH_ATTR", ",", "depth", ")", ";", "}", "}", "}" ]
Tell {@link #getDecodedServletPath} (and all that call it) to ignore the attribute that specifies the Servlet Include path, which is set when a Servlet include is done through RequestDispatcher. Normally, getDecodedServletPath tries the Servlet Include path before falling back to getServletPath() on the request. Note that this is basically a stack of instructions to ignore the include path, and this method expects each call with <code>ignore</code>==<code>true</code> to be balanced by a call with <code>ignore</code>==<code>false</code>.
[ "Tell", "{" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/internal/InternalUtils.java#L1100-L1123
jenkinsci/jenkins
core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java
WindowsInstallerLink.runElevated
static int runElevated(File jenkinsExe, String command, TaskListener out, File pwd) throws IOException, InterruptedException { """ Invokes jenkins.exe with a SCM management command. <p> If it fails in a way that indicates the presence of UAC, retry in an UAC compatible manner. """ try { return new LocalLauncher(out).launch().cmds(jenkinsExe, command).stdout(out).pwd(pwd).join(); } catch (IOException e) { if (e.getMessage().contains("CreateProcess") && e.getMessage().contains("=740")) { // fall through } else { throw e; } } // error code 740 is ERROR_ELEVATION_REQUIRED, indicating that // we run in UAC-enabled Windows and we need to run this in an elevated privilege SHELLEXECUTEINFO sei = new SHELLEXECUTEINFO(); sei.fMask = SEE_MASK_NOCLOSEPROCESS; sei.lpVerb = "runas"; sei.lpFile = jenkinsExe.getAbsolutePath(); sei.lpParameters = "/redirect redirect.log "+command; sei.lpDirectory = pwd.getAbsolutePath(); sei.nShow = SW_HIDE; if (!Shell32.INSTANCE.ShellExecuteEx(sei)) throw new IOException("Failed to shellExecute: "+ Native.getLastError()); try { return Kernel32Utils.waitForExitProcess(sei.hProcess); } finally { try (InputStream fin = Files.newInputStream(new File(pwd,"redirect.log").toPath())) { IOUtils.copy(fin, out.getLogger()); } catch (InvalidPathException e) { // ignore; } } }
java
static int runElevated(File jenkinsExe, String command, TaskListener out, File pwd) throws IOException, InterruptedException { try { return new LocalLauncher(out).launch().cmds(jenkinsExe, command).stdout(out).pwd(pwd).join(); } catch (IOException e) { if (e.getMessage().contains("CreateProcess") && e.getMessage().contains("=740")) { // fall through } else { throw e; } } // error code 740 is ERROR_ELEVATION_REQUIRED, indicating that // we run in UAC-enabled Windows and we need to run this in an elevated privilege SHELLEXECUTEINFO sei = new SHELLEXECUTEINFO(); sei.fMask = SEE_MASK_NOCLOSEPROCESS; sei.lpVerb = "runas"; sei.lpFile = jenkinsExe.getAbsolutePath(); sei.lpParameters = "/redirect redirect.log "+command; sei.lpDirectory = pwd.getAbsolutePath(); sei.nShow = SW_HIDE; if (!Shell32.INSTANCE.ShellExecuteEx(sei)) throw new IOException("Failed to shellExecute: "+ Native.getLastError()); try { return Kernel32Utils.waitForExitProcess(sei.hProcess); } finally { try (InputStream fin = Files.newInputStream(new File(pwd,"redirect.log").toPath())) { IOUtils.copy(fin, out.getLogger()); } catch (InvalidPathException e) { // ignore; } } }
[ "static", "int", "runElevated", "(", "File", "jenkinsExe", ",", "String", "command", ",", "TaskListener", "out", ",", "File", "pwd", ")", "throws", "IOException", ",", "InterruptedException", "{", "try", "{", "return", "new", "LocalLauncher", "(", "out", ")", ".", "launch", "(", ")", ".", "cmds", "(", "jenkinsExe", ",", "command", ")", ".", "stdout", "(", "out", ")", ".", "pwd", "(", "pwd", ")", ".", "join", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "e", ".", "getMessage", "(", ")", ".", "contains", "(", "\"CreateProcess\"", ")", "&&", "e", ".", "getMessage", "(", ")", ".", "contains", "(", "\"=740\"", ")", ")", "{", "// fall through", "}", "else", "{", "throw", "e", ";", "}", "}", "// error code 740 is ERROR_ELEVATION_REQUIRED, indicating that", "// we run in UAC-enabled Windows and we need to run this in an elevated privilege", "SHELLEXECUTEINFO", "sei", "=", "new", "SHELLEXECUTEINFO", "(", ")", ";", "sei", ".", "fMask", "=", "SEE_MASK_NOCLOSEPROCESS", ";", "sei", ".", "lpVerb", "=", "\"runas\"", ";", "sei", ".", "lpFile", "=", "jenkinsExe", ".", "getAbsolutePath", "(", ")", ";", "sei", ".", "lpParameters", "=", "\"/redirect redirect.log \"", "+", "command", ";", "sei", ".", "lpDirectory", "=", "pwd", ".", "getAbsolutePath", "(", ")", ";", "sei", ".", "nShow", "=", "SW_HIDE", ";", "if", "(", "!", "Shell32", ".", "INSTANCE", ".", "ShellExecuteEx", "(", "sei", ")", ")", "throw", "new", "IOException", "(", "\"Failed to shellExecute: \"", "+", "Native", ".", "getLastError", "(", ")", ")", ";", "try", "{", "return", "Kernel32Utils", ".", "waitForExitProcess", "(", "sei", ".", "hProcess", ")", ";", "}", "finally", "{", "try", "(", "InputStream", "fin", "=", "Files", ".", "newInputStream", "(", "new", "File", "(", "pwd", ",", "\"redirect.log\"", ")", ".", "toPath", "(", ")", ")", ")", "{", "IOUtils", ".", "copy", "(", "fin", ",", "out", ".", "getLogger", "(", ")", ")", ";", "}", "catch", "(", "InvalidPathException", "e", ")", "{", "// ignore;", "}", "}", "}" ]
Invokes jenkins.exe with a SCM management command. <p> If it fails in a way that indicates the presence of UAC, retry in an UAC compatible manner.
[ "Invokes", "jenkins", ".", "exe", "with", "a", "SCM", "management", "command", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java#L286-L318
hedyn/wsonrpc
wsonrpc-core/src/main/java/net/apexes/wsonrpc/core/JsonRpcControl.java
JsonRpcControl.receiveRequest
public void receiveRequest(byte[] bytes, Transport transport) throws IOException, WsonrpcException { """ 接收远端的调用请求,并将回复执行结果。 @param bytes 接收到的数据 @param transport {@link Transport} 实例 @throws IOException @throws WsonrpcException """ JsonRpcResponse resp; try { JsonRpcMessage msg = receive(bytes); if (msg instanceof JsonRpcRequest) { JsonRpcRequest req = (JsonRpcRequest) msg; resp = execute(req); } else { resp = new JsonRpcResponse(null, JsonRpcError.invalidRequestError(null)); } } catch (JsonException e) { resp = new JsonRpcResponse(null, JsonRpcError.parseError(e)); } catch (IOException e) { resp = new JsonRpcResponse(null, JsonRpcError.internalError(e)); } transmit(transport, resp); }
java
public void receiveRequest(byte[] bytes, Transport transport) throws IOException, WsonrpcException { JsonRpcResponse resp; try { JsonRpcMessage msg = receive(bytes); if (msg instanceof JsonRpcRequest) { JsonRpcRequest req = (JsonRpcRequest) msg; resp = execute(req); } else { resp = new JsonRpcResponse(null, JsonRpcError.invalidRequestError(null)); } } catch (JsonException e) { resp = new JsonRpcResponse(null, JsonRpcError.parseError(e)); } catch (IOException e) { resp = new JsonRpcResponse(null, JsonRpcError.internalError(e)); } transmit(transport, resp); }
[ "public", "void", "receiveRequest", "(", "byte", "[", "]", "bytes", ",", "Transport", "transport", ")", "throws", "IOException", ",", "WsonrpcException", "{", "JsonRpcResponse", "resp", ";", "try", "{", "JsonRpcMessage", "msg", "=", "receive", "(", "bytes", ")", ";", "if", "(", "msg", "instanceof", "JsonRpcRequest", ")", "{", "JsonRpcRequest", "req", "=", "(", "JsonRpcRequest", ")", "msg", ";", "resp", "=", "execute", "(", "req", ")", ";", "}", "else", "{", "resp", "=", "new", "JsonRpcResponse", "(", "null", ",", "JsonRpcError", ".", "invalidRequestError", "(", "null", ")", ")", ";", "}", "}", "catch", "(", "JsonException", "e", ")", "{", "resp", "=", "new", "JsonRpcResponse", "(", "null", ",", "JsonRpcError", ".", "parseError", "(", "e", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "resp", "=", "new", "JsonRpcResponse", "(", "null", ",", "JsonRpcError", ".", "internalError", "(", "e", ")", ")", ";", "}", "transmit", "(", "transport", ",", "resp", ")", ";", "}" ]
接收远端的调用请求,并将回复执行结果。 @param bytes 接收到的数据 @param transport {@link Transport} 实例 @throws IOException @throws WsonrpcException
[ "接收远端的调用请求,并将回复执行结果。" ]
train
https://github.com/hedyn/wsonrpc/blob/decbaad4cb8145590bab039d5cfe12437ada0d0a/wsonrpc-core/src/main/java/net/apexes/wsonrpc/core/JsonRpcControl.java#L65-L81
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java
StringGroovyMethods.eachMatch
public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options= { """ Process each regex group matched substring of the given CharSequence. If the closure parameter takes one argument, an array with all match groups is passed to it. If the closure takes as many arguments as there are match groups, then each parameter will be one match group. @param self the source CharSequence @param regex a Regex CharSequence @param closure a closure with one parameter or as much parameters as groups @return the source CharSequence @see #eachMatch(String, String, groovy.lang.Closure) @since 1.8.2 """"List<String>","String[]"}) Closure closure) { eachMatch(self.toString(), regex.toString(), closure); return self; }
java
public static <T extends CharSequence> T eachMatch(T self, CharSequence regex, @ClosureParams(value=FromString.class, options={"List<String>","String[]"}) Closure closure) { eachMatch(self.toString(), regex.toString(), closure); return self; }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "eachMatch", "(", "T", "self", ",", "CharSequence", "regex", ",", "@", "ClosureParams", "(", "value", "=", "FromString", ".", "class", ",", "options", "=", "{", "\"List<String>\"", ",", "\"String[]\"", "}", ")", "Closure", "closure", ")", "{", "eachMatch", "(", "self", ".", "toString", "(", ")", ",", "regex", ".", "toString", "(", ")", ",", "closure", ")", ";", "return", "self", ";", "}" ]
Process each regex group matched substring of the given CharSequence. If the closure parameter takes one argument, an array with all match groups is passed to it. If the closure takes as many arguments as there are match groups, then each parameter will be one match group. @param self the source CharSequence @param regex a Regex CharSequence @param closure a closure with one parameter or as much parameters as groups @return the source CharSequence @see #eachMatch(String, String, groovy.lang.Closure) @since 1.8.2
[ "Process", "each", "regex", "group", "matched", "substring", "of", "the", "given", "CharSequence", ".", "If", "the", "closure", "parameter", "takes", "one", "argument", "an", "array", "with", "all", "match", "groups", "is", "passed", "to", "it", ".", "If", "the", "closure", "takes", "as", "many", "arguments", "as", "there", "are", "match", "groups", "then", "each", "parameter", "will", "be", "one", "match", "group", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L692-L695
EXIficient/exificient-grammars
src/main/java/com/siemens/ct/exi/grammars/regex/RegularExpression.java
RegularExpression.matches
public boolean matches(String target, int start, int end) { """ Checks whether the <var>target</var> text <strong>contains</strong> this pattern in specified range or not. @param start Start offset of the range. @param end End offset +1 of the range. @return true if the target is matched to this regular expression. """ return this.matches(target, start, end, (Match) null); }
java
public boolean matches(String target, int start, int end) { return this.matches(target, start, end, (Match) null); }
[ "public", "boolean", "matches", "(", "String", "target", ",", "int", "start", ",", "int", "end", ")", "{", "return", "this", ".", "matches", "(", "target", ",", "start", ",", "end", ",", "(", "Match", ")", "null", ")", ";", "}" ]
Checks whether the <var>target</var> text <strong>contains</strong> this pattern in specified range or not. @param start Start offset of the range. @param end End offset +1 of the range. @return true if the target is matched to this regular expression.
[ "Checks", "whether", "the", "<var", ">", "target<", "/", "var", ">", "text", "<strong", ">", "contains<", "/", "strong", ">", "this", "pattern", "in", "specified", "range", "or", "not", "." ]
train
https://github.com/EXIficient/exificient-grammars/blob/d96477062ebdd4245920e44cc1995259699fc7fb/src/main/java/com/siemens/ct/exi/grammars/regex/RegularExpression.java#L981-L983
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/snapshot/SnapshotCreator.java
SnapshotCreator.createStatSnapshot
private static StatSnapshot createStatSnapshot(IStats stat, String intervalName, List<String> valueNames) { """ Creates a snapshot for one stat object. @param stat @param intervalName @param valueNames @return """ StatSnapshot snapshot = new StatSnapshot(stat.getName()); for (String valueName : valueNames){ snapshot.setValue(valueName, stat.getValueByNameAsString(valueName, intervalName, TimeUnit.NANOSECONDS)); } return snapshot; }
java
private static StatSnapshot createStatSnapshot(IStats stat, String intervalName, List<String> valueNames){ StatSnapshot snapshot = new StatSnapshot(stat.getName()); for (String valueName : valueNames){ snapshot.setValue(valueName, stat.getValueByNameAsString(valueName, intervalName, TimeUnit.NANOSECONDS)); } return snapshot; }
[ "private", "static", "StatSnapshot", "createStatSnapshot", "(", "IStats", "stat", ",", "String", "intervalName", ",", "List", "<", "String", ">", "valueNames", ")", "{", "StatSnapshot", "snapshot", "=", "new", "StatSnapshot", "(", "stat", ".", "getName", "(", ")", ")", ";", "for", "(", "String", "valueName", ":", "valueNames", ")", "{", "snapshot", ".", "setValue", "(", "valueName", ",", "stat", ".", "getValueByNameAsString", "(", "valueName", ",", "intervalName", ",", "TimeUnit", ".", "NANOSECONDS", ")", ")", ";", "}", "return", "snapshot", ";", "}" ]
Creates a snapshot for one stat object. @param stat @param intervalName @param valueNames @return
[ "Creates", "a", "snapshot", "for", "one", "stat", "object", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/snapshot/SnapshotCreator.java#L55-L66
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/protocol/LayoutVersion.java
LayoutVersion.supports
public static boolean supports(final Feature f, final int lv) { """ Returns true if a given feature is supported in the given layout version @param f Feature @param lv LayoutVersion @return true if {@code f} is supported in layout version {@code lv} """ final EnumSet<Feature> set = map.get(lv); return set != null && set.contains(f); }
java
public static boolean supports(final Feature f, final int lv) { final EnumSet<Feature> set = map.get(lv); return set != null && set.contains(f); }
[ "public", "static", "boolean", "supports", "(", "final", "Feature", "f", ",", "final", "int", "lv", ")", "{", "final", "EnumSet", "<", "Feature", ">", "set", "=", "map", ".", "get", "(", "lv", ")", ";", "return", "set", "!=", "null", "&&", "set", ".", "contains", "(", "f", ")", ";", "}" ]
Returns true if a given feature is supported in the given layout version @param f Feature @param lv LayoutVersion @return true if {@code f} is supported in layout version {@code lv}
[ "Returns", "true", "if", "a", "given", "feature", "is", "supported", "in", "the", "given", "layout", "version" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/protocol/LayoutVersion.java#L181-L184
google/closure-compiler
src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java
SourceMapGeneratorV3.mergeMapSection
public void mergeMapSection(int line, int column, String mapSectionContents) throws SourceMapParseException { """ Merges current mapping with {@code mapSectionContents} considering the offset {@code (line, column)}. Any extension in the map section will be ignored. @param line The line offset @param column The column offset @param mapSectionContents The map section to be appended @throws SourceMapParseException """ setStartingPosition(line, column); SourceMapConsumerV3 section = new SourceMapConsumerV3(); section.parse(mapSectionContents); section.visitMappings(new ConsumerEntryVisitor()); }
java
public void mergeMapSection(int line, int column, String mapSectionContents) throws SourceMapParseException { setStartingPosition(line, column); SourceMapConsumerV3 section = new SourceMapConsumerV3(); section.parse(mapSectionContents); section.visitMappings(new ConsumerEntryVisitor()); }
[ "public", "void", "mergeMapSection", "(", "int", "line", ",", "int", "column", ",", "String", "mapSectionContents", ")", "throws", "SourceMapParseException", "{", "setStartingPosition", "(", "line", ",", "column", ")", ";", "SourceMapConsumerV3", "section", "=", "new", "SourceMapConsumerV3", "(", ")", ";", "section", ".", "parse", "(", "mapSectionContents", ")", ";", "section", ".", "visitMappings", "(", "new", "ConsumerEntryVisitor", "(", ")", ")", ";", "}" ]
Merges current mapping with {@code mapSectionContents} considering the offset {@code (line, column)}. Any extension in the map section will be ignored. @param line The line offset @param column The column offset @param mapSectionContents The map section to be appended @throws SourceMapParseException
[ "Merges", "current", "mapping", "with", "{", "@code", "mapSectionContents", "}", "considering", "the", "offset", "{", "@code", "(", "line", "column", ")", "}", ".", "Any", "extension", "in", "the", "map", "section", "will", "be", "ignored", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/debugging/sourcemap/SourceMapGeneratorV3.java#L298-L304
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java
ProjectiveStructureByFactorization.getFeature3D
public void getFeature3D( int feature , Point4D_F64 out ) { """ Returns location of 3D feature for a view @param feature Index of feature to retrieve @param out (Output) Storage for 3D feature. homogenous coordinates """ out.x = X.get(0,feature); out.y = X.get(1,feature); out.z = X.get(2,feature); out.w = X.get(3,feature); }
java
public void getFeature3D( int feature , Point4D_F64 out ) { out.x = X.get(0,feature); out.y = X.get(1,feature); out.z = X.get(2,feature); out.w = X.get(3,feature); }
[ "public", "void", "getFeature3D", "(", "int", "feature", ",", "Point4D_F64", "out", ")", "{", "out", ".", "x", "=", "X", ".", "get", "(", "0", ",", "feature", ")", ";", "out", ".", "y", "=", "X", ".", "get", "(", "1", ",", "feature", ")", ";", "out", ".", "z", "=", "X", ".", "get", "(", "2", ",", "feature", ")", ";", "out", ".", "w", "=", "X", ".", "get", "(", "3", ",", "feature", ")", ";", "}" ]
Returns location of 3D feature for a view @param feature Index of feature to retrieve @param out (Output) Storage for 3D feature. homogenous coordinates
[ "Returns", "location", "of", "3D", "feature", "for", "a", "view" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/structure/ProjectiveStructureByFactorization.java#L234-L239
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/DatagramPacket.java
DatagramPacket.setData
public synchronized void setData(byte[] buf, int offset, int length) { """ Set the data buffer for this packet. This sets the data, length and offset of the packet. @param buf the buffer to set for this packet @param offset the offset into the data @param length the length of the data and/or the length of the buffer used to receive data @exception NullPointerException if the argument is null @see #getData @see #getOffset @see #getLength @since 1.2 """ /* this will check to see if buf is null */ if (length < 0 || offset < 0 || (length + offset) < 0 || ((length + offset) > buf.length)) { throw new IllegalArgumentException("illegal length or offset"); } this.buf = buf; this.length = length; this.bufLength = length; this.offset = offset; }
java
public synchronized void setData(byte[] buf, int offset, int length) { /* this will check to see if buf is null */ if (length < 0 || offset < 0 || (length + offset) < 0 || ((length + offset) > buf.length)) { throw new IllegalArgumentException("illegal length or offset"); } this.buf = buf; this.length = length; this.bufLength = length; this.offset = offset; }
[ "public", "synchronized", "void", "setData", "(", "byte", "[", "]", "buf", ",", "int", "offset", ",", "int", "length", ")", "{", "/* this will check to see if buf is null */", "if", "(", "length", "<", "0", "||", "offset", "<", "0", "||", "(", "length", "+", "offset", ")", "<", "0", "||", "(", "(", "length", "+", "offset", ")", ">", "buf", ".", "length", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"illegal length or offset\"", ")", ";", "}", "this", ".", "buf", "=", "buf", ";", "this", ".", "length", "=", "length", ";", "this", ".", "bufLength", "=", "length", ";", "this", ".", "offset", "=", "offset", ";", "}" ]
Set the data buffer for this packet. This sets the data, length and offset of the packet. @param buf the buffer to set for this packet @param offset the offset into the data @param length the length of the data and/or the length of the buffer used to receive data @exception NullPointerException if the argument is null @see #getData @see #getOffset @see #getLength @since 1.2
[ "Set", "the", "data", "buffer", "for", "this", "packet", ".", "This", "sets", "the", "data", "length", "and", "offset", "of", "the", "packet", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/DatagramPacket.java#L261-L272
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java
DefaultIncrementalAttributesMapper.lookupAttributes
public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String[] attributes) { """ Lookup all values for the specified attributes, looping through the results incrementally if necessary. @param ldapOperations The instance to use for performing the actual lookup. @param dn The distinguished name of the object to find. @param attributes names of the attributes to request. @return an Attributes instance, populated with all found values for the requested attributes. Never <code>null</code>, though the actual attributes may not be set if they was not set on the requested object. """ return loopForAllAttributeValues(ldapOperations, dn, attributes).getCollectedAttributes(); }
java
public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String[] attributes) { return loopForAllAttributeValues(ldapOperations, dn, attributes).getCollectedAttributes(); }
[ "public", "static", "Attributes", "lookupAttributes", "(", "LdapOperations", "ldapOperations", ",", "Name", "dn", ",", "String", "[", "]", "attributes", ")", "{", "return", "loopForAllAttributeValues", "(", "ldapOperations", ",", "dn", ",", "attributes", ")", ".", "getCollectedAttributes", "(", ")", ";", "}" ]
Lookup all values for the specified attributes, looping through the results incrementally if necessary. @param ldapOperations The instance to use for performing the actual lookup. @param dn The distinguished name of the object to find. @param attributes names of the attributes to request. @return an Attributes instance, populated with all found values for the requested attributes. Never <code>null</code>, though the actual attributes may not be set if they was not set on the requested object.
[ "Lookup", "all", "values", "for", "the", "specified", "attributes", "looping", "through", "the", "results", "incrementally", "if", "necessary", "." ]
train
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java#L304-L306
nightcode/yaranga
core/src/org/nightcode/common/base/Objects.java
Objects.validState
public static void validState(boolean expression, String message, Object... messageArgs) { """ Checks boolean expression. @param expression a boolean expression @param message error message @param messageArgs array of parameters to the message @throws IllegalArgumentException if boolean expression is false """ if (!expression) { throw new IllegalStateException(format(message, messageArgs)); } }
java
public static void validState(boolean expression, String message, Object... messageArgs) { if (!expression) { throw new IllegalStateException(format(message, messageArgs)); } }
[ "public", "static", "void", "validState", "(", "boolean", "expression", ",", "String", "message", ",", "Object", "...", "messageArgs", ")", "{", "if", "(", "!", "expression", ")", "{", "throw", "new", "IllegalStateException", "(", "format", "(", "message", ",", "messageArgs", ")", ")", ";", "}", "}" ]
Checks boolean expression. @param expression a boolean expression @param message error message @param messageArgs array of parameters to the message @throws IllegalArgumentException if boolean expression is false
[ "Checks", "boolean", "expression", "." ]
train
https://github.com/nightcode/yaranga/blob/f02cf8d8bcd365b6b1d55638938631a00e9ee808/core/src/org/nightcode/common/base/Objects.java#L76-L80
graphhopper/graphhopper
core/src/main/java/com/graphhopper/reader/ReaderElement.java
ReaderElement.hasTag
public boolean hasTag(List<String> keyList, Set<String> values) { """ Check a number of tags in the given order for the any of the given values. Used to parse hierarchical access restrictions """ for (String key : keyList) { if (values.contains(getTag(key, ""))) return true; } return false; }
java
public boolean hasTag(List<String> keyList, Set<String> values) { for (String key : keyList) { if (values.contains(getTag(key, ""))) return true; } return false; }
[ "public", "boolean", "hasTag", "(", "List", "<", "String", ">", "keyList", ",", "Set", "<", "String", ">", "values", ")", "{", "for", "(", "String", "key", ":", "keyList", ")", "{", "if", "(", "values", ".", "contains", "(", "getTag", "(", "key", ",", "\"\"", ")", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check a number of tags in the given order for the any of the given values. Used to parse hierarchical access restrictions
[ "Check", "a", "number", "of", "tags", "in", "the", "given", "order", "for", "the", "any", "of", "the", "given", "values", ".", "Used", "to", "parse", "hierarchical", "access", "restrictions" ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/ReaderElement.java#L140-L146
Jasig/uPortal
uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/properties/PropertyToAttributePropertiesManager.java
PropertyToAttributePropertiesManager.setPropertyMappings
@Resource(name = "portletPropertyToAttributeMappings") public void setPropertyMappings(Map<String, String> propertyMappings) { """ Map of portlet property names to attribute names, if the value is null the key will be used for both the property and attribute name """ this.propertyToAttributeMappings = ImmutableBiMap.copyOf(propertyMappings); this.attributeToPropertyMappings = this.propertyToAttributeMappings.inverse(); }
java
@Resource(name = "portletPropertyToAttributeMappings") public void setPropertyMappings(Map<String, String> propertyMappings) { this.propertyToAttributeMappings = ImmutableBiMap.copyOf(propertyMappings); this.attributeToPropertyMappings = this.propertyToAttributeMappings.inverse(); }
[ "@", "Resource", "(", "name", "=", "\"portletPropertyToAttributeMappings\"", ")", "public", "void", "setPropertyMappings", "(", "Map", "<", "String", ",", "String", ">", "propertyMappings", ")", "{", "this", ".", "propertyToAttributeMappings", "=", "ImmutableBiMap", ".", "copyOf", "(", "propertyMappings", ")", ";", "this", ".", "attributeToPropertyMappings", "=", "this", ".", "propertyToAttributeMappings", ".", "inverse", "(", ")", ";", "}" ]
Map of portlet property names to attribute names, if the value is null the key will be used for both the property and attribute name
[ "Map", "of", "portlet", "property", "names", "to", "attribute", "names", "if", "the", "value", "is", "null", "the", "key", "will", "be", "used", "for", "both", "the", "property", "and", "attribute", "name" ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/properties/PropertyToAttributePropertiesManager.java#L51-L55
intive-FDV/DynamicJasper
src/main/java/ar/com/fdvs/dj/domain/builders/CrosstabRowBuilder.java
CrosstabRowBuilder.setProperty
public CrosstabRowBuilder setProperty(String property, String className) { """ DJCrosstabRow row = new DJCrosstabRow(); row.setProperty(new ColumnProperty("productLine",String.class.getName())); row.setHeaderWidth(100); row.setHeight(30); row.setTitle("Product Line my mother teressa"); row.setShowTotals(true); row.setTotalStyle(totalStyle); row.setTotalHeaderStyle(totalHeader); row.setHeaderStyle(colAndRowHeaderStyle); @param property @param className @return """ row.setProperty(new ColumnProperty(property,className)); return this; }
java
public CrosstabRowBuilder setProperty(String property, String className){ row.setProperty(new ColumnProperty(property,className)); return this; }
[ "public", "CrosstabRowBuilder", "setProperty", "(", "String", "property", ",", "String", "className", ")", "{", "row", ".", "setProperty", "(", "new", "ColumnProperty", "(", "property", ",", "className", ")", ")", ";", "return", "this", ";", "}" ]
DJCrosstabRow row = new DJCrosstabRow(); row.setProperty(new ColumnProperty("productLine",String.class.getName())); row.setHeaderWidth(100); row.setHeight(30); row.setTitle("Product Line my mother teressa"); row.setShowTotals(true); row.setTotalStyle(totalStyle); row.setTotalHeaderStyle(totalHeader); row.setHeaderStyle(colAndRowHeaderStyle); @param property @param className @return
[ "DJCrosstabRow", "row", "=", "new", "DJCrosstabRow", "()", ";", "row", ".", "setProperty", "(", "new", "ColumnProperty", "(", "productLine", "String", ".", "class", ".", "getName", "()", "))", ";", "row", ".", "setHeaderWidth", "(", "100", ")", ";", "row", ".", "setHeight", "(", "30", ")", ";", "row", ".", "setTitle", "(", "Product", "Line", "my", "mother", "teressa", ")", ";", "row", ".", "setShowTotals", "(", "true", ")", ";", "row", ".", "setTotalStyle", "(", "totalStyle", ")", ";", "row", ".", "setTotalHeaderStyle", "(", "totalHeader", ")", ";", "row", ".", "setHeaderStyle", "(", "colAndRowHeaderStyle", ")", ";" ]
train
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/domain/builders/CrosstabRowBuilder.java#L59-L62
CenturyLinkCloud/mdw
mdw-workflow/src/com/centurylink/mdw/workflow/adapter/jms/JmsAdapter.java
JmsAdapter.openConnection
@Override protected Object openConnection() throws ConnectionException { """ The method overrides the one in the super class to perform JMS specific functions. """ qConnection = null; qSession = null; queue = null; try { String server_url = this.getAttributeValueSmart(SERVER_URL); if ("THIS_SERVER".equals(server_url)) server_url = null; String queue_name = this.getQueueName(); JMSServices jmsServices = JMSServices.getInstance(); QueueConnectionFactory qFactory = jmsServices.getQueueConnectionFactory(server_url); qConnection = qFactory.createQueueConnection(); qSession = qConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); qConnection.start(); queue = jmsServices.getQueue(qSession, queue_name); } catch (Exception e) { logger.severeException("Exception in JmsAdapter.openConnection()" , e); throw new ConnectionException(ConnectionException.CONNECTION_DOWN, "Exception in invoking JmsAdapter" , e); } return qSession; }
java
@Override protected Object openConnection() throws ConnectionException { qConnection = null; qSession = null; queue = null; try { String server_url = this.getAttributeValueSmart(SERVER_URL); if ("THIS_SERVER".equals(server_url)) server_url = null; String queue_name = this.getQueueName(); JMSServices jmsServices = JMSServices.getInstance(); QueueConnectionFactory qFactory = jmsServices.getQueueConnectionFactory(server_url); qConnection = qFactory.createQueueConnection(); qSession = qConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); qConnection.start(); queue = jmsServices.getQueue(qSession, queue_name); } catch (Exception e) { logger.severeException("Exception in JmsAdapter.openConnection()" , e); throw new ConnectionException(ConnectionException.CONNECTION_DOWN, "Exception in invoking JmsAdapter" , e); } return qSession; }
[ "@", "Override", "protected", "Object", "openConnection", "(", ")", "throws", "ConnectionException", "{", "qConnection", "=", "null", ";", "qSession", "=", "null", ";", "queue", "=", "null", ";", "try", "{", "String", "server_url", "=", "this", ".", "getAttributeValueSmart", "(", "SERVER_URL", ")", ";", "if", "(", "\"THIS_SERVER\"", ".", "equals", "(", "server_url", ")", ")", "server_url", "=", "null", ";", "String", "queue_name", "=", "this", ".", "getQueueName", "(", ")", ";", "JMSServices", "jmsServices", "=", "JMSServices", ".", "getInstance", "(", ")", ";", "QueueConnectionFactory", "qFactory", "=", "jmsServices", ".", "getQueueConnectionFactory", "(", "server_url", ")", ";", "qConnection", "=", "qFactory", ".", "createQueueConnection", "(", ")", ";", "qSession", "=", "qConnection", ".", "createQueueSession", "(", "false", ",", "Session", ".", "AUTO_ACKNOWLEDGE", ")", ";", "qConnection", ".", "start", "(", ")", ";", "queue", "=", "jmsServices", ".", "getQueue", "(", "qSession", ",", "queue_name", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "severeException", "(", "\"Exception in JmsAdapter.openConnection()\"", ",", "e", ")", ";", "throw", "new", "ConnectionException", "(", "ConnectionException", ".", "CONNECTION_DOWN", ",", "\"Exception in invoking JmsAdapter\"", ",", "e", ")", ";", "}", "return", "qSession", ";", "}" ]
The method overrides the one in the super class to perform JMS specific functions.
[ "The", "method", "overrides", "the", "one", "in", "the", "super", "class", "to", "perform", "JMS", "specific", "functions", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/src/com/centurylink/mdw/workflow/adapter/jms/JmsAdapter.java#L263-L284
sarl/sarl
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java
SARLQuickfixProvider.fixNoViableAlternativeAtKeyword
@Fix(SyntaxIssueCodes.USED_RESERVED_KEYWORD) public void fixNoViableAlternativeAtKeyword(final Issue issue, IssueResolutionAcceptor acceptor) { """ Quick fix for the no viable alternative at an input that is a SARL keyword. @param issue the issue. @param acceptor the quick fix acceptor. """ ProtectKeywordModification.accept(this, issue, acceptor); }
java
@Fix(SyntaxIssueCodes.USED_RESERVED_KEYWORD) public void fixNoViableAlternativeAtKeyword(final Issue issue, IssueResolutionAcceptor acceptor) { ProtectKeywordModification.accept(this, issue, acceptor); }
[ "@", "Fix", "(", "SyntaxIssueCodes", ".", "USED_RESERVED_KEYWORD", ")", "public", "void", "fixNoViableAlternativeAtKeyword", "(", "final", "Issue", "issue", ",", "IssueResolutionAcceptor", "acceptor", ")", "{", "ProtectKeywordModification", ".", "accept", "(", "this", ",", "issue", ",", "acceptor", ")", ";", "}" ]
Quick fix for the no viable alternative at an input that is a SARL keyword. @param issue the issue. @param acceptor the quick fix acceptor.
[ "Quick", "fix", "for", "the", "no", "viable", "alternative", "at", "an", "input", "that", "is", "a", "SARL", "keyword", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L964-L967
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageFileSystem.java
GoogleCloudStorageFileSystem.deleteInternal
private void deleteInternal(List<FileInfo> itemsToDelete, List<FileInfo> bucketsToDelete) throws IOException { """ Deletes all items in the given path list followed by all bucket items. """ // TODO(user): We might need to separate out children into separate batches from parents to // avoid deleting a parent before somehow failing to delete a child. // Delete children before their parents. // // Note: we modify the input list, which is ok for current usage. // We should make a copy in case that changes in future. itemsToDelete.sort(FILE_INFO_PATH_COMPARATOR.reversed()); if (!itemsToDelete.isEmpty()) { List<StorageResourceId> objectsToDelete = new ArrayList<>(itemsToDelete.size()); for (FileInfo fileInfo : itemsToDelete) { // TODO(b/110833109): populate generation ID in StorageResourceId when listing infos? objectsToDelete.add( new StorageResourceId( fileInfo.getItemInfo().getBucketName(), fileInfo.getItemInfo().getObjectName(), fileInfo.getItemInfo().getContentGeneration())); } gcs.deleteObjects(objectsToDelete); } if (!bucketsToDelete.isEmpty()) { List<String> bucketNames = new ArrayList<>(bucketsToDelete.size()); for (FileInfo bucketInfo : bucketsToDelete) { StorageResourceId resourceId = bucketInfo.getItemInfo().getResourceId(); gcs.waitForBucketEmpty(resourceId.getBucketName()); bucketNames.add(resourceId.getBucketName()); } if (options.enableBucketDelete()) { gcs.deleteBuckets(bucketNames); } else { logger.atInfo().log( "Skipping deletion of buckets because enableBucketDelete is false: %s", bucketNames); } } }
java
private void deleteInternal(List<FileInfo> itemsToDelete, List<FileInfo> bucketsToDelete) throws IOException { // TODO(user): We might need to separate out children into separate batches from parents to // avoid deleting a parent before somehow failing to delete a child. // Delete children before their parents. // // Note: we modify the input list, which is ok for current usage. // We should make a copy in case that changes in future. itemsToDelete.sort(FILE_INFO_PATH_COMPARATOR.reversed()); if (!itemsToDelete.isEmpty()) { List<StorageResourceId> objectsToDelete = new ArrayList<>(itemsToDelete.size()); for (FileInfo fileInfo : itemsToDelete) { // TODO(b/110833109): populate generation ID in StorageResourceId when listing infos? objectsToDelete.add( new StorageResourceId( fileInfo.getItemInfo().getBucketName(), fileInfo.getItemInfo().getObjectName(), fileInfo.getItemInfo().getContentGeneration())); } gcs.deleteObjects(objectsToDelete); } if (!bucketsToDelete.isEmpty()) { List<String> bucketNames = new ArrayList<>(bucketsToDelete.size()); for (FileInfo bucketInfo : bucketsToDelete) { StorageResourceId resourceId = bucketInfo.getItemInfo().getResourceId(); gcs.waitForBucketEmpty(resourceId.getBucketName()); bucketNames.add(resourceId.getBucketName()); } if (options.enableBucketDelete()) { gcs.deleteBuckets(bucketNames); } else { logger.atInfo().log( "Skipping deletion of buckets because enableBucketDelete is false: %s", bucketNames); } } }
[ "private", "void", "deleteInternal", "(", "List", "<", "FileInfo", ">", "itemsToDelete", ",", "List", "<", "FileInfo", ">", "bucketsToDelete", ")", "throws", "IOException", "{", "// TODO(user): We might need to separate out children into separate batches from parents to", "// avoid deleting a parent before somehow failing to delete a child.", "// Delete children before their parents.", "//", "// Note: we modify the input list, which is ok for current usage.", "// We should make a copy in case that changes in future.", "itemsToDelete", ".", "sort", "(", "FILE_INFO_PATH_COMPARATOR", ".", "reversed", "(", ")", ")", ";", "if", "(", "!", "itemsToDelete", ".", "isEmpty", "(", ")", ")", "{", "List", "<", "StorageResourceId", ">", "objectsToDelete", "=", "new", "ArrayList", "<>", "(", "itemsToDelete", ".", "size", "(", ")", ")", ";", "for", "(", "FileInfo", "fileInfo", ":", "itemsToDelete", ")", "{", "// TODO(b/110833109): populate generation ID in StorageResourceId when listing infos?", "objectsToDelete", ".", "add", "(", "new", "StorageResourceId", "(", "fileInfo", ".", "getItemInfo", "(", ")", ".", "getBucketName", "(", ")", ",", "fileInfo", ".", "getItemInfo", "(", ")", ".", "getObjectName", "(", ")", ",", "fileInfo", ".", "getItemInfo", "(", ")", ".", "getContentGeneration", "(", ")", ")", ")", ";", "}", "gcs", ".", "deleteObjects", "(", "objectsToDelete", ")", ";", "}", "if", "(", "!", "bucketsToDelete", ".", "isEmpty", "(", ")", ")", "{", "List", "<", "String", ">", "bucketNames", "=", "new", "ArrayList", "<>", "(", "bucketsToDelete", ".", "size", "(", ")", ")", ";", "for", "(", "FileInfo", "bucketInfo", ":", "bucketsToDelete", ")", "{", "StorageResourceId", "resourceId", "=", "bucketInfo", ".", "getItemInfo", "(", ")", ".", "getResourceId", "(", ")", ";", "gcs", ".", "waitForBucketEmpty", "(", "resourceId", ".", "getBucketName", "(", ")", ")", ";", "bucketNames", ".", "add", "(", "resourceId", ".", "getBucketName", "(", ")", ")", ";", "}", "if", "(", "options", ".", "enableBucketDelete", "(", ")", ")", "{", "gcs", ".", "deleteBuckets", "(", "bucketNames", ")", ";", "}", "else", "{", "logger", ".", "atInfo", "(", ")", ".", "log", "(", "\"Skipping deletion of buckets because enableBucketDelete is false: %s\"", ",", "bucketNames", ")", ";", "}", "}", "}" ]
Deletes all items in the given path list followed by all bucket items.
[ "Deletes", "all", "items", "in", "the", "given", "path", "list", "followed", "by", "all", "bucket", "items", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageFileSystem.java#L416-L454
amzn/ion-java
src/com/amazon/ion/util/IonTextUtils.java
IonTextUtils.printCodePointAsSurrogatePairHexDigits
private static void printCodePointAsSurrogatePairHexDigits(Appendable out, int c) throws IOException { """ Generates a surrogate pair as two four-digit hex escape sequences, {@code "\}{@code u}<i>{@code HHHH}</i>{@code \}{@code u}<i>{@code HHHH}</i>{@code "}, using lower-case for alphabetics. This for necessary for JSON when the code point is outside the BMP. """ for (final char unit : Character.toChars(c)) { printCodePointAsFourHexDigits(out, unit); } }
java
private static void printCodePointAsSurrogatePairHexDigits(Appendable out, int c) throws IOException { for (final char unit : Character.toChars(c)) { printCodePointAsFourHexDigits(out, unit); } }
[ "private", "static", "void", "printCodePointAsSurrogatePairHexDigits", "(", "Appendable", "out", ",", "int", "c", ")", "throws", "IOException", "{", "for", "(", "final", "char", "unit", ":", "Character", ".", "toChars", "(", "c", ")", ")", "{", "printCodePointAsFourHexDigits", "(", "out", ",", "unit", ")", ";", "}", "}" ]
Generates a surrogate pair as two four-digit hex escape sequences, {@code "\}{@code u}<i>{@code HHHH}</i>{@code \}{@code u}<i>{@code HHHH}</i>{@code "}, using lower-case for alphabetics. This for necessary for JSON when the code point is outside the BMP.
[ "Generates", "a", "surrogate", "pair", "as", "two", "four", "-", "digit", "hex", "escape", "sequences", "{" ]
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonTextUtils.java#L384-L390
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/NormalizeUtils.java
NormalizeUtils.hashQuads
private static String hashQuads(String id, Map<String, Object> bnodes, UniqueNamer namer) { """ Hashes all of the quads about a blank node. @param id the ID of the bnode to hash quads for. @param bnodes the mapping of bnodes to quads. @param namer the canonical bnode namer. @return the new hash. """ // return cached hash if (((Map<String, Object>) bnodes.get(id)).containsKey("hash")) { return (String) ((Map<String, Object>) bnodes.get(id)).get("hash"); } // serialize all of bnode's quads final List<Map<String, Object>> quads = (List<Map<String, Object>>) ((Map<String, Object>) bnodes .get(id)).get("quads"); final List<String> nquads = new ArrayList<String>(); for (int i = 0; i < quads.size(); ++i) { nquads.add(toNQuad((RDFDataset.Quad) quads.get(i), quads.get(i).get("name") != null ? (String) ((Map<String, Object>) quads.get(i).get("name")).get("value") : null, id)); } // sort serialized quads Collections.sort(nquads); // return hashed quads final String hash = sha1hash(nquads); ((Map<String, Object>) bnodes.get(id)).put("hash", hash); return hash; }
java
private static String hashQuads(String id, Map<String, Object> bnodes, UniqueNamer namer) { // return cached hash if (((Map<String, Object>) bnodes.get(id)).containsKey("hash")) { return (String) ((Map<String, Object>) bnodes.get(id)).get("hash"); } // serialize all of bnode's quads final List<Map<String, Object>> quads = (List<Map<String, Object>>) ((Map<String, Object>) bnodes .get(id)).get("quads"); final List<String> nquads = new ArrayList<String>(); for (int i = 0; i < quads.size(); ++i) { nquads.add(toNQuad((RDFDataset.Quad) quads.get(i), quads.get(i).get("name") != null ? (String) ((Map<String, Object>) quads.get(i).get("name")).get("value") : null, id)); } // sort serialized quads Collections.sort(nquads); // return hashed quads final String hash = sha1hash(nquads); ((Map<String, Object>) bnodes.get(id)).put("hash", hash); return hash; }
[ "private", "static", "String", "hashQuads", "(", "String", "id", ",", "Map", "<", "String", ",", "Object", ">", "bnodes", ",", "UniqueNamer", "namer", ")", "{", "// return cached hash", "if", "(", "(", "(", "Map", "<", "String", ",", "Object", ">", ")", "bnodes", ".", "get", "(", "id", ")", ")", ".", "containsKey", "(", "\"hash\"", ")", ")", "{", "return", "(", "String", ")", "(", "(", "Map", "<", "String", ",", "Object", ">", ")", "bnodes", ".", "get", "(", "id", ")", ")", ".", "get", "(", "\"hash\"", ")", ";", "}", "// serialize all of bnode's quads", "final", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "quads", "=", "(", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ")", "(", "(", "Map", "<", "String", ",", "Object", ">", ")", "bnodes", ".", "get", "(", "id", ")", ")", ".", "get", "(", "\"quads\"", ")", ";", "final", "List", "<", "String", ">", "nquads", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "quads", ".", "size", "(", ")", ";", "++", "i", ")", "{", "nquads", ".", "add", "(", "toNQuad", "(", "(", "RDFDataset", ".", "Quad", ")", "quads", ".", "get", "(", "i", ")", ",", "quads", ".", "get", "(", "i", ")", ".", "get", "(", "\"name\"", ")", "!=", "null", "?", "(", "String", ")", "(", "(", "Map", "<", "String", ",", "Object", ">", ")", "quads", ".", "get", "(", "i", ")", ".", "get", "(", "\"name\"", ")", ")", ".", "get", "(", "\"value\"", ")", ":", "null", ",", "id", ")", ")", ";", "}", "// sort serialized quads", "Collections", ".", "sort", "(", "nquads", ")", ";", "// return hashed quads", "final", "String", "hash", "=", "sha1hash", "(", "nquads", ")", ";", "(", "(", "Map", "<", "String", ",", "Object", ">", ")", "bnodes", ".", "get", "(", "id", ")", ")", ".", "put", "(", "\"hash\"", ",", "hash", ")", ";", "return", "hash", ";", "}" ]
Hashes all of the quads about a blank node. @param id the ID of the bnode to hash quads for. @param bnodes the mapping of bnodes to quads. @param namer the canonical bnode namer. @return the new hash.
[ "Hashes", "all", "of", "the", "quads", "about", "a", "blank", "node", "." ]
train
https://github.com/jsonld-java/jsonld-java/blob/efeef6ee96029a0011649633457035fa6be42da1/core/src/main/java/com/github/jsonldjava/core/NormalizeUtils.java#L427-L450
alkacon/opencms-core
src/org/opencms/ui/components/CmsToolBar.java
CmsToolBar.openFavoriteDialog
public static void openFavoriteDialog(CmsFileExplorer explorer) { """ Opens the favorite dialog. @param explorer the explorer instance (null if not currently in explorer) """ try { CmsExplorerFavoriteContext context = new CmsExplorerFavoriteContext(A_CmsUI.getCmsObject(), explorer); CmsFavoriteDialog dialog = new CmsFavoriteDialog(context, new CmsFavoriteDAO(A_CmsUI.getCmsObject())); Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); window.setContent(dialog); window.setCaption(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_FAVORITES_DIALOG_TITLE_0)); A_CmsUI.get().addWindow(window); window.center(); } catch (CmsException e) { CmsErrorDialog.showErrorDialog(e); } }
java
public static void openFavoriteDialog(CmsFileExplorer explorer) { try { CmsExplorerFavoriteContext context = new CmsExplorerFavoriteContext(A_CmsUI.getCmsObject(), explorer); CmsFavoriteDialog dialog = new CmsFavoriteDialog(context, new CmsFavoriteDAO(A_CmsUI.getCmsObject())); Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); window.setContent(dialog); window.setCaption(CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_FAVORITES_DIALOG_TITLE_0)); A_CmsUI.get().addWindow(window); window.center(); } catch (CmsException e) { CmsErrorDialog.showErrorDialog(e); } }
[ "public", "static", "void", "openFavoriteDialog", "(", "CmsFileExplorer", "explorer", ")", "{", "try", "{", "CmsExplorerFavoriteContext", "context", "=", "new", "CmsExplorerFavoriteContext", "(", "A_CmsUI", ".", "getCmsObject", "(", ")", ",", "explorer", ")", ";", "CmsFavoriteDialog", "dialog", "=", "new", "CmsFavoriteDialog", "(", "context", ",", "new", "CmsFavoriteDAO", "(", "A_CmsUI", ".", "getCmsObject", "(", ")", ")", ")", ";", "Window", "window", "=", "CmsBasicDialog", ".", "prepareWindow", "(", "DialogWidth", ".", "max", ")", ";", "window", ".", "setContent", "(", "dialog", ")", ";", "window", ".", "setCaption", "(", "CmsVaadinUtils", ".", "getMessageText", "(", "org", ".", "opencms", ".", "ui", ".", "Messages", ".", "GUI_FAVORITES_DIALOG_TITLE_0", ")", ")", ";", "A_CmsUI", ".", "get", "(", ")", ".", "addWindow", "(", "window", ")", ";", "window", ".", "center", "(", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "CmsErrorDialog", ".", "showErrorDialog", "(", "e", ")", ";", "}", "}" ]
Opens the favorite dialog. @param explorer the explorer instance (null if not currently in explorer)
[ "Opens", "the", "favorite", "dialog", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/components/CmsToolBar.java#L294-L307
opsmatters/opsmatters-core
src/main/java/com/opsmatters/core/util/DateUtilities.java
DateUtilities.convertToUtc
public static long convertToUtc(long millis, String tz) { """ Returns the given date converted to UTC using the given timezone. @param millis The date to convert @param tz The timezone associated with the date @return The given date converted using the given timezone """ long ret = millis; if(tz != null && tz.length() > 0) { DateTime dt = new DateTime(millis, DateTimeZone.forID(tz)); ret = dt.withZoneRetainFields(DateTimeZone.forID("UTC")).getMillis(); } return ret; }
java
public static long convertToUtc(long millis, String tz) { long ret = millis; if(tz != null && tz.length() > 0) { DateTime dt = new DateTime(millis, DateTimeZone.forID(tz)); ret = dt.withZoneRetainFields(DateTimeZone.forID("UTC")).getMillis(); } return ret; }
[ "public", "static", "long", "convertToUtc", "(", "long", "millis", ",", "String", "tz", ")", "{", "long", "ret", "=", "millis", ";", "if", "(", "tz", "!=", "null", "&&", "tz", ".", "length", "(", ")", ">", "0", ")", "{", "DateTime", "dt", "=", "new", "DateTime", "(", "millis", ",", "DateTimeZone", ".", "forID", "(", "tz", ")", ")", ";", "ret", "=", "dt", ".", "withZoneRetainFields", "(", "DateTimeZone", ".", "forID", "(", "\"UTC\"", ")", ")", ".", "getMillis", "(", ")", ";", "}", "return", "ret", ";", "}" ]
Returns the given date converted to UTC using the given timezone. @param millis The date to convert @param tz The timezone associated with the date @return The given date converted using the given timezone
[ "Returns", "the", "given", "date", "converted", "to", "UTC", "using", "the", "given", "timezone", "." ]
train
https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/DateUtilities.java#L379-L388
m-m-m/util
pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java
PojoDescriptorBuilderImpl.mergePropertyDescriptorWithSuperClass
private void mergePropertyDescriptorWithSuperClass(PojoPropertyDescriptorImpl propertyDescriptor, PojoPropertyDescriptorImpl superPropertyDescriptor) { """ This method merges the {@code superPropertyDescriptor} into the {@code propertyDescriptor}. @param propertyDescriptor is the {@link PojoPropertyDescriptorImpl} to build for the {@link net.sf.mmm.util.pojo.api.Pojo}. @param superPropertyDescriptor is the super {@link PojoPropertyDescriptorImpl} to "inherit" from. """ for (PojoPropertyAccessor superPropertyAccessor : superPropertyDescriptor.getAccessors()) { PojoPropertyAccessor propertyAccessor = propertyDescriptor.getAccessor(superPropertyAccessor.getMode()); if (propertyAccessor == null) { propertyDescriptor.putAccessor(superPropertyAccessor); } } Field field = superPropertyDescriptor.getField(); if ((field != null) && (propertyDescriptor.getField() == null)) { propertyDescriptor.setField(field); } }
java
private void mergePropertyDescriptorWithSuperClass(PojoPropertyDescriptorImpl propertyDescriptor, PojoPropertyDescriptorImpl superPropertyDescriptor) { for (PojoPropertyAccessor superPropertyAccessor : superPropertyDescriptor.getAccessors()) { PojoPropertyAccessor propertyAccessor = propertyDescriptor.getAccessor(superPropertyAccessor.getMode()); if (propertyAccessor == null) { propertyDescriptor.putAccessor(superPropertyAccessor); } } Field field = superPropertyDescriptor.getField(); if ((field != null) && (propertyDescriptor.getField() == null)) { propertyDescriptor.setField(field); } }
[ "private", "void", "mergePropertyDescriptorWithSuperClass", "(", "PojoPropertyDescriptorImpl", "propertyDescriptor", ",", "PojoPropertyDescriptorImpl", "superPropertyDescriptor", ")", "{", "for", "(", "PojoPropertyAccessor", "superPropertyAccessor", ":", "superPropertyDescriptor", ".", "getAccessors", "(", ")", ")", "{", "PojoPropertyAccessor", "propertyAccessor", "=", "propertyDescriptor", ".", "getAccessor", "(", "superPropertyAccessor", ".", "getMode", "(", ")", ")", ";", "if", "(", "propertyAccessor", "==", "null", ")", "{", "propertyDescriptor", ".", "putAccessor", "(", "superPropertyAccessor", ")", ";", "}", "}", "Field", "field", "=", "superPropertyDescriptor", ".", "getField", "(", ")", ";", "if", "(", "(", "field", "!=", "null", ")", "&&", "(", "propertyDescriptor", ".", "getField", "(", ")", "==", "null", ")", ")", "{", "propertyDescriptor", ".", "setField", "(", "field", ")", ";", "}", "}" ]
This method merges the {@code superPropertyDescriptor} into the {@code propertyDescriptor}. @param propertyDescriptor is the {@link PojoPropertyDescriptorImpl} to build for the {@link net.sf.mmm.util.pojo.api.Pojo}. @param superPropertyDescriptor is the super {@link PojoPropertyDescriptorImpl} to "inherit" from.
[ "This", "method", "merges", "the", "{", "@code", "superPropertyDescriptor", "}", "into", "the", "{", "@code", "propertyDescriptor", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/pojo/src/main/java/net/sf/mmm/util/pojo/descriptor/impl/PojoDescriptorBuilderImpl.java#L370-L383
thrau/jarchivelib
src/main/java/org/rauschig/jarchivelib/CommonsArchiver.java
CommonsArchiver.writeToArchive
protected void writeToArchive(File[] sources, ArchiveOutputStream archive) throws IOException { """ Recursion entry point for {@link #writeToArchive(File, File[], ArchiveOutputStream)}. <br> Recursively writes all given source {@link File}s into the given {@link ArchiveOutputStream}. @param sources the files to write in to the archive @param archive the archive to write into @throws IOException when an I/O error occurs """ for (File source : sources) { if (!source.exists()) { throw new FileNotFoundException(source.getPath()); } else if (!source.canRead()) { throw new FileNotFoundException(source.getPath() + " (Permission denied)"); } writeToArchive(source.getParentFile(), new File[]{ source }, archive); } }
java
protected void writeToArchive(File[] sources, ArchiveOutputStream archive) throws IOException { for (File source : sources) { if (!source.exists()) { throw new FileNotFoundException(source.getPath()); } else if (!source.canRead()) { throw new FileNotFoundException(source.getPath() + " (Permission denied)"); } writeToArchive(source.getParentFile(), new File[]{ source }, archive); } }
[ "protected", "void", "writeToArchive", "(", "File", "[", "]", "sources", ",", "ArchiveOutputStream", "archive", ")", "throws", "IOException", "{", "for", "(", "File", "source", ":", "sources", ")", "{", "if", "(", "!", "source", ".", "exists", "(", ")", ")", "{", "throw", "new", "FileNotFoundException", "(", "source", ".", "getPath", "(", ")", ")", ";", "}", "else", "if", "(", "!", "source", ".", "canRead", "(", ")", ")", "{", "throw", "new", "FileNotFoundException", "(", "source", ".", "getPath", "(", ")", "+", "\" (Permission denied)\"", ")", ";", "}", "writeToArchive", "(", "source", ".", "getParentFile", "(", ")", ",", "new", "File", "[", "]", "{", "source", "}", ",", "archive", ")", ";", "}", "}" ]
Recursion entry point for {@link #writeToArchive(File, File[], ArchiveOutputStream)}. <br> Recursively writes all given source {@link File}s into the given {@link ArchiveOutputStream}. @param sources the files to write in to the archive @param archive the archive to write into @throws IOException when an I/O error occurs
[ "Recursion", "entry", "point", "for", "{", "@link", "#writeToArchive", "(", "File", "File", "[]", "ArchiveOutputStream", ")", "}", ".", "<br", ">", "Recursively", "writes", "all", "given", "source", "{", "@link", "File", "}", "s", "into", "the", "given", "{", "@link", "ArchiveOutputStream", "}", "." ]
train
https://github.com/thrau/jarchivelib/blob/8afee5124c588f589306796985b722d63572bbfa/src/main/java/org/rauschig/jarchivelib/CommonsArchiver.java#L215-L225
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/util/ClassesManager.java
ClassesManager.isAssignableFrom
public static boolean isAssignableFrom(MappedField destination,MappedField source) { """ this method verify that the instruction: <p><code> destination = source </code> <p>is permitted, checking their generics also @param destination of type {@link MappedField} @param source of type {@link MappedField} @return true if destination is assignable from source """ return isAssignableFrom(destination.getValue(), source.getValue()); }
java
public static boolean isAssignableFrom(MappedField destination,MappedField source) { return isAssignableFrom(destination.getValue(), source.getValue()); }
[ "public", "static", "boolean", "isAssignableFrom", "(", "MappedField", "destination", ",", "MappedField", "source", ")", "{", "return", "isAssignableFrom", "(", "destination", ".", "getValue", "(", ")", ",", "source", ".", "getValue", "(", ")", ")", ";", "}" ]
this method verify that the instruction: <p><code> destination = source </code> <p>is permitted, checking their generics also @param destination of type {@link MappedField} @param source of type {@link MappedField} @return true if destination is assignable from source
[ "this", "method", "verify", "that", "the", "instruction", ":", "<p", ">", "<code", ">", "destination", "=", "source", "<", "/", "code", ">", "<p", ">", "is", "permitted", "checking", "their", "generics", "also" ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/util/ClassesManager.java#L98-L100
Ordinastie/MalisisCore
src/main/java/net/malisis/core/client/gui/element/position/Positions.java
Positions.centered
public static <T extends ISized & IChild<U>, U extends ISized> IntSupplier centered(T owner, int offset) { """ Positions the owner in the center of its parent.<br> Respects the parent padding. @param <T> the generic type @param <U> the generic type @param offset the offset @return the int supplier """ return () -> { U parent = owner.getParent(); if (parent == null) return 0; return (parent.size().width() - Padding.of(parent).horizontal() - owner.size().width()) / 2 + offset; }; }
java
public static <T extends ISized & IChild<U>, U extends ISized> IntSupplier centered(T owner, int offset) { return () -> { U parent = owner.getParent(); if (parent == null) return 0; return (parent.size().width() - Padding.of(parent).horizontal() - owner.size().width()) / 2 + offset; }; }
[ "public", "static", "<", "T", "extends", "ISized", "&", "IChild", "<", "U", ">", ",", "U", "extends", "ISized", ">", "IntSupplier", "centered", "(", "T", "owner", ",", "int", "offset", ")", "{", "return", "(", ")", "->", "{", "U", "parent", "=", "owner", ".", "getParent", "(", ")", ";", "if", "(", "parent", "==", "null", ")", "return", "0", ";", "return", "(", "parent", ".", "size", "(", ")", ".", "width", "(", ")", "-", "Padding", ".", "of", "(", "parent", ")", ".", "horizontal", "(", ")", "-", "owner", ".", "size", "(", ")", ".", "width", "(", ")", ")", "/", "2", "+", "offset", ";", "}", ";", "}" ]
Positions the owner in the center of its parent.<br> Respects the parent padding. @param <T> the generic type @param <U> the generic type @param offset the offset @return the int supplier
[ "Positions", "the", "owner", "in", "the", "center", "of", "its", "parent", ".", "<br", ">", "Respects", "the", "parent", "padding", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/client/gui/element/position/Positions.java#L89-L97