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
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTabSet.java
WTabSet.addTab
public WTab addTab(final WComponent content, final String tabName, final TabMode mode, final char accessKey) { """ Adds a tab to the tab set. @param content the tab set content. @param tabName the tab name. @param mode the tab mode. @param accessKey the access key used to activate the tab. @return the tab which was added to the tab set. """ return addTab(new WTab(content, tabName, mode, accessKey)); }
java
public WTab addTab(final WComponent content, final String tabName, final TabMode mode, final char accessKey) { return addTab(new WTab(content, tabName, mode, accessKey)); }
[ "public", "WTab", "addTab", "(", "final", "WComponent", "content", ",", "final", "String", "tabName", ",", "final", "TabMode", "mode", ",", "final", "char", "accessKey", ")", "{", "return", "addTab", "(", "new", "WTab", "(", "content", ",", "tabName", ",", "mode", ",", "accessKey", ")", ")", ";", "}" ]
Adds a tab to the tab set. @param content the tab set content. @param tabName the tab name. @param mode the tab mode. @param accessKey the access key used to activate the tab. @return the tab which was added to the tab set.
[ "Adds", "a", "tab", "to", "the", "tab", "set", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WTabSet.java#L251-L253
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java
PrettyPrinter.formatArgTo
private static void formatArgTo(List<Dependency> path, StringBuilder builder) { """ Formats a list of dependencies as a dependency path; see the class comments. """ if (path.isEmpty()) { return; } builder.append("\n"); boolean first = true; Key<?> previousTarget = null; // For sanity-checking. for (Dependency dependency : path) { Key<?> source = dependency.getSource(); Key<?> target = dependency.getTarget(); // Sanity-check. if (previousTarget != null && !previousTarget.equals(source)) { throw new IllegalArgumentException("Dependency list is not a path."); } // There are two possible overall shapes of the list: // // If it starts with GINJECTOR, we get this: // // Key1 [context] // -> Key2 [context] // ... // // Otherwise (e.g., if we're dumping a cycle), we get this: // // Key1 // -> Key2 [context] // -> Key3 [context] // ... if (first) { if (source == Dependency.GINJECTOR) { formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } else { formatArgTo(source, builder); builder.append("\n -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } first = false; } else { builder.append(" -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } previousTarget = target; } }
java
private static void formatArgTo(List<Dependency> path, StringBuilder builder) { if (path.isEmpty()) { return; } builder.append("\n"); boolean first = true; Key<?> previousTarget = null; // For sanity-checking. for (Dependency dependency : path) { Key<?> source = dependency.getSource(); Key<?> target = dependency.getTarget(); // Sanity-check. if (previousTarget != null && !previousTarget.equals(source)) { throw new IllegalArgumentException("Dependency list is not a path."); } // There are two possible overall shapes of the list: // // If it starts with GINJECTOR, we get this: // // Key1 [context] // -> Key2 [context] // ... // // Otherwise (e.g., if we're dumping a cycle), we get this: // // Key1 // -> Key2 [context] // -> Key3 [context] // ... if (first) { if (source == Dependency.GINJECTOR) { formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } else { formatArgTo(source, builder); builder.append("\n -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } first = false; } else { builder.append(" -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } previousTarget = target; } }
[ "private", "static", "void", "formatArgTo", "(", "List", "<", "Dependency", ">", "path", ",", "StringBuilder", "builder", ")", "{", "if", "(", "path", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "builder", ".", "append", "(", "\"\\n\"", ")", ";", "boolean", "first", "=", "true", ";", "Key", "<", "?", ">", "previousTarget", "=", "null", ";", "// For sanity-checking.", "for", "(", "Dependency", "dependency", ":", "path", ")", "{", "Key", "<", "?", ">", "source", "=", "dependency", ".", "getSource", "(", ")", ";", "Key", "<", "?", ">", "target", "=", "dependency", ".", "getTarget", "(", ")", ";", "// Sanity-check.", "if", "(", "previousTarget", "!=", "null", "&&", "!", "previousTarget", ".", "equals", "(", "source", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Dependency list is not a path.\"", ")", ";", "}", "// There are two possible overall shapes of the list:", "//", "// If it starts with GINJECTOR, we get this:", "//", "// Key1 [context]", "// -> Key2 [context]", "// ...", "//", "// Otherwise (e.g., if we're dumping a cycle), we get this:", "//", "// Key1", "// -> Key2 [context]", "// -> Key3 [context]", "// ...", "if", "(", "first", ")", "{", "if", "(", "source", "==", "Dependency", ".", "GINJECTOR", ")", "{", "formatArgTo", "(", "target", ",", "builder", ")", ";", "builder", ".", "append", "(", "String", ".", "format", "(", "\" [%s]%n\"", ",", "dependency", ".", "getContext", "(", ")", ")", ")", ";", "}", "else", "{", "formatArgTo", "(", "source", ",", "builder", ")", ";", "builder", ".", "append", "(", "\"\\n -> \"", ")", ";", "formatArgTo", "(", "target", ",", "builder", ")", ";", "builder", ".", "append", "(", "String", ".", "format", "(", "\" [%s]%n\"", ",", "dependency", ".", "getContext", "(", ")", ")", ")", ";", "}", "first", "=", "false", ";", "}", "else", "{", "builder", ".", "append", "(", "\" -> \"", ")", ";", "formatArgTo", "(", "target", ",", "builder", ")", ";", "builder", ".", "append", "(", "String", ".", "format", "(", "\" [%s]%n\"", ",", "dependency", ".", "getContext", "(", ")", ")", ")", ";", "}", "previousTarget", "=", "target", ";", "}", "}" ]
Formats a list of dependencies as a dependency path; see the class comments.
[ "Formats", "a", "list", "of", "dependencies", "as", "a", "dependency", "path", ";", "see", "the", "class", "comments", "." ]
train
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java#L146-L197
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/query/StructuredQueryBuilder.java
StructuredQueryBuilder.geoJSONPropertyPair
public GeospatialIndex geoJSONPropertyPair(JSONProperty parent, JSONProperty lat, JSONProperty lon) { """ Identifies a parent json property with child latitude and longitude json properties to match with a geospatial query. @param parent the parent json property of lat and lon @param lat the json property with the latitude coordinate @param lon the json property with the longitude coordinate @return the specification for the index on the geospatial coordinates """ if ( parent == null ) throw new IllegalArgumentException("parent cannot be null"); if ( lat == null ) throw new IllegalArgumentException("lat cannot be null"); if ( lon == null ) throw new IllegalArgumentException("lon cannot be null"); return new GeoJSONPropertyPairImpl(parent, lat, lon); }
java
public GeospatialIndex geoJSONPropertyPair(JSONProperty parent, JSONProperty lat, JSONProperty lon) { if ( parent == null ) throw new IllegalArgumentException("parent cannot be null"); if ( lat == null ) throw new IllegalArgumentException("lat cannot be null"); if ( lon == null ) throw new IllegalArgumentException("lon cannot be null"); return new GeoJSONPropertyPairImpl(parent, lat, lon); }
[ "public", "GeospatialIndex", "geoJSONPropertyPair", "(", "JSONProperty", "parent", ",", "JSONProperty", "lat", ",", "JSONProperty", "lon", ")", "{", "if", "(", "parent", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"parent cannot be null\"", ")", ";", "if", "(", "lat", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"lat cannot be null\"", ")", ";", "if", "(", "lon", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"lon cannot be null\"", ")", ";", "return", "new", "GeoJSONPropertyPairImpl", "(", "parent", ",", "lat", ",", "lon", ")", ";", "}" ]
Identifies a parent json property with child latitude and longitude json properties to match with a geospatial query. @param parent the parent json property of lat and lon @param lat the json property with the latitude coordinate @param lon the json property with the longitude coordinate @return the specification for the index on the geospatial coordinates
[ "Identifies", "a", "parent", "json", "property", "with", "child", "latitude", "and", "longitude", "json", "properties", "to", "match", "with", "a", "geospatial", "query", "." ]
train
https://github.com/marklogic/java-client-api/blob/acf60229a928abd4a8cc4b21b641d56957467da7/marklogic-client-api/src/main/java/com/marklogic/client/query/StructuredQueryBuilder.java#L857-L862
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/translator/DocumentReferenceTranslator.java
DocumentReferenceTranslator.toDomDocument
public Document toDomDocument(Object obj, boolean tryProviders) throws TranslationException { """ Default implementation ignores providers. Override to try registry lookup. """ if (this instanceof XmlDocumentTranslator) return ((XmlDocumentTranslator)this).toDomDocument(obj); else throw new UnsupportedOperationException("Translator: " + this.getClass().getName() + " does not implement" + XmlDocumentTranslator.class.getName()); }
java
public Document toDomDocument(Object obj, boolean tryProviders) throws TranslationException { if (this instanceof XmlDocumentTranslator) return ((XmlDocumentTranslator)this).toDomDocument(obj); else throw new UnsupportedOperationException("Translator: " + this.getClass().getName() + " does not implement" + XmlDocumentTranslator.class.getName()); }
[ "public", "Document", "toDomDocument", "(", "Object", "obj", ",", "boolean", "tryProviders", ")", "throws", "TranslationException", "{", "if", "(", "this", "instanceof", "XmlDocumentTranslator", ")", "return", "(", "(", "XmlDocumentTranslator", ")", "this", ")", ".", "toDomDocument", "(", "obj", ")", ";", "else", "throw", "new", "UnsupportedOperationException", "(", "\"Translator: \"", "+", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\" does not implement\"", "+", "XmlDocumentTranslator", ".", "class", ".", "getName", "(", ")", ")", ";", "}" ]
Default implementation ignores providers. Override to try registry lookup.
[ "Default", "implementation", "ignores", "providers", ".", "Override", "to", "try", "registry", "lookup", "." ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/translator/DocumentReferenceTranslator.java#L70-L75
FXMisc/RichTextFX
richtextfx/src/main/java/org/fxmisc/richtext/util/UndoUtils.java
UndoUtils.plainTextUndoManager
public static <PS, SEG, S> UndoManager<List<PlainTextChange>> plainTextUndoManager( GenericStyledArea<PS, SEG, S> area) { """ Returns an UndoManager with an unlimited history that can undo/redo {@link PlainTextChange}s. New changes emitted from the stream will not be merged with the previous change after {@link #DEFAULT_PREVENT_MERGE_DELAY} """ return plainTextUndoManager(area, DEFAULT_PREVENT_MERGE_DELAY); }
java
public static <PS, SEG, S> UndoManager<List<PlainTextChange>> plainTextUndoManager( GenericStyledArea<PS, SEG, S> area) { return plainTextUndoManager(area, DEFAULT_PREVENT_MERGE_DELAY); }
[ "public", "static", "<", "PS", ",", "SEG", ",", "S", ">", "UndoManager", "<", "List", "<", "PlainTextChange", ">", ">", "plainTextUndoManager", "(", "GenericStyledArea", "<", "PS", ",", "SEG", ",", "S", ">", "area", ")", "{", "return", "plainTextUndoManager", "(", "area", ",", "DEFAULT_PREVENT_MERGE_DELAY", ")", ";", "}" ]
Returns an UndoManager with an unlimited history that can undo/redo {@link PlainTextChange}s. New changes emitted from the stream will not be merged with the previous change after {@link #DEFAULT_PREVENT_MERGE_DELAY}
[ "Returns", "an", "UndoManager", "with", "an", "unlimited", "history", "that", "can", "undo", "/", "redo", "{" ]
train
https://github.com/FXMisc/RichTextFX/blob/bc7cab6a637855e0f37d9b9c12a9172c31545f0b/richtextfx/src/main/java/org/fxmisc/richtext/util/UndoUtils.java#L96-L99
lastaflute/lasta-thymeleaf
src/main/java/org/lastaflute/thymeleaf/expression/ClassificationExpressionObject.java
ClassificationExpressionObject.nameOf
public Classification nameOf(String classificationName, String name) { """ Get classification by name. @param classificationName The name of classification. (NotNull) @param name The name of classification to find. (NotNull) @return The found instance of classification for the code. (NotNull: if not found, throws exception) """ return findClassificationMeta((String) classificationName, () -> { return "nameOf('" + classificationName + "', '" + name + "')"; }).nameOf(name); }
java
public Classification nameOf(String classificationName, String name) { return findClassificationMeta((String) classificationName, () -> { return "nameOf('" + classificationName + "', '" + name + "')"; }).nameOf(name); }
[ "public", "Classification", "nameOf", "(", "String", "classificationName", ",", "String", "name", ")", "{", "return", "findClassificationMeta", "(", "(", "String", ")", "classificationName", ",", "(", ")", "->", "{", "return", "\"nameOf('\"", "+", "classificationName", "+", "\"', '\"", "+", "name", "+", "\"')\"", ";", "}", ")", ".", "nameOf", "(", "name", ")", ";", "}" ]
Get classification by name. @param classificationName The name of classification. (NotNull) @param name The name of classification to find. (NotNull) @return The found instance of classification for the code. (NotNull: if not found, throws exception)
[ "Get", "classification", "by", "name", "." ]
train
https://github.com/lastaflute/lasta-thymeleaf/blob/d340a6e7eeddfcc9177052958c383fecd4a7fefa/src/main/java/org/lastaflute/thymeleaf/expression/ClassificationExpressionObject.java#L225-L229
joniles/mpxj
src/main/java/net/sf/mpxj/Task.java
Task.removePredecessor
public boolean removePredecessor(Task targetTask, RelationType type, Duration lag) { """ This method allows a predecessor relationship to be removed from this task instance. It will only delete relationships that exactly match the given targetTask, type and lag time. @param targetTask the predecessor task @param type relation type @param lag relation lag @return returns true if the relation is found and removed """ boolean matchFound = false; // // Retrieve the list of predecessors // List<Relation> predecessorList = getPredecessors(); if (!predecessorList.isEmpty()) { // // Ensure that we have a valid lag duration // if (lag == null) { lag = Duration.getInstance(0, TimeUnit.DAYS); } // // Ensure that there is a predecessor relationship between // these two tasks, and remove it. // matchFound = removeRelation(predecessorList, targetTask, type, lag); // // If we have removed a predecessor, then we must remove the // corresponding successor entry from the target task list // if (matchFound) { // // Retrieve the list of successors // List<Relation> successorList = targetTask.getSuccessors(); if (!successorList.isEmpty()) { // // Ensure that there is a successor relationship between // these two tasks, and remove it. // removeRelation(successorList, this, type, lag); } } } return matchFound; }
java
public boolean removePredecessor(Task targetTask, RelationType type, Duration lag) { boolean matchFound = false; // // Retrieve the list of predecessors // List<Relation> predecessorList = getPredecessors(); if (!predecessorList.isEmpty()) { // // Ensure that we have a valid lag duration // if (lag == null) { lag = Duration.getInstance(0, TimeUnit.DAYS); } // // Ensure that there is a predecessor relationship between // these two tasks, and remove it. // matchFound = removeRelation(predecessorList, targetTask, type, lag); // // If we have removed a predecessor, then we must remove the // corresponding successor entry from the target task list // if (matchFound) { // // Retrieve the list of successors // List<Relation> successorList = targetTask.getSuccessors(); if (!successorList.isEmpty()) { // // Ensure that there is a successor relationship between // these two tasks, and remove it. // removeRelation(successorList, this, type, lag); } } } return matchFound; }
[ "public", "boolean", "removePredecessor", "(", "Task", "targetTask", ",", "RelationType", "type", ",", "Duration", "lag", ")", "{", "boolean", "matchFound", "=", "false", ";", "//", "// Retrieve the list of predecessors", "//", "List", "<", "Relation", ">", "predecessorList", "=", "getPredecessors", "(", ")", ";", "if", "(", "!", "predecessorList", ".", "isEmpty", "(", ")", ")", "{", "//", "// Ensure that we have a valid lag duration", "//", "if", "(", "lag", "==", "null", ")", "{", "lag", "=", "Duration", ".", "getInstance", "(", "0", ",", "TimeUnit", ".", "DAYS", ")", ";", "}", "//", "// Ensure that there is a predecessor relationship between", "// these two tasks, and remove it.", "//", "matchFound", "=", "removeRelation", "(", "predecessorList", ",", "targetTask", ",", "type", ",", "lag", ")", ";", "//", "// If we have removed a predecessor, then we must remove the", "// corresponding successor entry from the target task list", "//", "if", "(", "matchFound", ")", "{", "//", "// Retrieve the list of successors", "//", "List", "<", "Relation", ">", "successorList", "=", "targetTask", ".", "getSuccessors", "(", ")", ";", "if", "(", "!", "successorList", ".", "isEmpty", "(", ")", ")", "{", "//", "// Ensure that there is a successor relationship between", "// these two tasks, and remove it.", "//", "removeRelation", "(", "successorList", ",", "this", ",", "type", ",", "lag", ")", ";", "}", "}", "}", "return", "matchFound", ";", "}" ]
This method allows a predecessor relationship to be removed from this task instance. It will only delete relationships that exactly match the given targetTask, type and lag time. @param targetTask the predecessor task @param type relation type @param lag relation lag @return returns true if the relation is found and removed
[ "This", "method", "allows", "a", "predecessor", "relationship", "to", "be", "removed", "from", "this", "task", "instance", ".", "It", "will", "only", "delete", "relationships", "that", "exactly", "match", "the", "given", "targetTask", "type", "and", "lag", "time", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L4589-L4635
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/xen/physical_disk.java
physical_disk.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ physical_disk_responses result = (physical_disk_responses) service.get_payload_formatter().string_to_resource(physical_disk_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.physical_disk_response_array); } physical_disk[] result_physical_disk = new physical_disk[result.physical_disk_response_array.length]; for(int i = 0; i < result.physical_disk_response_array.length; i++) { result_physical_disk[i] = result.physical_disk_response_array[i].physical_disk[0]; } return result_physical_disk; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { physical_disk_responses result = (physical_disk_responses) service.get_payload_formatter().string_to_resource(physical_disk_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.physical_disk_response_array); } physical_disk[] result_physical_disk = new physical_disk[result.physical_disk_response_array.length]; for(int i = 0; i < result.physical_disk_response_array.length; i++) { result_physical_disk[i] = result.physical_disk_response_array[i].physical_disk[0]; } return result_physical_disk; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "physical_disk_responses", "result", "=", "(", "physical_disk_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "physical_disk_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "physical_disk_response_array", ")", ";", "}", "physical_disk", "[", "]", "result_physical_disk", "=", "new", "physical_disk", "[", "result", ".", "physical_disk_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "physical_disk_response_array", ".", "length", ";", "i", "++", ")", "{", "result_physical_disk", "[", "i", "]", "=", "result", ".", "physical_disk_response_array", "[", "i", "]", ".", "physical_disk", "[", "0", "]", ";", "}", "return", "result_physical_disk", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/physical_disk.java#L439-L456
tvbarthel/Cheerleader
library/src/main/java/fr/tvbarthel/cheerleader/library/player/CheerleaderPlayer.java
CheerleaderPlayer.addTrack
public void addTrack(SoundCloudTrack track, boolean playNow) { """ Add a track to the current SoundCloud player playlist. @param track {@link fr.tvbarthel.cheerleader.library.client.SoundCloudTrack} to be added to the player. @param playNow true to play the track immediately. """ checkState(); mPlayerPlaylist.add(track); for (CheerleaderPlaylistListener listener : mCheerleaderPlaylistListeners) { listener.onTrackAdded(track); } if (playNow) { play(mPlayerPlaylist.size() - 1); } }
java
public void addTrack(SoundCloudTrack track, boolean playNow) { checkState(); mPlayerPlaylist.add(track); for (CheerleaderPlaylistListener listener : mCheerleaderPlaylistListeners) { listener.onTrackAdded(track); } if (playNow) { play(mPlayerPlaylist.size() - 1); } }
[ "public", "void", "addTrack", "(", "SoundCloudTrack", "track", ",", "boolean", "playNow", ")", "{", "checkState", "(", ")", ";", "mPlayerPlaylist", ".", "add", "(", "track", ")", ";", "for", "(", "CheerleaderPlaylistListener", "listener", ":", "mCheerleaderPlaylistListeners", ")", "{", "listener", ".", "onTrackAdded", "(", "track", ")", ";", "}", "if", "(", "playNow", ")", "{", "play", "(", "mPlayerPlaylist", ".", "size", "(", ")", "-", "1", ")", ";", "}", "}" ]
Add a track to the current SoundCloud player playlist. @param track {@link fr.tvbarthel.cheerleader.library.client.SoundCloudTrack} to be added to the player. @param playNow true to play the track immediately.
[ "Add", "a", "track", "to", "the", "current", "SoundCloud", "player", "playlist", "." ]
train
https://github.com/tvbarthel/Cheerleader/blob/f61527e4cc44fcd0ed2e1e98aca285f8c236f24e/library/src/main/java/fr/tvbarthel/cheerleader/library/player/CheerleaderPlayer.java#L313-L322
google/closure-compiler
src/com/google/javascript/jscomp/TypeCheck.java
TypeCheck.visitName
boolean visitName(NodeTraversal t, Node n, Node parent) { """ Visits a NAME node. @param t The node traversal object that supplies context, such as the scope chain to use in name lookups as well as error reporting. @param n The node being visited. @param parent The parent of the node n. @return whether the node is typeable or not """ // At this stage, we need to determine whether this is a leaf // node in an expression (which therefore needs to have a type // assigned for it) versus some other decorative node that we // can safely ignore. Function names, arguments (children of PARAM_LIST nodes) and // variable declarations are ignored. // TODO(user): remove this short-circuiting in favor of a // pre order traversal of the FUNCTION, CATCH, PARAM_LIST and VAR nodes. Token parentNodeType = parent.getToken(); if (parentNodeType == Token.FUNCTION || parentNodeType == Token.CATCH || parentNodeType == Token.PARAM_LIST || NodeUtil.isNameDeclaration(parent) ) { return false; } // Not need to type first key in for-in or for-of. if (NodeUtil.isEnhancedFor(parent) && parent.getFirstChild() == n) { return false; } JSType type = n.getJSType(); if (type == null) { type = getNativeType(UNKNOWN_TYPE); TypedVar var = t.getTypedScope().getVar(n.getString()); if (var != null) { JSType varType = var.getType(); if (varType != null) { type = varType; } } } ensureTyped(n, type); return true; }
java
boolean visitName(NodeTraversal t, Node n, Node parent) { // At this stage, we need to determine whether this is a leaf // node in an expression (which therefore needs to have a type // assigned for it) versus some other decorative node that we // can safely ignore. Function names, arguments (children of PARAM_LIST nodes) and // variable declarations are ignored. // TODO(user): remove this short-circuiting in favor of a // pre order traversal of the FUNCTION, CATCH, PARAM_LIST and VAR nodes. Token parentNodeType = parent.getToken(); if (parentNodeType == Token.FUNCTION || parentNodeType == Token.CATCH || parentNodeType == Token.PARAM_LIST || NodeUtil.isNameDeclaration(parent) ) { return false; } // Not need to type first key in for-in or for-of. if (NodeUtil.isEnhancedFor(parent) && parent.getFirstChild() == n) { return false; } JSType type = n.getJSType(); if (type == null) { type = getNativeType(UNKNOWN_TYPE); TypedVar var = t.getTypedScope().getVar(n.getString()); if (var != null) { JSType varType = var.getType(); if (varType != null) { type = varType; } } } ensureTyped(n, type); return true; }
[ "boolean", "visitName", "(", "NodeTraversal", "t", ",", "Node", "n", ",", "Node", "parent", ")", "{", "// At this stage, we need to determine whether this is a leaf", "// node in an expression (which therefore needs to have a type", "// assigned for it) versus some other decorative node that we", "// can safely ignore. Function names, arguments (children of PARAM_LIST nodes) and", "// variable declarations are ignored.", "// TODO(user): remove this short-circuiting in favor of a", "// pre order traversal of the FUNCTION, CATCH, PARAM_LIST and VAR nodes.", "Token", "parentNodeType", "=", "parent", ".", "getToken", "(", ")", ";", "if", "(", "parentNodeType", "==", "Token", ".", "FUNCTION", "||", "parentNodeType", "==", "Token", ".", "CATCH", "||", "parentNodeType", "==", "Token", ".", "PARAM_LIST", "||", "NodeUtil", ".", "isNameDeclaration", "(", "parent", ")", ")", "{", "return", "false", ";", "}", "// Not need to type first key in for-in or for-of.", "if", "(", "NodeUtil", ".", "isEnhancedFor", "(", "parent", ")", "&&", "parent", ".", "getFirstChild", "(", ")", "==", "n", ")", "{", "return", "false", ";", "}", "JSType", "type", "=", "n", ".", "getJSType", "(", ")", ";", "if", "(", "type", "==", "null", ")", "{", "type", "=", "getNativeType", "(", "UNKNOWN_TYPE", ")", ";", "TypedVar", "var", "=", "t", ".", "getTypedScope", "(", ")", ".", "getVar", "(", "n", ".", "getString", "(", ")", ")", ";", "if", "(", "var", "!=", "null", ")", "{", "JSType", "varType", "=", "var", ".", "getType", "(", ")", ";", "if", "(", "varType", "!=", "null", ")", "{", "type", "=", "varType", ";", "}", "}", "}", "ensureTyped", "(", "n", ",", "type", ")", ";", "return", "true", ";", "}" ]
Visits a NAME node. @param t The node traversal object that supplies context, such as the scope chain to use in name lookups as well as error reporting. @param n The node being visited. @param parent The parent of the node n. @return whether the node is typeable or not
[ "Visits", "a", "NAME", "node", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/TypeCheck.java#L1844-L1879
mijecu25/dsa
src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java
LinearSearch.searchLast
public static int searchLast(char[] charArray, char value, int occurrence) { """ Search for the value in the char array and return the index of the first occurrence from the end of the array. @param charArray array that we are searching in. @param value value that is being searched in the array. @param occurrence number of times we have seen the value before returning the index. @return the index where the value is found in the array, else -1. """ if(occurrence <= 0 || occurrence > charArray.length) { throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than " + "the array length: " + occurrence); } int valuesSeen = 0; for(int i = charArray.length-1; i >=0; i--) { if(charArray[i] == value) { valuesSeen++; if(valuesSeen == occurrence) { return i; } } } return -1; }
java
public static int searchLast(char[] charArray, char value, int occurrence) { if(occurrence <= 0 || occurrence > charArray.length) { throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than " + "the array length: " + occurrence); } int valuesSeen = 0; for(int i = charArray.length-1; i >=0; i--) { if(charArray[i] == value) { valuesSeen++; if(valuesSeen == occurrence) { return i; } } } return -1; }
[ "public", "static", "int", "searchLast", "(", "char", "[", "]", "charArray", ",", "char", "value", ",", "int", "occurrence", ")", "{", "if", "(", "occurrence", "<=", "0", "||", "occurrence", ">", "charArray", ".", "length", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Occurrence must be greater or equal to 1 and less than \"", "+", "\"the array length: \"", "+", "occurrence", ")", ";", "}", "int", "valuesSeen", "=", "0", ";", "for", "(", "int", "i", "=", "charArray", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "charArray", "[", "i", "]", "==", "value", ")", "{", "valuesSeen", "++", ";", "if", "(", "valuesSeen", "==", "occurrence", ")", "{", "return", "i", ";", "}", "}", "}", "return", "-", "1", ";", "}" ]
Search for the value in the char array and return the index of the first occurrence from the end of the array. @param charArray array that we are searching in. @param value value that is being searched in the array. @param occurrence number of times we have seen the value before returning the index. @return the index where the value is found in the array, else -1.
[ "Search", "for", "the", "value", "in", "the", "char", "array", "and", "return", "the", "index", "of", "the", "first", "occurrence", "from", "the", "end", "of", "the", "array", "." ]
train
https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java#L1560-L1579
facebook/fresco
samples/gestures/src/main/java/com/facebook/samples/gestures/MultiPointerGestureDetector.java
MultiPointerGestureDetector.getPressedPointerIndex
private int getPressedPointerIndex(MotionEvent event, int i) { """ Gets the index of the i-th pressed pointer. Normally, the index will be equal to i, except in the case when the pointer is released. @return index of the specified pointer or -1 if not found (i.e. not enough pointers are down) """ final int count = event.getPointerCount(); final int action = event.getActionMasked(); final int index = event.getActionIndex(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { if (i >= index) { i++; } } return (i < count) ? i : -1; }
java
private int getPressedPointerIndex(MotionEvent event, int i) { final int count = event.getPointerCount(); final int action = event.getActionMasked(); final int index = event.getActionIndex(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { if (i >= index) { i++; } } return (i < count) ? i : -1; }
[ "private", "int", "getPressedPointerIndex", "(", "MotionEvent", "event", ",", "int", "i", ")", "{", "final", "int", "count", "=", "event", ".", "getPointerCount", "(", ")", ";", "final", "int", "action", "=", "event", ".", "getActionMasked", "(", ")", ";", "final", "int", "index", "=", "event", ".", "getActionIndex", "(", ")", ";", "if", "(", "action", "==", "MotionEvent", ".", "ACTION_UP", "||", "action", "==", "MotionEvent", ".", "ACTION_POINTER_UP", ")", "{", "if", "(", "i", ">=", "index", ")", "{", "i", "++", ";", "}", "}", "return", "(", "i", "<", "count", ")", "?", "i", ":", "-", "1", ";", "}" ]
Gets the index of the i-th pressed pointer. Normally, the index will be equal to i, except in the case when the pointer is released. @return index of the specified pointer or -1 if not found (i.e. not enough pointers are down)
[ "Gets", "the", "index", "of", "the", "i", "-", "th", "pressed", "pointer", ".", "Normally", "the", "index", "will", "be", "equal", "to", "i", "except", "in", "the", "case", "when", "the", "pointer", "is", "released", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/gestures/src/main/java/com/facebook/samples/gestures/MultiPointerGestureDetector.java#L116-L127
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java
BpmnParse.parseBoundaryConditionalEventDefinition
public BoundaryConditionalEventActivityBehavior parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) { """ Parses the given element as conditional boundary event. @param element the XML element which contains the conditional event information @param interrupting indicates if the event is interrupting or not @param conditionalActivity the conditional event activity @return the boundary conditional event behavior which contains the condition """ conditionalActivity.getProperties().set(BpmnProperties.TYPE, ActivityTypes.BOUNDARY_CONDITIONAL); ConditionalEventDefinition conditionalEventDefinition = parseConditionalEventDefinition(element, conditionalActivity); conditionalEventDefinition.setInterrupting(interrupting); addEventSubscriptionDeclaration(conditionalEventDefinition, conditionalActivity.getEventScope(), element); for (BpmnParseListener parseListener : parseListeners) { parseListener.parseBoundaryConditionalEventDefinition(element, interrupting, conditionalActivity); } return new BoundaryConditionalEventActivityBehavior(conditionalEventDefinition); }
java
public BoundaryConditionalEventActivityBehavior parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) { conditionalActivity.getProperties().set(BpmnProperties.TYPE, ActivityTypes.BOUNDARY_CONDITIONAL); ConditionalEventDefinition conditionalEventDefinition = parseConditionalEventDefinition(element, conditionalActivity); conditionalEventDefinition.setInterrupting(interrupting); addEventSubscriptionDeclaration(conditionalEventDefinition, conditionalActivity.getEventScope(), element); for (BpmnParseListener parseListener : parseListeners) { parseListener.parseBoundaryConditionalEventDefinition(element, interrupting, conditionalActivity); } return new BoundaryConditionalEventActivityBehavior(conditionalEventDefinition); }
[ "public", "BoundaryConditionalEventActivityBehavior", "parseBoundaryConditionalEventDefinition", "(", "Element", "element", ",", "boolean", "interrupting", ",", "ActivityImpl", "conditionalActivity", ")", "{", "conditionalActivity", ".", "getProperties", "(", ")", ".", "set", "(", "BpmnProperties", ".", "TYPE", ",", "ActivityTypes", ".", "BOUNDARY_CONDITIONAL", ")", ";", "ConditionalEventDefinition", "conditionalEventDefinition", "=", "parseConditionalEventDefinition", "(", "element", ",", "conditionalActivity", ")", ";", "conditionalEventDefinition", ".", "setInterrupting", "(", "interrupting", ")", ";", "addEventSubscriptionDeclaration", "(", "conditionalEventDefinition", ",", "conditionalActivity", ".", "getEventScope", "(", ")", ",", "element", ")", ";", "for", "(", "BpmnParseListener", "parseListener", ":", "parseListeners", ")", "{", "parseListener", ".", "parseBoundaryConditionalEventDefinition", "(", "element", ",", "interrupting", ",", "conditionalActivity", ")", ";", "}", "return", "new", "BoundaryConditionalEventActivityBehavior", "(", "conditionalEventDefinition", ")", ";", "}" ]
Parses the given element as conditional boundary event. @param element the XML element which contains the conditional event information @param interrupting indicates if the event is interrupting or not @param conditionalActivity the conditional event activity @return the boundary conditional event behavior which contains the condition
[ "Parses", "the", "given", "element", "as", "conditional", "boundary", "event", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParse.java#L3456-L3468
tupilabs/tap4j
tap4j/src/main/java/org/tap4j/model/TapElementFactory.java
TapElementFactory.addComment
public static void addComment(TapElement element, String comment) { """ Add a comment to a {@link TapElement}, as long as the comment is not empty. @param element TAP element @param comment a comment """ if (comment != null && comment.trim().length() > 0) { element.setComment(new Comment(comment, true)); } }
java
public static void addComment(TapElement element, String comment) { if (comment != null && comment.trim().length() > 0) { element.setComment(new Comment(comment, true)); } }
[ "public", "static", "void", "addComment", "(", "TapElement", "element", ",", "String", "comment", ")", "{", "if", "(", "comment", "!=", "null", "&&", "comment", ".", "trim", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "element", ".", "setComment", "(", "new", "Comment", "(", "comment", ",", "true", ")", ")", ";", "}", "}" ]
Add a comment to a {@link TapElement}, as long as the comment is not empty. @param element TAP element @param comment a comment
[ "Add", "a", "comment", "to", "a", "{" ]
train
https://github.com/tupilabs/tap4j/blob/1793b653ce7f3a06a7b5c9557cdf601e28dd1f55/tap4j/src/main/java/org/tap4j/model/TapElementFactory.java#L147-L151
ThreeTen/threeten-extra
src/main/java/org/threeten/extra/chrono/AccountingDate.java
AccountingDate.now
public static AccountingDate now(AccountingChronology chronology, Clock clock) { """ Obtains the current {@code AccountingDate} from the specified clock, translated with the given AccountingChronology. <p> This will query the specified clock to obtain the current date - today. Using this method allows the use of an alternate clock for testing. The alternate clock may be introduced using {@linkplain Clock dependency injection}. @param chronology the Accounting chronology to base the date on, not null @param clock the clock to use, not null @return the current date, not null @throws DateTimeException if the current date cannot be obtained, NullPointerException if an AccountingChronology was not provided """ LocalDate now = LocalDate.now(clock); return ofEpochDay(chronology, now.toEpochDay()); }
java
public static AccountingDate now(AccountingChronology chronology, Clock clock) { LocalDate now = LocalDate.now(clock); return ofEpochDay(chronology, now.toEpochDay()); }
[ "public", "static", "AccountingDate", "now", "(", "AccountingChronology", "chronology", ",", "Clock", "clock", ")", "{", "LocalDate", "now", "=", "LocalDate", ".", "now", "(", "clock", ")", ";", "return", "ofEpochDay", "(", "chronology", ",", "now", ".", "toEpochDay", "(", ")", ")", ";", "}" ]
Obtains the current {@code AccountingDate} from the specified clock, translated with the given AccountingChronology. <p> This will query the specified clock to obtain the current date - today. Using this method allows the use of an alternate clock for testing. The alternate clock may be introduced using {@linkplain Clock dependency injection}. @param chronology the Accounting chronology to base the date on, not null @param clock the clock to use, not null @return the current date, not null @throws DateTimeException if the current date cannot be obtained, NullPointerException if an AccountingChronology was not provided
[ "Obtains", "the", "current", "{", "@code", "AccountingDate", "}", "from", "the", "specified", "clock", "translated", "with", "the", "given", "AccountingChronology", ".", "<p", ">", "This", "will", "query", "the", "specified", "clock", "to", "obtain", "the", "current", "date", "-", "today", ".", "Using", "this", "method", "allows", "the", "use", "of", "an", "alternate", "clock", "for", "testing", ".", "The", "alternate", "clock", "may", "be", "introduced", "using", "{", "@linkplain", "Clock", "dependency", "injection", "}", "." ]
train
https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/chrono/AccountingDate.java#L164-L167
opendatatrentino/s-match
src/main/java/it/unitn/disi/smatch/filters/SPSMMappingFilter.java
SPSMMappingFilter.getRelatedIndex
private int getRelatedIndex(List<INode> source, List<INode> target, char relation) { """ Looks for the related index for the source list at the position sourceIndex in the target list beginning at the targetIndex position for the defined relation. @param source source list of siblings. @param target target list of siblings. @param relation relation @return the index of the related element in target, or -1 if there is no relate element. """ int srcIndex = sourceIndex.get(source.get(0).getLevel() - 1); int tgtIndex = targetIndex.get(target.get(0).getLevel() - 1); int returnIndex = -1; INode sourceNode = source.get(srcIndex); //find the first one who is related in the same level for (int i = tgtIndex + 1; i < target.size(); i++) { INode targetNode = target.get(i); if (isRelated(sourceNode, targetNode, relation)) { setStrongestMapping(sourceNode, targetNode); return i; } } //there was no correspondence between siblings in source and target lists //try to clean the mapping elements computeStrongestMappingForSource(source.get(srcIndex)); return returnIndex; }
java
private int getRelatedIndex(List<INode> source, List<INode> target, char relation) { int srcIndex = sourceIndex.get(source.get(0).getLevel() - 1); int tgtIndex = targetIndex.get(target.get(0).getLevel() - 1); int returnIndex = -1; INode sourceNode = source.get(srcIndex); //find the first one who is related in the same level for (int i = tgtIndex + 1; i < target.size(); i++) { INode targetNode = target.get(i); if (isRelated(sourceNode, targetNode, relation)) { setStrongestMapping(sourceNode, targetNode); return i; } } //there was no correspondence between siblings in source and target lists //try to clean the mapping elements computeStrongestMappingForSource(source.get(srcIndex)); return returnIndex; }
[ "private", "int", "getRelatedIndex", "(", "List", "<", "INode", ">", "source", ",", "List", "<", "INode", ">", "target", ",", "char", "relation", ")", "{", "int", "srcIndex", "=", "sourceIndex", ".", "get", "(", "source", ".", "get", "(", "0", ")", ".", "getLevel", "(", ")", "-", "1", ")", ";", "int", "tgtIndex", "=", "targetIndex", ".", "get", "(", "target", ".", "get", "(", "0", ")", ".", "getLevel", "(", ")", "-", "1", ")", ";", "int", "returnIndex", "=", "-", "1", ";", "INode", "sourceNode", "=", "source", ".", "get", "(", "srcIndex", ")", ";", "//find the first one who is related in the same level\r", "for", "(", "int", "i", "=", "tgtIndex", "+", "1", ";", "i", "<", "target", ".", "size", "(", ")", ";", "i", "++", ")", "{", "INode", "targetNode", "=", "target", ".", "get", "(", "i", ")", ";", "if", "(", "isRelated", "(", "sourceNode", ",", "targetNode", ",", "relation", ")", ")", "{", "setStrongestMapping", "(", "sourceNode", ",", "targetNode", ")", ";", "return", "i", ";", "}", "}", "//there was no correspondence between siblings in source and target lists\r", "//try to clean the mapping elements\r", "computeStrongestMappingForSource", "(", "source", ".", "get", "(", "srcIndex", ")", ")", ";", "return", "returnIndex", ";", "}" ]
Looks for the related index for the source list at the position sourceIndex in the target list beginning at the targetIndex position for the defined relation. @param source source list of siblings. @param target target list of siblings. @param relation relation @return the index of the related element in target, or -1 if there is no relate element.
[ "Looks", "for", "the", "related", "index", "for", "the", "source", "list", "at", "the", "position", "sourceIndex", "in", "the", "target", "list", "beginning", "at", "the", "targetIndex", "position", "for", "the", "defined", "relation", "." ]
train
https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/smatch/filters/SPSMMappingFilter.java#L218-L240
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/mediatype/hal/HalConfiguration.java
HalConfiguration.withRenderSingleLinksFor
public HalConfiguration withRenderSingleLinksFor(LinkRelation relation, RenderSingleLinks renderSingleLinks) { """ Configures how to render a single link for a given particular {@link LinkRelation}. This will override what has been configured via {@link #withRenderSingleLinks(RenderSingleLinks)} for that particular link relation. @param relation must not be {@literal null}. @param renderSingleLinks must not be {@literal null}. @return """ Assert.notNull(relation, "Link relation must not be null!"); Assert.notNull(renderSingleLinks, "RenderSingleLinks must not be null!"); return withRenderSingleLinksFor(relation.value(), renderSingleLinks); }
java
public HalConfiguration withRenderSingleLinksFor(LinkRelation relation, RenderSingleLinks renderSingleLinks) { Assert.notNull(relation, "Link relation must not be null!"); Assert.notNull(renderSingleLinks, "RenderSingleLinks must not be null!"); return withRenderSingleLinksFor(relation.value(), renderSingleLinks); }
[ "public", "HalConfiguration", "withRenderSingleLinksFor", "(", "LinkRelation", "relation", ",", "RenderSingleLinks", "renderSingleLinks", ")", "{", "Assert", ".", "notNull", "(", "relation", ",", "\"Link relation must not be null!\"", ")", ";", "Assert", ".", "notNull", "(", "renderSingleLinks", ",", "\"RenderSingleLinks must not be null!\"", ")", ";", "return", "withRenderSingleLinksFor", "(", "relation", ".", "value", "(", ")", ",", "renderSingleLinks", ")", ";", "}" ]
Configures how to render a single link for a given particular {@link LinkRelation}. This will override what has been configured via {@link #withRenderSingleLinks(RenderSingleLinks)} for that particular link relation. @param relation must not be {@literal null}. @param renderSingleLinks must not be {@literal null}. @return
[ "Configures", "how", "to", "render", "a", "single", "link", "for", "a", "given", "particular", "{", "@link", "LinkRelation", "}", ".", "This", "will", "override", "what", "has", "been", "configured", "via", "{", "@link", "#withRenderSingleLinks", "(", "RenderSingleLinks", ")", "}", "for", "that", "particular", "link", "relation", "." ]
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/hal/HalConfiguration.java#L68-L74
thinkaurelius/titan
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/BackendTransaction.java
BackendTransaction.rollback
@Override public void rollback() throws BackendException { """ Rolls back all transactions and makes sure that this does not get cut short by exceptions. If exceptions occur, the storage exception takes priority on re-throw. @throws BackendException """ Throwable excep = null; for (IndexTransaction itx : indexTx.values()) { try { itx.rollback(); } catch (Throwable e) { excep = e; } } storeTx.rollback(); if (excep!=null) { //throw any encountered index transaction rollback exceptions if (excep instanceof BackendException) throw (BackendException)excep; else throw new PermanentBackendException("Unexpected exception",excep); } }
java
@Override public void rollback() throws BackendException { Throwable excep = null; for (IndexTransaction itx : indexTx.values()) { try { itx.rollback(); } catch (Throwable e) { excep = e; } } storeTx.rollback(); if (excep!=null) { //throw any encountered index transaction rollback exceptions if (excep instanceof BackendException) throw (BackendException)excep; else throw new PermanentBackendException("Unexpected exception",excep); } }
[ "@", "Override", "public", "void", "rollback", "(", ")", "throws", "BackendException", "{", "Throwable", "excep", "=", "null", ";", "for", "(", "IndexTransaction", "itx", ":", "indexTx", ".", "values", "(", ")", ")", "{", "try", "{", "itx", ".", "rollback", "(", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "excep", "=", "e", ";", "}", "}", "storeTx", ".", "rollback", "(", ")", ";", "if", "(", "excep", "!=", "null", ")", "{", "//throw any encountered index transaction rollback exceptions", "if", "(", "excep", "instanceof", "BackendException", ")", "throw", "(", "BackendException", ")", "excep", ";", "else", "throw", "new", "PermanentBackendException", "(", "\"Unexpected exception\"", ",", "excep", ")", ";", "}", "}" ]
Rolls back all transactions and makes sure that this does not get cut short by exceptions. If exceptions occur, the storage exception takes priority on re-throw. @throws BackendException
[ "Rolls", "back", "all", "transactions", "and", "makes", "sure", "that", "this", "does", "not", "get", "cut", "short", "by", "exceptions", ".", "If", "exceptions", "occur", "the", "storage", "exception", "takes", "priority", "on", "re", "-", "throw", "." ]
train
https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/BackendTransaction.java#L144-L159
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityManagerImpl.java
EntityManagerImpl.setProperty
@Override public void setProperty(String paramString, Object paramObject) { """ Set an entity manager property or hint. If a vendor-specific property or hint is not recognized, it is silently ignored. @param propertyName name of property or hint @param value @throws IllegalArgumentException if the second argument is not valid for the implementation @see javax.persistence.EntityManager#setProperty(java.lang.String, java.lang.Object) """ checkClosed(); if (getProperties() == null) { this.properties = new HashMap<String, Object>(); } this.properties.put(paramString, paramObject); getPersistenceDelegator().populateClientProperties(this.properties); }
java
@Override public void setProperty(String paramString, Object paramObject) { checkClosed(); if (getProperties() == null) { this.properties = new HashMap<String, Object>(); } this.properties.put(paramString, paramObject); getPersistenceDelegator().populateClientProperties(this.properties); }
[ "@", "Override", "public", "void", "setProperty", "(", "String", "paramString", ",", "Object", "paramObject", ")", "{", "checkClosed", "(", ")", ";", "if", "(", "getProperties", "(", ")", "==", "null", ")", "{", "this", ".", "properties", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "}", "this", ".", "properties", ".", "put", "(", "paramString", ",", "paramObject", ")", ";", "getPersistenceDelegator", "(", ")", ".", "populateClientProperties", "(", "this", ".", "properties", ")", ";", "}" ]
Set an entity manager property or hint. If a vendor-specific property or hint is not recognized, it is silently ignored. @param propertyName name of property or hint @param value @throws IllegalArgumentException if the second argument is not valid for the implementation @see javax.persistence.EntityManager#setProperty(java.lang.String, java.lang.Object)
[ "Set", "an", "entity", "manager", "property", "or", "hint", ".", "If", "a", "vendor", "-", "specific", "property", "or", "hint", "is", "not", "recognized", "it", "is", "silently", "ignored", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityManagerImpl.java#L684-L695
SeleniumHQ/selenium
java/server/src/org/openqa/grid/selenium/proxy/DefaultRemoteProxy.java
DefaultRemoteProxy.getNewSession
@Override public TestSession getNewSession(Map<String, Object> requestedCapability) { """ overwrites the session allocation to discard the proxy that are down. """ if (down) { return null; } return super.getNewSession(requestedCapability); }
java
@Override public TestSession getNewSession(Map<String, Object> requestedCapability) { if (down) { return null; } return super.getNewSession(requestedCapability); }
[ "@", "Override", "public", "TestSession", "getNewSession", "(", "Map", "<", "String", ",", "Object", ">", "requestedCapability", ")", "{", "if", "(", "down", ")", "{", "return", "null", ";", "}", "return", "super", ".", "getNewSession", "(", "requestedCapability", ")", ";", "}" ]
overwrites the session allocation to discard the proxy that are down.
[ "overwrites", "the", "session", "allocation", "to", "discard", "the", "proxy", "that", "are", "down", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/server/src/org/openqa/grid/selenium/proxy/DefaultRemoteProxy.java#L211-L217
JM-Lab/utils-java8
src/main/java/kr/jm/utils/helper/JMPath.java
JMPath.extractSubPath
public static Path extractSubPath(Path basePath, Path sourcePath) { """ Extract sub path path. @param basePath the base path @param sourcePath the source path @return the path """ return sourcePath.subpath(basePath.getNameCount() - 1, sourcePath.getNameCount()); }
java
public static Path extractSubPath(Path basePath, Path sourcePath) { return sourcePath.subpath(basePath.getNameCount() - 1, sourcePath.getNameCount()); }
[ "public", "static", "Path", "extractSubPath", "(", "Path", "basePath", ",", "Path", "sourcePath", ")", "{", "return", "sourcePath", ".", "subpath", "(", "basePath", ".", "getNameCount", "(", ")", "-", "1", ",", "sourcePath", ".", "getNameCount", "(", ")", ")", ";", "}" ]
Extract sub path path. @param basePath the base path @param sourcePath the source path @return the path
[ "Extract", "sub", "path", "path", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMPath.java#L833-L836
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.appendStringInto
public static void appendStringInto( String s, File outputFile ) throws IOException { """ Appends a string into a file. @param s the string to write (not null) @param outputFile the file to write into @throws IOException if something went wrong """ OutputStreamWriter fw = null; try { fw = new OutputStreamWriter( new FileOutputStream( outputFile, true ), StandardCharsets.UTF_8 ); fw.append( s ); } finally { Utils.closeQuietly( fw ); } }
java
public static void appendStringInto( String s, File outputFile ) throws IOException { OutputStreamWriter fw = null; try { fw = new OutputStreamWriter( new FileOutputStream( outputFile, true ), StandardCharsets.UTF_8 ); fw.append( s ); } finally { Utils.closeQuietly( fw ); } }
[ "public", "static", "void", "appendStringInto", "(", "String", "s", ",", "File", "outputFile", ")", "throws", "IOException", "{", "OutputStreamWriter", "fw", "=", "null", ";", "try", "{", "fw", "=", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "outputFile", ",", "true", ")", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "fw", ".", "append", "(", "s", ")", ";", "}", "finally", "{", "Utils", ".", "closeQuietly", "(", "fw", ")", ";", "}", "}" ]
Appends a string into a file. @param s the string to write (not null) @param outputFile the file to write into @throws IOException if something went wrong
[ "Appends", "a", "string", "into", "a", "file", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L418-L428
weld/core
impl/src/main/java/org/jboss/weld/util/BeanMethods.java
BeanMethods.filterMethods
public static <T> Collection<EnhancedAnnotatedMethod<?, ? super T>> filterMethods(final Collection<EnhancedAnnotatedMethod<?, ? super T>> methods) { """ Oracle JDK 8 compiler (unlike prev versions) generates bridge methods which have method and parameter annotations copied from the original method. However such methods should not become observers, producers, disposers, initializers and lifecycle callbacks. Moreover, JDK8u60 propagates parameter annotations to the synthetic method generated for a lambda. Therefore, we should also ignore synthetic methods. @param methods @return a collection with bridge and synthetic methods filtered out @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6695379 @see https://issues.jboss.org/browse/WELD-2019 """ return methods.stream().filter(m -> !m.getJavaMember().isBridge() && !m.getJavaMember().isSynthetic()).collect(Collectors.toList()); }
java
public static <T> Collection<EnhancedAnnotatedMethod<?, ? super T>> filterMethods(final Collection<EnhancedAnnotatedMethod<?, ? super T>> methods) { return methods.stream().filter(m -> !m.getJavaMember().isBridge() && !m.getJavaMember().isSynthetic()).collect(Collectors.toList()); }
[ "public", "static", "<", "T", ">", "Collection", "<", "EnhancedAnnotatedMethod", "<", "?", ",", "?", "super", "T", ">", ">", "filterMethods", "(", "final", "Collection", "<", "EnhancedAnnotatedMethod", "<", "?", ",", "?", "super", "T", ">", ">", "methods", ")", "{", "return", "methods", ".", "stream", "(", ")", ".", "filter", "(", "m", "->", "!", "m", ".", "getJavaMember", "(", ")", ".", "isBridge", "(", ")", "&&", "!", "m", ".", "getJavaMember", "(", ")", ".", "isSynthetic", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Oracle JDK 8 compiler (unlike prev versions) generates bridge methods which have method and parameter annotations copied from the original method. However such methods should not become observers, producers, disposers, initializers and lifecycle callbacks. Moreover, JDK8u60 propagates parameter annotations to the synthetic method generated for a lambda. Therefore, we should also ignore synthetic methods. @param methods @return a collection with bridge and synthetic methods filtered out @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6695379 @see https://issues.jboss.org/browse/WELD-2019
[ "Oracle", "JDK", "8", "compiler", "(", "unlike", "prev", "versions", ")", "generates", "bridge", "methods", "which", "have", "method", "and", "parameter", "annotations", "copied", "from", "the", "original", "method", ".", "However", "such", "methods", "should", "not", "become", "observers", "producers", "disposers", "initializers", "and", "lifecycle", "callbacks", "." ]
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/util/BeanMethods.java#L311-L313
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.streamOfTypeForConstructorArgument
@SuppressWarnings("WeakerAccess") @Internal protected final Stream streamOfTypeForConstructorArgument(BeanResolutionContext resolutionContext, BeanContext context, @SuppressWarnings("unused") ConstructorInjectionPoint<T> constructorInjectionPoint, Argument argument) { """ Obtains all bean definitions for a constructor argument at the given index <p> Warning: this method is used by internal generated code and should not be called by user code. @param resolutionContext The resolution context @param context The context @param constructorInjectionPoint The constructor injection point @param argument The argument @return The resolved bean """ return resolveBeanWithGenericsFromConstructorArgument(resolutionContext, argument, (beanType, qualifier) -> ((DefaultBeanContext) context).streamOfType(resolutionContext, beanType, qualifier) ); }
java
@SuppressWarnings("WeakerAccess") @Internal protected final Stream streamOfTypeForConstructorArgument(BeanResolutionContext resolutionContext, BeanContext context, @SuppressWarnings("unused") ConstructorInjectionPoint<T> constructorInjectionPoint, Argument argument) { return resolveBeanWithGenericsFromConstructorArgument(resolutionContext, argument, (beanType, qualifier) -> ((DefaultBeanContext) context).streamOfType(resolutionContext, beanType, qualifier) ); }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "@", "Internal", "protected", "final", "Stream", "streamOfTypeForConstructorArgument", "(", "BeanResolutionContext", "resolutionContext", ",", "BeanContext", "context", ",", "@", "SuppressWarnings", "(", "\"unused\"", ")", "ConstructorInjectionPoint", "<", "T", ">", "constructorInjectionPoint", ",", "Argument", "argument", ")", "{", "return", "resolveBeanWithGenericsFromConstructorArgument", "(", "resolutionContext", ",", "argument", ",", "(", "beanType", ",", "qualifier", ")", "->", "(", "(", "DefaultBeanContext", ")", "context", ")", ".", "streamOfType", "(", "resolutionContext", ",", "beanType", ",", "qualifier", ")", ")", ";", "}" ]
Obtains all bean definitions for a constructor argument at the given index <p> Warning: this method is used by internal generated code and should not be called by user code. @param resolutionContext The resolution context @param context The context @param constructorInjectionPoint The constructor injection point @param argument The argument @return The resolved bean
[ "Obtains", "all", "bean", "definitions", "for", "a", "constructor", "argument", "at", "the", "given", "index", "<p", ">", "Warning", ":", "this", "method", "is", "used", "by", "internal", "generated", "code", "and", "should", "not", "be", "called", "by", "user", "code", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L1105-L1111
Impetus/Kundera
src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/EtherObjectConverterUtil.java
EtherObjectConverterUtil.convertEtherBlockToKunderaBlock
public static Block convertEtherBlockToKunderaBlock(EthBlock block, boolean includeTransactions) { """ Convert ether block to kundera block. @param block the block @param includeTransactions the include transactions @return the block """ Block kunderaBlk = new Block(); org.web3j.protocol.core.methods.response.EthBlock.Block blk = block.getBlock(); kunderaBlk.setAuthor(blk.getAuthor()); kunderaBlk.setDifficulty(blk.getDifficultyRaw()); kunderaBlk.setExtraData(blk.getExtraData()); kunderaBlk.setGasLimit(blk.getGasLimitRaw()); kunderaBlk.setGasUsed(blk.getGasUsedRaw()); kunderaBlk.setHash(blk.getHash()); kunderaBlk.setLogsBloom(blk.getLogsBloom()); kunderaBlk.setMiner(blk.getMiner()); kunderaBlk.setMixHash(blk.getMixHash()); kunderaBlk.setNonce(blk.getNonceRaw()); kunderaBlk.setNumber(blk.getNumberRaw()); kunderaBlk.setParentHash(blk.getParentHash()); kunderaBlk.setReceiptsRoot(blk.getReceiptsRoot()); kunderaBlk.setSealFields(blk.getSealFields()); kunderaBlk.setSha3Uncles(blk.getSha3Uncles()); kunderaBlk.setSize(blk.getSizeRaw()); kunderaBlk.setStateRoot(blk.getStateRoot()); kunderaBlk.setTimestamp(blk.getTimestampRaw()); kunderaBlk.setTotalDifficulty(blk.getTotalDifficultyRaw()); kunderaBlk.setTransactionsRoot(blk.getTransactionsRoot()); kunderaBlk.setUncles(blk.getUncles()); if (includeTransactions) { List<Transaction> kunderaTxs = new ArrayList<>(); List<TransactionResult> txResults = block.getBlock().getTransactions(); if (txResults != null && !txResults.isEmpty()) { for (TransactionResult transactionResult : txResults) { kunderaTxs.add(convertEtherTxToKunderaTx(transactionResult)); } kunderaBlk.setTransactions(kunderaTxs); } } return kunderaBlk; }
java
public static Block convertEtherBlockToKunderaBlock(EthBlock block, boolean includeTransactions) { Block kunderaBlk = new Block(); org.web3j.protocol.core.methods.response.EthBlock.Block blk = block.getBlock(); kunderaBlk.setAuthor(blk.getAuthor()); kunderaBlk.setDifficulty(blk.getDifficultyRaw()); kunderaBlk.setExtraData(blk.getExtraData()); kunderaBlk.setGasLimit(blk.getGasLimitRaw()); kunderaBlk.setGasUsed(blk.getGasUsedRaw()); kunderaBlk.setHash(blk.getHash()); kunderaBlk.setLogsBloom(blk.getLogsBloom()); kunderaBlk.setMiner(blk.getMiner()); kunderaBlk.setMixHash(blk.getMixHash()); kunderaBlk.setNonce(blk.getNonceRaw()); kunderaBlk.setNumber(blk.getNumberRaw()); kunderaBlk.setParentHash(blk.getParentHash()); kunderaBlk.setReceiptsRoot(blk.getReceiptsRoot()); kunderaBlk.setSealFields(blk.getSealFields()); kunderaBlk.setSha3Uncles(blk.getSha3Uncles()); kunderaBlk.setSize(blk.getSizeRaw()); kunderaBlk.setStateRoot(blk.getStateRoot()); kunderaBlk.setTimestamp(blk.getTimestampRaw()); kunderaBlk.setTotalDifficulty(blk.getTotalDifficultyRaw()); kunderaBlk.setTransactionsRoot(blk.getTransactionsRoot()); kunderaBlk.setUncles(blk.getUncles()); if (includeTransactions) { List<Transaction> kunderaTxs = new ArrayList<>(); List<TransactionResult> txResults = block.getBlock().getTransactions(); if (txResults != null && !txResults.isEmpty()) { for (TransactionResult transactionResult : txResults) { kunderaTxs.add(convertEtherTxToKunderaTx(transactionResult)); } kunderaBlk.setTransactions(kunderaTxs); } } return kunderaBlk; }
[ "public", "static", "Block", "convertEtherBlockToKunderaBlock", "(", "EthBlock", "block", ",", "boolean", "includeTransactions", ")", "{", "Block", "kunderaBlk", "=", "new", "Block", "(", ")", ";", "org", ".", "web3j", ".", "protocol", ".", "core", ".", "methods", ".", "response", ".", "EthBlock", ".", "Block", "blk", "=", "block", ".", "getBlock", "(", ")", ";", "kunderaBlk", ".", "setAuthor", "(", "blk", ".", "getAuthor", "(", ")", ")", ";", "kunderaBlk", ".", "setDifficulty", "(", "blk", ".", "getDifficultyRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setExtraData", "(", "blk", ".", "getExtraData", "(", ")", ")", ";", "kunderaBlk", ".", "setGasLimit", "(", "blk", ".", "getGasLimitRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setGasUsed", "(", "blk", ".", "getGasUsedRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setHash", "(", "blk", ".", "getHash", "(", ")", ")", ";", "kunderaBlk", ".", "setLogsBloom", "(", "blk", ".", "getLogsBloom", "(", ")", ")", ";", "kunderaBlk", ".", "setMiner", "(", "blk", ".", "getMiner", "(", ")", ")", ";", "kunderaBlk", ".", "setMixHash", "(", "blk", ".", "getMixHash", "(", ")", ")", ";", "kunderaBlk", ".", "setNonce", "(", "blk", ".", "getNonceRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setNumber", "(", "blk", ".", "getNumberRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setParentHash", "(", "blk", ".", "getParentHash", "(", ")", ")", ";", "kunderaBlk", ".", "setReceiptsRoot", "(", "blk", ".", "getReceiptsRoot", "(", ")", ")", ";", "kunderaBlk", ".", "setSealFields", "(", "blk", ".", "getSealFields", "(", ")", ")", ";", "kunderaBlk", ".", "setSha3Uncles", "(", "blk", ".", "getSha3Uncles", "(", ")", ")", ";", "kunderaBlk", ".", "setSize", "(", "blk", ".", "getSizeRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setStateRoot", "(", "blk", ".", "getStateRoot", "(", ")", ")", ";", "kunderaBlk", ".", "setTimestamp", "(", "blk", ".", "getTimestampRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setTotalDifficulty", "(", "blk", ".", "getTotalDifficultyRaw", "(", ")", ")", ";", "kunderaBlk", ".", "setTransactionsRoot", "(", "blk", ".", "getTransactionsRoot", "(", ")", ")", ";", "kunderaBlk", ".", "setUncles", "(", "blk", ".", "getUncles", "(", ")", ")", ";", "if", "(", "includeTransactions", ")", "{", "List", "<", "Transaction", ">", "kunderaTxs", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "TransactionResult", ">", "txResults", "=", "block", ".", "getBlock", "(", ")", ".", "getTransactions", "(", ")", ";", "if", "(", "txResults", "!=", "null", "&&", "!", "txResults", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "TransactionResult", "transactionResult", ":", "txResults", ")", "{", "kunderaTxs", ".", "add", "(", "convertEtherTxToKunderaTx", "(", "transactionResult", ")", ")", ";", "}", "kunderaBlk", ".", "setTransactions", "(", "kunderaTxs", ")", ";", "}", "}", "return", "kunderaBlk", ";", "}" ]
Convert ether block to kundera block. @param block the block @param includeTransactions the include transactions @return the block
[ "Convert", "ether", "block", "to", "kundera", "block", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/EtherObjectConverterUtil.java#L64-L108
aboutsip/pkts
pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipParser.java
SipParser.expectHCOLONStreamFriendly
public static int expectHCOLONStreamFriendly(final Buffer buffer) throws SipParseException { """ A problem with stream based protocols is that you don't have everything available right away so e.g. when expecting HCOLON you may consume white spaces but then you run out of bytes because you haven't received them yet so therefore the expect(buffer, COLON) will blow up for the wrong reasons. It may very well be that the next byte on the wire is indeed a ':' and as such you should rather signal that you didn't have enough bytes to do your job. This one does that. Note, still some issues with this one though. Let's say the header we are trying to parse is "X-Hello : whatever" and we have only received "X-Hello :" so far. So first off we consume "X-Hello" then call this method, which will consume " :" but ideally we also want to consume the white space after the colon. I.e., when we go off and consume the value of this header we will end up with white space which normally should have been consumed by this method. Hence, whenever dealing with streams you will run into this issue and will have to keep extra state around to solve it. See the {@link SipMessageStreamBuilder} for how it is dealing with this. @param buffer @return @throws SipParseException """ try { int consumed = consumeWS(buffer); if (buffer.hasReadableBytes()) { expect(buffer, COLON); } else { // normally the expect(buffer, COLON) would have thrown // an IndexOutOfBoundsException but let's signal that as // -1 return -1; } ++consumed; consumed += consumeSWSAfterHColon(buffer); return consumed; } catch (final IOException e) { throw new SipParseException(buffer.getReaderIndex(), UNABLE_TO_READ_FROM_STREAM, e); } }
java
public static int expectHCOLONStreamFriendly(final Buffer buffer) throws SipParseException { try { int consumed = consumeWS(buffer); if (buffer.hasReadableBytes()) { expect(buffer, COLON); } else { // normally the expect(buffer, COLON) would have thrown // an IndexOutOfBoundsException but let's signal that as // -1 return -1; } ++consumed; consumed += consumeSWSAfterHColon(buffer); return consumed; } catch (final IOException e) { throw new SipParseException(buffer.getReaderIndex(), UNABLE_TO_READ_FROM_STREAM, e); } }
[ "public", "static", "int", "expectHCOLONStreamFriendly", "(", "final", "Buffer", "buffer", ")", "throws", "SipParseException", "{", "try", "{", "int", "consumed", "=", "consumeWS", "(", "buffer", ")", ";", "if", "(", "buffer", ".", "hasReadableBytes", "(", ")", ")", "{", "expect", "(", "buffer", ",", "COLON", ")", ";", "}", "else", "{", "// normally the expect(buffer, COLON) would have thrown", "// an IndexOutOfBoundsException but let's signal that as", "// -1", "return", "-", "1", ";", "}", "++", "consumed", ";", "consumed", "+=", "consumeSWSAfterHColon", "(", "buffer", ")", ";", "return", "consumed", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "throw", "new", "SipParseException", "(", "buffer", ".", "getReaderIndex", "(", ")", ",", "UNABLE_TO_READ_FROM_STREAM", ",", "e", ")", ";", "}", "}" ]
A problem with stream based protocols is that you don't have everything available right away so e.g. when expecting HCOLON you may consume white spaces but then you run out of bytes because you haven't received them yet so therefore the expect(buffer, COLON) will blow up for the wrong reasons. It may very well be that the next byte on the wire is indeed a ':' and as such you should rather signal that you didn't have enough bytes to do your job. This one does that. Note, still some issues with this one though. Let's say the header we are trying to parse is "X-Hello : whatever" and we have only received "X-Hello :" so far. So first off we consume "X-Hello" then call this method, which will consume " :" but ideally we also want to consume the white space after the colon. I.e., when we go off and consume the value of this header we will end up with white space which normally should have been consumed by this method. Hence, whenever dealing with streams you will run into this issue and will have to keep extra state around to solve it. See the {@link SipMessageStreamBuilder} for how it is dealing with this. @param buffer @return @throws SipParseException
[ "A", "problem", "with", "stream", "based", "protocols", "is", "that", "you", "don", "t", "have", "everything", "available", "right", "away", "so", "e", ".", "g", ".", "when", "expecting", "HCOLON", "you", "may", "consume", "white", "spaces", "but", "then", "you", "run", "out", "of", "bytes", "because", "you", "haven", "t", "received", "them", "yet", "so", "therefore", "the", "expect", "(", "buffer", "COLON", ")", "will", "blow", "up", "for", "the", "wrong", "reasons", ".", "It", "may", "very", "well", "be", "that", "the", "next", "byte", "on", "the", "wire", "is", "indeed", "a", ":", "and", "as", "such", "you", "should", "rather", "signal", "that", "you", "didn", "t", "have", "enough", "bytes", "to", "do", "your", "job", ".", "This", "one", "does", "that", "." ]
train
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipParser.java#L618-L635
denisneuling/apitrary.jar
apitrary-api-client/src/main/java/com/apitrary/api/transport/ApiClientTransportFactory.java
ApiClientTransportFactory.newTransport
public Transport newTransport(ApitraryApi apitraryApi) { """ <p>newTransport.</p> @param apitraryApi a {@link com.apitrary.api.ApitraryApi} object. @return a {@link com.apitrary.api.transport.Transport} object. """ List<Class<Transport>> knownTransports = getAvailableTransports(); if (knownTransports.isEmpty()) { throw new ApiTransportException("No transport provider available. Is there one on the classpath?"); } return newTransport(apitraryApi, knownTransports.get(knownTransports.size() - 1)); }
java
public Transport newTransport(ApitraryApi apitraryApi) { List<Class<Transport>> knownTransports = getAvailableTransports(); if (knownTransports.isEmpty()) { throw new ApiTransportException("No transport provider available. Is there one on the classpath?"); } return newTransport(apitraryApi, knownTransports.get(knownTransports.size() - 1)); }
[ "public", "Transport", "newTransport", "(", "ApitraryApi", "apitraryApi", ")", "{", "List", "<", "Class", "<", "Transport", ">>", "knownTransports", "=", "getAvailableTransports", "(", ")", ";", "if", "(", "knownTransports", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "ApiTransportException", "(", "\"No transport provider available. Is there one on the classpath?\"", ")", ";", "}", "return", "newTransport", "(", "apitraryApi", ",", "knownTransports", ".", "get", "(", "knownTransports", ".", "size", "(", ")", "-", "1", ")", ")", ";", "}" ]
<p>newTransport.</p> @param apitraryApi a {@link com.apitrary.api.ApitraryApi} object. @return a {@link com.apitrary.api.transport.Transport} object.
[ "<p", ">", "newTransport", ".", "<", "/", "p", ">" ]
train
https://github.com/denisneuling/apitrary.jar/blob/b7f639a1e735c60ba2b1b62851926757f5de8628/apitrary-api-client/src/main/java/com/apitrary/api/transport/ApiClientTransportFactory.java#L60-L66
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/components/TimePickerSettings.java
TimePickerSettings.setColor
public void setColor(TimeArea area, Color color) { """ setColor, This sets a color for the specified area. Setting an area to null will restore the default color for that area. """ // If null was supplied, then use the default color. if (color == null) { color = area.defaultColor; } // Save the color to the color map. colors.put(area, color); // Call any "updating functions" that are appropriate for the specified area. if (parent != null) { parent.zDrawTextFieldIndicators(); } }
java
public void setColor(TimeArea area, Color color) { // If null was supplied, then use the default color. if (color == null) { color = area.defaultColor; } // Save the color to the color map. colors.put(area, color); // Call any "updating functions" that are appropriate for the specified area. if (parent != null) { parent.zDrawTextFieldIndicators(); } }
[ "public", "void", "setColor", "(", "TimeArea", "area", ",", "Color", "color", ")", "{", "// If null was supplied, then use the default color.", "if", "(", "color", "==", "null", ")", "{", "color", "=", "area", ".", "defaultColor", ";", "}", "// Save the color to the color map.", "colors", ".", "put", "(", "area", ",", "color", ")", ";", "// Call any \"updating functions\" that are appropriate for the specified area.", "if", "(", "parent", "!=", "null", ")", "{", "parent", ".", "zDrawTextFieldIndicators", "(", ")", ";", "}", "}" ]
setColor, This sets a color for the specified area. Setting an area to null will restore the default color for that area.
[ "setColor", "This", "sets", "a", "color", "for", "the", "specified", "area", ".", "Setting", "an", "area", "to", "null", "will", "restore", "the", "default", "color", "for", "that", "area", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/components/TimePickerSettings.java#L602-L614
recruit-mp/android-RMP-Appirater
library/src/main/java/jp/co/recruit_mp/android/rmp_appirater/RmpAppirater.java
RmpAppirater.setRateClickDate
public static void setRateClickDate(Context context, Date rateClickDate) { """ Modify internal value. <p/> If you use this method, you might need to have a good understanding of this class code. @param context Context @param rateClickDate Date of "Rate" button clicked. """ final long rateClickDateMills = ((rateClickDate != null) ? rateClickDate.getTime() : 0); SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putLong(PREF_KEY_RATE_CLICK_DATE, rateClickDateMills); prefsEditor.commit(); }
java
public static void setRateClickDate(Context context, Date rateClickDate) { final long rateClickDateMills = ((rateClickDate != null) ? rateClickDate.getTime() : 0); SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putLong(PREF_KEY_RATE_CLICK_DATE, rateClickDateMills); prefsEditor.commit(); }
[ "public", "static", "void", "setRateClickDate", "(", "Context", "context", ",", "Date", "rateClickDate", ")", "{", "final", "long", "rateClickDateMills", "=", "(", "(", "rateClickDate", "!=", "null", ")", "?", "rateClickDate", ".", "getTime", "(", ")", ":", "0", ")", ";", "SharedPreferences", "prefs", "=", "getSharedPreferences", "(", "context", ")", ";", "SharedPreferences", ".", "Editor", "prefsEditor", "=", "prefs", ".", "edit", "(", ")", ";", "prefsEditor", ".", "putLong", "(", "PREF_KEY_RATE_CLICK_DATE", ",", "rateClickDateMills", ")", ";", "prefsEditor", ".", "commit", "(", ")", ";", "}" ]
Modify internal value. <p/> If you use this method, you might need to have a good understanding of this class code. @param context Context @param rateClickDate Date of "Rate" button clicked.
[ "Modify", "internal", "value", ".", "<p", "/", ">", "If", "you", "use", "this", "method", "you", "might", "need", "to", "have", "a", "good", "understanding", "of", "this", "class", "code", "." ]
train
https://github.com/recruit-mp/android-RMP-Appirater/blob/14fcdf110dfb97120303f39aab1de9393e84b90a/library/src/main/java/jp/co/recruit_mp/android/rmp_appirater/RmpAppirater.java#L358-L367
lalyos/jfiglet
src/main/java/com/github/lalyos/jfiglet/FigletFont.java
FigletFont.getCharLineString
public String getCharLineString(int c, int l) { """ Selects a single line from a character. @param c Character id @param l Line number @return The selected line from the character """ if (font[c][l] == null) return null; else { return new String(font[c][l]).replace(hardblank, ' '); } }
java
public String getCharLineString(int c, int l) { if (font[c][l] == null) return null; else { return new String(font[c][l]).replace(hardblank, ' '); } }
[ "public", "String", "getCharLineString", "(", "int", "c", ",", "int", "l", ")", "{", "if", "(", "font", "[", "c", "]", "[", "l", "]", "==", "null", ")", "return", "null", ";", "else", "{", "return", "new", "String", "(", "font", "[", "c", "]", "[", "l", "]", ")", ".", "replace", "(", "hardblank", ",", "'", "'", ")", ";", "}", "}" ]
Selects a single line from a character. @param c Character id @param l Line number @return The selected line from the character
[ "Selects", "a", "single", "line", "from", "a", "character", "." ]
train
https://github.com/lalyos/jfiglet/blob/fc98c13622d753219267a2a8b5800cead198ebc9/src/main/java/com/github/lalyos/jfiglet/FigletFont.java#L68-L74
windup/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/service/WindupJavaConfigurationService.java
WindupJavaConfigurationService.checkIfIgnored
public boolean checkIfIgnored(final GraphRewrite event, FileModel file) { """ Checks if the {@link FileModel#getFilePath()} + {@link FileModel#getFileName()} is ignored by any of the specified regular expressions. """ List<String> patterns = getIgnoredFileRegexes(); boolean ignored = false; if (patterns != null && !patterns.isEmpty()) { for (String pattern : patterns) { if (file.getFilePath().matches(pattern)) { IgnoredFileModel ignoredFileModel = GraphService.addTypeToModel(event.getGraphContext(), file, IgnoredFileModel.class); ignoredFileModel.setIgnoredRegex(pattern); LOG.info("File/Directory placed in " + file.getFilePath() + " was ignored, because matched [" + pattern + "]."); ignored = true; break; } } } return ignored; }
java
public boolean checkIfIgnored(final GraphRewrite event, FileModel file) { List<String> patterns = getIgnoredFileRegexes(); boolean ignored = false; if (patterns != null && !patterns.isEmpty()) { for (String pattern : patterns) { if (file.getFilePath().matches(pattern)) { IgnoredFileModel ignoredFileModel = GraphService.addTypeToModel(event.getGraphContext(), file, IgnoredFileModel.class); ignoredFileModel.setIgnoredRegex(pattern); LOG.info("File/Directory placed in " + file.getFilePath() + " was ignored, because matched [" + pattern + "]."); ignored = true; break; } } } return ignored; }
[ "public", "boolean", "checkIfIgnored", "(", "final", "GraphRewrite", "event", ",", "FileModel", "file", ")", "{", "List", "<", "String", ">", "patterns", "=", "getIgnoredFileRegexes", "(", ")", ";", "boolean", "ignored", "=", "false", ";", "if", "(", "patterns", "!=", "null", "&&", "!", "patterns", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "String", "pattern", ":", "patterns", ")", "{", "if", "(", "file", ".", "getFilePath", "(", ")", ".", "matches", "(", "pattern", ")", ")", "{", "IgnoredFileModel", "ignoredFileModel", "=", "GraphService", ".", "addTypeToModel", "(", "event", ".", "getGraphContext", "(", ")", ",", "file", ",", "IgnoredFileModel", ".", "class", ")", ";", "ignoredFileModel", ".", "setIgnoredRegex", "(", "pattern", ")", ";", "LOG", ".", "info", "(", "\"File/Directory placed in \"", "+", "file", ".", "getFilePath", "(", ")", "+", "\" was ignored, because matched [\"", "+", "pattern", "+", "\"].\"", ")", ";", "ignored", "=", "true", ";", "break", ";", "}", "}", "}", "return", "ignored", ";", "}" ]
Checks if the {@link FileModel#getFilePath()} + {@link FileModel#getFileName()} is ignored by any of the specified regular expressions.
[ "Checks", "if", "the", "{" ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/service/WindupJavaConfigurationService.java#L50-L70
Alluxio/alluxio
job/server/src/main/java/alluxio/job/util/JobUtils.java
JobUtils.loadBlock
public static void loadBlock(FileSystem fs, FileSystemContext context, String path, long blockId) throws AlluxioException, IOException { """ Loads a block into the local worker. If the block doesn't exist in Alluxio, it will be read from the UFS. @param fs the filesystem @param context filesystem context @param path the file path of the block to load @param blockId the id of the block to load """ AlluxioBlockStore blockStore = AlluxioBlockStore.create(context); String localHostName = NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, ServerConfiguration.global()); List<BlockWorkerInfo> workerInfoList = blockStore.getAllWorkers(); WorkerNetAddress localNetAddress = null; for (BlockWorkerInfo workerInfo : workerInfoList) { if (workerInfo.getNetAddress().getHost().equals(localHostName)) { localNetAddress = workerInfo.getNetAddress(); break; } } if (localNetAddress == null) { throw new NotFoundException(ExceptionMessage.NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK .getMessage(blockId)); } // TODO(jiri): Replace with internal client that uses file ID once the internal client is // factored out of the core server module. The reason to prefer using file ID for this job is // to avoid the the race between "replicate" and "rename", so that even a file to replicate is // renamed, the job is still working on the correct file. URIStatus status = fs.getStatus(new AlluxioURI(path)); OpenFilePOptions openOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); AlluxioConfiguration conf = ServerConfiguration.global(); InStreamOptions inOptions = new InStreamOptions(status, openOptions, conf); // Set read location policy always to loca first for loading blocks for job tasks inOptions.setUfsReadLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); OutStreamOptions outOptions = OutStreamOptions.defaults(conf); // Set write location policy always to local first for loading blocks for job tasks outOptions.setLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); // use -1 to reuse the existing block size for this block try (OutputStream outputStream = blockStore.getOutStream(blockId, -1, localNetAddress, outOptions)) { try (InputStream inputStream = blockStore.getInStream(blockId, inOptions)) { ByteStreams.copy(inputStream, outputStream); } catch (Throwable t) { try { ((Cancelable) outputStream).cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } }
java
public static void loadBlock(FileSystem fs, FileSystemContext context, String path, long blockId) throws AlluxioException, IOException { AlluxioBlockStore blockStore = AlluxioBlockStore.create(context); String localHostName = NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, ServerConfiguration.global()); List<BlockWorkerInfo> workerInfoList = blockStore.getAllWorkers(); WorkerNetAddress localNetAddress = null; for (BlockWorkerInfo workerInfo : workerInfoList) { if (workerInfo.getNetAddress().getHost().equals(localHostName)) { localNetAddress = workerInfo.getNetAddress(); break; } } if (localNetAddress == null) { throw new NotFoundException(ExceptionMessage.NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK .getMessage(blockId)); } // TODO(jiri): Replace with internal client that uses file ID once the internal client is // factored out of the core server module. The reason to prefer using file ID for this job is // to avoid the the race between "replicate" and "rename", so that even a file to replicate is // renamed, the job is still working on the correct file. URIStatus status = fs.getStatus(new AlluxioURI(path)); OpenFilePOptions openOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); AlluxioConfiguration conf = ServerConfiguration.global(); InStreamOptions inOptions = new InStreamOptions(status, openOptions, conf); // Set read location policy always to loca first for loading blocks for job tasks inOptions.setUfsReadLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); OutStreamOptions outOptions = OutStreamOptions.defaults(conf); // Set write location policy always to local first for loading blocks for job tasks outOptions.setLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); // use -1 to reuse the existing block size for this block try (OutputStream outputStream = blockStore.getOutStream(blockId, -1, localNetAddress, outOptions)) { try (InputStream inputStream = blockStore.getInStream(blockId, inOptions)) { ByteStreams.copy(inputStream, outputStream); } catch (Throwable t) { try { ((Cancelable) outputStream).cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } }
[ "public", "static", "void", "loadBlock", "(", "FileSystem", "fs", ",", "FileSystemContext", "context", ",", "String", "path", ",", "long", "blockId", ")", "throws", "AlluxioException", ",", "IOException", "{", "AlluxioBlockStore", "blockStore", "=", "AlluxioBlockStore", ".", "create", "(", "context", ")", ";", "String", "localHostName", "=", "NetworkAddressUtils", ".", "getConnectHost", "(", "ServiceType", ".", "WORKER_RPC", ",", "ServerConfiguration", ".", "global", "(", ")", ")", ";", "List", "<", "BlockWorkerInfo", ">", "workerInfoList", "=", "blockStore", ".", "getAllWorkers", "(", ")", ";", "WorkerNetAddress", "localNetAddress", "=", "null", ";", "for", "(", "BlockWorkerInfo", "workerInfo", ":", "workerInfoList", ")", "{", "if", "(", "workerInfo", ".", "getNetAddress", "(", ")", ".", "getHost", "(", ")", ".", "equals", "(", "localHostName", ")", ")", "{", "localNetAddress", "=", "workerInfo", ".", "getNetAddress", "(", ")", ";", "break", ";", "}", "}", "if", "(", "localNetAddress", "==", "null", ")", "{", "throw", "new", "NotFoundException", "(", "ExceptionMessage", ".", "NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK", ".", "getMessage", "(", "blockId", ")", ")", ";", "}", "// TODO(jiri): Replace with internal client that uses file ID once the internal client is", "// factored out of the core server module. The reason to prefer using file ID for this job is", "// to avoid the the race between \"replicate\" and \"rename\", so that even a file to replicate is", "// renamed, the job is still working on the correct file.", "URIStatus", "status", "=", "fs", ".", "getStatus", "(", "new", "AlluxioURI", "(", "path", ")", ")", ";", "OpenFilePOptions", "openOptions", "=", "OpenFilePOptions", ".", "newBuilder", "(", ")", ".", "setReadType", "(", "ReadPType", ".", "NO_CACHE", ")", ".", "build", "(", ")", ";", "AlluxioConfiguration", "conf", "=", "ServerConfiguration", ".", "global", "(", ")", ";", "InStreamOptions", "inOptions", "=", "new", "InStreamOptions", "(", "status", ",", "openOptions", ",", "conf", ")", ";", "// Set read location policy always to loca first for loading blocks for job tasks", "inOptions", ".", "setUfsReadLocationPolicy", "(", "BlockLocationPolicy", ".", "Factory", ".", "create", "(", "LocalFirstPolicy", ".", "class", ".", "getCanonicalName", "(", ")", ",", "conf", ")", ")", ";", "OutStreamOptions", "outOptions", "=", "OutStreamOptions", ".", "defaults", "(", "conf", ")", ";", "// Set write location policy always to local first for loading blocks for job tasks", "outOptions", ".", "setLocationPolicy", "(", "BlockLocationPolicy", ".", "Factory", ".", "create", "(", "LocalFirstPolicy", ".", "class", ".", "getCanonicalName", "(", ")", ",", "conf", ")", ")", ";", "// use -1 to reuse the existing block size for this block", "try", "(", "OutputStream", "outputStream", "=", "blockStore", ".", "getOutStream", "(", "blockId", ",", "-", "1", ",", "localNetAddress", ",", "outOptions", ")", ")", "{", "try", "(", "InputStream", "inputStream", "=", "blockStore", ".", "getInStream", "(", "blockId", ",", "inOptions", ")", ")", "{", "ByteStreams", ".", "copy", "(", "inputStream", ",", "outputStream", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "try", "{", "(", "(", "Cancelable", ")", "outputStream", ")", ".", "cancel", "(", ")", ";", "}", "catch", "(", "Throwable", "t2", ")", "{", "t", ".", "addSuppressed", "(", "t2", ")", ";", "}", "throw", "t", ";", "}", "}", "}" ]
Loads a block into the local worker. If the block doesn't exist in Alluxio, it will be read from the UFS. @param fs the filesystem @param context filesystem context @param path the file path of the block to load @param blockId the id of the block to load
[ "Loads", "a", "block", "into", "the", "local", "worker", ".", "If", "the", "block", "doesn", "t", "exist", "in", "Alluxio", "it", "will", "be", "read", "from", "the", "UFS", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/job/util/JobUtils.java#L107-L161
devnied/Bit-lib4j
src/main/java/fr/devnied/bitlib/BitUtils.java
BitUtils.setNextLong
public void setNextLong(final long pValue, final int pLength) { """ Add Long to the current position with the specified size Be careful with java long bit sign @param pValue the value to set @param pLength the length of the long """ if (pLength > Long.SIZE) { throw new IllegalArgumentException("Long overflow with length > 64"); } setNextValue(pValue, pLength, Long.SIZE - 1); }
java
public void setNextLong(final long pValue, final int pLength) { if (pLength > Long.SIZE) { throw new IllegalArgumentException("Long overflow with length > 64"); } setNextValue(pValue, pLength, Long.SIZE - 1); }
[ "public", "void", "setNextLong", "(", "final", "long", "pValue", ",", "final", "int", "pLength", ")", "{", "if", "(", "pLength", ">", "Long", ".", "SIZE", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Long overflow with length > 64\"", ")", ";", "}", "setNextValue", "(", "pValue", ",", "pLength", ",", "Long", ".", "SIZE", "-", "1", ")", ";", "}" ]
Add Long to the current position with the specified size Be careful with java long bit sign @param pValue the value to set @param pLength the length of the long
[ "Add", "Long", "to", "the", "current", "position", "with", "the", "specified", "size" ]
train
https://github.com/devnied/Bit-lib4j/blob/bdfa79fd12e7e3d5cf1196291825ef1bb12a1ee0/src/main/java/fr/devnied/bitlib/BitUtils.java#L571-L578
jenkinsci/jenkins
core/src/main/java/hudson/model/listeners/ItemListener.java
ItemListener.fireLocationChange
public static void fireLocationChange(final Item rootItem, final String oldFullName) { """ Calls {@link #onRenamed} and {@link #onLocationChanged} as appropriate. @param rootItem the topmost item whose location has just changed @param oldFullName the previous {@link Item#getFullName} @since 1.548 """ String prefix = rootItem.getParent().getFullName(); if (!prefix.isEmpty()) { prefix += '/'; } final String newFullName = rootItem.getFullName(); assert newFullName.startsWith(prefix); int prefixS = prefix.length(); if (oldFullName.startsWith(prefix) && oldFullName.indexOf('/', prefixS) == -1) { final String oldName = oldFullName.substring(prefixS); final String newName = rootItem.getName(); assert newName.equals(newFullName.substring(prefixS)); forAll(new Function<ItemListener, Void>() { @Override public Void apply(ItemListener l) { l.onRenamed(rootItem, oldName, newName); return null; } }); } forAll(new Function<ItemListener, Void>() { @Override public Void apply(ItemListener l) { l.onLocationChanged(rootItem, oldFullName, newFullName); return null; } }); if (rootItem instanceof ItemGroup) { for (final Item child : Items.allItems(ACL.SYSTEM, (ItemGroup)rootItem, Item.class)) { final String childNew = child.getFullName(); assert childNew.startsWith(newFullName); assert childNew.charAt(newFullName.length()) == '/'; final String childOld = oldFullName + childNew.substring(newFullName.length()); forAll(new Function<ItemListener, Void>() { @Override public Void apply(ItemListener l) { l.onLocationChanged(child, childOld, childNew); return null; } }); } } }
java
public static void fireLocationChange(final Item rootItem, final String oldFullName) { String prefix = rootItem.getParent().getFullName(); if (!prefix.isEmpty()) { prefix += '/'; } final String newFullName = rootItem.getFullName(); assert newFullName.startsWith(prefix); int prefixS = prefix.length(); if (oldFullName.startsWith(prefix) && oldFullName.indexOf('/', prefixS) == -1) { final String oldName = oldFullName.substring(prefixS); final String newName = rootItem.getName(); assert newName.equals(newFullName.substring(prefixS)); forAll(new Function<ItemListener, Void>() { @Override public Void apply(ItemListener l) { l.onRenamed(rootItem, oldName, newName); return null; } }); } forAll(new Function<ItemListener, Void>() { @Override public Void apply(ItemListener l) { l.onLocationChanged(rootItem, oldFullName, newFullName); return null; } }); if (rootItem instanceof ItemGroup) { for (final Item child : Items.allItems(ACL.SYSTEM, (ItemGroup)rootItem, Item.class)) { final String childNew = child.getFullName(); assert childNew.startsWith(newFullName); assert childNew.charAt(newFullName.length()) == '/'; final String childOld = oldFullName + childNew.substring(newFullName.length()); forAll(new Function<ItemListener, Void>() { @Override public Void apply(ItemListener l) { l.onLocationChanged(child, childOld, childNew); return null; } }); } } }
[ "public", "static", "void", "fireLocationChange", "(", "final", "Item", "rootItem", ",", "final", "String", "oldFullName", ")", "{", "String", "prefix", "=", "rootItem", ".", "getParent", "(", ")", ".", "getFullName", "(", ")", ";", "if", "(", "!", "prefix", ".", "isEmpty", "(", ")", ")", "{", "prefix", "+=", "'", "'", ";", "}", "final", "String", "newFullName", "=", "rootItem", ".", "getFullName", "(", ")", ";", "assert", "newFullName", ".", "startsWith", "(", "prefix", ")", ";", "int", "prefixS", "=", "prefix", ".", "length", "(", ")", ";", "if", "(", "oldFullName", ".", "startsWith", "(", "prefix", ")", "&&", "oldFullName", ".", "indexOf", "(", "'", "'", ",", "prefixS", ")", "==", "-", "1", ")", "{", "final", "String", "oldName", "=", "oldFullName", ".", "substring", "(", "prefixS", ")", ";", "final", "String", "newName", "=", "rootItem", ".", "getName", "(", ")", ";", "assert", "newName", ".", "equals", "(", "newFullName", ".", "substring", "(", "prefixS", ")", ")", ";", "forAll", "(", "new", "Function", "<", "ItemListener", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "apply", "(", "ItemListener", "l", ")", "{", "l", ".", "onRenamed", "(", "rootItem", ",", "oldName", ",", "newName", ")", ";", "return", "null", ";", "}", "}", ")", ";", "}", "forAll", "(", "new", "Function", "<", "ItemListener", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "apply", "(", "ItemListener", "l", ")", "{", "l", ".", "onLocationChanged", "(", "rootItem", ",", "oldFullName", ",", "newFullName", ")", ";", "return", "null", ";", "}", "}", ")", ";", "if", "(", "rootItem", "instanceof", "ItemGroup", ")", "{", "for", "(", "final", "Item", "child", ":", "Items", ".", "allItems", "(", "ACL", ".", "SYSTEM", ",", "(", "ItemGroup", ")", "rootItem", ",", "Item", ".", "class", ")", ")", "{", "final", "String", "childNew", "=", "child", ".", "getFullName", "(", ")", ";", "assert", "childNew", ".", "startsWith", "(", "newFullName", ")", ";", "assert", "childNew", ".", "charAt", "(", "newFullName", ".", "length", "(", ")", ")", "==", "'", "'", ";", "final", "String", "childOld", "=", "oldFullName", "+", "childNew", ".", "substring", "(", "newFullName", ".", "length", "(", ")", ")", ";", "forAll", "(", "new", "Function", "<", "ItemListener", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "apply", "(", "ItemListener", "l", ")", "{", "l", ".", "onLocationChanged", "(", "child", ",", "childOld", ",", "childNew", ")", ";", "return", "null", ";", "}", "}", ")", ";", "}", "}", "}" ]
Calls {@link #onRenamed} and {@link #onLocationChanged} as appropriate. @param rootItem the topmost item whose location has just changed @param oldFullName the previous {@link Item#getFullName} @since 1.548
[ "Calls", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/listeners/ItemListener.java#L249-L288
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemCache.java
ProxiedFileSystemCache.getProxiedFileSystem
@Builder(builderClassName = "ProxiedFileSystemFromProperties", builderMethodName = "fromProperties") private static FileSystem getProxiedFileSystem(@NonNull String userNameToProxyAs, Properties properties, URI fsURI, Configuration configuration, FileSystem referenceFS) throws IOException { """ Gets a {@link FileSystem} that can perform any operations allowed by the specified userNameToProxyAs. @param userNameToProxyAs The name of the user the super user should proxy as @param properties {@link java.util.Properties} containing initialization properties. @param fsURI The {@link URI} for the {@link FileSystem} that should be created. @param configuration The {@link Configuration} for the {@link FileSystem} that should be created. @param referenceFS reference {@link FileSystem}. Used to replicate certain decorators of the reference FS: {@link RateControlledFileSystem}. @return a {@link FileSystem} that can execute commands on behalf of the specified userNameToProxyAs @throws IOException """ Preconditions.checkNotNull(userNameToProxyAs, "Must provide a user name to proxy as."); Preconditions.checkNotNull(properties, "Properties is a mandatory field for proxiedFileSystem generation."); URI actualURI = resolveUri(fsURI, configuration, referenceFS); Configuration actualConfiguration = resolveConfiguration(configuration, referenceFS); try { return USER_NAME_TO_FILESYSTEM_CACHE.get(getFileSystemKey(actualURI, userNameToProxyAs, referenceFS), new CreateProxiedFileSystemFromProperties(userNameToProxyAs, properties, actualURI, actualConfiguration, referenceFS)); } catch (ExecutionException ee) { throw new IOException("Failed to get proxied file system for user " + userNameToProxyAs, ee); } }
java
@Builder(builderClassName = "ProxiedFileSystemFromProperties", builderMethodName = "fromProperties") private static FileSystem getProxiedFileSystem(@NonNull String userNameToProxyAs, Properties properties, URI fsURI, Configuration configuration, FileSystem referenceFS) throws IOException { Preconditions.checkNotNull(userNameToProxyAs, "Must provide a user name to proxy as."); Preconditions.checkNotNull(properties, "Properties is a mandatory field for proxiedFileSystem generation."); URI actualURI = resolveUri(fsURI, configuration, referenceFS); Configuration actualConfiguration = resolveConfiguration(configuration, referenceFS); try { return USER_NAME_TO_FILESYSTEM_CACHE.get(getFileSystemKey(actualURI, userNameToProxyAs, referenceFS), new CreateProxiedFileSystemFromProperties(userNameToProxyAs, properties, actualURI, actualConfiguration, referenceFS)); } catch (ExecutionException ee) { throw new IOException("Failed to get proxied file system for user " + userNameToProxyAs, ee); } }
[ "@", "Builder", "(", "builderClassName", "=", "\"ProxiedFileSystemFromProperties\"", ",", "builderMethodName", "=", "\"fromProperties\"", ")", "private", "static", "FileSystem", "getProxiedFileSystem", "(", "@", "NonNull", "String", "userNameToProxyAs", ",", "Properties", "properties", ",", "URI", "fsURI", ",", "Configuration", "configuration", ",", "FileSystem", "referenceFS", ")", "throws", "IOException", "{", "Preconditions", ".", "checkNotNull", "(", "userNameToProxyAs", ",", "\"Must provide a user name to proxy as.\"", ")", ";", "Preconditions", ".", "checkNotNull", "(", "properties", ",", "\"Properties is a mandatory field for proxiedFileSystem generation.\"", ")", ";", "URI", "actualURI", "=", "resolveUri", "(", "fsURI", ",", "configuration", ",", "referenceFS", ")", ";", "Configuration", "actualConfiguration", "=", "resolveConfiguration", "(", "configuration", ",", "referenceFS", ")", ";", "try", "{", "return", "USER_NAME_TO_FILESYSTEM_CACHE", ".", "get", "(", "getFileSystemKey", "(", "actualURI", ",", "userNameToProxyAs", ",", "referenceFS", ")", ",", "new", "CreateProxiedFileSystemFromProperties", "(", "userNameToProxyAs", ",", "properties", ",", "actualURI", ",", "actualConfiguration", ",", "referenceFS", ")", ")", ";", "}", "catch", "(", "ExecutionException", "ee", ")", "{", "throw", "new", "IOException", "(", "\"Failed to get proxied file system for user \"", "+", "userNameToProxyAs", ",", "ee", ")", ";", "}", "}" ]
Gets a {@link FileSystem} that can perform any operations allowed by the specified userNameToProxyAs. @param userNameToProxyAs The name of the user the super user should proxy as @param properties {@link java.util.Properties} containing initialization properties. @param fsURI The {@link URI} for the {@link FileSystem} that should be created. @param configuration The {@link Configuration} for the {@link FileSystem} that should be created. @param referenceFS reference {@link FileSystem}. Used to replicate certain decorators of the reference FS: {@link RateControlledFileSystem}. @return a {@link FileSystem} that can execute commands on behalf of the specified userNameToProxyAs @throws IOException
[ "Gets", "a", "{", "@link", "FileSystem", "}", "that", "can", "perform", "any", "operations", "allowed", "by", "the", "specified", "userNameToProxyAs", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemCache.java#L125-L140
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/transform/fft/DiscreteFourierTransformOps.java
DiscreteFourierTransformOps.shiftZeroFrequency
public static void shiftZeroFrequency(InterleavedF32 transform, boolean forward ) { """ Moves the zero-frequency component into the image center (width/2,height/2). This function can be called to undo the transform. @param transform the DFT which is to be shifted. @param forward If true then it does the shift in the forward direction. If false then it undoes the transforms. """ int hw = transform.width/2; int hh = transform.height/2; if( transform.width%2 == 0 && transform.height%2 == 0 ) { // if both sides are even then a simple transform can be done for( int y = 0; y < hh; y++ ) { for( int x = 0; x < hw; x++ ) { float ra = transform.getBand(x,y,0); float ia = transform.getBand(x,y,1); float rb = transform.getBand(x+hw,y+hh,0); float ib = transform.getBand(x+hw,y+hh,1); transform.setBand(x,y,0,rb); transform.setBand(x,y,1,ib); transform.setBand(x+hw,y+hh,0,ra); transform.setBand(x+hw,y+hh,1,ia); ra = transform.getBand(x+hw,y,0); ia = transform.getBand(x+hw,y,1); rb = transform.getBand(x,y+hh,0); ib = transform.getBand(x,y+hh,1); transform.setBand(x+hw,y,0,rb); transform.setBand(x+hw,y,1,ib); transform.setBand(x,y+hh,0,ra); transform.setBand(x,y+hh,1,ia); } } } else { // with odd images, the easiest way to do it is by copying the regions int w = transform.width; int h = transform.height; int hw1 = hw + w%2; int hh1 = hh + h%2; if( forward ) { InterleavedF32 storageTL = new InterleavedF32(hw1,hh1,2); storageTL.setTo(transform.subimage(0, 0, hw1, hh1, null)); InterleavedF32 storageTR = new InterleavedF32(hw,hh1,2); storageTR.setTo(transform.subimage(hw1, 0, w, hh1, null)); transform.subimage(0,0,hw,hh, null).setTo(transform.subimage(hw1,hh1,w,h, null)); transform.subimage(hw,0,w, hh, null).setTo(transform.subimage(0,hh1,hw1,h, null)); transform.subimage(hw,hh,w,h, null).setTo(storageTL); transform.subimage(0,hh,hw,h, null).setTo(storageTR); } else { InterleavedF32 storageBL = new InterleavedF32(hw,hh1,2); storageBL.setTo(transform.subimage(0, hh, hw, h, null)); InterleavedF32 storageBR = new InterleavedF32(hw1,hh1,2); storageBR.setTo(transform.subimage(hw, hh, w, h, null)); transform.subimage(hw1,hh1,w,h, null).setTo(transform.subimage(0,0,hw,hh, null)); transform.subimage(0,hh1,hw1,h, null).setTo(transform.subimage(hw,0,w, hh, null)); transform.subimage(hw1,0,w,hh1, null).setTo(storageBL); transform.subimage(0,0,hw1,hh1, null).setTo(storageBR); } } }
java
public static void shiftZeroFrequency(InterleavedF32 transform, boolean forward ) { int hw = transform.width/2; int hh = transform.height/2; if( transform.width%2 == 0 && transform.height%2 == 0 ) { // if both sides are even then a simple transform can be done for( int y = 0; y < hh; y++ ) { for( int x = 0; x < hw; x++ ) { float ra = transform.getBand(x,y,0); float ia = transform.getBand(x,y,1); float rb = transform.getBand(x+hw,y+hh,0); float ib = transform.getBand(x+hw,y+hh,1); transform.setBand(x,y,0,rb); transform.setBand(x,y,1,ib); transform.setBand(x+hw,y+hh,0,ra); transform.setBand(x+hw,y+hh,1,ia); ra = transform.getBand(x+hw,y,0); ia = transform.getBand(x+hw,y,1); rb = transform.getBand(x,y+hh,0); ib = transform.getBand(x,y+hh,1); transform.setBand(x+hw,y,0,rb); transform.setBand(x+hw,y,1,ib); transform.setBand(x,y+hh,0,ra); transform.setBand(x,y+hh,1,ia); } } } else { // with odd images, the easiest way to do it is by copying the regions int w = transform.width; int h = transform.height; int hw1 = hw + w%2; int hh1 = hh + h%2; if( forward ) { InterleavedF32 storageTL = new InterleavedF32(hw1,hh1,2); storageTL.setTo(transform.subimage(0, 0, hw1, hh1, null)); InterleavedF32 storageTR = new InterleavedF32(hw,hh1,2); storageTR.setTo(transform.subimage(hw1, 0, w, hh1, null)); transform.subimage(0,0,hw,hh, null).setTo(transform.subimage(hw1,hh1,w,h, null)); transform.subimage(hw,0,w, hh, null).setTo(transform.subimage(0,hh1,hw1,h, null)); transform.subimage(hw,hh,w,h, null).setTo(storageTL); transform.subimage(0,hh,hw,h, null).setTo(storageTR); } else { InterleavedF32 storageBL = new InterleavedF32(hw,hh1,2); storageBL.setTo(transform.subimage(0, hh, hw, h, null)); InterleavedF32 storageBR = new InterleavedF32(hw1,hh1,2); storageBR.setTo(transform.subimage(hw, hh, w, h, null)); transform.subimage(hw1,hh1,w,h, null).setTo(transform.subimage(0,0,hw,hh, null)); transform.subimage(0,hh1,hw1,h, null).setTo(transform.subimage(hw,0,w, hh, null)); transform.subimage(hw1,0,w,hh1, null).setTo(storageBL); transform.subimage(0,0,hw1,hh1, null).setTo(storageBR); } } }
[ "public", "static", "void", "shiftZeroFrequency", "(", "InterleavedF32", "transform", ",", "boolean", "forward", ")", "{", "int", "hw", "=", "transform", ".", "width", "/", "2", ";", "int", "hh", "=", "transform", ".", "height", "/", "2", ";", "if", "(", "transform", ".", "width", "%", "2", "==", "0", "&&", "transform", ".", "height", "%", "2", "==", "0", ")", "{", "// if both sides are even then a simple transform can be done", "for", "(", "int", "y", "=", "0", ";", "y", "<", "hh", ";", "y", "++", ")", "{", "for", "(", "int", "x", "=", "0", ";", "x", "<", "hw", ";", "x", "++", ")", "{", "float", "ra", "=", "transform", ".", "getBand", "(", "x", ",", "y", ",", "0", ")", ";", "float", "ia", "=", "transform", ".", "getBand", "(", "x", ",", "y", ",", "1", ")", ";", "float", "rb", "=", "transform", ".", "getBand", "(", "x", "+", "hw", ",", "y", "+", "hh", ",", "0", ")", ";", "float", "ib", "=", "transform", ".", "getBand", "(", "x", "+", "hw", ",", "y", "+", "hh", ",", "1", ")", ";", "transform", ".", "setBand", "(", "x", ",", "y", ",", "0", ",", "rb", ")", ";", "transform", ".", "setBand", "(", "x", ",", "y", ",", "1", ",", "ib", ")", ";", "transform", ".", "setBand", "(", "x", "+", "hw", ",", "y", "+", "hh", ",", "0", ",", "ra", ")", ";", "transform", ".", "setBand", "(", "x", "+", "hw", ",", "y", "+", "hh", ",", "1", ",", "ia", ")", ";", "ra", "=", "transform", ".", "getBand", "(", "x", "+", "hw", ",", "y", ",", "0", ")", ";", "ia", "=", "transform", ".", "getBand", "(", "x", "+", "hw", ",", "y", ",", "1", ")", ";", "rb", "=", "transform", ".", "getBand", "(", "x", ",", "y", "+", "hh", ",", "0", ")", ";", "ib", "=", "transform", ".", "getBand", "(", "x", ",", "y", "+", "hh", ",", "1", ")", ";", "transform", ".", "setBand", "(", "x", "+", "hw", ",", "y", ",", "0", ",", "rb", ")", ";", "transform", ".", "setBand", "(", "x", "+", "hw", ",", "y", ",", "1", ",", "ib", ")", ";", "transform", ".", "setBand", "(", "x", ",", "y", "+", "hh", ",", "0", ",", "ra", ")", ";", "transform", ".", "setBand", "(", "x", ",", "y", "+", "hh", ",", "1", ",", "ia", ")", ";", "}", "}", "}", "else", "{", "// with odd images, the easiest way to do it is by copying the regions", "int", "w", "=", "transform", ".", "width", ";", "int", "h", "=", "transform", ".", "height", ";", "int", "hw1", "=", "hw", "+", "w", "%", "2", ";", "int", "hh1", "=", "hh", "+", "h", "%", "2", ";", "if", "(", "forward", ")", "{", "InterleavedF32", "storageTL", "=", "new", "InterleavedF32", "(", "hw1", ",", "hh1", ",", "2", ")", ";", "storageTL", ".", "setTo", "(", "transform", ".", "subimage", "(", "0", ",", "0", ",", "hw1", ",", "hh1", ",", "null", ")", ")", ";", "InterleavedF32", "storageTR", "=", "new", "InterleavedF32", "(", "hw", ",", "hh1", ",", "2", ")", ";", "storageTR", ".", "setTo", "(", "transform", ".", "subimage", "(", "hw1", ",", "0", ",", "w", ",", "hh1", ",", "null", ")", ")", ";", "transform", ".", "subimage", "(", "0", ",", "0", ",", "hw", ",", "hh", ",", "null", ")", ".", "setTo", "(", "transform", ".", "subimage", "(", "hw1", ",", "hh1", ",", "w", ",", "h", ",", "null", ")", ")", ";", "transform", ".", "subimage", "(", "hw", ",", "0", ",", "w", ",", "hh", ",", "null", ")", ".", "setTo", "(", "transform", ".", "subimage", "(", "0", ",", "hh1", ",", "hw1", ",", "h", ",", "null", ")", ")", ";", "transform", ".", "subimage", "(", "hw", ",", "hh", ",", "w", ",", "h", ",", "null", ")", ".", "setTo", "(", "storageTL", ")", ";", "transform", ".", "subimage", "(", "0", ",", "hh", ",", "hw", ",", "h", ",", "null", ")", ".", "setTo", "(", "storageTR", ")", ";", "}", "else", "{", "InterleavedF32", "storageBL", "=", "new", "InterleavedF32", "(", "hw", ",", "hh1", ",", "2", ")", ";", "storageBL", ".", "setTo", "(", "transform", ".", "subimage", "(", "0", ",", "hh", ",", "hw", ",", "h", ",", "null", ")", ")", ";", "InterleavedF32", "storageBR", "=", "new", "InterleavedF32", "(", "hw1", ",", "hh1", ",", "2", ")", ";", "storageBR", ".", "setTo", "(", "transform", ".", "subimage", "(", "hw", ",", "hh", ",", "w", ",", "h", ",", "null", ")", ")", ";", "transform", ".", "subimage", "(", "hw1", ",", "hh1", ",", "w", ",", "h", ",", "null", ")", ".", "setTo", "(", "transform", ".", "subimage", "(", "0", ",", "0", ",", "hw", ",", "hh", ",", "null", ")", ")", ";", "transform", ".", "subimage", "(", "0", ",", "hh1", ",", "hw1", ",", "h", ",", "null", ")", ".", "setTo", "(", "transform", ".", "subimage", "(", "hw", ",", "0", ",", "w", ",", "hh", ",", "null", ")", ")", ";", "transform", ".", "subimage", "(", "hw1", ",", "0", ",", "w", ",", "hh1", ",", "null", ")", ".", "setTo", "(", "storageBL", ")", ";", "transform", ".", "subimage", "(", "0", ",", "0", ",", "hw1", ",", "hh1", ",", "null", ")", ".", "setTo", "(", "storageBR", ")", ";", "}", "}", "}" ]
Moves the zero-frequency component into the image center (width/2,height/2). This function can be called to undo the transform. @param transform the DFT which is to be shifted. @param forward If true then it does the shift in the forward direction. If false then it undoes the transforms.
[ "Moves", "the", "zero", "-", "frequency", "component", "into", "the", "image", "center", "(", "width", "/", "2", "height", "/", "2", ")", ".", "This", "function", "can", "be", "called", "to", "undo", "the", "transform", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/fft/DiscreteFourierTransformOps.java#L111-L176
chennaione/sugar
library/src/main/java/com/orm/SugarDataSource.java
SugarDataSource.bulkInsert
public void bulkInsert(final List<T> objects, final SuccessCallback<List<Long>> successCallback, final ErrorCallback errorCallback) { """ Method that performs a bulk insert. It works on top of SugarRecord class, and executes the query asynchronously using Futures. @param objects the list of objects that you want to insert. They must be SugarRecord extended objects or @Table annotatd objects. @param successCallback the callback for successful bulk insert operation @param errorCallback the callback for an error in bulk insert operation """ checkNotNull(successCallback); checkNotNull(errorCallback); checkNotNull(objects); final Callable<List<Long>> call = new Callable<List<Long>>() { @Override public List<Long> call() throws Exception { List<Long> ids = new ArrayList<>(objects.size()); for (int i = 0; i < objects.size(); i++) { Long id = SugarRecord.save(objects.get(i)); ids.add(i, id); } return ids; } }; final Future<List<Long>> future = doInBackground(call); List<Long> ids; try { ids = future.get(); if (null == ids || ids.isEmpty()) { errorCallback.onError(new Exception("Error when performing bulk insert")); } else { successCallback.onSuccess(ids); } } catch (Exception e) { errorCallback.onError(e); } }
java
public void bulkInsert(final List<T> objects, final SuccessCallback<List<Long>> successCallback, final ErrorCallback errorCallback) { checkNotNull(successCallback); checkNotNull(errorCallback); checkNotNull(objects); final Callable<List<Long>> call = new Callable<List<Long>>() { @Override public List<Long> call() throws Exception { List<Long> ids = new ArrayList<>(objects.size()); for (int i = 0; i < objects.size(); i++) { Long id = SugarRecord.save(objects.get(i)); ids.add(i, id); } return ids; } }; final Future<List<Long>> future = doInBackground(call); List<Long> ids; try { ids = future.get(); if (null == ids || ids.isEmpty()) { errorCallback.onError(new Exception("Error when performing bulk insert")); } else { successCallback.onSuccess(ids); } } catch (Exception e) { errorCallback.onError(e); } }
[ "public", "void", "bulkInsert", "(", "final", "List", "<", "T", ">", "objects", ",", "final", "SuccessCallback", "<", "List", "<", "Long", ">", ">", "successCallback", ",", "final", "ErrorCallback", "errorCallback", ")", "{", "checkNotNull", "(", "successCallback", ")", ";", "checkNotNull", "(", "errorCallback", ")", ";", "checkNotNull", "(", "objects", ")", ";", "final", "Callable", "<", "List", "<", "Long", ">", ">", "call", "=", "new", "Callable", "<", "List", "<", "Long", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "Long", ">", "call", "(", ")", "throws", "Exception", "{", "List", "<", "Long", ">", "ids", "=", "new", "ArrayList", "<>", "(", "objects", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "objects", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Long", "id", "=", "SugarRecord", ".", "save", "(", "objects", ".", "get", "(", "i", ")", ")", ";", "ids", ".", "add", "(", "i", ",", "id", ")", ";", "}", "return", "ids", ";", "}", "}", ";", "final", "Future", "<", "List", "<", "Long", ">", ">", "future", "=", "doInBackground", "(", "call", ")", ";", "List", "<", "Long", ">", "ids", ";", "try", "{", "ids", "=", "future", ".", "get", "(", ")", ";", "if", "(", "null", "==", "ids", "||", "ids", ".", "isEmpty", "(", ")", ")", "{", "errorCallback", ".", "onError", "(", "new", "Exception", "(", "\"Error when performing bulk insert\"", ")", ")", ";", "}", "else", "{", "successCallback", ".", "onSuccess", "(", "ids", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "errorCallback", ".", "onError", "(", "e", ")", ";", "}", "}" ]
Method that performs a bulk insert. It works on top of SugarRecord class, and executes the query asynchronously using Futures. @param objects the list of objects that you want to insert. They must be SugarRecord extended objects or @Table annotatd objects. @param successCallback the callback for successful bulk insert operation @param errorCallback the callback for an error in bulk insert operation
[ "Method", "that", "performs", "a", "bulk", "insert", ".", "It", "works", "on", "top", "of", "SugarRecord", "class", "and", "executes", "the", "query", "asynchronously", "using", "Futures", "." ]
train
https://github.com/chennaione/sugar/blob/2ff1b9d5b11563346b69b4e97324107ff680a61a/library/src/main/java/com/orm/SugarDataSource.java#L91-L125
LearnLib/automatalib
util/src/main/java/net/automatalib/util/automata/random/RandomICAutomatonGenerator.java
RandomICAutomatonGenerator.withStateProperties
@SafeVarargs public final RandomICAutomatonGenerator<SP, TP> withStateProperties(SP... possibleSps) { """ Sets the possible state properties, and returns {@code this}. State properties are selected from this array using {@link RandomUtil#choose(Object[], Random)}. If the array is empty, {@code null} will always be chosen as the state property. @param possibleSps the possible state properties @return {@code this} """ if (possibleSps.length == 0) { return withStateProperties(r -> null); } return withStateProperties(r -> RandomUtil.choose(possibleSps, r)); }
java
@SafeVarargs public final RandomICAutomatonGenerator<SP, TP> withStateProperties(SP... possibleSps) { if (possibleSps.length == 0) { return withStateProperties(r -> null); } return withStateProperties(r -> RandomUtil.choose(possibleSps, r)); }
[ "@", "SafeVarargs", "public", "final", "RandomICAutomatonGenerator", "<", "SP", ",", "TP", ">", "withStateProperties", "(", "SP", "...", "possibleSps", ")", "{", "if", "(", "possibleSps", ".", "length", "==", "0", ")", "{", "return", "withStateProperties", "(", "r", "->", "null", ")", ";", "}", "return", "withStateProperties", "(", "r", "->", "RandomUtil", ".", "choose", "(", "possibleSps", ",", "r", ")", ")", ";", "}" ]
Sets the possible state properties, and returns {@code this}. State properties are selected from this array using {@link RandomUtil#choose(Object[], Random)}. If the array is empty, {@code null} will always be chosen as the state property. @param possibleSps the possible state properties @return {@code this}
[ "Sets", "the", "possible", "state", "properties", "and", "returns", "{", "@code", "this", "}", ".", "State", "properties", "are", "selected", "from", "this", "array", "using", "{", "@link", "RandomUtil#choose", "(", "Object", "[]", "Random", ")", "}", ".", "If", "the", "array", "is", "empty", "{", "@code", "null", "}", "will", "always", "be", "chosen", "as", "the", "state", "property", "." ]
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/automata/random/RandomICAutomatonGenerator.java#L144-L150
landawn/AbacusUtil
src/com/landawn/abacus/util/Array.java
Array.binarySearch
static <T> int binarySearch(final T[] a, final T key, final Comparator<? super T> cmp) { """ {@link Arrays#binarySearch(Object[], Object, Comparator)} @param a @param key @param cmp @return """ if (N.isNullOrEmpty(a)) { return N.INDEX_NOT_FOUND; } return Arrays.binarySearch(a, key, cmp == null ? Comparators.NATURAL_ORDER : cmp); }
java
static <T> int binarySearch(final T[] a, final T key, final Comparator<? super T> cmp) { if (N.isNullOrEmpty(a)) { return N.INDEX_NOT_FOUND; } return Arrays.binarySearch(a, key, cmp == null ? Comparators.NATURAL_ORDER : cmp); }
[ "static", "<", "T", ">", "int", "binarySearch", "(", "final", "T", "[", "]", "a", ",", "final", "T", "key", ",", "final", "Comparator", "<", "?", "super", "T", ">", "cmp", ")", "{", "if", "(", "N", ".", "isNullOrEmpty", "(", "a", ")", ")", "{", "return", "N", ".", "INDEX_NOT_FOUND", ";", "}", "return", "Arrays", ".", "binarySearch", "(", "a", ",", "key", ",", "cmp", "==", "null", "?", "Comparators", ".", "NATURAL_ORDER", ":", "cmp", ")", ";", "}" ]
{@link Arrays#binarySearch(Object[], Object, Comparator)} @param a @param key @param cmp @return
[ "{", "@link", "Arrays#binarySearch", "(", "Object", "[]", "Object", "Comparator", ")", "}" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Array.java#L3525-L3531
googleapis/google-http-java-client
google-http-client/src/main/java/com/google/api/client/util/FieldInfo.java
FieldInfo.setFieldValue
public static void setFieldValue(Field field, Object obj, Object value) { """ Sets the given field in the given object to the given value using reflection. <p>If the field is final, it checks that the value being set is identical to the existing value. """ if (Modifier.isFinal(field.getModifiers())) { Object finalValue = getFieldValue(field, obj); if (value == null ? finalValue != null : !value.equals(finalValue)) { throw new IllegalArgumentException( "expected final value <" + finalValue + "> but was <" + value + "> on " + field.getName() + " field in " + obj.getClass().getName()); } } else { try { field.set(obj, value); } catch (SecurityException e) { throw new IllegalArgumentException(e); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } } }
java
public static void setFieldValue(Field field, Object obj, Object value) { if (Modifier.isFinal(field.getModifiers())) { Object finalValue = getFieldValue(field, obj); if (value == null ? finalValue != null : !value.equals(finalValue)) { throw new IllegalArgumentException( "expected final value <" + finalValue + "> but was <" + value + "> on " + field.getName() + " field in " + obj.getClass().getName()); } } else { try { field.set(obj, value); } catch (SecurityException e) { throw new IllegalArgumentException(e); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } } }
[ "public", "static", "void", "setFieldValue", "(", "Field", "field", ",", "Object", "obj", ",", "Object", "value", ")", "{", "if", "(", "Modifier", ".", "isFinal", "(", "field", ".", "getModifiers", "(", ")", ")", ")", "{", "Object", "finalValue", "=", "getFieldValue", "(", "field", ",", "obj", ")", ";", "if", "(", "value", "==", "null", "?", "finalValue", "!=", "null", ":", "!", "value", ".", "equals", "(", "finalValue", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"expected final value <\"", "+", "finalValue", "+", "\"> but was <\"", "+", "value", "+", "\"> on \"", "+", "field", ".", "getName", "(", ")", "+", "\" field in \"", "+", "obj", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "}", "else", "{", "try", "{", "field", ".", "set", "(", "obj", ",", "value", ")", ";", "}", "catch", "(", "SecurityException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "e", ")", ";", "}", "}", "}" ]
Sets the given field in the given object to the given value using reflection. <p>If the field is final, it checks that the value being set is identical to the existing value.
[ "Sets", "the", "given", "field", "in", "the", "given", "object", "to", "the", "given", "value", "using", "reflection", "." ]
train
https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/util/FieldInfo.java#L260-L283
jenkinsci/jenkins
core/src/main/java/hudson/Util.java
Util.deleteContentsRecursive
@Restricted(NoExternalUse.class) public static void deleteContentsRecursive(@Nonnull Path path, @Nonnull PathRemover.PathChecker pathChecker) throws IOException { """ Deletes the given directory contents (but not the directory itself) recursively using a PathChecker. @param path a directory to delete @param pathChecker a security check to validate a path before deleting @throws IOException if the operation fails """ newPathRemover(pathChecker).forceRemoveDirectoryContents(path); }
java
@Restricted(NoExternalUse.class) public static void deleteContentsRecursive(@Nonnull Path path, @Nonnull PathRemover.PathChecker pathChecker) throws IOException { newPathRemover(pathChecker).forceRemoveDirectoryContents(path); }
[ "@", "Restricted", "(", "NoExternalUse", ".", "class", ")", "public", "static", "void", "deleteContentsRecursive", "(", "@", "Nonnull", "Path", "path", ",", "@", "Nonnull", "PathRemover", ".", "PathChecker", "pathChecker", ")", "throws", "IOException", "{", "newPathRemover", "(", "pathChecker", ")", ".", "forceRemoveDirectoryContents", "(", "path", ")", ";", "}" ]
Deletes the given directory contents (but not the directory itself) recursively using a PathChecker. @param path a directory to delete @param pathChecker a security check to validate a path before deleting @throws IOException if the operation fails
[ "Deletes", "the", "given", "directory", "contents", "(", "but", "not", "the", "directory", "itself", ")", "recursively", "using", "a", "PathChecker", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Util.java#L257-L260
kiegroup/jbpm
jbpm-runtime-manager/src/main/java/org/jbpm/runtime/manager/impl/RuntimeEnvironmentBuilder.java
RuntimeEnvironmentBuilder.getDefault
public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version) { """ Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on: <ul> <li>DefaultRuntimeEnvironment</li> </ul> This one is tailored to works smoothly with kjars as the notion of kbase and ksessions @param groupId group id of kjar @param artifactId artifact id of kjar @param version version number of kjar @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults @see DefaultRuntimeEnvironment """ return getDefault(groupId, artifactId, version, null, null); }
java
public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version) { return getDefault(groupId, artifactId, version, null, null); }
[ "public", "static", "RuntimeEnvironmentBuilder", "getDefault", "(", "String", "groupId", ",", "String", "artifactId", ",", "String", "version", ")", "{", "return", "getDefault", "(", "groupId", ",", "artifactId", ",", "version", ",", "null", ",", "null", ")", ";", "}" ]
Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on: <ul> <li>DefaultRuntimeEnvironment</li> </ul> This one is tailored to works smoothly with kjars as the notion of kbase and ksessions @param groupId group id of kjar @param artifactId artifact id of kjar @param version version number of kjar @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults @see DefaultRuntimeEnvironment
[ "Provides", "default", "configuration", "of", "<code", ">", "RuntimeEnvironmentBuilder<", "/", "code", ">", "that", "is", "based", "on", ":", "<ul", ">", "<li", ">", "DefaultRuntimeEnvironment<", "/", "li", ">", "<", "/", "ul", ">", "This", "one", "is", "tailored", "to", "works", "smoothly", "with", "kjars", "as", "the", "notion", "of", "kbase", "and", "ksessions", "@param", "groupId", "group", "id", "of", "kjar", "@param", "artifactId", "artifact", "id", "of", "kjar", "@param", "version", "version", "number", "of", "kjar", "@return", "new", "instance", "of", "<code", ">", "RuntimeEnvironmentBuilder<", "/", "code", ">", "that", "is", "already", "preconfigured", "with", "defaults" ]
train
https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-runtime-manager/src/main/java/org/jbpm/runtime/manager/impl/RuntimeEnvironmentBuilder.java#L144-L146
Omertron/api-thetvdb
src/main/java/com/omertron/thetvdbapi/TheTVDBApi.java
TheTVDBApi.getTVEpisode
private Episode getTVEpisode(String seriesId, int seasonNbr, int episodeNbr, String language, String episodeType) throws TvDbException { """ Generic function to get either the standard TV episode list or the DVD list @param seriesId @param seasonNbr @param episodeNbr @param language @param episodeType @return @throws com.omertron.thetvdbapi.TvDbException """ if (!isValidNumber(seriesId) || !isValidNumber(seasonNbr) || !isValidNumber(episodeNbr)) { // Invalid number passed return new Episode(); } StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(BASE_URL) .append(apiKey) .append(SERIES_URL) .append(seriesId) .append(episodeType) .append(seasonNbr) .append("/") .append(episodeNbr) .append("/"); if (StringUtils.isNotBlank(language)) { urlBuilder.append(language).append(XML_EXTENSION); } LOG.trace(URL, urlBuilder.toString()); return TvdbParser.getEpisode(urlBuilder.toString()); }
java
private Episode getTVEpisode(String seriesId, int seasonNbr, int episodeNbr, String language, String episodeType) throws TvDbException { if (!isValidNumber(seriesId) || !isValidNumber(seasonNbr) || !isValidNumber(episodeNbr)) { // Invalid number passed return new Episode(); } StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(BASE_URL) .append(apiKey) .append(SERIES_URL) .append(seriesId) .append(episodeType) .append(seasonNbr) .append("/") .append(episodeNbr) .append("/"); if (StringUtils.isNotBlank(language)) { urlBuilder.append(language).append(XML_EXTENSION); } LOG.trace(URL, urlBuilder.toString()); return TvdbParser.getEpisode(urlBuilder.toString()); }
[ "private", "Episode", "getTVEpisode", "(", "String", "seriesId", ",", "int", "seasonNbr", ",", "int", "episodeNbr", ",", "String", "language", ",", "String", "episodeType", ")", "throws", "TvDbException", "{", "if", "(", "!", "isValidNumber", "(", "seriesId", ")", "||", "!", "isValidNumber", "(", "seasonNbr", ")", "||", "!", "isValidNumber", "(", "episodeNbr", ")", ")", "{", "// Invalid number passed", "return", "new", "Episode", "(", ")", ";", "}", "StringBuilder", "urlBuilder", "=", "new", "StringBuilder", "(", ")", ";", "urlBuilder", ".", "append", "(", "BASE_URL", ")", ".", "append", "(", "apiKey", ")", ".", "append", "(", "SERIES_URL", ")", ".", "append", "(", "seriesId", ")", ".", "append", "(", "episodeType", ")", ".", "append", "(", "seasonNbr", ")", ".", "append", "(", "\"/\"", ")", ".", "append", "(", "episodeNbr", ")", ".", "append", "(", "\"/\"", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "language", ")", ")", "{", "urlBuilder", ".", "append", "(", "language", ")", ".", "append", "(", "XML_EXTENSION", ")", ";", "}", "LOG", ".", "trace", "(", "URL", ",", "urlBuilder", ".", "toString", "(", ")", ")", ";", "return", "TvdbParser", ".", "getEpisode", "(", "urlBuilder", ".", "toString", "(", ")", ")", ";", "}" ]
Generic function to get either the standard TV episode list or the DVD list @param seriesId @param seasonNbr @param episodeNbr @param language @param episodeType @return @throws com.omertron.thetvdbapi.TvDbException
[ "Generic", "function", "to", "get", "either", "the", "standard", "TV", "episode", "list", "or", "the", "DVD", "list" ]
train
https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/TheTVDBApi.java#L209-L231
sporniket/core
sporniket-core-strings/src/main/java/com/sporniket/strings/QuickDiff.java
QuickDiff.getTextLine
private String getTextLine(String[] textLines, int line) { """ Return the specified line from the text. @param textLines The source text as an array of lines. @param line The line to return. @return the line as is, or trimed, according to {@link #isIgnoreTrailingWhiteSpaces()}. """ return (isIgnoreTrailingWhiteSpaces()) ? textLines[line].trim() : textLines[line]; }
java
private String getTextLine(String[] textLines, int line) { return (isIgnoreTrailingWhiteSpaces()) ? textLines[line].trim() : textLines[line]; }
[ "private", "String", "getTextLine", "(", "String", "[", "]", "textLines", ",", "int", "line", ")", "{", "return", "(", "isIgnoreTrailingWhiteSpaces", "(", ")", ")", "?", "textLines", "[", "line", "]", ".", "trim", "(", ")", ":", "textLines", "[", "line", "]", ";", "}" ]
Return the specified line from the text. @param textLines The source text as an array of lines. @param line The line to return. @return the line as is, or trimed, according to {@link #isIgnoreTrailingWhiteSpaces()}.
[ "Return", "the", "specified", "line", "from", "the", "text", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-strings/src/main/java/com/sporniket/strings/QuickDiff.java#L324-L327
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java
SecureDfuImpl.writeExecute
private void writeExecute() throws DfuException, DeviceDisconnectedException, UploadAbortedException, UnknownResponseException, RemoteDfuException { """ Sends the Execute operation code and awaits for a return notification containing status code. The Execute command will confirm the last chunk of data or the last command that was sent. Creating the same object again, instead of executing it allows to retransmitting it in case of a CRC error. @throws DfuException @throws DeviceDisconnectedException @throws UploadAbortedException @throws UnknownResponseException @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}. """ if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Executing object failed", status); }
java
private void writeExecute() throws DfuException, DeviceDisconnectedException, UploadAbortedException, UnknownResponseException, RemoteDfuException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Executing object failed", status); }
[ "private", "void", "writeExecute", "(", ")", "throws", "DfuException", ",", "DeviceDisconnectedException", ",", "UploadAbortedException", ",", "UnknownResponseException", ",", "RemoteDfuException", "{", "if", "(", "!", "mConnected", ")", "throw", "new", "DeviceDisconnectedException", "(", "\"Unable to read Checksum: device disconnected\"", ")", ";", "writeOpCode", "(", "mControlPointCharacteristic", ",", "OP_CODE_EXECUTE", ")", ";", "final", "byte", "[", "]", "response", "=", "readNotificationResponse", "(", ")", ";", "final", "int", "status", "=", "getStatusCode", "(", "response", ",", "OP_CODE_EXECUTE_KEY", ")", ";", "if", "(", "status", "==", "SecureDfuError", ".", "EXTENDED_ERROR", ")", "throw", "new", "RemoteDfuExtendedErrorException", "(", "\"Executing object failed\"", ",", "response", "[", "3", "]", ")", ";", "if", "(", "status", "!=", "DFU_STATUS_SUCCESS", ")", "throw", "new", "RemoteDfuException", "(", "\"Executing object failed\"", ",", "status", ")", ";", "}" ]
Sends the Execute operation code and awaits for a return notification containing status code. The Execute command will confirm the last chunk of data or the last command that was sent. Creating the same object again, instead of executing it allows to retransmitting it in case of a CRC error. @throws DfuException @throws DeviceDisconnectedException @throws UploadAbortedException @throws UnknownResponseException @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}.
[ "Sends", "the", "Execute", "operation", "code", "and", "awaits", "for", "a", "return", "notification", "containing", "status", "code", ".", "The", "Execute", "command", "will", "confirm", "the", "last", "chunk", "of", "data", "or", "the", "last", "command", "that", "was", "sent", ".", "Creating", "the", "same", "object", "again", "instead", "of", "executing", "it", "allows", "to", "retransmitting", "it", "in", "case", "of", "a", "CRC", "error", "." ]
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/SecureDfuImpl.java#L903-L916
liyiorg/weixin-popular
src/main/java/weixin/popular/util/MapUtil.java
MapUtil.mapJoin
public static String mapJoin(Map<String, String> map,boolean keyLower,boolean valueUrlencode) { """ url 参数串连 @param map map @param keyLower keyLower @param valueUrlencode valueUrlencode @return string """ StringBuilder stringBuilder = new StringBuilder(); for(String key :map.keySet()){ if(map.get(key)!=null&&!"".equals(map.get(key))){ try { String temp = (key.endsWith("_")&&key.length()>1)?key.substring(0,key.length()-1):key; stringBuilder.append(keyLower?temp.toLowerCase():temp) .append("=") .append(valueUrlencode?URLEncoder.encode(map.get(key),"utf-8").replace("+", "%20"):map.get(key)) .append("&"); } catch (UnsupportedEncodingException e) { logger.error("", e); } } } if(stringBuilder.length()>0){ stringBuilder.deleteCharAt(stringBuilder.length()-1); } return stringBuilder.toString(); }
java
public static String mapJoin(Map<String, String> map,boolean keyLower,boolean valueUrlencode){ StringBuilder stringBuilder = new StringBuilder(); for(String key :map.keySet()){ if(map.get(key)!=null&&!"".equals(map.get(key))){ try { String temp = (key.endsWith("_")&&key.length()>1)?key.substring(0,key.length()-1):key; stringBuilder.append(keyLower?temp.toLowerCase():temp) .append("=") .append(valueUrlencode?URLEncoder.encode(map.get(key),"utf-8").replace("+", "%20"):map.get(key)) .append("&"); } catch (UnsupportedEncodingException e) { logger.error("", e); } } } if(stringBuilder.length()>0){ stringBuilder.deleteCharAt(stringBuilder.length()-1); } return stringBuilder.toString(); }
[ "public", "static", "String", "mapJoin", "(", "Map", "<", "String", ",", "String", ">", "map", ",", "boolean", "keyLower", ",", "boolean", "valueUrlencode", ")", "{", "StringBuilder", "stringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "key", ":", "map", ".", "keySet", "(", ")", ")", "{", "if", "(", "map", ".", "get", "(", "key", ")", "!=", "null", "&&", "!", "\"\"", ".", "equals", "(", "map", ".", "get", "(", "key", ")", ")", ")", "{", "try", "{", "String", "temp", "=", "(", "key", ".", "endsWith", "(", "\"_\"", ")", "&&", "key", ".", "length", "(", ")", ">", "1", ")", "?", "key", ".", "substring", "(", "0", ",", "key", ".", "length", "(", ")", "-", "1", ")", ":", "key", ";", "stringBuilder", ".", "append", "(", "keyLower", "?", "temp", ".", "toLowerCase", "(", ")", ":", "temp", ")", ".", "append", "(", "\"=\"", ")", ".", "append", "(", "valueUrlencode", "?", "URLEncoder", ".", "encode", "(", "map", ".", "get", "(", "key", ")", ",", "\"utf-8\"", ")", ".", "replace", "(", "\"+\"", ",", "\"%20\"", ")", ":", "map", ".", "get", "(", "key", ")", ")", ".", "append", "(", "\"&\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "logger", ".", "error", "(", "\"\"", ",", "e", ")", ";", "}", "}", "}", "if", "(", "stringBuilder", ".", "length", "(", ")", ">", "0", ")", "{", "stringBuilder", ".", "deleteCharAt", "(", "stringBuilder", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "stringBuilder", ".", "toString", "(", ")", ";", "}" ]
url 参数串连 @param map map @param keyLower keyLower @param valueUrlencode valueUrlencode @return string
[ "url", "参数串连" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/MapUtil.java#L90-L109
meertensinstituut/mtas
src/main/java/mtas/codec/util/CodecInfo.java
CodecInfo.getObjectById
public MtasToken getObjectById(String field, int docId, int mtasId) throws IOException { """ Gets the object by id. @param field the field @param docId the doc id @param mtasId the mtas id @return the object by id @throws IOException Signals that an I/O exception has occurred. """ try { Long ref; Long objectRefApproxCorrection; IndexDoc doc = getDoc(field, docId); IndexInput inObjectId = indexInputList.get("indexObjectId"); IndexInput inObject = indexInputList.get("object"); IndexInput inTerm = indexInputList.get("term"); if (doc.storageFlags == MtasCodecPostingsFormat.MTAS_STORAGE_BYTE) { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 1L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readByte()); } else if (doc.storageFlags == MtasCodecPostingsFormat.MTAS_STORAGE_SHORT) { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 2L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readShort()); } else if (doc.storageFlags == MtasCodecPostingsFormat.MTAS_STORAGE_INTEGER) { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 4L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readInt()); } else { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 8L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readLong()); } ref = objectRefApproxCorrection + doc.objectRefApproxOffset + (mtasId * (long) doc.objectRefApproxQuotient); return MtasCodecPostingsFormat.getToken(inObject, inTerm, ref); } catch (Exception e) { throw new IOException(e); } }
java
public MtasToken getObjectById(String field, int docId, int mtasId) throws IOException { try { Long ref; Long objectRefApproxCorrection; IndexDoc doc = getDoc(field, docId); IndexInput inObjectId = indexInputList.get("indexObjectId"); IndexInput inObject = indexInputList.get("object"); IndexInput inTerm = indexInputList.get("term"); if (doc.storageFlags == MtasCodecPostingsFormat.MTAS_STORAGE_BYTE) { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 1L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readByte()); } else if (doc.storageFlags == MtasCodecPostingsFormat.MTAS_STORAGE_SHORT) { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 2L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readShort()); } else if (doc.storageFlags == MtasCodecPostingsFormat.MTAS_STORAGE_INTEGER) { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 4L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readInt()); } else { inObjectId.seek(doc.fpIndexObjectId + (mtasId * 8L)); objectRefApproxCorrection = Long.valueOf(inObjectId.readLong()); } ref = objectRefApproxCorrection + doc.objectRefApproxOffset + (mtasId * (long) doc.objectRefApproxQuotient); return MtasCodecPostingsFormat.getToken(inObject, inTerm, ref); } catch (Exception e) { throw new IOException(e); } }
[ "public", "MtasToken", "getObjectById", "(", "String", "field", ",", "int", "docId", ",", "int", "mtasId", ")", "throws", "IOException", "{", "try", "{", "Long", "ref", ";", "Long", "objectRefApproxCorrection", ";", "IndexDoc", "doc", "=", "getDoc", "(", "field", ",", "docId", ")", ";", "IndexInput", "inObjectId", "=", "indexInputList", ".", "get", "(", "\"indexObjectId\"", ")", ";", "IndexInput", "inObject", "=", "indexInputList", ".", "get", "(", "\"object\"", ")", ";", "IndexInput", "inTerm", "=", "indexInputList", ".", "get", "(", "\"term\"", ")", ";", "if", "(", "doc", ".", "storageFlags", "==", "MtasCodecPostingsFormat", ".", "MTAS_STORAGE_BYTE", ")", "{", "inObjectId", ".", "seek", "(", "doc", ".", "fpIndexObjectId", "+", "(", "mtasId", "*", "1L", ")", ")", ";", "objectRefApproxCorrection", "=", "Long", ".", "valueOf", "(", "inObjectId", ".", "readByte", "(", ")", ")", ";", "}", "else", "if", "(", "doc", ".", "storageFlags", "==", "MtasCodecPostingsFormat", ".", "MTAS_STORAGE_SHORT", ")", "{", "inObjectId", ".", "seek", "(", "doc", ".", "fpIndexObjectId", "+", "(", "mtasId", "*", "2L", ")", ")", ";", "objectRefApproxCorrection", "=", "Long", ".", "valueOf", "(", "inObjectId", ".", "readShort", "(", ")", ")", ";", "}", "else", "if", "(", "doc", ".", "storageFlags", "==", "MtasCodecPostingsFormat", ".", "MTAS_STORAGE_INTEGER", ")", "{", "inObjectId", ".", "seek", "(", "doc", ".", "fpIndexObjectId", "+", "(", "mtasId", "*", "4L", ")", ")", ";", "objectRefApproxCorrection", "=", "Long", ".", "valueOf", "(", "inObjectId", ".", "readInt", "(", ")", ")", ";", "}", "else", "{", "inObjectId", ".", "seek", "(", "doc", ".", "fpIndexObjectId", "+", "(", "mtasId", "*", "8L", ")", ")", ";", "objectRefApproxCorrection", "=", "Long", ".", "valueOf", "(", "inObjectId", ".", "readLong", "(", ")", ")", ";", "}", "ref", "=", "objectRefApproxCorrection", "+", "doc", ".", "objectRefApproxOffset", "+", "(", "mtasId", "*", "(", "long", ")", "doc", ".", "objectRefApproxQuotient", ")", ";", "return", "MtasCodecPostingsFormat", ".", "getToken", "(", "inObject", ",", "inTerm", ",", "ref", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IOException", "(", "e", ")", ";", "}", "}" ]
Gets the object by id. @param field the field @param docId the doc id @param mtasId the mtas id @return the object by id @throws IOException Signals that an I/O exception has occurred.
[ "Gets", "the", "object", "by", "id", "." ]
train
https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/codec/util/CodecInfo.java#L155-L183
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/util/AbstractFileLookup.java
AbstractFileLookup.lookupFileStrict
@Override public InputStream lookupFileStrict(String filename, ClassLoader cl) throws FileNotFoundException { """ Looks up the file, see : {@link DefaultFileLookup}. @param filename might be the name of the file (too look it up in the class path) or an url to a file. @return an input stream to the file or null if nothing found through all lookup steps. @throws FileNotFoundException if file cannot be found """ InputStream is = filename == null || filename.length() == 0 ? null : getAsInputStreamFromClassLoader(filename, cl); if (is == null) { if (log.isDebugEnabled()) log.debugf("Unable to find file %s in classpath; searching for this file on the filesystem instead.", filename); return new FileInputStream(filename); } return is; }
java
@Override public InputStream lookupFileStrict(String filename, ClassLoader cl) throws FileNotFoundException { InputStream is = filename == null || filename.length() == 0 ? null : getAsInputStreamFromClassLoader(filename, cl); if (is == null) { if (log.isDebugEnabled()) log.debugf("Unable to find file %s in classpath; searching for this file on the filesystem instead.", filename); return new FileInputStream(filename); } return is; }
[ "@", "Override", "public", "InputStream", "lookupFileStrict", "(", "String", "filename", ",", "ClassLoader", "cl", ")", "throws", "FileNotFoundException", "{", "InputStream", "is", "=", "filename", "==", "null", "||", "filename", ".", "length", "(", ")", "==", "0", "?", "null", ":", "getAsInputStreamFromClassLoader", "(", "filename", ",", "cl", ")", ";", "if", "(", "is", "==", "null", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debugf", "(", "\"Unable to find file %s in classpath; searching for this file on the filesystem instead.\"", ",", "filename", ")", ";", "return", "new", "FileInputStream", "(", "filename", ")", ";", "}", "return", "is", ";", "}" ]
Looks up the file, see : {@link DefaultFileLookup}. @param filename might be the name of the file (too look it up in the class path) or an url to a file. @return an input stream to the file or null if nothing found through all lookup steps. @throws FileNotFoundException if file cannot be found
[ "Looks", "up", "the", "file", "see", ":", "{", "@link", "DefaultFileLookup", "}", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/util/AbstractFileLookup.java#L50-L59
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.installationTemplate_templateName_partitionScheme_schemeName_partition_mountpoint_DELETE
public void installationTemplate_templateName_partitionScheme_schemeName_partition_mountpoint_DELETE(String templateName, String schemeName, String mountpoint) throws IOException { """ remove this partition REST: DELETE /me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition/{mountpoint} @param templateName [required] This template name @param schemeName [required] name of this partitioning scheme @param mountpoint [required] partition mount point """ String qPath = "/me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition/{mountpoint}"; StringBuilder sb = path(qPath, templateName, schemeName, mountpoint); exec(qPath, "DELETE", sb.toString(), null); }
java
public void installationTemplate_templateName_partitionScheme_schemeName_partition_mountpoint_DELETE(String templateName, String schemeName, String mountpoint) throws IOException { String qPath = "/me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition/{mountpoint}"; StringBuilder sb = path(qPath, templateName, schemeName, mountpoint); exec(qPath, "DELETE", sb.toString(), null); }
[ "public", "void", "installationTemplate_templateName_partitionScheme_schemeName_partition_mountpoint_DELETE", "(", "String", "templateName", ",", "String", "schemeName", ",", "String", "mountpoint", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition/{mountpoint}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "templateName", ",", "schemeName", ",", "mountpoint", ")", ";", "exec", "(", "qPath", ",", "\"DELETE\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "}" ]
remove this partition REST: DELETE /me/installationTemplate/{templateName}/partitionScheme/{schemeName}/partition/{mountpoint} @param templateName [required] This template name @param schemeName [required] name of this partitioning scheme @param mountpoint [required] partition mount point
[ "remove", "this", "partition" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L3701-L3705
cesarferreira/AndroidQuickUtils
library/src/main/java/quickutils/core/views/image/CompassImageView.java
CompassImageView.setPhysical
public void setPhysical(float inertiaMoment, float alpha, float mB) { """ Use this to set physical properties. Negative values will be replaced by default values @param inertiaMoment Moment of inertia (default 0.1) @param alpha Damping coefficient (default 10) @param mB Magnetic field coefficient (default 1000) """ this.inertiaMoment = inertiaMoment >= 0 ? inertiaMoment : this.INERTIA_MOMENT_DEFAULT; this.alpha = alpha >= 0 ? alpha : ALPHA_DEFAULT; this.mB = mB >= 0 ? mB : MB_DEFAULT; }
java
public void setPhysical(float inertiaMoment, float alpha, float mB) { this.inertiaMoment = inertiaMoment >= 0 ? inertiaMoment : this.INERTIA_MOMENT_DEFAULT; this.alpha = alpha >= 0 ? alpha : ALPHA_DEFAULT; this.mB = mB >= 0 ? mB : MB_DEFAULT; }
[ "public", "void", "setPhysical", "(", "float", "inertiaMoment", ",", "float", "alpha", ",", "float", "mB", ")", "{", "this", ".", "inertiaMoment", "=", "inertiaMoment", ">=", "0", "?", "inertiaMoment", ":", "this", ".", "INERTIA_MOMENT_DEFAULT", ";", "this", ".", "alpha", "=", "alpha", ">=", "0", "?", "alpha", ":", "ALPHA_DEFAULT", ";", "this", ".", "mB", "=", "mB", ">=", "0", "?", "mB", ":", "MB_DEFAULT", ";", "}" ]
Use this to set physical properties. Negative values will be replaced by default values @param inertiaMoment Moment of inertia (default 0.1) @param alpha Damping coefficient (default 10) @param mB Magnetic field coefficient (default 1000)
[ "Use", "this", "to", "set", "physical", "properties", ".", "Negative", "values", "will", "be", "replaced", "by", "default", "values" ]
train
https://github.com/cesarferreira/AndroidQuickUtils/blob/73a91daedbb9f7be7986ea786fbc441c9e5a881c/library/src/main/java/quickutils/core/views/image/CompassImageView.java#L105-L109
briandilley/jsonrpc4j
src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java
ProxyUtil.createClientProxy
@SuppressWarnings("unchecked") private static <T> T createClientProxy(ClassLoader classLoader, Class<T> proxyInterface, final IJsonRpcClient client, final Map<String, String> extraHeaders) { """ Creates a {@link Proxy} of the given {@code proxyInterface} that uses the given {@link IJsonRpcClient}. @param <T> the proxy type @param classLoader the {@link ClassLoader} @param proxyInterface the interface to proxy @param client the {@link JsonRpcHttpClient} @param extraHeaders extra HTTP headers to be added to each response @return the proxied interface """ return (T) Proxy.newProxyInstance(classLoader, new Class<?>[]{proxyInterface}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (isDeclaringClassAnObject(method)) return proxyObjectMethods(method, proxy, args); final Object arguments = ReflectionUtil.parseArguments(method, args); final String methodName = getMethodName(method); return client.invoke(methodName, arguments, method.getGenericReturnType(), extraHeaders); } }); }
java
@SuppressWarnings("unchecked") private static <T> T createClientProxy(ClassLoader classLoader, Class<T> proxyInterface, final IJsonRpcClient client, final Map<String, String> extraHeaders) { return (T) Proxy.newProxyInstance(classLoader, new Class<?>[]{proxyInterface}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (isDeclaringClassAnObject(method)) return proxyObjectMethods(method, proxy, args); final Object arguments = ReflectionUtil.parseArguments(method, args); final String methodName = getMethodName(method); return client.invoke(methodName, arguments, method.getGenericReturnType(), extraHeaders); } }); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "<", "T", ">", "T", "createClientProxy", "(", "ClassLoader", "classLoader", ",", "Class", "<", "T", ">", "proxyInterface", ",", "final", "IJsonRpcClient", "client", ",", "final", "Map", "<", "String", ",", "String", ">", "extraHeaders", ")", "{", "return", "(", "T", ")", "Proxy", ".", "newProxyInstance", "(", "classLoader", ",", "new", "Class", "<", "?", ">", "[", "]", "{", "proxyInterface", "}", ",", "new", "InvocationHandler", "(", ")", "{", "@", "Override", "public", "Object", "invoke", "(", "Object", "proxy", ",", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "if", "(", "isDeclaringClassAnObject", "(", "method", ")", ")", "return", "proxyObjectMethods", "(", "method", ",", "proxy", ",", "args", ")", ";", "final", "Object", "arguments", "=", "ReflectionUtil", ".", "parseArguments", "(", "method", ",", "args", ")", ";", "final", "String", "methodName", "=", "getMethodName", "(", "method", ")", ";", "return", "client", ".", "invoke", "(", "methodName", ",", "arguments", ",", "method", ".", "getGenericReturnType", "(", ")", ",", "extraHeaders", ")", ";", "}", "}", ")", ";", "}" ]
Creates a {@link Proxy} of the given {@code proxyInterface} that uses the given {@link IJsonRpcClient}. @param <T> the proxy type @param classLoader the {@link ClassLoader} @param proxyInterface the interface to proxy @param client the {@link JsonRpcHttpClient} @param extraHeaders extra HTTP headers to be added to each response @return the proxied interface
[ "Creates", "a", "{", "@link", "Proxy", "}", "of", "the", "given", "{", "@code", "proxyInterface", "}", "that", "uses", "the", "given", "{", "@link", "IJsonRpcClient", "}", "." ]
train
https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/ProxyUtil.java#L203-L216
SeaCloudsEU/SeaCloudsPlatform
discoverer/src/main/java/eu/seaclouds/platform/discoverer/crawler/CloudHarmonySPECint.java
CloudHarmonySPECint.getSPECint
public static Integer getSPECint(String providerName, String instanceType) { """ Gets the SPECint of the specified instance of the specified offerings provider @param providerName the name of the offerings provider @param instanceType istance type as specified in the CloudHarmony API @return SPECint of the specified instance """ String key = providerName + "." + instanceType; return SPECint.get(key); }
java
public static Integer getSPECint(String providerName, String instanceType) { String key = providerName + "." + instanceType; return SPECint.get(key); }
[ "public", "static", "Integer", "getSPECint", "(", "String", "providerName", ",", "String", "instanceType", ")", "{", "String", "key", "=", "providerName", "+", "\".\"", "+", "instanceType", ";", "return", "SPECint", ".", "get", "(", "key", ")", ";", "}" ]
Gets the SPECint of the specified instance of the specified offerings provider @param providerName the name of the offerings provider @param instanceType istance type as specified in the CloudHarmony API @return SPECint of the specified instance
[ "Gets", "the", "SPECint", "of", "the", "specified", "instance", "of", "the", "specified", "offerings", "provider" ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/discoverer/src/main/java/eu/seaclouds/platform/discoverer/crawler/CloudHarmonySPECint.java#L79-L82
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.readPropertyObject
public CmsProperty readPropertyObject(CmsRequestContext context, CmsResource resource, String key, boolean search) throws CmsException { """ Reads a property object from a resource specified by a property name.<p> Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> @param context the context of the current request @param resource the resource where the property is mapped to @param key the property key name @param search if <code>true</code>, the property is searched on all parent folders of the resource. if it's not found attached directly to the resource. @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found @throws CmsException if something goes wrong """ return readPropertyObject(context, resource, key, search, null); }
java
public CmsProperty readPropertyObject(CmsRequestContext context, CmsResource resource, String key, boolean search) throws CmsException { return readPropertyObject(context, resource, key, search, null); }
[ "public", "CmsProperty", "readPropertyObject", "(", "CmsRequestContext", "context", ",", "CmsResource", "resource", ",", "String", "key", ",", "boolean", "search", ")", "throws", "CmsException", "{", "return", "readPropertyObject", "(", "context", ",", "resource", ",", "key", ",", "search", ",", "null", ")", ";", "}" ]
Reads a property object from a resource specified by a property name.<p> Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> @param context the context of the current request @param resource the resource where the property is mapped to @param key the property key name @param search if <code>true</code>, the property is searched on all parent folders of the resource. if it's not found attached directly to the resource. @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found @throws CmsException if something goes wrong
[ "Reads", "a", "property", "object", "from", "a", "resource", "specified", "by", "a", "property", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L4835-L4839
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java
VmlGraphicsContext.unhide
public void unhide(Object group, String name) { """ Show the specified element in the specified group. If the element does not exist, nothing will happen. @param group The group object. @param name The element name. """ if (isAttached()) { Element element = helper.getElement(group, name); if (element != null) { Dom.setStyleAttribute(element, "visibility", "inherit"); } } }
java
public void unhide(Object group, String name) { if (isAttached()) { Element element = helper.getElement(group, name); if (element != null) { Dom.setStyleAttribute(element, "visibility", "inherit"); } } }
[ "public", "void", "unhide", "(", "Object", "group", ",", "String", "name", ")", "{", "if", "(", "isAttached", "(", ")", ")", "{", "Element", "element", "=", "helper", ".", "getElement", "(", "group", ",", "name", ")", ";", "if", "(", "element", "!=", "null", ")", "{", "Dom", ".", "setStyleAttribute", "(", "element", ",", "\"visibility\"", ",", "\"inherit\"", ")", ";", "}", "}", "}" ]
Show the specified element in the specified group. If the element does not exist, nothing will happen. @param group The group object. @param name The element name.
[ "Show", "the", "specified", "element", "in", "the", "specified", "group", ".", "If", "the", "element", "does", "not", "exist", "nothing", "will", "happen", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/VmlGraphicsContext.java#L699-L706
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ObjectUtils.java
ObjectUtils.returnValueOrDefaultIfNull
public static <T> T returnValueOrDefaultIfNull(T value, Supplier<T> supplier) { """ Returns the given {@code value} if not {@literal null} or call the given {@link Supplier} to supply a value. @param <T> {@link Class} type of the {@code value}. @param value {@link Object} to evaluate for {@literal null}. @param supplier {@link Supplier} used to supply a value if {@code value} is {@literal null}. @return the given {@code value} if not {@literal null} or call the given {@link Supplier} to supply a value. @see java.util.function.Supplier """ return Optional.ofNullable(value).orElseGet(supplier); }
java
public static <T> T returnValueOrDefaultIfNull(T value, Supplier<T> supplier) { return Optional.ofNullable(value).orElseGet(supplier); }
[ "public", "static", "<", "T", ">", "T", "returnValueOrDefaultIfNull", "(", "T", "value", ",", "Supplier", "<", "T", ">", "supplier", ")", "{", "return", "Optional", ".", "ofNullable", "(", "value", ")", ".", "orElseGet", "(", "supplier", ")", ";", "}" ]
Returns the given {@code value} if not {@literal null} or call the given {@link Supplier} to supply a value. @param <T> {@link Class} type of the {@code value}. @param value {@link Object} to evaluate for {@literal null}. @param supplier {@link Supplier} used to supply a value if {@code value} is {@literal null}. @return the given {@code value} if not {@literal null} or call the given {@link Supplier} to supply a value. @see java.util.function.Supplier
[ "Returns", "the", "given", "{", "@code", "value", "}", "if", "not", "{", "@literal", "null", "}", "or", "call", "the", "given", "{", "@link", "Supplier", "}", "to", "supply", "a", "value", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ObjectUtils.java#L203-L205
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/core/PeerGroup.java
PeerGroup.setUserAgent
public void setUserAgent(String name, String version, @Nullable String comments) { """ Sets information that identifies this software to remote nodes. This is a convenience wrapper for creating a new {@link VersionMessage}, calling {@link VersionMessage#appendToSubVer(String, String, String)} on it, and then calling {@link PeerGroup#setVersionMessage(VersionMessage)} on the result of that. See the docs for {@link VersionMessage#appendToSubVer(String, String, String)} for information on what the fields should contain. """ //TODO Check that height is needed here (it wasnt, but it should be, no?) int height = chain == null ? 0 : chain.getBestChainHeight(); VersionMessage ver = new VersionMessage(params, height); ver.relayTxesBeforeFilter = false; updateVersionMessageRelayTxesBeforeFilter(ver); ver.appendToSubVer(name, version, comments); setVersionMessage(ver); }
java
public void setUserAgent(String name, String version, @Nullable String comments) { //TODO Check that height is needed here (it wasnt, but it should be, no?) int height = chain == null ? 0 : chain.getBestChainHeight(); VersionMessage ver = new VersionMessage(params, height); ver.relayTxesBeforeFilter = false; updateVersionMessageRelayTxesBeforeFilter(ver); ver.appendToSubVer(name, version, comments); setVersionMessage(ver); }
[ "public", "void", "setUserAgent", "(", "String", "name", ",", "String", "version", ",", "@", "Nullable", "String", "comments", ")", "{", "//TODO Check that height is needed here (it wasnt, but it should be, no?)", "int", "height", "=", "chain", "==", "null", "?", "0", ":", "chain", ".", "getBestChainHeight", "(", ")", ";", "VersionMessage", "ver", "=", "new", "VersionMessage", "(", "params", ",", "height", ")", ";", "ver", ".", "relayTxesBeforeFilter", "=", "false", ";", "updateVersionMessageRelayTxesBeforeFilter", "(", "ver", ")", ";", "ver", ".", "appendToSubVer", "(", "name", ",", "version", ",", "comments", ")", ";", "setVersionMessage", "(", "ver", ")", ";", "}" ]
Sets information that identifies this software to remote nodes. This is a convenience wrapper for creating a new {@link VersionMessage}, calling {@link VersionMessage#appendToSubVer(String, String, String)} on it, and then calling {@link PeerGroup#setVersionMessage(VersionMessage)} on the result of that. See the docs for {@link VersionMessage#appendToSubVer(String, String, String)} for information on what the fields should contain.
[ "Sets", "information", "that", "identifies", "this", "software", "to", "remote", "nodes", ".", "This", "is", "a", "convenience", "wrapper", "for", "creating", "a", "new", "{" ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L594-L602
dbflute-session/tomcat-boot
src/main/java/org/dbflute/tomcat/util/BotmReflectionUtil.java
BotmReflectionUtil.getWholeMethodFlexibly
public static Method getWholeMethodFlexibly(Class<?> clazz, String methodName, Class<?>[] argTypes) { """ Get the method in whole methods that means as follows: <pre> o target class's methods = all o superclass's methods = all (also contains private) </pre> And it has the flexibly searching so you can specify types of sub-class to argTypes. <br> But if overload methods exist, it returns the first-found method. <br> And no cache so you should cache it yourself if you call several times. @param clazz The type of class that defines the method. (NotNull) @param methodName The name of method. (NotNull) @param argTypes The type of argument. (NotNull) @return The instance of method. (NullAllowed: if null, not found) """ assertObjectNotNull("clazz", clazz); assertStringNotNullAndNotTrimmedEmpty("methodName", methodName); return findMethod(clazz, methodName, argTypes, VisibilityType.WHOLE, true); }
java
public static Method getWholeMethodFlexibly(Class<?> clazz, String methodName, Class<?>[] argTypes) { assertObjectNotNull("clazz", clazz); assertStringNotNullAndNotTrimmedEmpty("methodName", methodName); return findMethod(clazz, methodName, argTypes, VisibilityType.WHOLE, true); }
[ "public", "static", "Method", "getWholeMethodFlexibly", "(", "Class", "<", "?", ">", "clazz", ",", "String", "methodName", ",", "Class", "<", "?", ">", "[", "]", "argTypes", ")", "{", "assertObjectNotNull", "(", "\"clazz\"", ",", "clazz", ")", ";", "assertStringNotNullAndNotTrimmedEmpty", "(", "\"methodName\"", ",", "methodName", ")", ";", "return", "findMethod", "(", "clazz", ",", "methodName", ",", "argTypes", ",", "VisibilityType", ".", "WHOLE", ",", "true", ")", ";", "}" ]
Get the method in whole methods that means as follows: <pre> o target class's methods = all o superclass's methods = all (also contains private) </pre> And it has the flexibly searching so you can specify types of sub-class to argTypes. <br> But if overload methods exist, it returns the first-found method. <br> And no cache so you should cache it yourself if you call several times. @param clazz The type of class that defines the method. (NotNull) @param methodName The name of method. (NotNull) @param argTypes The type of argument. (NotNull) @return The instance of method. (NullAllowed: if null, not found)
[ "Get", "the", "method", "in", "whole", "methods", "that", "means", "as", "follows", ":", "<pre", ">", "o", "target", "class", "s", "methods", "=", "all", "o", "superclass", "s", "methods", "=", "all", "(", "also", "contains", "private", ")", "<", "/", "pre", ">", "And", "it", "has", "the", "flexibly", "searching", "so", "you", "can", "specify", "types", "of", "sub", "-", "class", "to", "argTypes", ".", "<br", ">", "But", "if", "overload", "methods", "exist", "it", "returns", "the", "first", "-", "found", "method", ".", "<br", ">", "And", "no", "cache", "so", "you", "should", "cache", "it", "yourself", "if", "you", "call", "several", "times", "." ]
train
https://github.com/dbflute-session/tomcat-boot/blob/fe941f88b6be083781873126f5b12d4c16bb9073/src/main/java/org/dbflute/tomcat/util/BotmReflectionUtil.java#L422-L426
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AbstractDoclet.java
AbstractDoclet.startGeneration
private void startGeneration(DocletEnvironment docEnv) throws DocletException { """ Start the generation of files. Call generate methods in the individual writers, which will in turn generate the documentation files. Call the TreeWriter generation first to ensure the Class Hierarchy is built first and then can be used in the later generation. @see jdk.doclet.DocletEnvironment @throws DocletException if there is a problem while generating the documentation """ if (configuration.getIncludedTypeElements().isEmpty()) { messages.error("doclet.No_Public_Classes_To_Document"); return; } if (!configuration.setOptions()) { return; } messages.notice("doclet.build_version", configuration.getDocletSpecificBuildDate()); ClassTree classtree = new ClassTree(configuration, configuration.nodeprecated); generateClassFiles(docEnv, classtree); PackageListWriter.generate(configuration); generatePackageFiles(classtree); generateModuleFiles(); generateOtherFiles(docEnv, classtree); configuration.tagletManager.printReport(); }
java
private void startGeneration(DocletEnvironment docEnv) throws DocletException { if (configuration.getIncludedTypeElements().isEmpty()) { messages.error("doclet.No_Public_Classes_To_Document"); return; } if (!configuration.setOptions()) { return; } messages.notice("doclet.build_version", configuration.getDocletSpecificBuildDate()); ClassTree classtree = new ClassTree(configuration, configuration.nodeprecated); generateClassFiles(docEnv, classtree); PackageListWriter.generate(configuration); generatePackageFiles(classtree); generateModuleFiles(); generateOtherFiles(docEnv, classtree); configuration.tagletManager.printReport(); }
[ "private", "void", "startGeneration", "(", "DocletEnvironment", "docEnv", ")", "throws", "DocletException", "{", "if", "(", "configuration", ".", "getIncludedTypeElements", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "messages", ".", "error", "(", "\"doclet.No_Public_Classes_To_Document\"", ")", ";", "return", ";", "}", "if", "(", "!", "configuration", ".", "setOptions", "(", ")", ")", "{", "return", ";", "}", "messages", ".", "notice", "(", "\"doclet.build_version\"", ",", "configuration", ".", "getDocletSpecificBuildDate", "(", ")", ")", ";", "ClassTree", "classtree", "=", "new", "ClassTree", "(", "configuration", ",", "configuration", ".", "nodeprecated", ")", ";", "generateClassFiles", "(", "docEnv", ",", "classtree", ")", ";", "PackageListWriter", ".", "generate", "(", "configuration", ")", ";", "generatePackageFiles", "(", "classtree", ")", ";", "generateModuleFiles", "(", ")", ";", "generateOtherFiles", "(", "docEnv", ",", "classtree", ")", ";", "configuration", ".", "tagletManager", ".", "printReport", "(", ")", ";", "}" ]
Start the generation of files. Call generate methods in the individual writers, which will in turn generate the documentation files. Call the TreeWriter generation first to ensure the Class Hierarchy is built first and then can be used in the later generation. @see jdk.doclet.DocletEnvironment @throws DocletException if there is a problem while generating the documentation
[ "Start", "the", "generation", "of", "files", ".", "Call", "generate", "methods", "in", "the", "individual", "writers", "which", "will", "in", "turn", "generate", "the", "documentation", "files", ".", "Call", "the", "TreeWriter", "generation", "first", "to", "ensure", "the", "Class", "Hierarchy", "is", "built", "first", "and", "then", "can", "be", "used", "in", "the", "later", "generation", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AbstractDoclet.java#L195-L215
alibaba/jstorm
jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java
UIMetricUtils.getTaskMetric
public static UITaskMetric getTaskMetric(List<MetricInfo> taskStreamMetrics, String component, int id, int window) { """ get the specific task metric @param taskStreamMetrics raw metric info @param component component name @param id task id @param window window duration for metrics in seconds @return the task metric """ UITaskMetric taskMetric = new UITaskMetric(component, id); if (taskStreamMetrics.size() > 1) { MetricInfo info = taskStreamMetrics.get(0); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); int taskId = JStormUtils.parseInt(UIMetricUtils.extractTaskId(split_name)); if (taskId != id) continue; //only handle the specific task String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } MetricSnapshot snapshot = metric.getValue().get(window); taskMetric.setMetricValue(snapshot, parentComp, metricName); } } } taskMetric.mergeValue(); return taskMetric; }
java
public static UITaskMetric getTaskMetric(List<MetricInfo> taskStreamMetrics, String component, int id, int window) { UITaskMetric taskMetric = new UITaskMetric(component, id); if (taskStreamMetrics.size() > 1) { MetricInfo info = taskStreamMetrics.get(0); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { String name = metric.getKey(); String[] split_name = name.split("@"); int taskId = JStormUtils.parseInt(UIMetricUtils.extractTaskId(split_name)); if (taskId != id) continue; //only handle the specific task String metricName = UIMetricUtils.extractMetricName(split_name); String parentComp = null; if (metricName != null && metricName.contains(".")) { parentComp = metricName.split("\\.")[0]; metricName = metricName.split("\\.")[1]; } MetricSnapshot snapshot = metric.getValue().get(window); taskMetric.setMetricValue(snapshot, parentComp, metricName); } } } taskMetric.mergeValue(); return taskMetric; }
[ "public", "static", "UITaskMetric", "getTaskMetric", "(", "List", "<", "MetricInfo", ">", "taskStreamMetrics", ",", "String", "component", ",", "int", "id", ",", "int", "window", ")", "{", "UITaskMetric", "taskMetric", "=", "new", "UITaskMetric", "(", "component", ",", "id", ")", ";", "if", "(", "taskStreamMetrics", ".", "size", "(", ")", ">", "1", ")", "{", "MetricInfo", "info", "=", "taskStreamMetrics", ".", "get", "(", "0", ")", ";", "if", "(", "info", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Map", "<", "Integer", ",", "MetricSnapshot", ">", ">", "metric", ":", "info", ".", "get_metrics", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "name", "=", "metric", ".", "getKey", "(", ")", ";", "String", "[", "]", "split_name", "=", "name", ".", "split", "(", "\"@\"", ")", ";", "int", "taskId", "=", "JStormUtils", ".", "parseInt", "(", "UIMetricUtils", ".", "extractTaskId", "(", "split_name", ")", ")", ";", "if", "(", "taskId", "!=", "id", ")", "continue", ";", "//only handle the specific task", "String", "metricName", "=", "UIMetricUtils", ".", "extractMetricName", "(", "split_name", ")", ";", "String", "parentComp", "=", "null", ";", "if", "(", "metricName", "!=", "null", "&&", "metricName", ".", "contains", "(", "\".\"", ")", ")", "{", "parentComp", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "0", "]", ";", "metricName", "=", "metricName", ".", "split", "(", "\"\\\\.\"", ")", "[", "1", "]", ";", "}", "MetricSnapshot", "snapshot", "=", "metric", ".", "getValue", "(", ")", ".", "get", "(", "window", ")", ";", "taskMetric", ".", "setMetricValue", "(", "snapshot", ",", "parentComp", ",", "metricName", ")", ";", "}", "}", "}", "taskMetric", ".", "mergeValue", "(", ")", ";", "return", "taskMetric", ";", "}" ]
get the specific task metric @param taskStreamMetrics raw metric info @param component component name @param id task id @param window window duration for metrics in seconds @return the task metric
[ "get", "the", "specific", "task", "metric" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-ui/src/main/java/com/alibaba/jstorm/ui/utils/UIMetricUtils.java#L449-L477
io7m/jaffirm
com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Invariants.java
Invariants.checkInvariantI
public static int checkInvariantI( final int value, final IntPredicate predicate, final IntFunction<String> describer) { """ An {@code int} specialized version of {@link #checkInvariant(Object, ContractConditionType)}. @param value The value @param predicate The predicate @param describer The describer for the predicate @return value @throws InvariantViolationException If the predicate is false """ final boolean ok; try { ok = predicate.test(value); } catch (final Throwable e) { final Violations violations = singleViolation(failedPredicate(e)); throw new InvariantViolationException( failedMessage(Integer.valueOf(value), violations), e, violations.count()); } return innerCheckInvariantI(value, ok, describer); }
java
public static int checkInvariantI( final int value, final IntPredicate predicate, final IntFunction<String> describer) { final boolean ok; try { ok = predicate.test(value); } catch (final Throwable e) { final Violations violations = singleViolation(failedPredicate(e)); throw new InvariantViolationException( failedMessage(Integer.valueOf(value), violations), e, violations.count()); } return innerCheckInvariantI(value, ok, describer); }
[ "public", "static", "int", "checkInvariantI", "(", "final", "int", "value", ",", "final", "IntPredicate", "predicate", ",", "final", "IntFunction", "<", "String", ">", "describer", ")", "{", "final", "boolean", "ok", ";", "try", "{", "ok", "=", "predicate", ".", "test", "(", "value", ")", ";", "}", "catch", "(", "final", "Throwable", "e", ")", "{", "final", "Violations", "violations", "=", "singleViolation", "(", "failedPredicate", "(", "e", ")", ")", ";", "throw", "new", "InvariantViolationException", "(", "failedMessage", "(", "Integer", ".", "valueOf", "(", "value", ")", ",", "violations", ")", ",", "e", ",", "violations", ".", "count", "(", ")", ")", ";", "}", "return", "innerCheckInvariantI", "(", "value", ",", "ok", ",", "describer", ")", ";", "}" ]
An {@code int} specialized version of {@link #checkInvariant(Object, ContractConditionType)}. @param value The value @param predicate The predicate @param describer The describer for the predicate @return value @throws InvariantViolationException If the predicate is false
[ "An", "{", "@code", "int", "}", "specialized", "version", "of", "{", "@link", "#checkInvariant", "(", "Object", "ContractConditionType", ")", "}", "." ]
train
https://github.com/io7m/jaffirm/blob/c97d246242d381e48832838737418cfe4cb57b4d/com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Invariants.java#L379-L394
Wolfgang-Schuetzelhofer/jcypher
src/main/java/iot/jcypher/query/LiteralMapList.java
LiteralMapList.selectFirst
public LiteralMap selectFirst(JcPrimitive key, Object value) { """ Answer the first literal map with the given key and value @param key @param value @return """ for (LiteralMap lm : this) { if (isEqual(value, lm.get(ValueAccess.getName(key)))) return lm; } return null; }
java
public LiteralMap selectFirst(JcPrimitive key, Object value) { for (LiteralMap lm : this) { if (isEqual(value, lm.get(ValueAccess.getName(key)))) return lm; } return null; }
[ "public", "LiteralMap", "selectFirst", "(", "JcPrimitive", "key", ",", "Object", "value", ")", "{", "for", "(", "LiteralMap", "lm", ":", "this", ")", "{", "if", "(", "isEqual", "(", "value", ",", "lm", ".", "get", "(", "ValueAccess", ".", "getName", "(", "key", ")", ")", ")", ")", "return", "lm", ";", "}", "return", "null", ";", "}" ]
Answer the first literal map with the given key and value @param key @param value @return
[ "Answer", "the", "first", "literal", "map", "with", "the", "given", "key", "and", "value" ]
train
https://github.com/Wolfgang-Schuetzelhofer/jcypher/blob/0f36914b4d6993a004cc235bb18dd3e02a59d253/src/main/java/iot/jcypher/query/LiteralMapList.java#L77-L83
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java
LazyList.toXml
public String toXml(boolean pretty, boolean declaration, String... attrs) { """ Generates a XML document from content of this list. @param pretty pretty format (human readable), or one line text. @param declaration true to include XML declaration at the top @param attrs list of attributes to include. No arguments == include all attributes. @return generated XML. """ String topNode = Inflector.pluralize(Inflector.underscore(metaModel.getModelClass().getSimpleName())); hydrate(); StringBuilder sb = new StringBuilder(); if(declaration) { sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if (pretty) sb.append('\n'); } sb.append('<').append(topNode).append('>'); if (pretty) { sb.append('\n'); } for (T t : delegate) { t.toXmlP(sb, pretty, pretty ? " " : "", attrs); } sb.append("</").append(topNode).append('>'); if (pretty) { sb.append('\n'); } return sb.toString(); }
java
public String toXml(boolean pretty, boolean declaration, String... attrs) { String topNode = Inflector.pluralize(Inflector.underscore(metaModel.getModelClass().getSimpleName())); hydrate(); StringBuilder sb = new StringBuilder(); if(declaration) { sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if (pretty) sb.append('\n'); } sb.append('<').append(topNode).append('>'); if (pretty) { sb.append('\n'); } for (T t : delegate) { t.toXmlP(sb, pretty, pretty ? " " : "", attrs); } sb.append("</").append(topNode).append('>'); if (pretty) { sb.append('\n'); } return sb.toString(); }
[ "public", "String", "toXml", "(", "boolean", "pretty", ",", "boolean", "declaration", ",", "String", "...", "attrs", ")", "{", "String", "topNode", "=", "Inflector", ".", "pluralize", "(", "Inflector", ".", "underscore", "(", "metaModel", ".", "getModelClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ")", ";", "hydrate", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "declaration", ")", "{", "sb", ".", "append", "(", "\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\"", ")", ";", "if", "(", "pretty", ")", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "sb", ".", "append", "(", "'", "'", ")", ".", "append", "(", "topNode", ")", ".", "append", "(", "'", "'", ")", ";", "if", "(", "pretty", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "for", "(", "T", "t", ":", "delegate", ")", "{", "t", ".", "toXmlP", "(", "sb", ",", "pretty", ",", "pretty", "?", "\" \"", ":", "\"\"", ",", "attrs", ")", ";", "}", "sb", ".", "append", "(", "\"</\"", ")", ".", "append", "(", "topNode", ")", ".", "append", "(", "'", "'", ")", ";", "if", "(", "pretty", ")", "{", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Generates a XML document from content of this list. @param pretty pretty format (human readable), or one line text. @param declaration true to include XML declaration at the top @param attrs list of attributes to include. No arguments == include all attributes. @return generated XML.
[ "Generates", "a", "XML", "document", "from", "content", "of", "this", "list", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java#L203-L221
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/APIClient.java
APIClient.updateApiKey
public JSONObject updateApiKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException { """ Update an api key @param acls the list of ACL for this key. Defined by an array of strings that can contains the following values: - search: allow to search (https and http) - addObject: allows to add/update an object in the index (https only) - deleteObject : allows to delete an existing object (https only) - deleteIndex : allows to delete index content (https only) - settings : allows to get index settings (https only) - editSettings : allows to change index settings (https only) @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit). @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited) @param indexes the list of targeted indexes """ JSONObject jsonObject = generateUserKeyJson(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, indexes); return updateApiKey(key, jsonObject); }
java
public JSONObject updateApiKey(String key, List<String> acls, int validity, int maxQueriesPerIPPerHour, int maxHitsPerQuery, List<String> indexes) throws AlgoliaException { JSONObject jsonObject = generateUserKeyJson(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, indexes); return updateApiKey(key, jsonObject); }
[ "public", "JSONObject", "updateApiKey", "(", "String", "key", ",", "List", "<", "String", ">", "acls", ",", "int", "validity", ",", "int", "maxQueriesPerIPPerHour", ",", "int", "maxHitsPerQuery", ",", "List", "<", "String", ">", "indexes", ")", "throws", "AlgoliaException", "{", "JSONObject", "jsonObject", "=", "generateUserKeyJson", "(", "acls", ",", "validity", ",", "maxQueriesPerIPPerHour", ",", "maxHitsPerQuery", ",", "indexes", ")", ";", "return", "updateApiKey", "(", "key", ",", "jsonObject", ")", ";", "}" ]
Update an api key @param acls the list of ACL for this key. Defined by an array of strings that can contains the following values: - search: allow to search (https and http) - addObject: allows to add/update an object in the index (https only) - deleteObject : allows to delete an existing object (https only) - deleteIndex : allows to delete index content (https only) - settings : allows to get index settings (https only) - editSettings : allows to change index settings (https only) @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. Defaults to 0 (no rate limit). @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. Defaults to 0 (unlimited) @param indexes the list of targeted indexes
[ "Update", "an", "api", "key" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/APIClient.java#L925-L928
looly/hutool
hutool-db/src/main/java/cn/hutool/db/handler/HandleHelper.java
HandleHelper.handleRow
public static <T extends Entity> T handleRow(T row, int columnCount, ResultSetMetaData meta, ResultSet rs, boolean withMetaInfo) throws SQLException { """ 处理单条数据 @param <T> Entity及其子对象 @param row Entity对象 @param columnCount 列数 @param meta ResultSetMetaData @param rs 数据集 @param withMetaInfo 是否包含表名、字段名等元信息 @return 每一行的Entity @throws SQLException SQL执行异常 @since 3.3.1 """ String columnLabel; int type; for (int i = 1; i <= columnCount; i++) { columnLabel = meta.getColumnLabel(i); type = meta.getColumnType(i); row.put(columnLabel, getColumnValue(rs, columnLabel, type, null)); } if (withMetaInfo) { row.setTableName(meta.getTableName(1)); row.setFieldNames(row.keySet()); } return row; }
java
public static <T extends Entity> T handleRow(T row, int columnCount, ResultSetMetaData meta, ResultSet rs, boolean withMetaInfo) throws SQLException { String columnLabel; int type; for (int i = 1; i <= columnCount; i++) { columnLabel = meta.getColumnLabel(i); type = meta.getColumnType(i); row.put(columnLabel, getColumnValue(rs, columnLabel, type, null)); } if (withMetaInfo) { row.setTableName(meta.getTableName(1)); row.setFieldNames(row.keySet()); } return row; }
[ "public", "static", "<", "T", "extends", "Entity", ">", "T", "handleRow", "(", "T", "row", ",", "int", "columnCount", ",", "ResultSetMetaData", "meta", ",", "ResultSet", "rs", ",", "boolean", "withMetaInfo", ")", "throws", "SQLException", "{", "String", "columnLabel", ";", "int", "type", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "columnCount", ";", "i", "++", ")", "{", "columnLabel", "=", "meta", ".", "getColumnLabel", "(", "i", ")", ";", "type", "=", "meta", ".", "getColumnType", "(", "i", ")", ";", "row", ".", "put", "(", "columnLabel", ",", "getColumnValue", "(", "rs", ",", "columnLabel", ",", "type", ",", "null", ")", ")", ";", "}", "if", "(", "withMetaInfo", ")", "{", "row", ".", "setTableName", "(", "meta", ".", "getTableName", "(", "1", ")", ")", ";", "row", ".", "setFieldNames", "(", "row", ".", "keySet", "(", ")", ")", ";", "}", "return", "row", ";", "}" ]
处理单条数据 @param <T> Entity及其子对象 @param row Entity对象 @param columnCount 列数 @param meta ResultSetMetaData @param rs 数据集 @param withMetaInfo 是否包含表名、字段名等元信息 @return 每一行的Entity @throws SQLException SQL执行异常 @since 3.3.1
[ "处理单条数据" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/handler/HandleHelper.java#L128-L141
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/jmx/JmxUtil.java
JmxUtil.registerMBean
public static void registerMBean(Object mbean, ObjectName objectName, MBeanServer mBeanServer) throws Exception { """ Register the given dynamic JMX MBean. @param mbean Dynamic MBean to register @param objectName {@link ObjectName} under which to register the MBean. @param mBeanServer {@link MBeanServer} where to store the MBean. @throws Exception If registration could not be completed. """ if (!mBeanServer.isRegistered(objectName)) { try { SecurityActions.registerMBean(mbean, objectName, mBeanServer); log.tracef("Registered %s under %s", mbean, objectName); } catch (InstanceAlreadyExistsException e) { //this might happen if multiple instances are trying to concurrently register same objectName log.couldNotRegisterObjectName(objectName, e); } } else { log.debugf("Object name %s already registered", objectName); } }
java
public static void registerMBean(Object mbean, ObjectName objectName, MBeanServer mBeanServer) throws Exception { if (!mBeanServer.isRegistered(objectName)) { try { SecurityActions.registerMBean(mbean, objectName, mBeanServer); log.tracef("Registered %s under %s", mbean, objectName); } catch (InstanceAlreadyExistsException e) { //this might happen if multiple instances are trying to concurrently register same objectName log.couldNotRegisterObjectName(objectName, e); } } else { log.debugf("Object name %s already registered", objectName); } }
[ "public", "static", "void", "registerMBean", "(", "Object", "mbean", ",", "ObjectName", "objectName", ",", "MBeanServer", "mBeanServer", ")", "throws", "Exception", "{", "if", "(", "!", "mBeanServer", ".", "isRegistered", "(", "objectName", ")", ")", "{", "try", "{", "SecurityActions", ".", "registerMBean", "(", "mbean", ",", "objectName", ",", "mBeanServer", ")", ";", "log", ".", "tracef", "(", "\"Registered %s under %s\"", ",", "mbean", ",", "objectName", ")", ";", "}", "catch", "(", "InstanceAlreadyExistsException", "e", ")", "{", "//this might happen if multiple instances are trying to concurrently register same objectName", "log", ".", "couldNotRegisterObjectName", "(", "objectName", ",", "e", ")", ";", "}", "}", "else", "{", "log", ".", "debugf", "(", "\"Object name %s already registered\"", ",", "objectName", ")", ";", "}", "}" ]
Register the given dynamic JMX MBean. @param mbean Dynamic MBean to register @param objectName {@link ObjectName} under which to register the MBean. @param mBeanServer {@link MBeanServer} where to store the MBean. @throws Exception If registration could not be completed.
[ "Register", "the", "given", "dynamic", "JMX", "MBean", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/jmx/JmxUtil.java#L59-L71
auth0/Lock.Android
lib/src/main/java/com/auth0/android/lock/views/PasswordlessRequestCodeFormView.java
PasswordlessRequestCodeFormView.onCountryCodeSelected
@SuppressWarnings("unused") public void onCountryCodeSelected(String isoCode, String dialCode) { """ Notifies the form that a new country code was selected by the user. @param isoCode the selected country iso code (2 chars). @param dialCode the dial code for this country """ Country selectedCountry = new Country(isoCode, dialCode); countryCodeSelector.setSelectedCountry(selectedCountry); }
java
@SuppressWarnings("unused") public void onCountryCodeSelected(String isoCode, String dialCode) { Country selectedCountry = new Country(isoCode, dialCode); countryCodeSelector.setSelectedCountry(selectedCountry); }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "void", "onCountryCodeSelected", "(", "String", "isoCode", ",", "String", "dialCode", ")", "{", "Country", "selectedCountry", "=", "new", "Country", "(", "isoCode", ",", "dialCode", ")", ";", "countryCodeSelector", ".", "setSelectedCountry", "(", "selectedCountry", ")", ";", "}" ]
Notifies the form that a new country code was selected by the user. @param isoCode the selected country iso code (2 chars). @param dialCode the dial code for this country
[ "Notifies", "the", "form", "that", "a", "new", "country", "code", "was", "selected", "by", "the", "user", "." ]
train
https://github.com/auth0/Lock.Android/blob/8eb2a979048d2eb6cf0ec631e82e6c3fe6e7d220/lib/src/main/java/com/auth0/android/lock/views/PasswordlessRequestCodeFormView.java#L142-L146
UrielCh/ovh-java-sdk
ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java
ApiOvhIpLoadbalancing.serviceName_http_frontend_frontendId_PUT
public void serviceName_http_frontend_frontendId_PUT(String serviceName, Long frontendId, OvhFrontendHttp body) throws IOException { """ Alter this object properties REST: PUT /ipLoadbalancing/{serviceName}/http/frontend/{frontendId} @param body [required] New object properties @param serviceName [required] The internal name of your IP load balancing @param frontendId [required] Id of your frontend """ String qPath = "/ipLoadbalancing/{serviceName}/http/frontend/{frontendId}"; StringBuilder sb = path(qPath, serviceName, frontendId); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_http_frontend_frontendId_PUT(String serviceName, Long frontendId, OvhFrontendHttp body) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/http/frontend/{frontendId}"; StringBuilder sb = path(qPath, serviceName, frontendId); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_http_frontend_frontendId_PUT", "(", "String", "serviceName", ",", "Long", "frontendId", ",", "OvhFrontendHttp", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ipLoadbalancing/{serviceName}/http/frontend/{frontendId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "frontendId", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /ipLoadbalancing/{serviceName}/http/frontend/{frontendId} @param body [required] New object properties @param serviceName [required] The internal name of your IP load balancing @param frontendId [required] Id of your frontend
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L338-L342
OpenLiberty/open-liberty
dev/com.ibm.ws.security.common/src/com/ibm/ws/security/common/config/CommonConfigUtils.java
CommonConfigUtils.getConfigAttributeWithDefaultValue
public String getConfigAttributeWithDefaultValue(Map<String, Object> props, String key, String defaultValue) { """ Returns the value for the configuration attribute matching the key provided. If the value does not exist or is empty, the provided default value will be returned. """ String result = getAndTrimConfigAttribute(props, key); if (key != null && result == null) { if (defaultValue != null) { result = defaultValue; } } return result; }
java
public String getConfigAttributeWithDefaultValue(Map<String, Object> props, String key, String defaultValue) { String result = getAndTrimConfigAttribute(props, key); if (key != null && result == null) { if (defaultValue != null) { result = defaultValue; } } return result; }
[ "public", "String", "getConfigAttributeWithDefaultValue", "(", "Map", "<", "String", ",", "Object", ">", "props", ",", "String", "key", ",", "String", "defaultValue", ")", "{", "String", "result", "=", "getAndTrimConfigAttribute", "(", "props", ",", "key", ")", ";", "if", "(", "key", "!=", "null", "&&", "result", "==", "null", ")", "{", "if", "(", "defaultValue", "!=", "null", ")", "{", "result", "=", "defaultValue", ";", "}", "}", "return", "result", ";", "}" ]
Returns the value for the configuration attribute matching the key provided. If the value does not exist or is empty, the provided default value will be returned.
[ "Returns", "the", "value", "for", "the", "configuration", "attribute", "matching", "the", "key", "provided", ".", "If", "the", "value", "does", "not", "exist", "or", "is", "empty", "the", "provided", "default", "value", "will", "be", "returned", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.common/src/com/ibm/ws/security/common/config/CommonConfigUtils.java#L38-L46
gallandarakhneorg/afc
advanced/bootique/bootique-printconfig/src/main/java/org/arakhne/afc/bootique/printconfig/commands/PrintConfigCommand.java
PrintConfigCommand.generateXml
@SuppressWarnings( { """ Generate the Xml representation of the given map. @param map the map to print out. @return the Xml representation. @throws JsonProcessingException when XML cannot be processed. """"static-method"}) protected String generateXml(Map<String, Object> map) throws JsonProcessingException { final XmlMapper mapper = new XmlMapper(); return mapper.writerWithDefaultPrettyPrinter().withRootName(XML_ROOT_NAME).writeValueAsString(map); }
java
@SuppressWarnings({"static-method"}) protected String generateXml(Map<String, Object> map) throws JsonProcessingException { final XmlMapper mapper = new XmlMapper(); return mapper.writerWithDefaultPrettyPrinter().withRootName(XML_ROOT_NAME).writeValueAsString(map); }
[ "@", "SuppressWarnings", "(", "{", "\"static-method\"", "}", ")", "protected", "String", "generateXml", "(", "Map", "<", "String", ",", "Object", ">", "map", ")", "throws", "JsonProcessingException", "{", "final", "XmlMapper", "mapper", "=", "new", "XmlMapper", "(", ")", ";", "return", "mapper", ".", "writerWithDefaultPrettyPrinter", "(", ")", ".", "withRootName", "(", "XML_ROOT_NAME", ")", ".", "writeValueAsString", "(", "map", ")", ";", "}" ]
Generate the Xml representation of the given map. @param map the map to print out. @return the Xml representation. @throws JsonProcessingException when XML cannot be processed.
[ "Generate", "the", "Xml", "representation", "of", "the", "given", "map", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/bootique/bootique-printconfig/src/main/java/org/arakhne/afc/bootique/printconfig/commands/PrintConfigCommand.java#L175-L179
landawn/AbacusUtil
src/com/landawn/abacus/util/ByteList.java
ByteList.noneMatch
public <E extends Exception> boolean noneMatch(Try.BytePredicate<E> filter) throws E { """ Returns whether no elements of this List match the provided predicate. @param filter @return """ return noneMatch(0, size(), filter); }
java
public <E extends Exception> boolean noneMatch(Try.BytePredicate<E> filter) throws E { return noneMatch(0, size(), filter); }
[ "public", "<", "E", "extends", "Exception", ">", "boolean", "noneMatch", "(", "Try", ".", "BytePredicate", "<", "E", ">", "filter", ")", "throws", "E", "{", "return", "noneMatch", "(", "0", ",", "size", "(", ")", ",", "filter", ")", ";", "}" ]
Returns whether no elements of this List match the provided predicate. @param filter @return
[ "Returns", "whether", "no", "elements", "of", "this", "List", "match", "the", "provided", "predicate", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/ByteList.java#L971-L973
roboconf/roboconf-platform
miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/TargetWsDelegate.java
TargetWsDelegate.associateTarget
public void associateTarget( AbstractApplication app, String instancePathOrComponentName, String targetId, boolean bind ) throws TargetWsException { """ Associates or dissociates an application and a target. @param app an application or application template @param targetId a target ID @param instancePathOrComponentName an instance path or a component name (can be null) @param bind true to create a binding, false to delete one @throws TargetWsException """ if( bind ) this.logger.finer( "Associating " + app + " :: " + instancePathOrComponentName + " with " + targetId ); else this.logger.finer( "Dissociating " + app + " :: " + instancePathOrComponentName + " from " + targetId ); WebResource path = this.resource.path( UrlConstants.TARGETS ) .path( targetId ).path( "associations" ) .queryParam( "bind", Boolean.toString( bind )) .queryParam( "name", app.getName()); if( instancePathOrComponentName != null ) path = path.queryParam( "elt", instancePathOrComponentName ); if( app instanceof ApplicationTemplate ) path = path.queryParam( "qualifier", ((ApplicationTemplate) app).getVersion()); ClientResponse response = this.wsClient.createBuilder( path ) .accept( MediaType.APPLICATION_JSON ) .post( ClientResponse.class ); handleResponse( response ); }
java
public void associateTarget( AbstractApplication app, String instancePathOrComponentName, String targetId, boolean bind ) throws TargetWsException { if( bind ) this.logger.finer( "Associating " + app + " :: " + instancePathOrComponentName + " with " + targetId ); else this.logger.finer( "Dissociating " + app + " :: " + instancePathOrComponentName + " from " + targetId ); WebResource path = this.resource.path( UrlConstants.TARGETS ) .path( targetId ).path( "associations" ) .queryParam( "bind", Boolean.toString( bind )) .queryParam( "name", app.getName()); if( instancePathOrComponentName != null ) path = path.queryParam( "elt", instancePathOrComponentName ); if( app instanceof ApplicationTemplate ) path = path.queryParam( "qualifier", ((ApplicationTemplate) app).getVersion()); ClientResponse response = this.wsClient.createBuilder( path ) .accept( MediaType.APPLICATION_JSON ) .post( ClientResponse.class ); handleResponse( response ); }
[ "public", "void", "associateTarget", "(", "AbstractApplication", "app", ",", "String", "instancePathOrComponentName", ",", "String", "targetId", ",", "boolean", "bind", ")", "throws", "TargetWsException", "{", "if", "(", "bind", ")", "this", ".", "logger", ".", "finer", "(", "\"Associating \"", "+", "app", "+", "\" :: \"", "+", "instancePathOrComponentName", "+", "\" with \"", "+", "targetId", ")", ";", "else", "this", ".", "logger", ".", "finer", "(", "\"Dissociating \"", "+", "app", "+", "\" :: \"", "+", "instancePathOrComponentName", "+", "\" from \"", "+", "targetId", ")", ";", "WebResource", "path", "=", "this", ".", "resource", ".", "path", "(", "UrlConstants", ".", "TARGETS", ")", ".", "path", "(", "targetId", ")", ".", "path", "(", "\"associations\"", ")", ".", "queryParam", "(", "\"bind\"", ",", "Boolean", ".", "toString", "(", "bind", ")", ")", ".", "queryParam", "(", "\"name\"", ",", "app", ".", "getName", "(", ")", ")", ";", "if", "(", "instancePathOrComponentName", "!=", "null", ")", "path", "=", "path", ".", "queryParam", "(", "\"elt\"", ",", "instancePathOrComponentName", ")", ";", "if", "(", "app", "instanceof", "ApplicationTemplate", ")", "path", "=", "path", ".", "queryParam", "(", "\"qualifier\"", ",", "(", "(", "ApplicationTemplate", ")", "app", ")", ".", "getVersion", "(", ")", ")", ";", "ClientResponse", "response", "=", "this", ".", "wsClient", ".", "createBuilder", "(", "path", ")", ".", "accept", "(", "MediaType", ".", "APPLICATION_JSON", ")", ".", "post", "(", "ClientResponse", ".", "class", ")", ";", "handleResponse", "(", "response", ")", ";", "}" ]
Associates or dissociates an application and a target. @param app an application or application template @param targetId a target ID @param instancePathOrComponentName an instance path or a component name (can be null) @param bind true to create a binding, false to delete one @throws TargetWsException
[ "Associates", "or", "dissociates", "an", "application", "and", "a", "target", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/miscellaneous/roboconf-dm-rest-client/src/main/java/net/roboconf/dm/rest/client/delegates/TargetWsDelegate.java#L136-L160
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/MultimapJoiner.java
MultimapJoiner.appendTo
public StringBuilder appendTo(StringBuilder builder, Multimap<?, ?> map) { """ Appends the string representation of each entry of {@code map}, using the previously configured separator and key-value separator, to {@code builder}. Identical to {@link #appendTo(Appendable, Multimap)}, except that it does not throw {@link IOException}. """ return appendTo(builder, map.asMap().entrySet()); }
java
public StringBuilder appendTo(StringBuilder builder, Multimap<?, ?> map) { return appendTo(builder, map.asMap().entrySet()); }
[ "public", "StringBuilder", "appendTo", "(", "StringBuilder", "builder", ",", "Multimap", "<", "?", ",", "?", ">", "map", ")", "{", "return", "appendTo", "(", "builder", ",", "map", ".", "asMap", "(", ")", ".", "entrySet", "(", ")", ")", ";", "}" ]
Appends the string representation of each entry of {@code map}, using the previously configured separator and key-value separator, to {@code builder}. Identical to {@link #appendTo(Appendable, Multimap)}, except that it does not throw {@link IOException}.
[ "Appends", "the", "string", "representation", "of", "each", "entry", "of", "{" ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/MultimapJoiner.java#L62-L64
selenide/selenide
src/main/java/com/codeborne/selenide/impl/ScreenShotLaboratory.java
ScreenShotLaboratory.takeScreenShot
public String takeScreenShot(Driver driver, String fileName) { """ Takes screenshot of current browser window. Stores 2 files: html of page (if "savePageSource" option is enabled), and (if possible) image in PNG format. @param fileName name of file (without extension) to store screenshot to. @return the name of last saved screenshot or null if failed to create screenshot """ return ifWebDriverStarted(driver, webDriver -> ifReportsFolderNotNull(driver.config(), config -> takeScreenShot(config, webDriver, fileName))); }
java
public String takeScreenShot(Driver driver, String fileName) { return ifWebDriverStarted(driver, webDriver -> ifReportsFolderNotNull(driver.config(), config -> takeScreenShot(config, webDriver, fileName))); }
[ "public", "String", "takeScreenShot", "(", "Driver", "driver", ",", "String", "fileName", ")", "{", "return", "ifWebDriverStarted", "(", "driver", ",", "webDriver", "->", "ifReportsFolderNotNull", "(", "driver", ".", "config", "(", ")", ",", "config", "->", "takeScreenShot", "(", "config", ",", "webDriver", ",", "fileName", ")", ")", ")", ";", "}" ]
Takes screenshot of current browser window. Stores 2 files: html of page (if "savePageSource" option is enabled), and (if possible) image in PNG format. @param fileName name of file (without extension) to store screenshot to. @return the name of last saved screenshot or null if failed to create screenshot
[ "Takes", "screenshot", "of", "current", "browser", "window", ".", "Stores", "2", "files", ":", "html", "of", "page", "(", "if", "savePageSource", "option", "is", "enabled", ")", "and", "(", "if", "possible", ")", "image", "in", "PNG", "format", "." ]
train
https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/impl/ScreenShotLaboratory.java#L78-L82
graphql-java/graphql-java
src/main/java/graphql/execution/ValuesResolver.java
ValuesResolver.coerceArgumentValues
public Map<String, Object> coerceArgumentValues(GraphQLSchema schema, List<VariableDefinition> variableDefinitions, Map<String, Object> variableValues) { """ The http://facebook.github.io/graphql/#sec-Coercing-Variable-Values says : <pre> 1. Let coercedValues be an empty unordered Map. 2. Let variableDefinitions be the variables defined by operation. 3. For each variableDefinition in variableDefinitions: a. Let variableName be the name of variableDefinition. b. Let variableType be the expected type of variableDefinition. c. Let defaultValue be the default value for variableDefinition. d. Let value be the value provided in variableValues for the name variableName. e. If value does not exist (was not provided in variableValues): i. If defaultValue exists (including null): 1. Add an entry to coercedValues named variableName with the value defaultValue. ii. Otherwise if variableType is a Non‐Nullable type, throw a query error. iii. Otherwise, continue to the next variable definition. f. Otherwise, if value cannot be coerced according to the input coercion rules of variableType, throw a query error. g. Let coercedValue be the result of coercing value according to the input coercion rules of variableType. h. Add an entry to coercedValues named variableName with the value coercedValue. 4. Return coercedValues. </pre> @param schema the schema @param variableDefinitions the variable definitions @param variableValues the supplied variables @return coerced variable values as a map """ GraphqlFieldVisibility fieldVisibility = schema.getFieldVisibility(); Map<String, Object> coercedValues = new LinkedHashMap<>(); for (VariableDefinition variableDefinition : variableDefinitions) { String variableName = variableDefinition.getName(); GraphQLType variableType = TypeFromAST.getTypeFromAST(schema, variableDefinition.getType()); // 3.e if (!variableValues.containsKey(variableName)) { Value defaultValue = variableDefinition.getDefaultValue(); if (defaultValue != null) { // 3.e.i Object coercedValue = coerceValueAst(fieldVisibility, variableType, variableDefinition.getDefaultValue(), null); coercedValues.put(variableName, coercedValue); } else if (isNonNull(variableType)) { // 3.e.ii throw new NonNullableValueCoercedAsNullException(variableDefinition, variableType); } } else { Object value = variableValues.get(variableName); // 3.f Object coercedValue = getVariableValue(fieldVisibility, variableDefinition, variableType, value); // 3.g coercedValues.put(variableName, coercedValue); } } return coercedValues; }
java
public Map<String, Object> coerceArgumentValues(GraphQLSchema schema, List<VariableDefinition> variableDefinitions, Map<String, Object> variableValues) { GraphqlFieldVisibility fieldVisibility = schema.getFieldVisibility(); Map<String, Object> coercedValues = new LinkedHashMap<>(); for (VariableDefinition variableDefinition : variableDefinitions) { String variableName = variableDefinition.getName(); GraphQLType variableType = TypeFromAST.getTypeFromAST(schema, variableDefinition.getType()); // 3.e if (!variableValues.containsKey(variableName)) { Value defaultValue = variableDefinition.getDefaultValue(); if (defaultValue != null) { // 3.e.i Object coercedValue = coerceValueAst(fieldVisibility, variableType, variableDefinition.getDefaultValue(), null); coercedValues.put(variableName, coercedValue); } else if (isNonNull(variableType)) { // 3.e.ii throw new NonNullableValueCoercedAsNullException(variableDefinition, variableType); } } else { Object value = variableValues.get(variableName); // 3.f Object coercedValue = getVariableValue(fieldVisibility, variableDefinition, variableType, value); // 3.g coercedValues.put(variableName, coercedValue); } } return coercedValues; }
[ "public", "Map", "<", "String", ",", "Object", ">", "coerceArgumentValues", "(", "GraphQLSchema", "schema", ",", "List", "<", "VariableDefinition", ">", "variableDefinitions", ",", "Map", "<", "String", ",", "Object", ">", "variableValues", ")", "{", "GraphqlFieldVisibility", "fieldVisibility", "=", "schema", ".", "getFieldVisibility", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "coercedValues", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "for", "(", "VariableDefinition", "variableDefinition", ":", "variableDefinitions", ")", "{", "String", "variableName", "=", "variableDefinition", ".", "getName", "(", ")", ";", "GraphQLType", "variableType", "=", "TypeFromAST", ".", "getTypeFromAST", "(", "schema", ",", "variableDefinition", ".", "getType", "(", ")", ")", ";", "// 3.e", "if", "(", "!", "variableValues", ".", "containsKey", "(", "variableName", ")", ")", "{", "Value", "defaultValue", "=", "variableDefinition", ".", "getDefaultValue", "(", ")", ";", "if", "(", "defaultValue", "!=", "null", ")", "{", "// 3.e.i", "Object", "coercedValue", "=", "coerceValueAst", "(", "fieldVisibility", ",", "variableType", ",", "variableDefinition", ".", "getDefaultValue", "(", ")", ",", "null", ")", ";", "coercedValues", ".", "put", "(", "variableName", ",", "coercedValue", ")", ";", "}", "else", "if", "(", "isNonNull", "(", "variableType", ")", ")", "{", "// 3.e.ii", "throw", "new", "NonNullableValueCoercedAsNullException", "(", "variableDefinition", ",", "variableType", ")", ";", "}", "}", "else", "{", "Object", "value", "=", "variableValues", ".", "get", "(", "variableName", ")", ";", "// 3.f", "Object", "coercedValue", "=", "getVariableValue", "(", "fieldVisibility", ",", "variableDefinition", ",", "variableType", ",", "value", ")", ";", "// 3.g", "coercedValues", ".", "put", "(", "variableName", ",", "coercedValue", ")", ";", "}", "}", "return", "coercedValues", ";", "}" ]
The http://facebook.github.io/graphql/#sec-Coercing-Variable-Values says : <pre> 1. Let coercedValues be an empty unordered Map. 2. Let variableDefinitions be the variables defined by operation. 3. For each variableDefinition in variableDefinitions: a. Let variableName be the name of variableDefinition. b. Let variableType be the expected type of variableDefinition. c. Let defaultValue be the default value for variableDefinition. d. Let value be the value provided in variableValues for the name variableName. e. If value does not exist (was not provided in variableValues): i. If defaultValue exists (including null): 1. Add an entry to coercedValues named variableName with the value defaultValue. ii. Otherwise if variableType is a Non‐Nullable type, throw a query error. iii. Otherwise, continue to the next variable definition. f. Otherwise, if value cannot be coerced according to the input coercion rules of variableType, throw a query error. g. Let coercedValue be the result of coercing value according to the input coercion rules of variableType. h. Add an entry to coercedValues named variableName with the value coercedValue. 4. Return coercedValues. </pre> @param schema the schema @param variableDefinitions the variable definitions @param variableValues the supplied variables @return coerced variable values as a map
[ "The", "http", ":", "//", "facebook", ".", "github", ".", "io", "/", "graphql", "/", "#sec", "-", "Coercing", "-", "Variable", "-", "Values", "says", ":" ]
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/execution/ValuesResolver.java#L70-L98
mapbox/mapbox-plugins-android
plugin-localization/src/main/java/com/mapbox/mapboxsdk/plugins/localization/LocalizationPlugin.java
LocalizationPlugin.setCameraToLocaleCountry
public void setCameraToLocaleCountry(MapLocale mapLocale, int padding) { """ You can pass in a {@link MapLocale} directly into this method which uses the country bounds defined in it to represent the language found on the map. @param mapLocale the {@link MapLocale} object which contains the desired map bounds @param padding camera padding @since 0.1.0 """ LatLngBounds bounds = mapLocale.getCountryBounds(); if (bounds == null) { throw new NullPointerException("Expected a LatLngBounds object but received null instead. Mak" + "e sure your MapLocale instance also has a country bounding box defined."); } mapboxMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding)); }
java
public void setCameraToLocaleCountry(MapLocale mapLocale, int padding) { LatLngBounds bounds = mapLocale.getCountryBounds(); if (bounds == null) { throw new NullPointerException("Expected a LatLngBounds object but received null instead. Mak" + "e sure your MapLocale instance also has a country bounding box defined."); } mapboxMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding)); }
[ "public", "void", "setCameraToLocaleCountry", "(", "MapLocale", "mapLocale", ",", "int", "padding", ")", "{", "LatLngBounds", "bounds", "=", "mapLocale", ".", "getCountryBounds", "(", ")", ";", "if", "(", "bounds", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Expected a LatLngBounds object but received null instead. Mak\"", "+", "\"e sure your MapLocale instance also has a country bounding box defined.\"", ")", ";", "}", "mapboxMap", ".", "moveCamera", "(", "CameraUpdateFactory", ".", "newLatLngBounds", "(", "bounds", ",", "padding", ")", ")", ";", "}" ]
You can pass in a {@link MapLocale} directly into this method which uses the country bounds defined in it to represent the language found on the map. @param mapLocale the {@link MapLocale} object which contains the desired map bounds @param padding camera padding @since 0.1.0
[ "You", "can", "pass", "in", "a", "{", "@link", "MapLocale", "}", "directly", "into", "this", "method", "which", "uses", "the", "country", "bounds", "defined", "in", "it", "to", "represent", "the", "language", "found", "on", "the", "map", "." ]
train
https://github.com/mapbox/mapbox-plugins-android/blob/c683cad4d8306945d71838d96fae73b8cbe2e6c9/plugin-localization/src/main/java/com/mapbox/mapboxsdk/plugins/localization/LocalizationPlugin.java#L344-L351
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/layer/LayerImpl.java
LayerImpl.generateCacheKey
protected String generateCacheKey(HttpServletRequest request, Map<String, ICacheKeyGenerator> cacheKeyGenerators) throws IOException { """ Generates a cache key for the layer. @param request the request object @param cacheKeyGenerators map of cache key generator class names to instance objects @return the cache key @throws IOException """ String cacheKey = null; if (cacheKeyGenerators != null) { // First, decompose any composite cache key generators into their // constituent cache key generators so that we can combine them // more effectively. Use TreeMap to get predictable ordering of // keys. Map<String, ICacheKeyGenerator> gens = new TreeMap<String, ICacheKeyGenerator>(); for (ICacheKeyGenerator gen : cacheKeyGenerators.values()) { List<ICacheKeyGenerator> constituentGens = gen.getCacheKeyGenerators(request); addCacheKeyGenerators(gens, constituentGens == null ? Arrays.asList(new ICacheKeyGenerator[]{gen}) : constituentGens); } cacheKey = KeyGenUtil.generateKey( request, gens.values()); } return cacheKey; }
java
protected String generateCacheKey(HttpServletRequest request, Map<String, ICacheKeyGenerator> cacheKeyGenerators) throws IOException { String cacheKey = null; if (cacheKeyGenerators != null) { // First, decompose any composite cache key generators into their // constituent cache key generators so that we can combine them // more effectively. Use TreeMap to get predictable ordering of // keys. Map<String, ICacheKeyGenerator> gens = new TreeMap<String, ICacheKeyGenerator>(); for (ICacheKeyGenerator gen : cacheKeyGenerators.values()) { List<ICacheKeyGenerator> constituentGens = gen.getCacheKeyGenerators(request); addCacheKeyGenerators(gens, constituentGens == null ? Arrays.asList(new ICacheKeyGenerator[]{gen}) : constituentGens); } cacheKey = KeyGenUtil.generateKey( request, gens.values()); } return cacheKey; }
[ "protected", "String", "generateCacheKey", "(", "HttpServletRequest", "request", ",", "Map", "<", "String", ",", "ICacheKeyGenerator", ">", "cacheKeyGenerators", ")", "throws", "IOException", "{", "String", "cacheKey", "=", "null", ";", "if", "(", "cacheKeyGenerators", "!=", "null", ")", "{", "// First, decompose any composite cache key generators into their\r", "// constituent cache key generators so that we can combine them\r", "// more effectively. Use TreeMap to get predictable ordering of\r", "// keys.\r", "Map", "<", "String", ",", "ICacheKeyGenerator", ">", "gens", "=", "new", "TreeMap", "<", "String", ",", "ICacheKeyGenerator", ">", "(", ")", ";", "for", "(", "ICacheKeyGenerator", "gen", ":", "cacheKeyGenerators", ".", "values", "(", ")", ")", "{", "List", "<", "ICacheKeyGenerator", ">", "constituentGens", "=", "gen", ".", "getCacheKeyGenerators", "(", "request", ")", ";", "addCacheKeyGenerators", "(", "gens", ",", "constituentGens", "==", "null", "?", "Arrays", ".", "asList", "(", "new", "ICacheKeyGenerator", "[", "]", "{", "gen", "}", ")", ":", "constituentGens", ")", ";", "}", "cacheKey", "=", "KeyGenUtil", ".", "generateKey", "(", "request", ",", "gens", ".", "values", "(", ")", ")", ";", "}", "return", "cacheKey", ";", "}" ]
Generates a cache key for the layer. @param request the request object @param cacheKeyGenerators map of cache key generator class names to instance objects @return the cache key @throws IOException
[ "Generates", "a", "cache", "key", "for", "the", "layer", "." ]
train
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/layer/LayerImpl.java#L654-L674
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/Oid.java
Oid.fromToken
public static Oid fromToken(String oidtoken, IMetaModel meta) throws OidException { """ Create an OID from a token @param oidtoken - token to parse @param meta - metamodel @return an Oid @throws OidException - if the OID cannot be created. """ try { if (oidtoken.equals(NullOidToken)) { return Null; } String[] parts = oidtoken.split(SEPARATOR); IAssetType type = meta.getAssetType(parts[0]); int id = Integer.parseInt(parts[1]); if (parts.length > 2) { int moment = Integer.parseInt(parts[2]); return new com.versionone.Oid(type, id, moment); } return new com.versionone.Oid(type, id); } catch (Exception e) { throw new OidException("Invalid OID token", oidtoken, e); } }
java
public static Oid fromToken(String oidtoken, IMetaModel meta) throws OidException { try { if (oidtoken.equals(NullOidToken)) { return Null; } String[] parts = oidtoken.split(SEPARATOR); IAssetType type = meta.getAssetType(parts[0]); int id = Integer.parseInt(parts[1]); if (parts.length > 2) { int moment = Integer.parseInt(parts[2]); return new com.versionone.Oid(type, id, moment); } return new com.versionone.Oid(type, id); } catch (Exception e) { throw new OidException("Invalid OID token", oidtoken, e); } }
[ "public", "static", "Oid", "fromToken", "(", "String", "oidtoken", ",", "IMetaModel", "meta", ")", "throws", "OidException", "{", "try", "{", "if", "(", "oidtoken", ".", "equals", "(", "NullOidToken", ")", ")", "{", "return", "Null", ";", "}", "String", "[", "]", "parts", "=", "oidtoken", ".", "split", "(", "SEPARATOR", ")", ";", "IAssetType", "type", "=", "meta", ".", "getAssetType", "(", "parts", "[", "0", "]", ")", ";", "int", "id", "=", "Integer", ".", "parseInt", "(", "parts", "[", "1", "]", ")", ";", "if", "(", "parts", ".", "length", ">", "2", ")", "{", "int", "moment", "=", "Integer", ".", "parseInt", "(", "parts", "[", "2", "]", ")", ";", "return", "new", "com", ".", "versionone", ".", "Oid", "(", "type", ",", "id", ",", "moment", ")", ";", "}", "return", "new", "com", ".", "versionone", ".", "Oid", "(", "type", ",", "id", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "OidException", "(", "\"Invalid OID token\"", ",", "oidtoken", ",", "e", ")", ";", "}", "}" ]
Create an OID from a token @param oidtoken - token to parse @param meta - metamodel @return an Oid @throws OidException - if the OID cannot be created.
[ "Create", "an", "OID", "from", "a", "token" ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/Oid.java#L154-L170
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.setFieldValue
static void setFieldValue(Object target, String name, Object value) throws IllegalAccessException, NoSuchFieldException, SecurityException { """ Set the value of the specified field of the supplied object. @param target target object @param name field name @param value value to set in the specified field of the supplied object @throws IllegalAccessException if the {@code Field} object is enforcing access control for an inaccessible field @throws NoSuchFieldException if a field with the specified name is not found @throws SecurityException if the request is denied """ Field field = getDeclaredField(target, name); field.setAccessible(true); field.set(target, value); }
java
static void setFieldValue(Object target, String name, Object value) throws IllegalAccessException, NoSuchFieldException, SecurityException { Field field = getDeclaredField(target, name); field.setAccessible(true); field.set(target, value); }
[ "static", "void", "setFieldValue", "(", "Object", "target", ",", "String", "name", ",", "Object", "value", ")", "throws", "IllegalAccessException", ",", "NoSuchFieldException", ",", "SecurityException", "{", "Field", "field", "=", "getDeclaredField", "(", "target", ",", "name", ")", ";", "field", ".", "setAccessible", "(", "true", ")", ";", "field", ".", "set", "(", "target", ",", "value", ")", ";", "}" ]
Set the value of the specified field of the supplied object. @param target target object @param name field name @param value value to set in the specified field of the supplied object @throws IllegalAccessException if the {@code Field} object is enforcing access control for an inaccessible field @throws NoSuchFieldException if a field with the specified name is not found @throws SecurityException if the request is denied
[ "Set", "the", "value", "of", "the", "specified", "field", "of", "the", "supplied", "object", "." ]
train
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L337-L341
diegossilveira/jcors
src/main/java/org/jcors/web/PreflightRequestHandler.java
PreflightRequestHandler.checkRequestMethod
private String checkRequestMethod(HttpServletRequest request, JCorsConfig config) { """ Checks if the requested method is allowed @param request @param config """ String requestMethod = request.getHeader(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD_HEADER); Constraint.ensureNotEmpty(requestMethod, "Request Method Header must be supplied"); Constraint.ensureTrue(config.isMethodAllowed(requestMethod), String.format("The specified method is not allowed: '%s'", requestMethod)); return requestMethod; }
java
private String checkRequestMethod(HttpServletRequest request, JCorsConfig config) { String requestMethod = request.getHeader(CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD_HEADER); Constraint.ensureNotEmpty(requestMethod, "Request Method Header must be supplied"); Constraint.ensureTrue(config.isMethodAllowed(requestMethod), String.format("The specified method is not allowed: '%s'", requestMethod)); return requestMethod; }
[ "private", "String", "checkRequestMethod", "(", "HttpServletRequest", "request", ",", "JCorsConfig", "config", ")", "{", "String", "requestMethod", "=", "request", ".", "getHeader", "(", "CorsHeaders", ".", "ACCESS_CONTROL_REQUEST_METHOD_HEADER", ")", ";", "Constraint", ".", "ensureNotEmpty", "(", "requestMethod", ",", "\"Request Method Header must be supplied\"", ")", ";", "Constraint", ".", "ensureTrue", "(", "config", ".", "isMethodAllowed", "(", "requestMethod", ")", ",", "String", ".", "format", "(", "\"The specified method is not allowed: '%s'\"", ",", "requestMethod", ")", ")", ";", "return", "requestMethod", ";", "}" ]
Checks if the requested method is allowed @param request @param config
[ "Checks", "if", "the", "requested", "method", "is", "allowed" ]
train
https://github.com/diegossilveira/jcors/blob/cd56a9e2055d629baa42f93b27dd5615ced9632f/src/main/java/org/jcors/web/PreflightRequestHandler.java#L80-L89
apereo/cas
support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java
LdapUtils.newLdaptiveSearchExecutor
public static SearchExecutor newLdaptiveSearchExecutor(final String baseDn, final String filterQuery, final List<String> params) { """ New search executor. @param baseDn the base dn @param filterQuery the filter query @param params the params @return the search executor """ return newLdaptiveSearchExecutor(baseDn, filterQuery, params, ReturnAttributes.ALL.value()); }
java
public static SearchExecutor newLdaptiveSearchExecutor(final String baseDn, final String filterQuery, final List<String> params) { return newLdaptiveSearchExecutor(baseDn, filterQuery, params, ReturnAttributes.ALL.value()); }
[ "public", "static", "SearchExecutor", "newLdaptiveSearchExecutor", "(", "final", "String", "baseDn", ",", "final", "String", "filterQuery", ",", "final", "List", "<", "String", ">", "params", ")", "{", "return", "newLdaptiveSearchExecutor", "(", "baseDn", ",", "filterQuery", ",", "params", ",", "ReturnAttributes", ".", "ALL", ".", "value", "(", ")", ")", ";", "}" ]
New search executor. @param baseDn the base dn @param filterQuery the filter query @param params the params @return the search executor
[ "New", "search", "executor", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ldap-core/src/main/java/org/apereo/cas/util/LdapUtils.java#L576-L578
cloudendpoints/endpoints-management-java
endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java
ResourceName.parentName
public ResourceName parentName() { """ Returns the parent resource name. For example, if the name is {@code shelves/s1/books/b1}, the parent is {@code shelves/s1/books}. """ PathTemplate parentTemplate = template.parentTemplate(); return new ResourceName(parentTemplate, values, endpoint); }
java
public ResourceName parentName() { PathTemplate parentTemplate = template.parentTemplate(); return new ResourceName(parentTemplate, values, endpoint); }
[ "public", "ResourceName", "parentName", "(", ")", "{", "PathTemplate", "parentTemplate", "=", "template", ".", "parentTemplate", "(", ")", ";", "return", "new", "ResourceName", "(", "parentTemplate", ",", "values", ",", "endpoint", ")", ";", "}" ]
Returns the parent resource name. For example, if the name is {@code shelves/s1/books/b1}, the parent is {@code shelves/s1/books}.
[ "Returns", "the", "parent", "resource", "name", ".", "For", "example", "if", "the", "name", "is", "{" ]
train
https://github.com/cloudendpoints/endpoints-management-java/blob/5bbf20ddadbbd51b890049e3c338c28abe2c9f94/endpoints-control/src/main/java/com/google/api/control/model/ResourceName.java#L201-L204
VoltDB/voltdb
src/frontend/org/voltdb/SnapshotDaemon.java
SnapshotDaemon.processScanResponse
private void processScanResponse(ClientResponse response) { """ Process the response to a snapshot scan. Find the snapshots that are managed by this daemon by path and nonce and add it the list. Initiate a delete of any that should not be retained @param response @return """ setState(State.WAITING); if (response.getStatus() != ClientResponse.SUCCESS) { logFailureResponse("Initial snapshot scan failed", response); return; } final VoltTable results[] = response.getResults(); if (results.length == 1) { final VoltTable result = results[0]; boolean advanced = result.advanceRow(); assert(advanced); assert(result.getColumnCount() == 1); assert(result.getColumnType(0) == VoltType.STRING); SNAP_LOG.warn("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG")); return; } assert(results.length == 3); final VoltTable snapshots = results[0]; assert(snapshots.getColumnCount() == 10); final File myPath = new File(m_path); while (snapshots.advanceRow()) { final String path = snapshots.getString("PATH"); final File pathFile = new File(path); if (pathFile.equals(myPath)) { final String nonce = snapshots.getString("NONCE"); if (nonce.startsWith(m_prefixAndSeparator)) { final Long txnId = snapshots.getLong("TXNID"); m_snapshots.add(new Snapshot(path, SnapshotPathType.SNAP_AUTO, nonce, txnId)); } } } java.util.Collections.sort(m_snapshots); deleteExtraSnapshots(); }
java
private void processScanResponse(ClientResponse response) { setState(State.WAITING); if (response.getStatus() != ClientResponse.SUCCESS) { logFailureResponse("Initial snapshot scan failed", response); return; } final VoltTable results[] = response.getResults(); if (results.length == 1) { final VoltTable result = results[0]; boolean advanced = result.advanceRow(); assert(advanced); assert(result.getColumnCount() == 1); assert(result.getColumnType(0) == VoltType.STRING); SNAP_LOG.warn("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG")); return; } assert(results.length == 3); final VoltTable snapshots = results[0]; assert(snapshots.getColumnCount() == 10); final File myPath = new File(m_path); while (snapshots.advanceRow()) { final String path = snapshots.getString("PATH"); final File pathFile = new File(path); if (pathFile.equals(myPath)) { final String nonce = snapshots.getString("NONCE"); if (nonce.startsWith(m_prefixAndSeparator)) { final Long txnId = snapshots.getLong("TXNID"); m_snapshots.add(new Snapshot(path, SnapshotPathType.SNAP_AUTO, nonce, txnId)); } } } java.util.Collections.sort(m_snapshots); deleteExtraSnapshots(); }
[ "private", "void", "processScanResponse", "(", "ClientResponse", "response", ")", "{", "setState", "(", "State", ".", "WAITING", ")", ";", "if", "(", "response", ".", "getStatus", "(", ")", "!=", "ClientResponse", ".", "SUCCESS", ")", "{", "logFailureResponse", "(", "\"Initial snapshot scan failed\"", ",", "response", ")", ";", "return", ";", "}", "final", "VoltTable", "results", "[", "]", "=", "response", ".", "getResults", "(", ")", ";", "if", "(", "results", ".", "length", "==", "1", ")", "{", "final", "VoltTable", "result", "=", "results", "[", "0", "]", ";", "boolean", "advanced", "=", "result", ".", "advanceRow", "(", ")", ";", "assert", "(", "advanced", ")", ";", "assert", "(", "result", ".", "getColumnCount", "(", ")", "==", "1", ")", ";", "assert", "(", "result", ".", "getColumnType", "(", "0", ")", "==", "VoltType", ".", "STRING", ")", ";", "SNAP_LOG", ".", "warn", "(", "\"Initial snapshot scan failed with failure response: \"", "+", "result", ".", "getString", "(", "\"ERR_MSG\"", ")", ")", ";", "return", ";", "}", "assert", "(", "results", ".", "length", "==", "3", ")", ";", "final", "VoltTable", "snapshots", "=", "results", "[", "0", "]", ";", "assert", "(", "snapshots", ".", "getColumnCount", "(", ")", "==", "10", ")", ";", "final", "File", "myPath", "=", "new", "File", "(", "m_path", ")", ";", "while", "(", "snapshots", ".", "advanceRow", "(", ")", ")", "{", "final", "String", "path", "=", "snapshots", ".", "getString", "(", "\"PATH\"", ")", ";", "final", "File", "pathFile", "=", "new", "File", "(", "path", ")", ";", "if", "(", "pathFile", ".", "equals", "(", "myPath", ")", ")", "{", "final", "String", "nonce", "=", "snapshots", ".", "getString", "(", "\"NONCE\"", ")", ";", "if", "(", "nonce", ".", "startsWith", "(", "m_prefixAndSeparator", ")", ")", "{", "final", "Long", "txnId", "=", "snapshots", ".", "getLong", "(", "\"TXNID\"", ")", ";", "m_snapshots", ".", "add", "(", "new", "Snapshot", "(", "path", ",", "SnapshotPathType", ".", "SNAP_AUTO", ",", "nonce", ",", "txnId", ")", ")", ";", "}", "}", "}", "java", ".", "util", ".", "Collections", ".", "sort", "(", "m_snapshots", ")", ";", "deleteExtraSnapshots", "(", ")", ";", "}" ]
Process the response to a snapshot scan. Find the snapshots that are managed by this daemon by path and nonce and add it the list. Initiate a delete of any that should not be retained @param response @return
[ "Process", "the", "response", "to", "a", "snapshot", "scan", ".", "Find", "the", "snapshots", "that", "are", "managed", "by", "this", "daemon", "by", "path", "and", "nonce", "and", "add", "it", "the", "list", ".", "Initiate", "a", "delete", "of", "any", "that", "should", "not", "be", "retained" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/SnapshotDaemon.java#L1536-L1574
febit/wit
wit-core/src/main/java/org/febit/wit_shaded/asm/ClassWriter.java
ClassWriter.newClassItem
Item newClassItem(final String value) { """ Adds a class reference to the constant pool of the class being build. Does nothing if the constant pool already contains a similar item. <i>This method is intended for {@link Attribute} sub classes, and is normally not needed by class generators or adapters.</i> @param value the internal name of the class. @return a new or already existing class reference item. """ Item result = get(key2.set(CLASS, value, null, null)); if (result == null) { pool.putBS(CLASS, newUTF8(value)); result = new Item(poolIndex++, key2); put(result); } return result; }
java
Item newClassItem(final String value) { Item result = get(key2.set(CLASS, value, null, null)); if (result == null) { pool.putBS(CLASS, newUTF8(value)); result = new Item(poolIndex++, key2); put(result); } return result; }
[ "Item", "newClassItem", "(", "final", "String", "value", ")", "{", "Item", "result", "=", "get", "(", "key2", ".", "set", "(", "CLASS", ",", "value", ",", "null", ",", "null", ")", ")", ";", "if", "(", "result", "==", "null", ")", "{", "pool", ".", "putBS", "(", "CLASS", ",", "newUTF8", "(", "value", ")", ")", ";", "result", "=", "new", "Item", "(", "poolIndex", "++", ",", "key2", ")", ";", "put", "(", "result", ")", ";", "}", "return", "result", ";", "}" ]
Adds a class reference to the constant pool of the class being build. Does nothing if the constant pool already contains a similar item. <i>This method is intended for {@link Attribute} sub classes, and is normally not needed by class generators or adapters.</i> @param value the internal name of the class. @return a new or already existing class reference item.
[ "Adds", "a", "class", "reference", "to", "the", "constant", "pool", "of", "the", "class", "being", "build", ".", "Does", "nothing", "if", "the", "constant", "pool", "already", "contains", "a", "similar", "item", ".", "<i", ">", "This", "method", "is", "intended", "for", "{", "@link", "Attribute", "}", "sub", "classes", "and", "is", "normally", "not", "needed", "by", "class", "generators", "or", "adapters", ".", "<", "/", "i", ">" ]
train
https://github.com/febit/wit/blob/89ee29efbc5633b79c30c3c7b953c9f4130575af/wit-core/src/main/java/org/febit/wit_shaded/asm/ClassWriter.java#L549-L557
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FileSystem.java
FileSystem.listLocatedBlockStatus
public RemoteIterator<LocatedBlockFileStatus> listLocatedBlockStatus( final Path f) throws FileNotFoundException, IOException { """ List the statuses of the files/directories in the given path if the path is a directory. Return the file's status, blocks and locations if the path is a file. If a returned status is a file, it contains the file's blocks and locations. @param f is the path @return an iterator that traverses statuses of the files/directories in the given path @throws FileNotFoundException If <code>f</code> does not exist @throws IOException If an I/O error occurred """ return listLocatedBlockStatus(f, DEFAULT_FILTER); }
java
public RemoteIterator<LocatedBlockFileStatus> listLocatedBlockStatus( final Path f) throws FileNotFoundException, IOException { return listLocatedBlockStatus(f, DEFAULT_FILTER); }
[ "public", "RemoteIterator", "<", "LocatedBlockFileStatus", ">", "listLocatedBlockStatus", "(", "final", "Path", "f", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "return", "listLocatedBlockStatus", "(", "f", ",", "DEFAULT_FILTER", ")", ";", "}" ]
List the statuses of the files/directories in the given path if the path is a directory. Return the file's status, blocks and locations if the path is a file. If a returned status is a file, it contains the file's blocks and locations. @param f is the path @return an iterator that traverses statuses of the files/directories in the given path @throws FileNotFoundException If <code>f</code> does not exist @throws IOException If an I/O error occurred
[ "List", "the", "statuses", "of", "the", "files", "/", "directories", "in", "the", "given", "path", "if", "the", "path", "is", "a", "directory", ".", "Return", "the", "file", "s", "status", "blocks", "and", "locations", "if", "the", "path", "is", "a", "file", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileSystem.java#L1107-L1110
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/SmartTable.java
SmartTable.removeStyleNames
public void removeStyleNames (int row, int column, String... styles) { """ Removes the specified style names on the specified row and column. """ for (String style : styles) { getFlexCellFormatter().removeStyleName(row, column, style); } }
java
public void removeStyleNames (int row, int column, String... styles) { for (String style : styles) { getFlexCellFormatter().removeStyleName(row, column, style); } }
[ "public", "void", "removeStyleNames", "(", "int", "row", ",", "int", "column", ",", "String", "...", "styles", ")", "{", "for", "(", "String", "style", ":", "styles", ")", "{", "getFlexCellFormatter", "(", ")", ".", "removeStyleName", "(", "row", ",", "column", ",", "style", ")", ";", "}", "}" ]
Removes the specified style names on the specified row and column.
[ "Removes", "the", "specified", "style", "names", "on", "the", "specified", "row", "and", "column", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/SmartTable.java#L362-L367
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/parser/ParameterizedDynamicFunctionSymbol.java
ParameterizedDynamicFunctionSymbol.assignSuperDfs
private void assignSuperDfs( IDynamicFunctionSymbol dfsDelegate, IGosuClass owner ) { """ Assign the super dfs in terms of the deriving class's type parameters """ IDynamicFunctionSymbol rawSuperDfs = dfsDelegate.getSuperDfs(); if( rawSuperDfs instanceof DynamicFunctionSymbol ) { while( rawSuperDfs.getBackingDfs() instanceof DynamicFunctionSymbol && rawSuperDfs.getBackingDfs() != rawSuperDfs ) { rawSuperDfs = rawSuperDfs.getBackingDfs(); } IType ownersType = rawSuperDfs.getDeclaringTypeInfo().getOwnersType(); if( !IGosuClass.ProxyUtil.isProxy( ownersType ) ) { IType superOwner = TypeLord.findParameterizedType( owner, ownersType ); if( superOwner == null ) { superOwner = ownersType; } setSuperDfs( ((DynamicFunctionSymbol)rawSuperDfs).getParameterizedVersion( (IGosuClass)superOwner ) ); } } }
java
private void assignSuperDfs( IDynamicFunctionSymbol dfsDelegate, IGosuClass owner ) { IDynamicFunctionSymbol rawSuperDfs = dfsDelegate.getSuperDfs(); if( rawSuperDfs instanceof DynamicFunctionSymbol ) { while( rawSuperDfs.getBackingDfs() instanceof DynamicFunctionSymbol && rawSuperDfs.getBackingDfs() != rawSuperDfs ) { rawSuperDfs = rawSuperDfs.getBackingDfs(); } IType ownersType = rawSuperDfs.getDeclaringTypeInfo().getOwnersType(); if( !IGosuClass.ProxyUtil.isProxy( ownersType ) ) { IType superOwner = TypeLord.findParameterizedType( owner, ownersType ); if( superOwner == null ) { superOwner = ownersType; } setSuperDfs( ((DynamicFunctionSymbol)rawSuperDfs).getParameterizedVersion( (IGosuClass)superOwner ) ); } } }
[ "private", "void", "assignSuperDfs", "(", "IDynamicFunctionSymbol", "dfsDelegate", ",", "IGosuClass", "owner", ")", "{", "IDynamicFunctionSymbol", "rawSuperDfs", "=", "dfsDelegate", ".", "getSuperDfs", "(", ")", ";", "if", "(", "rawSuperDfs", "instanceof", "DynamicFunctionSymbol", ")", "{", "while", "(", "rawSuperDfs", ".", "getBackingDfs", "(", ")", "instanceof", "DynamicFunctionSymbol", "&&", "rawSuperDfs", ".", "getBackingDfs", "(", ")", "!=", "rawSuperDfs", ")", "{", "rawSuperDfs", "=", "rawSuperDfs", ".", "getBackingDfs", "(", ")", ";", "}", "IType", "ownersType", "=", "rawSuperDfs", ".", "getDeclaringTypeInfo", "(", ")", ".", "getOwnersType", "(", ")", ";", "if", "(", "!", "IGosuClass", ".", "ProxyUtil", ".", "isProxy", "(", "ownersType", ")", ")", "{", "IType", "superOwner", "=", "TypeLord", ".", "findParameterizedType", "(", "owner", ",", "ownersType", ")", ";", "if", "(", "superOwner", "==", "null", ")", "{", "superOwner", "=", "ownersType", ";", "}", "setSuperDfs", "(", "(", "(", "DynamicFunctionSymbol", ")", "rawSuperDfs", ")", ".", "getParameterizedVersion", "(", "(", "IGosuClass", ")", "superOwner", ")", ")", ";", "}", "}", "}" ]
Assign the super dfs in terms of the deriving class's type parameters
[ "Assign", "the", "super", "dfs", "in", "terms", "of", "the", "deriving", "class", "s", "type", "parameters" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/parser/ParameterizedDynamicFunctionSymbol.java#L41-L61
alkacon/opencms-core
src/org/opencms/file/wrapper/CmsResourceWrapperXmlPage.java
CmsResourceWrapperXmlPage.getResourceForLocale
private CmsResource getResourceForLocale(CmsResource xmlPage, Locale locale) { """ Creates a new virtual resource for the locale in the xml page as a folder.<p> The new created resource uses the values of the origin resource of the xml page where it is possible.<p> @param xmlPage the xml page resource with the locale to create a resource of @param locale the locale in the xml page to use for the new resource @return a new created CmsResource """ CmsWrappedResource wrap = new CmsWrappedResource(xmlPage); wrap.setRootPath(xmlPage.getRootPath() + "/" + locale.getLanguage() + "/"); int plainId; try { plainId = OpenCms.getResourceManager().getResourceType( CmsResourceTypePlain.getStaticTypeName()).getTypeId(); } catch (CmsLoaderException e) { // this should really never happen plainId = CmsResourceTypePlain.getStaticTypeId(); } wrap.setTypeId(plainId); wrap.setFolder(true); return wrap.getResource(); }
java
private CmsResource getResourceForLocale(CmsResource xmlPage, Locale locale) { CmsWrappedResource wrap = new CmsWrappedResource(xmlPage); wrap.setRootPath(xmlPage.getRootPath() + "/" + locale.getLanguage() + "/"); int plainId; try { plainId = OpenCms.getResourceManager().getResourceType( CmsResourceTypePlain.getStaticTypeName()).getTypeId(); } catch (CmsLoaderException e) { // this should really never happen plainId = CmsResourceTypePlain.getStaticTypeId(); } wrap.setTypeId(plainId); wrap.setFolder(true); return wrap.getResource(); }
[ "private", "CmsResource", "getResourceForLocale", "(", "CmsResource", "xmlPage", ",", "Locale", "locale", ")", "{", "CmsWrappedResource", "wrap", "=", "new", "CmsWrappedResource", "(", "xmlPage", ")", ";", "wrap", ".", "setRootPath", "(", "xmlPage", ".", "getRootPath", "(", ")", "+", "\"/\"", "+", "locale", ".", "getLanguage", "(", ")", "+", "\"/\"", ")", ";", "int", "plainId", ";", "try", "{", "plainId", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "CmsResourceTypePlain", ".", "getStaticTypeName", "(", ")", ")", ".", "getTypeId", "(", ")", ";", "}", "catch", "(", "CmsLoaderException", "e", ")", "{", "// this should really never happen", "plainId", "=", "CmsResourceTypePlain", ".", "getStaticTypeId", "(", ")", ";", "}", "wrap", ".", "setTypeId", "(", "plainId", ")", ";", "wrap", ".", "setFolder", "(", "true", ")", ";", "return", "wrap", ".", "getResource", "(", ")", ";", "}" ]
Creates a new virtual resource for the locale in the xml page as a folder.<p> The new created resource uses the values of the origin resource of the xml page where it is possible.<p> @param xmlPage the xml page resource with the locale to create a resource of @param locale the locale in the xml page to use for the new resource @return a new created CmsResource
[ "Creates", "a", "new", "virtual", "resource", "for", "the", "locale", "in", "the", "xml", "page", "as", "a", "folder", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/wrapper/CmsResourceWrapperXmlPage.java#L1047-L1063
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/SecurityDocument.java
SecurityDocument.apply
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, SecurityDocument.Parameters params) { """ Builds the security MarkupDocument. @return the security MarkupDocument """ Map<String, SecuritySchemeDefinition> definitions = params.securitySchemeDefinitions; if (MapUtils.isNotEmpty(definitions)) { applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildSecurityTitle(markupDocBuilder, labels.getLabel(SECURITY)); applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildSecuritySchemeDefinitionsSection(markupDocBuilder, definitions); applySecurityDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applySecurityDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); } return markupDocBuilder; }
java
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, SecurityDocument.Parameters params) { Map<String, SecuritySchemeDefinition> definitions = params.securitySchemeDefinitions; if (MapUtils.isNotEmpty(definitions)) { applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildSecurityTitle(markupDocBuilder, labels.getLabel(SECURITY)); applySecurityDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildSecuritySchemeDefinitionsSection(markupDocBuilder, definitions); applySecurityDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applySecurityDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); } return markupDocBuilder; }
[ "@", "Override", "public", "MarkupDocBuilder", "apply", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "SecurityDocument", ".", "Parameters", "params", ")", "{", "Map", "<", "String", ",", "SecuritySchemeDefinition", ">", "definitions", "=", "params", ".", "securitySchemeDefinitions", ";", "if", "(", "MapUtils", ".", "isNotEmpty", "(", "definitions", ")", ")", "{", "applySecurityDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEFORE", ",", "markupDocBuilder", ")", ")", ";", "buildSecurityTitle", "(", "markupDocBuilder", ",", "labels", ".", "getLabel", "(", "SECURITY", ")", ")", ";", "applySecurityDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEGIN", ",", "markupDocBuilder", ")", ")", ";", "buildSecuritySchemeDefinitionsSection", "(", "markupDocBuilder", ",", "definitions", ")", ";", "applySecurityDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_END", ",", "markupDocBuilder", ")", ")", ";", "applySecurityDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_AFTER", ",", "markupDocBuilder", ")", ")", ";", "}", "return", "markupDocBuilder", ";", "}" ]
Builds the security MarkupDocument. @return the security MarkupDocument
[ "Builds", "the", "security", "MarkupDocument", "." ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/SecurityDocument.java#L54-L66
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/UsersApi.java
UsersApi.deleteUserWithHttpInfo
public ApiResponse<ApiSuccessResponse> deleteUserWithHttpInfo(String dbid, Boolean keepPlaces) throws ApiException { """ Remove a user. Remove the specified user, along with their associated login, places, and DNs. This removes the [CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson) object and any associated [CfgAgentLogin](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgAgentLogin), [CfgPlace](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPlace), [CfgDN](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgDN) objects. @param dbid The users&#39; DBID. (required) @param keepPlaces If &#x60;true&#x60; or absent, the user&#39;s places and DNs are not deleted. (optional) @return ApiResponse&lt;ApiSuccessResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(dbid, keepPlaces, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
public ApiResponse<ApiSuccessResponse> deleteUserWithHttpInfo(String dbid, Boolean keepPlaces) throws ApiException { com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(dbid, keepPlaces, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
[ "public", "ApiResponse", "<", "ApiSuccessResponse", ">", "deleteUserWithHttpInfo", "(", "String", "dbid", ",", "Boolean", "keepPlaces", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "deleteUserValidateBeforeCall", "(", "dbid", ",", "keepPlaces", ",", "null", ",", "null", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "ApiSuccessResponse", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "return", "apiClient", ".", "execute", "(", "call", ",", "localVarReturnType", ")", ";", "}" ]
Remove a user. Remove the specified user, along with their associated login, places, and DNs. This removes the [CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson) object and any associated [CfgAgentLogin](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgAgentLogin), [CfgPlace](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPlace), [CfgDN](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgDN) objects. @param dbid The users&#39; DBID. (required) @param keepPlaces If &#x60;true&#x60; or absent, the user&#39;s places and DNs are not deleted. (optional) @return ApiResponse&lt;ApiSuccessResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Remove", "a", "user", ".", "Remove", "the", "specified", "user", "along", "with", "their", "associated", "login", "places", "and", "DNs", ".", "This", "removes", "the", "[", "CfgPerson", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgPerson", ")", "object", "and", "any", "associated", "[", "CfgAgentLogin", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgAgentLogin", ")", "[", "CfgPlace", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgPlace", ")", "[", "CfgDN", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgDN", ")", "objects", "." ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/UsersApi.java#L272-L276
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/FlowTwillProgramController.java
FlowTwillProgramController.changeInstances
private synchronized void changeInstances(String flowletId, int newInstanceCount, int oldInstanceCount) throws Exception { """ Change the number of instances of the running flowlet. Notice that this method needs to be synchronized as change of instances involves multiple steps that need to be completed all at once. @param flowletId Name of the flowlet. @param newInstanceCount New instance count. @param oldInstanceCount Old instance count. @throws java.util.concurrent.ExecutionException @throws InterruptedException """ instanceUpdater.update(flowletId, newInstanceCount, oldInstanceCount); }
java
private synchronized void changeInstances(String flowletId, int newInstanceCount, int oldInstanceCount) throws Exception { instanceUpdater.update(flowletId, newInstanceCount, oldInstanceCount); }
[ "private", "synchronized", "void", "changeInstances", "(", "String", "flowletId", ",", "int", "newInstanceCount", ",", "int", "oldInstanceCount", ")", "throws", "Exception", "{", "instanceUpdater", ".", "update", "(", "flowletId", ",", "newInstanceCount", ",", "oldInstanceCount", ")", ";", "}" ]
Change the number of instances of the running flowlet. Notice that this method needs to be synchronized as change of instances involves multiple steps that need to be completed all at once. @param flowletId Name of the flowlet. @param newInstanceCount New instance count. @param oldInstanceCount Old instance count. @throws java.util.concurrent.ExecutionException @throws InterruptedException
[ "Change", "the", "number", "of", "instances", "of", "the", "running", "flowlet", ".", "Notice", "that", "this", "method", "needs", "to", "be", "synchronized", "as", "change", "of", "instances", "involves", "multiple", "steps", "that", "need", "to", "be", "completed", "all", "at", "once", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/FlowTwillProgramController.java#L73-L76
eclipse/xtext-extras
org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/binary/asm/SignatureUtil.java
SignatureUtil.scanTypeArgumentSignatures
private static int scanTypeArgumentSignatures(String string, int start) { """ Scans the given string for a list of type argument signatures starting at the given index and returns the index of the last character. <pre> TypeArgumentSignatures: <b>&lt;</b> TypeArgumentSignature* <b>&gt;</b> </pre> Note that although there is supposed to be at least one type argument, there is no syntactic ambiguity if there are none. This method will accept zero type argument signatures without complaint. @param string the signature string @param start the 0-based character index of the first character @return the 0-based character index of the last character @exception IllegalArgumentException if this is not a list of type arguments signatures """ // need a minimum 2 char "<>" if (start >= string.length() - 1) { throw new IllegalArgumentException(); } char c = string.charAt(start); if (c != C_GENERIC_START) { throw new IllegalArgumentException(); } int p = start + 1; while (true) { if (p >= string.length()) { throw new IllegalArgumentException(); } c = string.charAt(p); if (c == C_GENERIC_END) { return p; } int e = scanTypeArgumentSignature(string, p); p = e + 1; } }
java
private static int scanTypeArgumentSignatures(String string, int start) { // need a minimum 2 char "<>" if (start >= string.length() - 1) { throw new IllegalArgumentException(); } char c = string.charAt(start); if (c != C_GENERIC_START) { throw new IllegalArgumentException(); } int p = start + 1; while (true) { if (p >= string.length()) { throw new IllegalArgumentException(); } c = string.charAt(p); if (c == C_GENERIC_END) { return p; } int e = scanTypeArgumentSignature(string, p); p = e + 1; } }
[ "private", "static", "int", "scanTypeArgumentSignatures", "(", "String", "string", ",", "int", "start", ")", "{", "// need a minimum 2 char \"<>\"", "if", "(", "start", ">=", "string", ".", "length", "(", ")", "-", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "char", "c", "=", "string", ".", "charAt", "(", "start", ")", ";", "if", "(", "c", "!=", "C_GENERIC_START", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "int", "p", "=", "start", "+", "1", ";", "while", "(", "true", ")", "{", "if", "(", "p", ">=", "string", ".", "length", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "c", "=", "string", ".", "charAt", "(", "p", ")", ";", "if", "(", "c", "==", "C_GENERIC_END", ")", "{", "return", "p", ";", "}", "int", "e", "=", "scanTypeArgumentSignature", "(", "string", ",", "p", ")", ";", "p", "=", "e", "+", "1", ";", "}", "}" ]
Scans the given string for a list of type argument signatures starting at the given index and returns the index of the last character. <pre> TypeArgumentSignatures: <b>&lt;</b> TypeArgumentSignature* <b>&gt;</b> </pre> Note that although there is supposed to be at least one type argument, there is no syntactic ambiguity if there are none. This method will accept zero type argument signatures without complaint. @param string the signature string @param start the 0-based character index of the first character @return the 0-based character index of the last character @exception IllegalArgumentException if this is not a list of type arguments signatures
[ "Scans", "the", "given", "string", "for", "a", "list", "of", "type", "argument", "signatures", "starting", "at", "the", "given", "index", "and", "returns", "the", "index", "of", "the", "last", "character", ".", "<pre", ">", "TypeArgumentSignatures", ":", "<b", ">", "&lt", ";", "<", "/", "b", ">", "TypeArgumentSignature", "*", "<b", ">", "&gt", ";", "<", "/", "b", ">", "<", "/", "pre", ">", "Note", "that", "although", "there", "is", "supposed", "to", "be", "at", "least", "one", "type", "argument", "there", "is", "no", "syntactic", "ambiguity", "if", "there", "are", "none", ".", "This", "method", "will", "accept", "zero", "type", "argument", "signatures", "without", "complaint", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.common.types/src/org/eclipse/xtext/common/types/access/binary/asm/SignatureUtil.java#L475-L496
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/threading/Deadline.java
Deadline.waitFor
public void waitFor(final Object monitor, final boolean ignoreInterrupts) { """ Waits on the listed monitor until it returns or until this deadline has expired; if <code>mayInterrupt</code> is true then an interrupt will cause this method to return true @param ignoreInterrupts false if the code should return early in the event of an interrupt, otherwise true if InterruptedExceptions should be ignored """ synchronized (monitor) { try { monitor.wait(this.getTimeLeft(TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { if (!ignoreInterrupts) return; } } return; }
java
public void waitFor(final Object monitor, final boolean ignoreInterrupts) { synchronized (monitor) { try { monitor.wait(this.getTimeLeft(TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { if (!ignoreInterrupts) return; } } return; }
[ "public", "void", "waitFor", "(", "final", "Object", "monitor", ",", "final", "boolean", "ignoreInterrupts", ")", "{", "synchronized", "(", "monitor", ")", "{", "try", "{", "monitor", ".", "wait", "(", "this", ".", "getTimeLeft", "(", "TimeUnit", ".", "MILLISECONDS", ")", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "if", "(", "!", "ignoreInterrupts", ")", "return", ";", "}", "}", "return", ";", "}" ]
Waits on the listed monitor until it returns or until this deadline has expired; if <code>mayInterrupt</code> is true then an interrupt will cause this method to return true @param ignoreInterrupts false if the code should return early in the event of an interrupt, otherwise true if InterruptedExceptions should be ignored
[ "Waits", "on", "the", "listed", "monitor", "until", "it", "returns", "or", "until", "this", "deadline", "has", "expired", ";", "if", "<code", ">", "mayInterrupt<", "/", "code", ">", "is", "true", "then", "an", "interrupt", "will", "cause", "this", "method", "to", "return", "true" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/threading/Deadline.java#L239-L255
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/search/FileSearchExtensions.java
FileSearchExtensions.containsFile
public static boolean containsFile(final File fileToSearch, final String pathname) { """ Checks if the given file contains in the parent file. @param fileToSearch The parent directory to search. @param pathname The file to search. @return 's true if the file exists in the parent directory otherwise false. """ final String[] allFiles = fileToSearch.list(); if (allFiles == null) { return false; } final List<String> list = Arrays.asList(allFiles); return list.contains(pathname); }
java
public static boolean containsFile(final File fileToSearch, final String pathname) { final String[] allFiles = fileToSearch.list(); if (allFiles == null) { return false; } final List<String> list = Arrays.asList(allFiles); return list.contains(pathname); }
[ "public", "static", "boolean", "containsFile", "(", "final", "File", "fileToSearch", ",", "final", "String", "pathname", ")", "{", "final", "String", "[", "]", "allFiles", "=", "fileToSearch", ".", "list", "(", ")", ";", "if", "(", "allFiles", "==", "null", ")", "{", "return", "false", ";", "}", "final", "List", "<", "String", ">", "list", "=", "Arrays", ".", "asList", "(", "allFiles", ")", ";", "return", "list", ".", "contains", "(", "pathname", ")", ";", "}" ]
Checks if the given file contains in the parent file. @param fileToSearch The parent directory to search. @param pathname The file to search. @return 's true if the file exists in the parent directory otherwise false.
[ "Checks", "if", "the", "given", "file", "contains", "in", "the", "parent", "file", "." ]
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/search/FileSearchExtensions.java#L80-L89
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/webdriver/WebDriverHelper.java
WebDriverHelper.goToUrlWithCookie
public void goToUrlWithCookie(final String url, final String cookieName, final String cookieValue) { """ Opens the specified URL using the specified cookie. @param url the url you want to open @param cookieName the cookie name @param cookieValue the cookie value """ // we'll do a trick to prevent Selenium falsely reporting a cross // domain cookie attempt LOG.info("Getting: " + url + " with cookieName: " + cookieName + " and cookieValue: " + cookieValue); driver.get(url + "/404.html"); // this should display 404 not found driver.manage().deleteAllCookies(); driver.manage().addCookie(new Cookie(cookieName, cookieValue)); driver.get(url); }
java
public void goToUrlWithCookie(final String url, final String cookieName, final String cookieValue) { // we'll do a trick to prevent Selenium falsely reporting a cross // domain cookie attempt LOG.info("Getting: " + url + " with cookieName: " + cookieName + " and cookieValue: " + cookieValue); driver.get(url + "/404.html"); // this should display 404 not found driver.manage().deleteAllCookies(); driver.manage().addCookie(new Cookie(cookieName, cookieValue)); driver.get(url); }
[ "public", "void", "goToUrlWithCookie", "(", "final", "String", "url", ",", "final", "String", "cookieName", ",", "final", "String", "cookieValue", ")", "{", "// we'll do a trick to prevent Selenium falsely reporting a cross", "// domain cookie attempt", "LOG", ".", "info", "(", "\"Getting: \"", "+", "url", "+", "\" with cookieName: \"", "+", "cookieName", "+", "\" and cookieValue: \"", "+", "cookieValue", ")", ";", "driver", ".", "get", "(", "url", "+", "\"/404.html\"", ")", ";", "// this should display 404 not found", "driver", ".", "manage", "(", ")", ".", "deleteAllCookies", "(", ")", ";", "driver", ".", "manage", "(", ")", ".", "addCookie", "(", "new", "Cookie", "(", "cookieName", ",", "cookieValue", ")", ")", ";", "driver", ".", "get", "(", "url", ")", ";", "}" ]
Opens the specified URL using the specified cookie. @param url the url you want to open @param cookieName the cookie name @param cookieValue the cookie value
[ "Opens", "the", "specified", "URL", "using", "the", "specified", "cookie", "." ]
train
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/webdriver/WebDriverHelper.java#L1115-L1125
kirgor/enklib
rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java
RESTClient.postWithListResult
public <T> EntityResponse<List<T>> postWithListResult(Class<T> entityClass, String path, Object payload, Map<String, String> headers) throws IOException, RESTException { """ Performs POST request, while expected response entity is a list of specified type. @param entityClass Class, which contains expected response entity fields. @param path Request path. @param payload Entity, which will be used as request payload. @param headers Map of HTTP request headers. @param <T> Type of class, which contains expected response entity fields. @throws IOException If error during HTTP connection or entity parsing occurs. @throws RESTException If HTTP response code is non OK. """ return postWithListResultInternal(entityClass, payload, new HttpPost(baseUrl + path), headers); }
java
public <T> EntityResponse<List<T>> postWithListResult(Class<T> entityClass, String path, Object payload, Map<String, String> headers) throws IOException, RESTException { return postWithListResultInternal(entityClass, payload, new HttpPost(baseUrl + path), headers); }
[ "public", "<", "T", ">", "EntityResponse", "<", "List", "<", "T", ">", ">", "postWithListResult", "(", "Class", "<", "T", ">", "entityClass", ",", "String", "path", ",", "Object", "payload", ",", "Map", "<", "String", ",", "String", ">", "headers", ")", "throws", "IOException", ",", "RESTException", "{", "return", "postWithListResultInternal", "(", "entityClass", ",", "payload", ",", "new", "HttpPost", "(", "baseUrl", "+", "path", ")", ",", "headers", ")", ";", "}" ]
Performs POST request, while expected response entity is a list of specified type. @param entityClass Class, which contains expected response entity fields. @param path Request path. @param payload Entity, which will be used as request payload. @param headers Map of HTTP request headers. @param <T> Type of class, which contains expected response entity fields. @throws IOException If error during HTTP connection or entity parsing occurs. @throws RESTException If HTTP response code is non OK.
[ "Performs", "POST", "request", "while", "expected", "response", "entity", "is", "a", "list", "of", "specified", "type", "." ]
train
https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/rest/src/main/java/com/kirgor/enklib/rest/RESTClient.java#L262-L264
apiman/apiman
gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/CachingJdbcRegistry.java
CachingJdbcRegistry.getApi
protected Api getApi(String orgId, String apiId, String version) throws SQLException { """ Gets the api either from the cache or from ES. @param orgId @param apiId @param version """ String apiIdx = getApiId(orgId, apiId, version); Api api; synchronized (mutex) { api = apiCache.get(apiIdx); } if (api == null) { api = super.getApiInternal(orgId, apiId, version); synchronized (mutex) { if (api != null) { apiCache.put(apiIdx, api); } } } return api; }
java
protected Api getApi(String orgId, String apiId, String version) throws SQLException { String apiIdx = getApiId(orgId, apiId, version); Api api; synchronized (mutex) { api = apiCache.get(apiIdx); } if (api == null) { api = super.getApiInternal(orgId, apiId, version); synchronized (mutex) { if (api != null) { apiCache.put(apiIdx, api); } } } return api; }
[ "protected", "Api", "getApi", "(", "String", "orgId", ",", "String", "apiId", ",", "String", "version", ")", "throws", "SQLException", "{", "String", "apiIdx", "=", "getApiId", "(", "orgId", ",", "apiId", ",", "version", ")", ";", "Api", "api", ";", "synchronized", "(", "mutex", ")", "{", "api", "=", "apiCache", ".", "get", "(", "apiIdx", ")", ";", "}", "if", "(", "api", "==", "null", ")", "{", "api", "=", "super", ".", "getApiInternal", "(", "orgId", ",", "apiId", ",", "version", ")", ";", "synchronized", "(", "mutex", ")", "{", "if", "(", "api", "!=", "null", ")", "{", "apiCache", ".", "put", "(", "apiIdx", ",", "api", ")", ";", "}", "}", "}", "return", "api", ";", "}" ]
Gets the api either from the cache or from ES. @param orgId @param apiId @param version
[ "Gets", "the", "api", "either", "from", "the", "cache", "or", "from", "ES", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/CachingJdbcRegistry.java#L128-L145
lessthanoptimal/ejml
main/ejml-zdense/src/org/ejml/dense/row/SpecializedOps_ZDRM.java
SpecializedOps_ZDRM.pivotMatrix
public static ZMatrixRMaj pivotMatrix(ZMatrixRMaj ret, int pivots[], int numPivots, boolean transposed ) { """ <p> Creates a pivot matrix that exchanges the rows in a matrix: <br> A' = P*A<br> </p> <p> For example, if element 0 in 'pivots' is 2 then the first row in A' will be the 3rd row in A. </p> @param ret If null then a new matrix is declared otherwise the results are written to it. Is modified. @param pivots Specifies the new order of rows in a matrix. @param numPivots How many elements in pivots are being used. @param transposed If the transpose of the matrix is returned. @return A pivot matrix. """ if( ret == null ) { ret = new ZMatrixRMaj(numPivots, numPivots); } else { if( ret.numCols != numPivots || ret.numRows != numPivots ) throw new IllegalArgumentException("Unexpected matrix dimension"); CommonOps_ZDRM.fill(ret, 0,0); } if( transposed ) { for( int i = 0; i < numPivots; i++ ) { ret.set(pivots[i],i,1,0); } } else { for( int i = 0; i < numPivots; i++ ) { ret.set(i,pivots[i],1,0); } } return ret; }
java
public static ZMatrixRMaj pivotMatrix(ZMatrixRMaj ret, int pivots[], int numPivots, boolean transposed ) { if( ret == null ) { ret = new ZMatrixRMaj(numPivots, numPivots); } else { if( ret.numCols != numPivots || ret.numRows != numPivots ) throw new IllegalArgumentException("Unexpected matrix dimension"); CommonOps_ZDRM.fill(ret, 0,0); } if( transposed ) { for( int i = 0; i < numPivots; i++ ) { ret.set(pivots[i],i,1,0); } } else { for( int i = 0; i < numPivots; i++ ) { ret.set(i,pivots[i],1,0); } } return ret; }
[ "public", "static", "ZMatrixRMaj", "pivotMatrix", "(", "ZMatrixRMaj", "ret", ",", "int", "pivots", "[", "]", ",", "int", "numPivots", ",", "boolean", "transposed", ")", "{", "if", "(", "ret", "==", "null", ")", "{", "ret", "=", "new", "ZMatrixRMaj", "(", "numPivots", ",", "numPivots", ")", ";", "}", "else", "{", "if", "(", "ret", ".", "numCols", "!=", "numPivots", "||", "ret", ".", "numRows", "!=", "numPivots", ")", "throw", "new", "IllegalArgumentException", "(", "\"Unexpected matrix dimension\"", ")", ";", "CommonOps_ZDRM", ".", "fill", "(", "ret", ",", "0", ",", "0", ")", ";", "}", "if", "(", "transposed", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numPivots", ";", "i", "++", ")", "{", "ret", ".", "set", "(", "pivots", "[", "i", "]", ",", "i", ",", "1", ",", "0", ")", ";", "}", "}", "else", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numPivots", ";", "i", "++", ")", "{", "ret", ".", "set", "(", "i", ",", "pivots", "[", "i", "]", ",", "1", ",", "0", ")", ";", "}", "}", "return", "ret", ";", "}" ]
<p> Creates a pivot matrix that exchanges the rows in a matrix: <br> A' = P*A<br> </p> <p> For example, if element 0 in 'pivots' is 2 then the first row in A' will be the 3rd row in A. </p> @param ret If null then a new matrix is declared otherwise the results are written to it. Is modified. @param pivots Specifies the new order of rows in a matrix. @param numPivots How many elements in pivots are being used. @param transposed If the transpose of the matrix is returned. @return A pivot matrix.
[ "<p", ">", "Creates", "a", "pivot", "matrix", "that", "exchanges", "the", "rows", "in", "a", "matrix", ":", "<br", ">", "A", "=", "P", "*", "A<br", ">", "<", "/", "p", ">", "<p", ">", "For", "example", "if", "element", "0", "in", "pivots", "is", "2", "then", "the", "first", "row", "in", "A", "will", "be", "the", "3rd", "row", "in", "A", ".", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-zdense/src/org/ejml/dense/row/SpecializedOps_ZDRM.java#L93-L114
hawkular/hawkular-agent
hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SecurityDomainJBossASClient.java
SecurityDomainJBossASClient.removeSecurityDomain
public void removeSecurityDomain(String securityDomainName) throws Exception { """ Convenience method that removes a security domain by name. Useful when changing the characteristics of the login modules. @param securityDomainName the name of the new security domain @throws Exception if failed to remove the security domain """ // If not there just return if (!isSecurityDomain(securityDomainName)) { return; } final Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName); ModelNode removeSecurityDomainNode = createRequest(REMOVE, addr); final ModelNode results = execute(removeSecurityDomainNode); if (!isSuccess(results)) { throw new FailureException(results, "Failed to remove security domain [" + securityDomainName + "]"); } return; }
java
public void removeSecurityDomain(String securityDomainName) throws Exception { // If not there just return if (!isSecurityDomain(securityDomainName)) { return; } final Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, securityDomainName); ModelNode removeSecurityDomainNode = createRequest(REMOVE, addr); final ModelNode results = execute(removeSecurityDomainNode); if (!isSuccess(results)) { throw new FailureException(results, "Failed to remove security domain [" + securityDomainName + "]"); } return; }
[ "public", "void", "removeSecurityDomain", "(", "String", "securityDomainName", ")", "throws", "Exception", "{", "// If not there just return", "if", "(", "!", "isSecurityDomain", "(", "securityDomainName", ")", ")", "{", "return", ";", "}", "final", "Address", "addr", "=", "Address", ".", "root", "(", ")", ".", "add", "(", "SUBSYSTEM", ",", "SUBSYSTEM_SECURITY", ",", "SECURITY_DOMAIN", ",", "securityDomainName", ")", ";", "ModelNode", "removeSecurityDomainNode", "=", "createRequest", "(", "REMOVE", ",", "addr", ")", ";", "final", "ModelNode", "results", "=", "execute", "(", "removeSecurityDomainNode", ")", ";", "if", "(", "!", "isSuccess", "(", "results", ")", ")", "{", "throw", "new", "FailureException", "(", "results", ",", "\"Failed to remove security domain [\"", "+", "securityDomainName", "+", "\"]\"", ")", ";", "}", "return", ";", "}" ]
Convenience method that removes a security domain by name. Useful when changing the characteristics of the login modules. @param securityDomainName the name of the new security domain @throws Exception if failed to remove the security domain
[ "Convenience", "method", "that", "removes", "a", "security", "domain", "by", "name", ".", "Useful", "when", "changing", "the", "characteristics", "of", "the", "login", "modules", "." ]
train
https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-dmr-client/src/main/java/org/hawkular/dmrclient/SecurityDomainJBossASClient.java#L247-L263
statefulj/statefulj
statefulj-persistence/statefulj-persistence-jpa/src/main/java/org/statefulj/persistence/jpa/JPAPerister.java
JPAPerister.setCurrent
@Override public void setCurrent(T stateful, State<T> current, State<T> next) throws StaleStateException { """ Set the current State. This method will ensure that the state in the db matches the expected current state. If not, it will throw a StateStateException @param stateful Stateful Entity @param current Expected current State @param next The value of the next State @throws StaleStateException thrown if the value of the State does not equal to the provided current State """ try { // Has this Entity been persisted to the database? // Object id = getId(stateful); if (id != null && entityManager.contains(stateful)) { updateStateInDB(stateful, current, next, id); setState(stateful, next.getName()); } else { updateStateInMemory(stateful, current, next); } } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
java
@Override public void setCurrent(T stateful, State<T> current, State<T> next) throws StaleStateException { try { // Has this Entity been persisted to the database? // Object id = getId(stateful); if (id != null && entityManager.contains(stateful)) { updateStateInDB(stateful, current, next, id); setState(stateful, next.getName()); } else { updateStateInMemory(stateful, current, next); } } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
[ "@", "Override", "public", "void", "setCurrent", "(", "T", "stateful", ",", "State", "<", "T", ">", "current", ",", "State", "<", "T", ">", "next", ")", "throws", "StaleStateException", "{", "try", "{", "// Has this Entity been persisted to the database?", "//", "Object", "id", "=", "getId", "(", "stateful", ")", ";", "if", "(", "id", "!=", "null", "&&", "entityManager", ".", "contains", "(", "stateful", ")", ")", "{", "updateStateInDB", "(", "stateful", ",", "current", ",", "next", ",", "id", ")", ";", "setState", "(", "stateful", ",", "next", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "updateStateInMemory", "(", "stateful", ",", "current", ",", "next", ")", ";", "}", "}", "catch", "(", "NoSuchFieldException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "SecurityException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Set the current State. This method will ensure that the state in the db matches the expected current state. If not, it will throw a StateStateException @param stateful Stateful Entity @param current Expected current State @param next The value of the next State @throws StaleStateException thrown if the value of the State does not equal to the provided current State
[ "Set", "the", "current", "State", ".", "This", "method", "will", "ensure", "that", "the", "state", "in", "the", "db", "matches", "the", "expected", "current", "state", ".", "If", "not", "it", "will", "throw", "a", "StateStateException" ]
train
https://github.com/statefulj/statefulj/blob/d3459b3cb12bd508643027743401484a231e5fa1/statefulj-persistence/statefulj-persistence-jpa/src/main/java/org/statefulj/persistence/jpa/JPAPerister.java#L78-L100
dwdyer/watchmaker
examples/src/java/main/org/uncommons/watchmaker/examples/geneticprogramming/GeneticProgrammingExample.java
GeneticProgrammingExample.evolveProgram
public static Node evolveProgram(Map<double[], Double> data) { """ Evolve a function to fit the specified data. @param data A map from input values to expected output values. @return A program that generates the correct outputs for all specified sets of input. """ TreeFactory factory = new TreeFactory(2, // Number of parameters passed into each program. 4, // Maximum depth of generated trees. Probability.EVENS, // Probability that a node is a function node. new Probability(0.6d)); // Probability that other nodes are params rather than constants. List<EvolutionaryOperator<Node>> operators = new ArrayList<EvolutionaryOperator<Node>>(3); operators.add(new TreeMutation(factory, new Probability(0.4d))); operators.add(new TreeCrossover()); operators.add(new Simplification()); TreeEvaluator evaluator = new TreeEvaluator(data); EvolutionEngine<Node> engine = new GenerationalEvolutionEngine<Node>(factory, new EvolutionPipeline<Node>(operators), evaluator, new RouletteWheelSelection(), new MersenneTwisterRNG()); engine.addEvolutionObserver(new EvolutionLogger<Node>()); return engine.evolve(1000, 5, new TargetFitness(0d, evaluator.isNatural())); }
java
public static Node evolveProgram(Map<double[], Double> data) { TreeFactory factory = new TreeFactory(2, // Number of parameters passed into each program. 4, // Maximum depth of generated trees. Probability.EVENS, // Probability that a node is a function node. new Probability(0.6d)); // Probability that other nodes are params rather than constants. List<EvolutionaryOperator<Node>> operators = new ArrayList<EvolutionaryOperator<Node>>(3); operators.add(new TreeMutation(factory, new Probability(0.4d))); operators.add(new TreeCrossover()); operators.add(new Simplification()); TreeEvaluator evaluator = new TreeEvaluator(data); EvolutionEngine<Node> engine = new GenerationalEvolutionEngine<Node>(factory, new EvolutionPipeline<Node>(operators), evaluator, new RouletteWheelSelection(), new MersenneTwisterRNG()); engine.addEvolutionObserver(new EvolutionLogger<Node>()); return engine.evolve(1000, 5, new TargetFitness(0d, evaluator.isNatural())); }
[ "public", "static", "Node", "evolveProgram", "(", "Map", "<", "double", "[", "]", ",", "Double", ">", "data", ")", "{", "TreeFactory", "factory", "=", "new", "TreeFactory", "(", "2", ",", "// Number of parameters passed into each program.", "4", ",", "// Maximum depth of generated trees.", "Probability", ".", "EVENS", ",", "// Probability that a node is a function node.", "new", "Probability", "(", "0.6d", ")", ")", ";", "// Probability that other nodes are params rather than constants.", "List", "<", "EvolutionaryOperator", "<", "Node", ">", ">", "operators", "=", "new", "ArrayList", "<", "EvolutionaryOperator", "<", "Node", ">", ">", "(", "3", ")", ";", "operators", ".", "add", "(", "new", "TreeMutation", "(", "factory", ",", "new", "Probability", "(", "0.4d", ")", ")", ")", ";", "operators", ".", "add", "(", "new", "TreeCrossover", "(", ")", ")", ";", "operators", ".", "add", "(", "new", "Simplification", "(", ")", ")", ";", "TreeEvaluator", "evaluator", "=", "new", "TreeEvaluator", "(", "data", ")", ";", "EvolutionEngine", "<", "Node", ">", "engine", "=", "new", "GenerationalEvolutionEngine", "<", "Node", ">", "(", "factory", ",", "new", "EvolutionPipeline", "<", "Node", ">", "(", "operators", ")", ",", "evaluator", ",", "new", "RouletteWheelSelection", "(", ")", ",", "new", "MersenneTwisterRNG", "(", ")", ")", ";", "engine", ".", "addEvolutionObserver", "(", "new", "EvolutionLogger", "<", "Node", ">", "(", ")", ")", ";", "return", "engine", ".", "evolve", "(", "1000", ",", "5", ",", "new", "TargetFitness", "(", "0d", ",", "evaluator", ".", "isNatural", "(", ")", ")", ")", ";", "}" ]
Evolve a function to fit the specified data. @param data A map from input values to expected output values. @return A program that generates the correct outputs for all specified sets of input.
[ "Evolve", "a", "function", "to", "fit", "the", "specified", "data", "." ]
train
https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/examples/src/java/main/org/uncommons/watchmaker/examples/geneticprogramming/GeneticProgrammingExample.java#L66-L84