repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
192
func_name
stringlengths
5
108
whole_func_string
stringlengths
75
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.91k
func_code_tokens
listlengths
21
629
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
111
306
fernandospr/javapns-jdk16
src/main/java/javapns/notification/Payload.java
Payload.addCustomDictionary
public void addCustomDictionary(String name, List values) throws JSONException { logger.debug("Adding custom Dictionary [" + name + "] = (list)"); put(name, values, payload, false); }
java
public void addCustomDictionary(String name, List values) throws JSONException { logger.debug("Adding custom Dictionary [" + name + "] = (list)"); put(name, values, payload, false); }
[ "public", "void", "addCustomDictionary", "(", "String", "name", ",", "List", "values", ")", "throws", "JSONException", "{", "logger", ".", "debug", "(", "\"Adding custom Dictionary [\"", "+", "name", "+", "\"] = (list)\"", ")", ";", "put", "(", "name", ",", "v...
Add a custom dictionnary with multiple values @param name @param values @throws JSONException
[ "Add", "a", "custom", "dictionnary", "with", "multiple", "values" ]
train
https://github.com/fernandospr/javapns-jdk16/blob/84de6d9328ab01af92f77cc60c4554de02420909/src/main/java/javapns/notification/Payload.java#L101-L104
groundupworks/wings
wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookSettings.java
FacebookSettings.newInstance
static FacebookSettings newInstance(int destinationId, String accountName, String albumName, String albumGraphPath, String pageAccessToken, String photoPrivacy) { FacebookSettings settings = null; if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(albumName) && !TextUtils.isEmpty(albumGraphPath)) { if (destinationId == FacebookEndpoint.DestinationId.PROFILE) { settings = new FacebookSettings(destinationId, accountName, albumName, albumGraphPath, pageAccessToken, photoPrivacy); } else if ((destinationId == FacebookEndpoint.DestinationId.PAGE || destinationId == FacebookEndpoint.DestinationId.PAGE_ALBUM) && !TextUtils.isEmpty(pageAccessToken)) { settings = new FacebookSettings(destinationId, accountName, albumName, albumGraphPath, pageAccessToken, photoPrivacy); } } return settings; }
java
static FacebookSettings newInstance(int destinationId, String accountName, String albumName, String albumGraphPath, String pageAccessToken, String photoPrivacy) { FacebookSettings settings = null; if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(albumName) && !TextUtils.isEmpty(albumGraphPath)) { if (destinationId == FacebookEndpoint.DestinationId.PROFILE) { settings = new FacebookSettings(destinationId, accountName, albumName, albumGraphPath, pageAccessToken, photoPrivacy); } else if ((destinationId == FacebookEndpoint.DestinationId.PAGE || destinationId == FacebookEndpoint.DestinationId.PAGE_ALBUM) && !TextUtils.isEmpty(pageAccessToken)) { settings = new FacebookSettings(destinationId, accountName, albumName, albumGraphPath, pageAccessToken, photoPrivacy); } } return settings; }
[ "static", "FacebookSettings", "newInstance", "(", "int", "destinationId", ",", "String", "accountName", ",", "String", "albumName", ",", "String", "albumGraphPath", ",", "String", "pageAccessToken", ",", "String", "photoPrivacy", ")", "{", "FacebookSettings", "setting...
Creates a new {@link FacebookSettings} instance. @param destinationId the destination id. @param accountName the user name associated with the account. @param albumName the name of the album to share to. @param albumGraphPath the graph path of the album to share to. @param pageAccessToken the Page access token. Only used for sharing to Pages. May be null. @param photoPrivacy the privacy level of shared photos. Only used for albums with 'custom' privacy level. May be null. @return a new {@link FacebookSettings} instance; or null if any of the params are invalid.
[ "Creates", "a", "new", "{", "@link", "FacebookSettings", "}", "instance", "." ]
train
https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookSettings.java#L96-L109
michael-rapp/AndroidUtil
library/src/main/java/de/mrapp/android/util/view/HeaderAndFooterGridView.java
HeaderAndFooterGridView.addFooterView
public final void addFooterView(@NonNull final View view, @Nullable final Object data, final boolean selectable) { Condition.INSTANCE.ensureNotNull(view, "The view may not be null"); footers.add(new FullWidthItem(view, data, selectable)); notifyDataSetChanged(); }
java
public final void addFooterView(@NonNull final View view, @Nullable final Object data, final boolean selectable) { Condition.INSTANCE.ensureNotNull(view, "The view may not be null"); footers.add(new FullWidthItem(view, data, selectable)); notifyDataSetChanged(); }
[ "public", "final", "void", "addFooterView", "(", "@", "NonNull", "final", "View", "view", ",", "@", "Nullable", "final", "Object", "data", ",", "final", "boolean", "selectable", ")", "{", "Condition", ".", "INSTANCE", ".", "ensureNotNull", "(", "view", ",", ...
Adds a fixed view to appear at the bottom of the adapter view. If this method is called more than once, the views will appear in the order they were added. @param view The footer view, which should be added, as an instance of the class {@link View}. The view may not be null @param data The data, which should be associated with the footer view, as an instance of the class {@link Object}, or null, if no data should be associated with the view @param selectable True, if the footer view should be selectable, false otherwise
[ "Adds", "a", "fixed", "view", "to", "appear", "at", "the", "bottom", "of", "the", "adapter", "view", ".", "If", "this", "method", "is", "called", "more", "than", "once", "the", "views", "will", "appear", "in", "the", "order", "they", "were", "added", "...
train
https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/view/HeaderAndFooterGridView.java#L646-L651
apache/incubator-atlas
graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/GraphDbObjectFactory.java
GraphDbObjectFactory.createEdge
public static Titan1Edge createEdge(Titan1Graph graph, Edge source) { if (source == null) { return null; } return new Titan1Edge(graph, source); }
java
public static Titan1Edge createEdge(Titan1Graph graph, Edge source) { if (source == null) { return null; } return new Titan1Edge(graph, source); }
[ "public", "static", "Titan1Edge", "createEdge", "(", "Titan1Graph", "graph", ",", "Edge", "source", ")", "{", "if", "(", "source", "==", "null", ")", "{", "return", "null", ";", "}", "return", "new", "Titan1Edge", "(", "graph", ",", "source", ")", ";", ...
Creates a Titan1Edge that corresponds to the given Gremlin Edge. @param graph The graph the edge should be created in @param source The gremlin edge
[ "Creates", "a", "Titan1Edge", "that", "corresponds", "to", "the", "given", "Gremlin", "Edge", "." ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/GraphDbObjectFactory.java#L48-L54
ModeShape/modeshape
sequencers/modeshape-sequencer-xml/src/main/java/org/modeshape/sequencer/xml/XmlSequencerHandler.java
XmlSequencerHandler.endContent
protected void endContent() throws RepositoryException { // Process the content of the element ... String content = StringUtil.normalize(contentBuilder.toString()); // Null-out builder to setup for subsequent content. // Must be done before call to startElement below to prevent infinite loop. contentBuilder = null; // Skip if nothing in content but whitespace if (content.length() > 0) { // Create separate node for each content entry since entries can be interspersed amongst child elements startNode(XmlLexicon.ELEMENT_CONTENT, XmlLexicon.ELEMENT_CONTENT); currentNode.setProperty(XmlLexicon.ELEMENT_CONTENT, content); endNode(); } }
java
protected void endContent() throws RepositoryException { // Process the content of the element ... String content = StringUtil.normalize(contentBuilder.toString()); // Null-out builder to setup for subsequent content. // Must be done before call to startElement below to prevent infinite loop. contentBuilder = null; // Skip if nothing in content but whitespace if (content.length() > 0) { // Create separate node for each content entry since entries can be interspersed amongst child elements startNode(XmlLexicon.ELEMENT_CONTENT, XmlLexicon.ELEMENT_CONTENT); currentNode.setProperty(XmlLexicon.ELEMENT_CONTENT, content); endNode(); } }
[ "protected", "void", "endContent", "(", ")", "throws", "RepositoryException", "{", "// Process the content of the element ...", "String", "content", "=", "StringUtil", ".", "normalize", "(", "contentBuilder", ".", "toString", "(", ")", ")", ";", "// Null-out builder to ...
See if there is any element content that needs to be completed. @throws RepositoryException if there is a problem writing the content to the repository session
[ "See", "if", "there", "is", "any", "element", "content", "that", "needs", "to", "be", "completed", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-xml/src/main/java/org/modeshape/sequencer/xml/XmlSequencerHandler.java#L104-L117
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/PanButtonCollection.java
PanButtonCollection.accept
public void accept(PainterVisitor visitor, Object group, Bbox bounds, boolean recursive) { // Apply position on all pan buttons: applyPosition(); // Then render them: map.getVectorContext().drawGroup(group, this); map.getVectorContext().drawImage(this, background.getId(), background.getHref(), background.getBounds(), (PictureStyle) background.getStyle()); north.accept(visitor, group, bounds, recursive); east.accept(visitor, group, bounds, recursive); south.accept(visitor, group, bounds, recursive); west.accept(visitor, group, bounds, recursive); }
java
public void accept(PainterVisitor visitor, Object group, Bbox bounds, boolean recursive) { // Apply position on all pan buttons: applyPosition(); // Then render them: map.getVectorContext().drawGroup(group, this); map.getVectorContext().drawImage(this, background.getId(), background.getHref(), background.getBounds(), (PictureStyle) background.getStyle()); north.accept(visitor, group, bounds, recursive); east.accept(visitor, group, bounds, recursive); south.accept(visitor, group, bounds, recursive); west.accept(visitor, group, bounds, recursive); }
[ "public", "void", "accept", "(", "PainterVisitor", "visitor", ",", "Object", "group", ",", "Bbox", "bounds", ",", "boolean", "recursive", ")", "{", "// Apply position on all pan buttons:", "applyPosition", "(", ")", ";", "// Then render them:", "map", ".", "getVecto...
Apply the correct positions on all panning buttons, and render them.
[ "Apply", "the", "correct", "positions", "on", "all", "panning", "buttons", "and", "render", "them", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/paintable/mapaddon/PanButtonCollection.java#L104-L116
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.copyStream
public static void copyStream( InputStream in, File outputFile ) throws IOException { OutputStream os = new FileOutputStream( outputFile ); try { copyStreamUnsafelyUseWithCaution( in, os ); } finally { os.close (); } }
java
public static void copyStream( InputStream in, File outputFile ) throws IOException { OutputStream os = new FileOutputStream( outputFile ); try { copyStreamUnsafelyUseWithCaution( in, os ); } finally { os.close (); } }
[ "public", "static", "void", "copyStream", "(", "InputStream", "in", ",", "File", "outputFile", ")", "throws", "IOException", "{", "OutputStream", "os", "=", "new", "FileOutputStream", "(", "outputFile", ")", ";", "try", "{", "copyStreamUnsafelyUseWithCaution", "("...
Copies the content from in into outputFile. <p> <i>in</i> is not closed by this method.<br> It must be explicitly closed after this method is called. </p> @param in an input stream (not null) @param outputFile will be created if it does not exist @throws IOException if the file could not be created
[ "Copies", "the", "content", "from", "in", "into", "outputFile", ".", "<p", ">", "<i", ">", "in<", "/", "i", ">", "is", "not", "closed", "by", "this", "method", ".", "<br", ">", "It", "must", "be", "explicitly", "closed", "after", "this", "method", "i...
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L354-L361
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/list/AbstractList.java
AbstractList.beforeInsertAllOf
public void beforeInsertAllOf(int index, java.util.Collection collection) { this.beforeInsertDummies(index, collection.size()); this.replaceFromWith(index, collection); }
java
public void beforeInsertAllOf(int index, java.util.Collection collection) { this.beforeInsertDummies(index, collection.size()); this.replaceFromWith(index, collection); }
[ "public", "void", "beforeInsertAllOf", "(", "int", "index", ",", "java", ".", "util", ".", "Collection", "collection", ")", "{", "this", ".", "beforeInsertDummies", "(", "index", ",", "collection", ".", "size", "(", ")", ")", ";", "this", ".", "replaceFrom...
Inserts all elements of the specified collection before the specified position into the receiver. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). @param index index before which to insert first element from the specified collection. @param collection the collection to be inserted @exception ClassCastException if an element in the collection is not of the same parameter type of the receiver. @throws IndexOutOfBoundsException if <tt>index &lt; 0 || index &gt; size()</tt>.
[ "Inserts", "all", "elements", "of", "the", "specified", "collection", "before", "the", "specified", "position", "into", "the", "receiver", ".", "Shifts", "the", "element", "currently", "at", "that", "position", "(", "if", "any", ")", "and", "any", "subsequent"...
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/AbstractList.java#L49-L52
drewnoakes/metadata-extractor
Source/com/drew/metadata/xmp/XmpReader.java
XmpReader.readJpegSegments
public void readJpegSegments(@NotNull Iterable<byte[]> segments, @NotNull Metadata metadata, @NotNull JpegSegmentType segmentType) { final int preambleLength = XMP_JPEG_PREAMBLE.length(); final int extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length(); String extendedXMPGUID = null; byte[] extendedXMPBuffer = null; for (byte[] segmentBytes : segments) { // XMP in a JPEG file has an identifying preamble which is not valid XML if (segmentBytes.length >= preambleLength) { // NOTE we expect the full preamble here, but some images (such as that reported on GitHub #102) // start with "XMP\0://ns.adobe.com/xap/1.0/" which appears to be an error but is easily recovered // from. In such cases, the actual XMP data begins at the same offset. if (XMP_JPEG_PREAMBLE.equalsIgnoreCase(new String(segmentBytes, 0, preambleLength)) || "XMP".equalsIgnoreCase(new String(segmentBytes, 0, 3))) { byte[] xmlBytes = new byte[segmentBytes.length - preambleLength]; System.arraycopy(segmentBytes, preambleLength, xmlBytes, 0, xmlBytes.length); extract(xmlBytes, metadata); // Check in the Standard XMP if there should be a Extended XMP part in other chunks. extendedXMPGUID = getExtendedXMPGUID(metadata); continue; } } // If we know that there's Extended XMP chunks, look for them. if (extendedXMPGUID != null && segmentBytes.length >= extensionPreambleLength && XMP_EXTENSION_JPEG_PREAMBLE.equalsIgnoreCase(new String(segmentBytes, 0, extensionPreambleLength))) { extendedXMPBuffer = processExtendedXMPChunk(metadata, segmentBytes, extendedXMPGUID, extendedXMPBuffer); } } // Now that the Extended XMP chunks have been concatenated, let's parse and merge with the Standard XMP. if (extendedXMPBuffer != null) { extract(extendedXMPBuffer, metadata); } }
java
public void readJpegSegments(@NotNull Iterable<byte[]> segments, @NotNull Metadata metadata, @NotNull JpegSegmentType segmentType) { final int preambleLength = XMP_JPEG_PREAMBLE.length(); final int extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length(); String extendedXMPGUID = null; byte[] extendedXMPBuffer = null; for (byte[] segmentBytes : segments) { // XMP in a JPEG file has an identifying preamble which is not valid XML if (segmentBytes.length >= preambleLength) { // NOTE we expect the full preamble here, but some images (such as that reported on GitHub #102) // start with "XMP\0://ns.adobe.com/xap/1.0/" which appears to be an error but is easily recovered // from. In such cases, the actual XMP data begins at the same offset. if (XMP_JPEG_PREAMBLE.equalsIgnoreCase(new String(segmentBytes, 0, preambleLength)) || "XMP".equalsIgnoreCase(new String(segmentBytes, 0, 3))) { byte[] xmlBytes = new byte[segmentBytes.length - preambleLength]; System.arraycopy(segmentBytes, preambleLength, xmlBytes, 0, xmlBytes.length); extract(xmlBytes, metadata); // Check in the Standard XMP if there should be a Extended XMP part in other chunks. extendedXMPGUID = getExtendedXMPGUID(metadata); continue; } } // If we know that there's Extended XMP chunks, look for them. if (extendedXMPGUID != null && segmentBytes.length >= extensionPreambleLength && XMP_EXTENSION_JPEG_PREAMBLE.equalsIgnoreCase(new String(segmentBytes, 0, extensionPreambleLength))) { extendedXMPBuffer = processExtendedXMPChunk(metadata, segmentBytes, extendedXMPGUID, extendedXMPBuffer); } } // Now that the Extended XMP chunks have been concatenated, let's parse and merge with the Standard XMP. if (extendedXMPBuffer != null) { extract(extendedXMPBuffer, metadata); } }
[ "public", "void", "readJpegSegments", "(", "@", "NotNull", "Iterable", "<", "byte", "[", "]", ">", "segments", ",", "@", "NotNull", "Metadata", "metadata", ",", "@", "NotNull", "JpegSegmentType", "segmentType", ")", "{", "final", "int", "preambleLength", "=", ...
Version specifically for dealing with XMP found in JPEG segments. This form of XMP has a peculiar preamble, which must be removed before parsing the XML. @param segments The byte array from which the metadata should be extracted. @param metadata The {@link Metadata} object into which extracted values should be merged. @param segmentType The {@link JpegSegmentType} being read.
[ "Version", "specifically", "for", "dealing", "with", "XMP", "found", "in", "JPEG", "segments", ".", "This", "form", "of", "XMP", "has", "a", "peculiar", "preamble", "which", "must", "be", "removed", "before", "parsing", "the", "XML", "." ]
train
https://github.com/drewnoakes/metadata-extractor/blob/a958e0b61b50e590731b3be1dca8df8e21ebd43c/Source/com/drew/metadata/xmp/XmpReader.java#L88-L126
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java
Form.setAnswer
public void setAnswer(String variable, List<? extends CharSequence> values) { if (!isSubmitType()) { throw new IllegalStateException("Cannot set an answer if the form is not of type " + "\"submit\""); } FormField field = getField(variable); if (field != null) { // Check that the field can accept a collection of values switch (field.getType()) { case jid_multi: case list_multi: case list_single: case text_multi: case hidden: break; default: throw new IllegalArgumentException("This field only accept list of values."); } // Clear the old values field.resetValues(); // Set the new values. The string representation of each value will be actually used. field.addValues(values); } else { throw new IllegalArgumentException("Couldn't find a field for the specified variable."); } }
java
public void setAnswer(String variable, List<? extends CharSequence> values) { if (!isSubmitType()) { throw new IllegalStateException("Cannot set an answer if the form is not of type " + "\"submit\""); } FormField field = getField(variable); if (field != null) { // Check that the field can accept a collection of values switch (field.getType()) { case jid_multi: case list_multi: case list_single: case text_multi: case hidden: break; default: throw new IllegalArgumentException("This field only accept list of values."); } // Clear the old values field.resetValues(); // Set the new values. The string representation of each value will be actually used. field.addValues(values); } else { throw new IllegalArgumentException("Couldn't find a field for the specified variable."); } }
[ "public", "void", "setAnswer", "(", "String", "variable", ",", "List", "<", "?", "extends", "CharSequence", ">", "values", ")", "{", "if", "(", "!", "isSubmitType", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Cannot set an answer if th...
Sets a new values to a given form's field. The field whose variable matches the requested variable will be completed with the specified values. If no field could be found for the specified variable then an exception will be raised.<p> The Objects contained in the List could be of any type. The String representation of them (i.e. #toString) will be actually used when sending the answer to the server. @param variable the variable that was completed. @param values the values that were answered. @throws IllegalStateException if the form is not of type "submit". @throws IllegalArgumentException if the form does not include the specified variable.
[ "Sets", "a", "new", "values", "to", "a", "given", "form", "s", "field", ".", "The", "field", "whose", "variable", "matches", "the", "requested", "variable", "will", "be", "completed", "with", "the", "specified", "values", ".", "If", "no", "field", "could",...
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/Form.java#L280-L306
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemWithParam.java
ElemWithParam.callChildVisitors
protected void callChildVisitors(XSLTVisitor visitor, boolean callAttrs) { if(callAttrs && (null != m_selectPattern)) m_selectPattern.getExpression().callVisitors(m_selectPattern, visitor); super.callChildVisitors(visitor, callAttrs); }
java
protected void callChildVisitors(XSLTVisitor visitor, boolean callAttrs) { if(callAttrs && (null != m_selectPattern)) m_selectPattern.getExpression().callVisitors(m_selectPattern, visitor); super.callChildVisitors(visitor, callAttrs); }
[ "protected", "void", "callChildVisitors", "(", "XSLTVisitor", "visitor", ",", "boolean", "callAttrs", ")", "{", "if", "(", "callAttrs", "&&", "(", "null", "!=", "m_selectPattern", ")", ")", "m_selectPattern", ".", "getExpression", "(", ")", ".", "callVisitors", ...
Call the children visitors. @param visitor The visitor whose appropriate method will be called.
[ "Call", "the", "children", "visitors", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemWithParam.java#L232-L237
bjuvensjo/rsimulator
rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/SimulatorAdapter.java
SimulatorAdapter.service
public Object service(String declaringClassCanonicalName, String methodName, Object[] arguments, String rootPath, boolean useRootRelativePath) throws Exception { log.debug("declaringClassCanonicalName: {}, methodName: {}, arguments: {}, rootPath: {}, useRootRelativePath: {}", new Object[]{declaringClassCanonicalName, methodName, arguments, rootPath, useRootRelativePath}); String rootRelativePath = useRootRelativePath ? getRootRelativePath(declaringClassCanonicalName, methodName) : ""; String simulatorRequest = createRequest(arguments); Optional<SimulatorResponse> simulatorResponseOptional = simulator.service(rootPath, rootRelativePath, simulatorRequest, CONTENT_TYPE); SimulatorResponse simulatorResponse = simulatorResponseOptional.get(); Object response = createResponse(simulatorResponse.getResponse()); if (response instanceof Throwable) { throw (Exception) response; } return response; }
java
public Object service(String declaringClassCanonicalName, String methodName, Object[] arguments, String rootPath, boolean useRootRelativePath) throws Exception { log.debug("declaringClassCanonicalName: {}, methodName: {}, arguments: {}, rootPath: {}, useRootRelativePath: {}", new Object[]{declaringClassCanonicalName, methodName, arguments, rootPath, useRootRelativePath}); String rootRelativePath = useRootRelativePath ? getRootRelativePath(declaringClassCanonicalName, methodName) : ""; String simulatorRequest = createRequest(arguments); Optional<SimulatorResponse> simulatorResponseOptional = simulator.service(rootPath, rootRelativePath, simulatorRequest, CONTENT_TYPE); SimulatorResponse simulatorResponse = simulatorResponseOptional.get(); Object response = createResponse(simulatorResponse.getResponse()); if (response instanceof Throwable) { throw (Exception) response; } return response; }
[ "public", "Object", "service", "(", "String", "declaringClassCanonicalName", ",", "String", "methodName", ",", "Object", "[", "]", "arguments", ",", "String", "rootPath", ",", "boolean", "useRootRelativePath", ")", "throws", "Exception", "{", "log", ".", "debug", ...
Returns some simulation response if found. @param declaringClassCanonicalName the class that declares the intercepted method @param methodName the name of the intercepted method @param arguments the arguments to the intercepted method @param rootPath the root path in which to (recursively) find simulator test data @param useRootRelativePath true if the declaringClassCanonicalName and methodName should be used as an relative path extension of rootPath, otherwise false @return some simulation response @throws Exception
[ "Returns", "some", "simulation", "response", "if", "found", "." ]
train
https://github.com/bjuvensjo/rsimulator/blob/fa98dea3e6cf8ef9d27516a1c5f95482412174a1/rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/SimulatorAdapter.java#L42-L58
biojava/biojava
biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java
FileDownloadUtils.downloadFile
public static void downloadFile(URL url, File destination) throws IOException { int count = 0; int maxTries = 10; int timeout = 60000; //60 sec File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); // Took following recipe from stackoverflow: // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java // It seems to be the most efficient way to transfer a file // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html ReadableByteChannel rbc = null; FileOutputStream fos = null; while (true) { try { URLConnection connection = prepareURLConnection(url.toString(), timeout); connection.connect(); InputStream inputStream = connection.getInputStream(); rbc = Channels.newChannel(inputStream); fos = new FileOutputStream(tempFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); break; } catch (SocketTimeoutException e) { if (++count == maxTries) throw e; } finally { if (rbc != null) { rbc.close(); } if (fos != null) { fos.close(); } } } logger.debug("Copying temp file {} to final location {}", tempFile, destination); copy(tempFile, destination); // delete the tmp file tempFile.delete(); }
java
public static void downloadFile(URL url, File destination) throws IOException { int count = 0; int maxTries = 10; int timeout = 60000; //60 sec File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); // Took following recipe from stackoverflow: // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java // It seems to be the most efficient way to transfer a file // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html ReadableByteChannel rbc = null; FileOutputStream fos = null; while (true) { try { URLConnection connection = prepareURLConnection(url.toString(), timeout); connection.connect(); InputStream inputStream = connection.getInputStream(); rbc = Channels.newChannel(inputStream); fos = new FileOutputStream(tempFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); break; } catch (SocketTimeoutException e) { if (++count == maxTries) throw e; } finally { if (rbc != null) { rbc.close(); } if (fos != null) { fos.close(); } } } logger.debug("Copying temp file {} to final location {}", tempFile, destination); copy(tempFile, destination); // delete the tmp file tempFile.delete(); }
[ "public", "static", "void", "downloadFile", "(", "URL", "url", ",", "File", "destination", ")", "throws", "IOException", "{", "int", "count", "=", "0", ";", "int", "maxTries", "=", "10", ";", "int", "timeout", "=", "60000", ";", "//60 sec", "File", "temp...
Download the content provided at URL url and store the result to a local file, using a temp file to cache the content in case something goes wrong in download @param url @param destination @throws IOException
[ "Download", "the", "content", "provided", "at", "URL", "url", "and", "store", "the", "result", "to", "a", "local", "file", "using", "a", "temp", "file", "to", "cache", "the", "content", "in", "case", "something", "goes", "wrong", "in", "download" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java#L110-L151
Waikato/moa
moa/src/main/java/moa/options/AbstractClassOption.java
AbstractClassOption.classToCLIString
public static String classToCLIString(Class<?> aClass, Class<?> requiredType) { String className = aClass.getName(); String packageName = requiredType.getPackage().getName(); if (className.startsWith(packageName)) { // cut off package name className = className.substring(packageName.length() + 1, className.length()); } else if (Task.class.isAssignableFrom(aClass)) { packageName = Task.class.getPackage().getName(); if (className.startsWith(packageName)) { // cut off task package name className = className.substring(packageName.length() + 1, className.length()); } } return className; }
java
public static String classToCLIString(Class<?> aClass, Class<?> requiredType) { String className = aClass.getName(); String packageName = requiredType.getPackage().getName(); if (className.startsWith(packageName)) { // cut off package name className = className.substring(packageName.length() + 1, className.length()); } else if (Task.class.isAssignableFrom(aClass)) { packageName = Task.class.getPackage().getName(); if (className.startsWith(packageName)) { // cut off task package name className = className.substring(packageName.length() + 1, className.length()); } } return className; }
[ "public", "static", "String", "classToCLIString", "(", "Class", "<", "?", ">", "aClass", ",", "Class", "<", "?", ">", "requiredType", ")", "{", "String", "className", "=", "aClass", ".", "getName", "(", ")", ";", "String", "packageName", "=", "requiredType...
Gets the command line interface text of the class. @param aClass the class @param requiredType the class type @return the command line interface text of the class
[ "Gets", "the", "command", "line", "interface", "text", "of", "the", "class", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/options/AbstractClassOption.java#L196-L211
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/validation/text/PlainTextMessageValidator.java
PlainTextMessageValidator.validateText
private void validateText(String receivedMessagePayload, String controlMessagePayload) { if (!StringUtils.hasText(controlMessagePayload)) { log.debug("Skip message payload validation as no control message was defined"); return; } else { Assert.isTrue(StringUtils.hasText(receivedMessagePayload), "Validation failed - " + "expected message contents, but received empty message!"); } if (!receivedMessagePayload.equals(controlMessagePayload)) { if (StringUtils.trimAllWhitespace(receivedMessagePayload).equals(StringUtils.trimAllWhitespace(controlMessagePayload))) { throw new ValidationException("Text values not equal (only whitespaces!), expected '" + controlMessagePayload + "' " + "but was '" + receivedMessagePayload + "'"); } else { throw new ValidationException("Text values not equal, expected '" + controlMessagePayload + "' " + "but was '" + receivedMessagePayload + "'"); } } }
java
private void validateText(String receivedMessagePayload, String controlMessagePayload) { if (!StringUtils.hasText(controlMessagePayload)) { log.debug("Skip message payload validation as no control message was defined"); return; } else { Assert.isTrue(StringUtils.hasText(receivedMessagePayload), "Validation failed - " + "expected message contents, but received empty message!"); } if (!receivedMessagePayload.equals(controlMessagePayload)) { if (StringUtils.trimAllWhitespace(receivedMessagePayload).equals(StringUtils.trimAllWhitespace(controlMessagePayload))) { throw new ValidationException("Text values not equal (only whitespaces!), expected '" + controlMessagePayload + "' " + "but was '" + receivedMessagePayload + "'"); } else { throw new ValidationException("Text values not equal, expected '" + controlMessagePayload + "' " + "but was '" + receivedMessagePayload + "'"); } } }
[ "private", "void", "validateText", "(", "String", "receivedMessagePayload", ",", "String", "controlMessagePayload", ")", "{", "if", "(", "!", "StringUtils", ".", "hasText", "(", "controlMessagePayload", ")", ")", "{", "log", ".", "debug", "(", "\"Skip message payl...
Compares two string with each other in order to validate plain text. @param receivedMessagePayload @param controlMessagePayload
[ "Compares", "two", "string", "with", "each", "other", "in", "order", "to", "validate", "plain", "text", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/validation/text/PlainTextMessageValidator.java#L168-L186
landawn/AbacusUtil
src/com/landawn/abacus/util/N.java
N.mapToChar
public static <T, E extends Exception> CharList mapToChar(final T[] a, final int fromIndex, final int toIndex, final Try.ToCharFunction<? super T, E> func) throws E { checkFromToIndex(fromIndex, toIndex, len(a)); N.checkArgNotNull(func); if (N.isNullOrEmpty(a)) { return new CharList(); } final CharList result = new CharList(toIndex - fromIndex); for (int i = fromIndex; i < toIndex; i++) { result.add(func.applyAsChar(a[i])); } return result; }
java
public static <T, E extends Exception> CharList mapToChar(final T[] a, final int fromIndex, final int toIndex, final Try.ToCharFunction<? super T, E> func) throws E { checkFromToIndex(fromIndex, toIndex, len(a)); N.checkArgNotNull(func); if (N.isNullOrEmpty(a)) { return new CharList(); } final CharList result = new CharList(toIndex - fromIndex); for (int i = fromIndex; i < toIndex; i++) { result.add(func.applyAsChar(a[i])); } return result; }
[ "public", "static", "<", "T", ",", "E", "extends", "Exception", ">", "CharList", "mapToChar", "(", "final", "T", "[", "]", "a", ",", "final", "int", "fromIndex", ",", "final", "int", "toIndex", ",", "final", "Try", ".", "ToCharFunction", "<", "?", "sup...
Mostly it's designed for one-step operation to complete the operation in one step. <code>java.util.stream.Stream</code> is preferred for multiple phases operation. @param a @param fromIndex @param toIndex @param func @return
[ "Mostly", "it", "s", "designed", "for", "one", "-", "step", "operation", "to", "complete", "the", "operation", "in", "one", "step", ".", "<code", ">", "java", ".", "util", ".", "stream", ".", "Stream<", "/", "code", ">", "is", "preferred", "for", "mult...
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L14601-L14617
deeplearning4j/deeplearning4j
datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java
SparkUtils.readObjectFromFile
public static <T> T readObjectFromFile(String path, Class<T> type, JavaSparkContext sc) throws IOException { return readObjectFromFile(path, type, sc.sc()); }
java
public static <T> T readObjectFromFile(String path, Class<T> type, JavaSparkContext sc) throws IOException { return readObjectFromFile(path, type, sc.sc()); }
[ "public", "static", "<", "T", ">", "T", "readObjectFromFile", "(", "String", "path", ",", "Class", "<", "T", ">", "type", ",", "JavaSparkContext", "sc", ")", "throws", "IOException", "{", "return", "readObjectFromFile", "(", "path", ",", "type", ",", "sc",...
Read an object from HDFS (or local) using default Java object serialization @param path File to read @param type Class of the object to read @param sc Spark context @param <T> Type of the object to read
[ "Read", "an", "object", "from", "HDFS", "(", "or", "local", ")", "using", "default", "Java", "object", "serialization" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java#L182-L184
fengwenyi/JavaLib
src/main/java/com/fengwenyi/javalib/util/RSAUtil.java
RSAUtil.verify
public static boolean verify(String content, String signature, String algorithm, String publicKey, String charset) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, UnsupportedEncodingException { Signature signTool = Signature.getInstance(algorithm); PublicKey key = commonGetPublickeyByText(publicKey); signTool.initVerify(key); if (StringUtils.isEmpty(charset)) { signTool.update(content.getBytes()); } else { signTool.update(content.getBytes(charset)); } return signTool.verify(Base64.altBase64ToByteArray(signature)); }
java
public static boolean verify(String content, String signature, String algorithm, String publicKey, String charset) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, UnsupportedEncodingException { Signature signTool = Signature.getInstance(algorithm); PublicKey key = commonGetPublickeyByText(publicKey); signTool.initVerify(key); if (StringUtils.isEmpty(charset)) { signTool.update(content.getBytes()); } else { signTool.update(content.getBytes(charset)); } return signTool.verify(Base64.altBase64ToByteArray(signature)); }
[ "public", "static", "boolean", "verify", "(", "String", "content", ",", "String", "signature", ",", "String", "algorithm", ",", "String", "publicKey", ",", "String", "charset", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", ",", "InvalidK...
验证签名 @param content 签名的内容 @param signature 签名 @param algorithm 签名算法 @param publicKey 公钥 @param charset 当签名内容为中文时,你可能需要指定编码 @return 该签名是否和内容匹配 @throws NoSuchAlgorithmException 签名算法异常 @throws InvalidKeySpecException 密钥格式不正确 @throws InvalidKeyException 密钥异常 @throws SignatureException 签名异常 @throws UnsupportedEncodingException 可能你指定的编码不能正确读取你要签名的内容
[ "验证签名" ]
train
https://github.com/fengwenyi/JavaLib/blob/14838b13fb11c024e41be766aa3e13ead4be1703/src/main/java/com/fengwenyi/javalib/util/RSAUtil.java#L233-L245
MenoData/Time4J
base/src/main/java/net/time4j/PlainDate.java
PlainDate.doAdd
static PlainDate doAdd( CalendarUnit unit, PlainDate context, long amount, int policy ) { switch (unit) { case MILLENNIA: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12 * 1000), policy); case CENTURIES: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12 * 100), policy); case DECADES: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12 * 10), policy); case YEARS: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12), policy); case QUARTERS: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 3), policy); case MONTHS: long months = MathUtils.safeAdd(context.getEpochMonths(), amount); return PlainDate.fromEpochMonths( context, months, context.dayOfMonth, policy); case WEEKS: return doAdd( CalendarUnit.DAYS, context, MathUtils.safeMultiply(amount, 7), policy); case DAYS: return addDays(context, amount); default: throw new UnsupportedOperationException(unit.name()); } }
java
static PlainDate doAdd( CalendarUnit unit, PlainDate context, long amount, int policy ) { switch (unit) { case MILLENNIA: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12 * 1000), policy); case CENTURIES: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12 * 100), policy); case DECADES: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12 * 10), policy); case YEARS: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 12), policy); case QUARTERS: return doAdd( CalendarUnit.MONTHS, context, MathUtils.safeMultiply(amount, 3), policy); case MONTHS: long months = MathUtils.safeAdd(context.getEpochMonths(), amount); return PlainDate.fromEpochMonths( context, months, context.dayOfMonth, policy); case WEEKS: return doAdd( CalendarUnit.DAYS, context, MathUtils.safeMultiply(amount, 7), policy); case DAYS: return addDays(context, amount); default: throw new UnsupportedOperationException(unit.name()); } }
[ "static", "PlainDate", "doAdd", "(", "CalendarUnit", "unit", ",", "PlainDate", "context", ",", "long", "amount", ",", "int", "policy", ")", "{", "switch", "(", "unit", ")", "{", "case", "MILLENNIA", ":", "return", "doAdd", "(", "CalendarUnit", ".", "MONTHS...
<p>Additionsmethode. </p> @param unit calendar unit @param context calendar date @param amount amount to be added @param policy overflow policy @return result of addition
[ "<p", ">", "Additionsmethode", ".", "<", "/", "p", ">" ]
train
https://github.com/MenoData/Time4J/blob/08b2eda6b2dbb140b92011cf7071bb087edd46a5/base/src/main/java/net/time4j/PlainDate.java#L1742-L1800
auth0/java-jwt
lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java
JsonNodeClaim.claimFromNode
static Claim claimFromNode(JsonNode node, ObjectReader objectReader) { if (node == null || node.isNull() || node.isMissingNode()) { return new NullClaim(); } return new JsonNodeClaim(node, objectReader); }
java
static Claim claimFromNode(JsonNode node, ObjectReader objectReader) { if (node == null || node.isNull() || node.isMissingNode()) { return new NullClaim(); } return new JsonNodeClaim(node, objectReader); }
[ "static", "Claim", "claimFromNode", "(", "JsonNode", "node", ",", "ObjectReader", "objectReader", ")", "{", "if", "(", "node", "==", "null", "||", "node", ".", "isNull", "(", ")", "||", "node", ".", "isMissingNode", "(", ")", ")", "{", "return", "new", ...
Helper method to create a Claim representation from the given JsonNode. @param node the JsonNode to convert into a Claim. @return a valid Claim instance. If the node is null or missing, a NullClaim will be returned.
[ "Helper", "method", "to", "create", "a", "Claim", "representation", "from", "the", "given", "JsonNode", "." ]
train
https://github.com/auth0/java-jwt/blob/890538970a9699b7251a4bfe4f26e8d7605ad530/lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java#L149-L154
otto-de/edison-microservice
edison-mongo/src/main/java/de/otto/edison/mongo/AbstractMongoRepository.java
AbstractMongoRepository.updateIfMatch
public UpdateIfMatchResult updateIfMatch(final V value, final String eTag) { return updateIfMatch(value, eTag, mongoProperties.getDefaultWriteTimeout(), TimeUnit.MILLISECONDS); }
java
public UpdateIfMatchResult updateIfMatch(final V value, final String eTag) { return updateIfMatch(value, eTag, mongoProperties.getDefaultWriteTimeout(), TimeUnit.MILLISECONDS); }
[ "public", "UpdateIfMatchResult", "updateIfMatch", "(", "final", "V", "value", ",", "final", "String", "eTag", ")", "{", "return", "updateIfMatch", "(", "value", ",", "eTag", ",", "mongoProperties", ".", "getDefaultWriteTimeout", "(", ")", ",", "TimeUnit", ".", ...
Updates the document if the document's ETAG is matching the given etag (conditional put). <p> Using this method requires that the document contains an "etag" field that is updated if the document is changed. </p> @param value the new value @param eTag the etag used for conditional update @return {@link UpdateIfMatchResult}
[ "Updates", "the", "document", "if", "the", "document", "s", "ETAG", "is", "matching", "the", "given", "etag", "(", "conditional", "put", ")", ".", "<p", ">", "Using", "this", "method", "requires", "that", "the", "document", "contains", "an", "etag", "field...
train
https://github.com/otto-de/edison-microservice/blob/89ecf0a0dee40977f004370b0b474a36c699e8a2/edison-mongo/src/main/java/de/otto/edison/mongo/AbstractMongoRepository.java#L230-L232
astrapi69/mystic-crypt
crypt-data/src/main/java/de/alpharogroup/crypto/factories/KeyPairFactory.java
KeyPairFactory.newKeyPair
public static KeyPair newKeyPair(final Algorithm algorithm, final KeySize keySize) throws NoSuchAlgorithmException, NoSuchProviderException { return newKeyPair(algorithm.getAlgorithm(), keySize.getKeySize()); }
java
public static KeyPair newKeyPair(final Algorithm algorithm, final KeySize keySize) throws NoSuchAlgorithmException, NoSuchProviderException { return newKeyPair(algorithm.getAlgorithm(), keySize.getKeySize()); }
[ "public", "static", "KeyPair", "newKeyPair", "(", "final", "Algorithm", "algorithm", ",", "final", "KeySize", "keySize", ")", "throws", "NoSuchAlgorithmException", ",", "NoSuchProviderException", "{", "return", "newKeyPair", "(", "algorithm", ".", "getAlgorithm", "(",...
Factory method for creating a new {@link KeyPair} from the given algorithm and {@link KeySize} @param algorithm the algorithm @param keySize the key size as enum @return the new {@link KeyPair} from the given salt and iteration count @throws NoSuchAlgorithmException is thrown if no Provider supports a KeyPairGeneratorSpi implementation for the specified algorithm @throws NoSuchProviderException is thrown if the specified provider is not registered in the security provider list
[ "Factory", "method", "for", "creating", "a", "new", "{", "@link", "KeyPair", "}", "from", "the", "given", "algorithm", "and", "{", "@link", "KeySize", "}" ]
train
https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/factories/KeyPairFactory.java#L68-L72
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java
PatternBox.hasNonSelfEffect
public static Pattern hasNonSelfEffect() { Pattern p = new Pattern(PhysicalEntity.class, "SPE"); p.add(peToER(), "SPE", "ER"); p.add(linkToComplex(), "SPE", "PE"); p.add(peToControl(), "PE", "Control"); p.add(controlToInter(), "Control", "Inter"); p.add(new NOT(participantER()), "Inter", "ER"); return p; }
java
public static Pattern hasNonSelfEffect() { Pattern p = new Pattern(PhysicalEntity.class, "SPE"); p.add(peToER(), "SPE", "ER"); p.add(linkToComplex(), "SPE", "PE"); p.add(peToControl(), "PE", "Control"); p.add(controlToInter(), "Control", "Inter"); p.add(new NOT(participantER()), "Inter", "ER"); return p; }
[ "public", "static", "Pattern", "hasNonSelfEffect", "(", ")", "{", "Pattern", "p", "=", "new", "Pattern", "(", "PhysicalEntity", ".", "class", ",", "\"SPE\"", ")", ";", "p", ".", "add", "(", "peToER", "(", ")", ",", "\"SPE\"", ",", "\"ER\"", ")", ";", ...
Pattern for detecting PhysicalEntity that controls a Conversion whose participants are not associated with the EntityReference of the initial PhysicalEntity. @return the pattern
[ "Pattern", "for", "detecting", "PhysicalEntity", "that", "controls", "a", "Conversion", "whose", "participants", "are", "not", "associated", "with", "the", "EntityReference", "of", "the", "initial", "PhysicalEntity", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/PatternBox.java#L844-L853
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java
HashMap.compareComparables
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); }
java
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); }
[ "@", "SuppressWarnings", "(", "{", "\"rawtypes\"", ",", "\"unchecked\"", "}", ")", "// for cast to Comparable", "static", "int", "compareComparables", "(", "Class", "<", "?", ">", "kc", ",", "Object", "k", ",", "Object", "x", ")", "{", "return", "(", "x", ...
Returns k.compareTo(x) if x matches kc (k's screened comparable class), else 0.
[ "Returns", "k", ".", "compareTo", "(", "x", ")", "if", "x", "matches", "kc", "(", "k", "s", "screened", "comparable", "class", ")", "else", "0", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java#L374-L378
looly/hutool
hutool-cron/src/main/java/cn/hutool/cron/pattern/CronPatternUtil.java
CronPatternUtil.matchedDates
public static List<Date> matchedDates(String patternStr, Date start, Date end, int count, boolean isMatchSecond) { return matchedDates(patternStr, start.getTime(), end.getTime(), count, isMatchSecond); }
java
public static List<Date> matchedDates(String patternStr, Date start, Date end, int count, boolean isMatchSecond) { return matchedDates(patternStr, start.getTime(), end.getTime(), count, isMatchSecond); }
[ "public", "static", "List", "<", "Date", ">", "matchedDates", "(", "String", "patternStr", ",", "Date", "start", ",", "Date", "end", ",", "int", "count", ",", "boolean", "isMatchSecond", ")", "{", "return", "matchedDates", "(", "patternStr", ",", "start", ...
列举指定日期范围内所有匹配表达式的日期 @param patternStr 表达式字符串 @param start 起始时间 @param end 结束时间 @param count 列举数量 @param isMatchSecond 是否匹配秒 @return 日期列表
[ "列举指定日期范围内所有匹配表达式的日期" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-cron/src/main/java/cn/hutool/cron/pattern/CronPatternUtil.java#L42-L44
Omertron/api-omdb
src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java
OmdbUrlBuilder.appendParam
private static void appendParam(final OmdbParameters params, final Param key, StringBuilder sb) { if (params.has(key)) { sb.append(DELIMITER_SUBSEQUENT).append(key.getValue()).append(params.get(key)); } }
java
private static void appendParam(final OmdbParameters params, final Param key, StringBuilder sb) { if (params.has(key)) { sb.append(DELIMITER_SUBSEQUENT).append(key.getValue()).append(params.get(key)); } }
[ "private", "static", "void", "appendParam", "(", "final", "OmdbParameters", "params", ",", "final", "Param", "key", ",", "StringBuilder", "sb", ")", "{", "if", "(", "params", ".", "has", "(", "key", ")", ")", "{", "sb", ".", "append", "(", "DELIMITER_SUB...
Append a parameter and value to the URL line @param params The parameter list @param key The parameter to add @param sb The StringBuilder instance to use
[ "Append", "a", "parameter", "and", "value", "to", "the", "URL", "line" ]
train
https://github.com/Omertron/api-omdb/blob/acb506ded2d7b8a4159b48161ffab8cb5b7bad44/src/main/java/com/omertron/omdbapi/tools/OmdbUrlBuilder.java#L121-L125
Esri/spatial-framework-for-hadoop
hive/src/main/java/com/esri/hadoop/hive/BinUtils.java
BinUtils.queryEnvelope
public void queryEnvelope(double x, double y, Envelope envelope) { double down = (extentMax - y) / binSize; double over = (x - extentMin) / binSize; double xmin = extentMin + (over * binSize); double xmax = xmin + binSize; double ymax = extentMax - (down * binSize); double ymin = ymax - binSize; envelope.setCoords(xmin, ymin, xmax, ymax); }
java
public void queryEnvelope(double x, double y, Envelope envelope) { double down = (extentMax - y) / binSize; double over = (x - extentMin) / binSize; double xmin = extentMin + (over * binSize); double xmax = xmin + binSize; double ymax = extentMax - (down * binSize); double ymin = ymax - binSize; envelope.setCoords(xmin, ymin, xmax, ymax); }
[ "public", "void", "queryEnvelope", "(", "double", "x", ",", "double", "y", ",", "Envelope", "envelope", ")", "{", "double", "down", "=", "(", "extentMax", "-", "y", ")", "/", "binSize", ";", "double", "over", "=", "(", "x", "-", "extentMin", ")", "/"...
Gets the envelope for the bin that contains the x,y coords. @param x @param y @param envelope
[ "Gets", "the", "envelope", "for", "the", "bin", "that", "contains", "the", "x", "y", "coords", "." ]
train
https://github.com/Esri/spatial-framework-for-hadoop/blob/00959d6b4465313c934aaa8aaf17b52d6c9c60d4/hive/src/main/java/com/esri/hadoop/hive/BinUtils.java#L65-L75
EdwardRaff/JSAT
JSAT/src/jsat/regression/StochasticGradientBoosting.java
StochasticGradientBoosting.getDerivativeFunc
private Function1D getDerivativeFunc(final RegressionDataSet backingResidsList, final Regressor h) { final Function1D fhPrime = (double x) -> { double c1 = x;//c2=c1-eps double eps = 1e-5; double c1Pc2 = c1 * 2 - eps;//c1+c2 = c1+c1-eps double result = 0; /* * Computing the estimate of the derivative directly, f'(x) approx = f(x)-f(x-eps) * * hEst is the output of the new regressor, target is the true residual target value * * So we have several * (hEst_i c1 - target)^2 - (hEst_i c2 -target)^2 //4 muls, 3 subs * Where c2 = c1-eps * Which simplifies to * (c1 - c2) hEst ((c1 + c2) hEst - 2 target) * = * eps hEst (c1Pc2 hEst - 2 target)//3 muls, 1 sub, 1 shift (mul by 2) * * because eps is on the outside and independent of each * individual summation, we can move it out and do the eps * multiplicatio ont he final result. Reducing us to * * 2 muls, 1 sub, 1 shift (mul by 2) * * per loop * * Which reduce computation, and allows us to get the result * in one pass of the data */ for(int i = 0; i < backingResidsList.size(); i++) { double hEst = h.regress(backingResidsList.getDataPoint(i)); double target = backingResidsList.getTargetValue(i); result += hEst * (c1Pc2 * hEst - 2 * target); } return result * eps; }; return fhPrime; }
java
private Function1D getDerivativeFunc(final RegressionDataSet backingResidsList, final Regressor h) { final Function1D fhPrime = (double x) -> { double c1 = x;//c2=c1-eps double eps = 1e-5; double c1Pc2 = c1 * 2 - eps;//c1+c2 = c1+c1-eps double result = 0; /* * Computing the estimate of the derivative directly, f'(x) approx = f(x)-f(x-eps) * * hEst is the output of the new regressor, target is the true residual target value * * So we have several * (hEst_i c1 - target)^2 - (hEst_i c2 -target)^2 //4 muls, 3 subs * Where c2 = c1-eps * Which simplifies to * (c1 - c2) hEst ((c1 + c2) hEst - 2 target) * = * eps hEst (c1Pc2 hEst - 2 target)//3 muls, 1 sub, 1 shift (mul by 2) * * because eps is on the outside and independent of each * individual summation, we can move it out and do the eps * multiplicatio ont he final result. Reducing us to * * 2 muls, 1 sub, 1 shift (mul by 2) * * per loop * * Which reduce computation, and allows us to get the result * in one pass of the data */ for(int i = 0; i < backingResidsList.size(); i++) { double hEst = h.regress(backingResidsList.getDataPoint(i)); double target = backingResidsList.getTargetValue(i); result += hEst * (c1Pc2 * hEst - 2 * target); } return result * eps; }; return fhPrime; }
[ "private", "Function1D", "getDerivativeFunc", "(", "final", "RegressionDataSet", "backingResidsList", ",", "final", "Regressor", "h", ")", "{", "final", "Function1D", "fhPrime", "=", "(", "double", "x", ")", "->", "{", "double", "c1", "=", "x", ";", "//c2=c1-e...
Returns a function object that approximates the derivative of the squared error of the Regressor as a function of the constant factor multiplied on the Regressor's output. @param backingResidsList the DataPointPair list of residuals @param h the regressor that is having the error of its output minimized @return a Function object approximating the derivative of the squared error
[ "Returns", "a", "function", "object", "that", "approximates", "the", "derivative", "of", "the", "squared", "error", "of", "the", "Regressor", "as", "a", "function", "of", "the", "constant", "factor", "multiplied", "on", "the", "Regressor", "s", "output", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/regression/StochasticGradientBoosting.java#L320-L365
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.projectiveToMetricKnownK
public static void projectiveToMetricKnownK( DMatrixRMaj cameraMatrix , DMatrixRMaj H , DMatrixRMaj K, Se3_F64 worldToView ) { DMatrixRMaj tmp = new DMatrixRMaj(3,4); CommonOps_DDRM.mult(cameraMatrix,H,tmp); DMatrixRMaj K_inv = new DMatrixRMaj(3,3); CommonOps_DDRM.invert(K,K_inv); DMatrixRMaj P = new DMatrixRMaj(3,4); CommonOps_DDRM.mult(K_inv,tmp,P); CommonOps_DDRM.extract(P,0,0,worldToView.R); worldToView.T.x = P.get(0,3); worldToView.T.y = P.get(1,3); worldToView.T.z = P.get(2,3); SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(true,true,true); DMatrixRMaj R = worldToView.R; if( !svd.decompose(R)) throw new RuntimeException("SVD Failed"); CommonOps_DDRM.multTransB(svd.getU(null,false),svd.getV(null,false),R); // determinant should be +1 double det = CommonOps_DDRM.det(R); if( det < 0 ) { CommonOps_DDRM.scale(-1,R); worldToView.T.scale(-1); } }
java
public static void projectiveToMetricKnownK( DMatrixRMaj cameraMatrix , DMatrixRMaj H , DMatrixRMaj K, Se3_F64 worldToView ) { DMatrixRMaj tmp = new DMatrixRMaj(3,4); CommonOps_DDRM.mult(cameraMatrix,H,tmp); DMatrixRMaj K_inv = new DMatrixRMaj(3,3); CommonOps_DDRM.invert(K,K_inv); DMatrixRMaj P = new DMatrixRMaj(3,4); CommonOps_DDRM.mult(K_inv,tmp,P); CommonOps_DDRM.extract(P,0,0,worldToView.R); worldToView.T.x = P.get(0,3); worldToView.T.y = P.get(1,3); worldToView.T.z = P.get(2,3); SingularValueDecomposition_F64<DMatrixRMaj> svd = DecompositionFactory_DDRM.svd(true,true,true); DMatrixRMaj R = worldToView.R; if( !svd.decompose(R)) throw new RuntimeException("SVD Failed"); CommonOps_DDRM.multTransB(svd.getU(null,false),svd.getV(null,false),R); // determinant should be +1 double det = CommonOps_DDRM.det(R); if( det < 0 ) { CommonOps_DDRM.scale(-1,R); worldToView.T.scale(-1); } }
[ "public", "static", "void", "projectiveToMetricKnownK", "(", "DMatrixRMaj", "cameraMatrix", ",", "DMatrixRMaj", "H", ",", "DMatrixRMaj", "K", ",", "Se3_F64", "worldToView", ")", "{", "DMatrixRMaj", "tmp", "=", "new", "DMatrixRMaj", "(", "3", ",", "4", ")", ";"...
Convert the projective camera matrix into a metric transform given the rectifying homography and a known calibration matrix. {@code P = K*[R|T]*H} where H is the inverse of the rectifying homography. @param cameraMatrix (Input) camera matrix. 3x4 @param H (Input) Rectifying homography. 4x4 @param K (Input) Known calibration matrix @param worldToView (Output) transform from world to camera view
[ "Convert", "the", "projective", "camera", "matrix", "into", "a", "metric", "transform", "given", "the", "rectifying", "homography", "and", "a", "known", "calibration", "matrix", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L1378-L1410
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/version/finder/DateTimeDatasetVersionFinder.java
DateTimeDatasetVersionFinder.getDatasetVersion
@Override public TimestampedDatasetVersion getDatasetVersion(Path pathRelativeToDatasetRoot, FileStatus versionFileStatus) { String dateTimeString = null; try { // pathRelativeToDatasetRoot can be daily/2016/03/02 or 2016/03/02. In either case we need to pick 2016/03/02 as version dateTimeString = StringUtils.substring(pathRelativeToDatasetRoot.toString(), pathRelativeToDatasetRoot.toString().length() - this.datePartitionPattern.length()); return new FileStatusTimestampedDatasetVersion(this.formatter.parseDateTime(dateTimeString), versionFileStatus); } catch (IllegalArgumentException exception) { LOGGER.warn(String.format( "Candidate dataset version with pathRelativeToDatasetRoot: %s has inferred dataTimeString:%s. " + "It does not match expected datetime pattern %s. Ignoring.", pathRelativeToDatasetRoot, dateTimeString, this.datePartitionPattern)); return null; } }
java
@Override public TimestampedDatasetVersion getDatasetVersion(Path pathRelativeToDatasetRoot, FileStatus versionFileStatus) { String dateTimeString = null; try { // pathRelativeToDatasetRoot can be daily/2016/03/02 or 2016/03/02. In either case we need to pick 2016/03/02 as version dateTimeString = StringUtils.substring(pathRelativeToDatasetRoot.toString(), pathRelativeToDatasetRoot.toString().length() - this.datePartitionPattern.length()); return new FileStatusTimestampedDatasetVersion(this.formatter.parseDateTime(dateTimeString), versionFileStatus); } catch (IllegalArgumentException exception) { LOGGER.warn(String.format( "Candidate dataset version with pathRelativeToDatasetRoot: %s has inferred dataTimeString:%s. " + "It does not match expected datetime pattern %s. Ignoring.", pathRelativeToDatasetRoot, dateTimeString, this.datePartitionPattern)); return null; } }
[ "@", "Override", "public", "TimestampedDatasetVersion", "getDatasetVersion", "(", "Path", "pathRelativeToDatasetRoot", ",", "FileStatus", "versionFileStatus", ")", "{", "String", "dateTimeString", "=", "null", ";", "try", "{", "// pathRelativeToDatasetRoot can be daily/2016/0...
Parse {@link org.joda.time.DateTime} from {@link org.apache.hadoop.fs.Path} using datetime pattern.
[ "Parse", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/version/finder/DateTimeDatasetVersionFinder.java#L120-L139
opsmatters/opsmatters-core
src/main/java/com/opsmatters/core/documents/Workbook.java
Workbook.createWorkbook
public static Workbook createWorkbook(FileFormat format, OutputStream os) throws IOException { return createWorkbook(format, os, null); }
java
public static Workbook createWorkbook(FileFormat format, OutputStream os) throws IOException { return createWorkbook(format, os, null); }
[ "public", "static", "Workbook", "createWorkbook", "(", "FileFormat", "format", ",", "OutputStream", "os", ")", "throws", "IOException", "{", "return", "createWorkbook", "(", "format", ",", "os", ",", "null", ")", ";", "}" ]
Creates a new workbook object. @param format The format of the workbook (XLS or XLSX) @param os The output stream to write the workbook to @return The new workbook created @throws IOException if the file cannot be written
[ "Creates", "a", "new", "workbook", "object", "." ]
train
https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/documents/Workbook.java#L114-L118
zxing/zxing
core/src/main/java/com/google/zxing/datamatrix/decoder/BitMatrixParser.java
BitMatrixParser.readModule
private boolean readModule(int row, int column, int numRows, int numColumns) { // Adjust the row and column indices based on boundary wrapping if (row < 0) { row += numRows; column += 4 - ((numRows + 4) & 0x07); } if (column < 0) { column += numColumns; row += 4 - ((numColumns + 4) & 0x07); } readMappingMatrix.set(column, row); return mappingBitMatrix.get(column, row); }
java
private boolean readModule(int row, int column, int numRows, int numColumns) { // Adjust the row and column indices based on boundary wrapping if (row < 0) { row += numRows; column += 4 - ((numRows + 4) & 0x07); } if (column < 0) { column += numColumns; row += 4 - ((numColumns + 4) & 0x07); } readMappingMatrix.set(column, row); return mappingBitMatrix.get(column, row); }
[ "private", "boolean", "readModule", "(", "int", "row", ",", "int", "column", ",", "int", "numRows", ",", "int", "numColumns", ")", "{", "// Adjust the row and column indices based on boundary wrapping", "if", "(", "row", "<", "0", ")", "{", "row", "+=", "numRows...
<p>Reads a bit of the mapping matrix accounting for boundary wrapping.</p> @param row Row to read in the mapping matrix @param column Column to read in the mapping matrix @param numRows Number of rows in the mapping matrix @param numColumns Number of columns in the mapping matrix @return value of the given bit in the mapping matrix
[ "<p", ">", "Reads", "a", "bit", "of", "the", "mapping", "matrix", "accounting", "for", "boundary", "wrapping", ".", "<", "/", "p", ">" ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/datamatrix/decoder/BitMatrixParser.java#L154-L166
Azure/azure-sdk-for-java
storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java
StorageAccountsInner.createOrUpdateManagementPoliciesAsync
public Observable<StorageAccountManagementPoliciesInner> createOrUpdateManagementPoliciesAsync(String resourceGroupName, String accountName, Object policy) { return createOrUpdateManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName, policy).map(new Func1<ServiceResponse<StorageAccountManagementPoliciesInner>, StorageAccountManagementPoliciesInner>() { @Override public StorageAccountManagementPoliciesInner call(ServiceResponse<StorageAccountManagementPoliciesInner> response) { return response.body(); } }); }
java
public Observable<StorageAccountManagementPoliciesInner> createOrUpdateManagementPoliciesAsync(String resourceGroupName, String accountName, Object policy) { return createOrUpdateManagementPoliciesWithServiceResponseAsync(resourceGroupName, accountName, policy).map(new Func1<ServiceResponse<StorageAccountManagementPoliciesInner>, StorageAccountManagementPoliciesInner>() { @Override public StorageAccountManagementPoliciesInner call(ServiceResponse<StorageAccountManagementPoliciesInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "StorageAccountManagementPoliciesInner", ">", "createOrUpdateManagementPoliciesAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "Object", "policy", ")", "{", "return", "createOrUpdateManagementPoliciesWithServiceResponseA...
Sets the data policy rules associated with the specified storage account. @param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive. @param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. @param policy The Storage Account ManagementPolicies Rules, in JSON format. See more details in: https://docs.microsoft.com/en-us/azure/storage/common/storage-lifecycle-managment-concepts. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the StorageAccountManagementPoliciesInner object
[ "Sets", "the", "data", "policy", "rules", "associated", "with", "the", "specified", "storage", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java#L1400-L1407
JavaMoney/jsr354-api
src/main/java/javax/money/RoundingContextBuilder.java
RoundingContextBuilder.setCurrency
public RoundingContextBuilder setCurrency(CurrencyUnit currencyUnit) { Objects.requireNonNull(currencyUnit); return set(CurrencyUnit.class, currencyUnit); }
java
public RoundingContextBuilder setCurrency(CurrencyUnit currencyUnit) { Objects.requireNonNull(currencyUnit); return set(CurrencyUnit.class, currencyUnit); }
[ "public", "RoundingContextBuilder", "setCurrency", "(", "CurrencyUnit", "currencyUnit", ")", "{", "Objects", ".", "requireNonNull", "(", "currencyUnit", ")", ";", "return", "set", "(", "CurrencyUnit", ".", "class", ",", "currencyUnit", ")", ";", "}" ]
Get the basic {@link CurrencyUnit}, which is based for this rounding type. @param currencyUnit the target currency unit not null. @return the target CurrencyUnit, or null.
[ "Get", "the", "basic", "{" ]
train
https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/RoundingContextBuilder.java#L60-L63
grails/grails-core
grails-core/src/main/groovy/org/grails/core/AbstractGrailsClass.java
AbstractGrailsClass.getPropertyOrStaticPropertyOrFieldValue
protected <T> T getPropertyOrStaticPropertyOrFieldValue(String name, Class<T> type) { return ClassPropertyFetcher.getStaticPropertyValue(getClazz(), name, type); }
java
protected <T> T getPropertyOrStaticPropertyOrFieldValue(String name, Class<T> type) { return ClassPropertyFetcher.getStaticPropertyValue(getClazz(), name, type); }
[ "protected", "<", "T", ">", "T", "getPropertyOrStaticPropertyOrFieldValue", "(", "String", "name", ",", "Class", "<", "T", ">", "type", ")", "{", "return", "ClassPropertyFetcher", ".", "getStaticPropertyValue", "(", "getClazz", "(", ")", ",", "name", ",", "typ...
<p>Looks for a property of the reference instance with a given name and type.</p> <p>If found its value is returned. We follow the Java bean conventions with augmentation for groovy support and static fields/properties. We will therefore match, in this order: </p> <ol> <li>Public static field <li>Public static property with getter method <li>Standard public bean property (with getter or just public field, using normal introspection) </ol> @return property value or null if no property or static field was found
[ "<p", ">", "Looks", "for", "a", "property", "of", "the", "reference", "instance", "with", "a", "given", "name", "and", "type", ".", "<", "/", "p", ">", "<p", ">", "If", "found", "its", "value", "is", "returned", ".", "We", "follow", "the", "Java", ...
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/core/AbstractGrailsClass.java#L227-L229
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.extractStringResult
static public String extractStringResult(ResultSet rs, ResultSetMetaData rsmd, int index) throws Exception { int count = rsmd.getColumnCount(); if( index > count || index < 1 ) { throw new Exception("Invalid index"); } int type = rsmd.getColumnType(index); switch (type) { case java.sql.Types.VARCHAR: case java.sql.Types.CHAR: return rs.getString(index); } throw new Exception("Column type ("+type+") invalid for a string at index: "+index); }
java
static public String extractStringResult(ResultSet rs, ResultSetMetaData rsmd, int index) throws Exception { int count = rsmd.getColumnCount(); if( index > count || index < 1 ) { throw new Exception("Invalid index"); } int type = rsmd.getColumnType(index); switch (type) { case java.sql.Types.VARCHAR: case java.sql.Types.CHAR: return rs.getString(index); } throw new Exception("Column type ("+type+") invalid for a string at index: "+index); }
[ "static", "public", "String", "extractStringResult", "(", "ResultSet", "rs", ",", "ResultSetMetaData", "rsmd", ",", "int", "index", ")", "throws", "Exception", "{", "int", "count", "=", "rsmd", ".", "getColumnCount", "(", ")", ";", "if", "(", "index", ">", ...
This method returns a String result at a given index. @param stmt Statement that has been successfully executed @param index Index of expected column @return A string returned at the specified index @throws Exception If there is no column at index
[ "This", "method", "returns", "a", "String", "result", "at", "a", "given", "index", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L106-L121
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/distance/ST_LongestLine.java
ST_LongestLine.longestLine
public static Geometry longestLine(Geometry geomA, Geometry geomB) { Coordinate[] coords = new MaxDistanceOp(geomA, geomB).getCoordinatesDistance(); if(coords!=null){ return geomA.getFactory().createLineString(coords); } return null; }
java
public static Geometry longestLine(Geometry geomA, Geometry geomB) { Coordinate[] coords = new MaxDistanceOp(geomA, geomB).getCoordinatesDistance(); if(coords!=null){ return geomA.getFactory().createLineString(coords); } return null; }
[ "public", "static", "Geometry", "longestLine", "(", "Geometry", "geomA", ",", "Geometry", "geomB", ")", "{", "Coordinate", "[", "]", "coords", "=", "new", "MaxDistanceOp", "(", "geomA", ",", "geomB", ")", ".", "getCoordinatesDistance", "(", ")", ";", "if", ...
Return the longest line between the points of two geometries. @param geomA @param geomB @return
[ "Return", "the", "longest", "line", "between", "the", "points", "of", "two", "geometries", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/distance/ST_LongestLine.java#L50-L56
hibernate/hibernate-ogm
neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jAssociationQueries.java
BaseNeo4jAssociationQueries.removeAssociation
public void removeAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey) { executionEngine.execute( removeAssociationQuery, params( associationKey.getEntityKey().getColumnValues() ) ); }
java
public void removeAssociation(GraphDatabaseService executionEngine, AssociationKey associationKey) { executionEngine.execute( removeAssociationQuery, params( associationKey.getEntityKey().getColumnValues() ) ); }
[ "public", "void", "removeAssociation", "(", "GraphDatabaseService", "executionEngine", ",", "AssociationKey", "associationKey", ")", "{", "executionEngine", ".", "execute", "(", "removeAssociationQuery", ",", "params", "(", "associationKey", ".", "getEntityKey", "(", ")...
Removes the relationship(s) representing the given association. If the association refers to an embedded entity (collection), the referenced entities are removed as well. @param executionEngine the {@link GraphDatabaseService} used to run the query @param associationKey represents the association
[ "Removes", "the", "relationship", "(", "s", ")", "representing", "the", "given", "association", ".", "If", "the", "association", "refers", "to", "an", "embedded", "entity", "(", "collection", ")", "the", "referenced", "entities", "are", "removed", "as", "well"...
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jAssociationQueries.java#L229-L231
Whiley/WhileyCompiler
src/main/java/wyc/io/WhileyFileParser.java
WhileyFileParser.parseLifetime
private Identifier parseLifetime(EnclosingScope scope, boolean terminated) { Identifier id = parseOptionalLifetimeIdentifier(scope, terminated); if (id != null) { return id; } else { syntaxError("expecting lifetime identifier", tokens.get(index)); } throw new RuntimeException("deadcode"); // dead-code }
java
private Identifier parseLifetime(EnclosingScope scope, boolean terminated) { Identifier id = parseOptionalLifetimeIdentifier(scope, terminated); if (id != null) { return id; } else { syntaxError("expecting lifetime identifier", tokens.get(index)); } throw new RuntimeException("deadcode"); // dead-code }
[ "private", "Identifier", "parseLifetime", "(", "EnclosingScope", "scope", ",", "boolean", "terminated", ")", "{", "Identifier", "id", "=", "parseOptionalLifetimeIdentifier", "(", "scope", ",", "terminated", ")", ";", "if", "(", "id", "!=", "null", ")", "{", "r...
Parse a currently declared lifetime. @return the matched lifetime name
[ "Parse", "a", "currently", "declared", "lifetime", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L4107-L4115
fabric8io/kubernetes-client
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/ApiVersionUtil.java
ApiVersionUtil.apiGroup
public static <T> String apiGroup(T item, String apiGroup) { if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) { return trimGroupOrNull(((HasMetadata) item).getApiVersion()); } else if (apiGroup != null && !apiGroup.isEmpty()) { return trimGroup(apiGroup); } return null; }
java
public static <T> String apiGroup(T item, String apiGroup) { if (item instanceof HasMetadata && Utils.isNotNullOrEmpty(((HasMetadata) item).getApiVersion())) { return trimGroupOrNull(((HasMetadata) item).getApiVersion()); } else if (apiGroup != null && !apiGroup.isEmpty()) { return trimGroup(apiGroup); } return null; }
[ "public", "static", "<", "T", ">", "String", "apiGroup", "(", "T", "item", ",", "String", "apiGroup", ")", "{", "if", "(", "item", "instanceof", "HasMetadata", "&&", "Utils", ".", "isNotNullOrEmpty", "(", "(", "(", "HasMetadata", ")", "item", ")", ".", ...
Extracts apiGroupName from apiGroupVersion when in resource for apiGroupName/apiGroupVersion combination @param <T> Template argument provided @param item resource which is being used @param apiGroup apiGroupName present if any @return Just the apiGroupName part without apiGroupVersion
[ "Extracts", "apiGroupName", "from", "apiGroupVersion", "when", "in", "resource", "for", "apiGroupName", "/", "apiGroupVersion", "combination" ]
train
https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/utils/ApiVersionUtil.java#L29-L36
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java
XmlUtil.appendChild
public static Element appendChild(Node node, String tagName) { Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument(); Element child = doc.createElement(tagName); node.appendChild(child); return child; }
java
public static Element appendChild(Node node, String tagName) { Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument(); Element child = doc.createElement(tagName); node.appendChild(child); return child; }
[ "public", "static", "Element", "appendChild", "(", "Node", "node", ",", "String", "tagName", ")", "{", "Document", "doc", "=", "(", "node", "instanceof", "Document", ")", "?", "(", "Document", ")", "node", ":", "node", ".", "getOwnerDocument", "(", ")", ...
在已有节点上创建子节点 @param node 节点 @param tagName 标签名 @return 子节点 @since 4.0.9
[ "在已有节点上创建子节点" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/XmlUtil.java#L777-L782
victims/victims-lib-java
src/main/java/com/redhat/victims/database/VictimsSQL.java
VictimsSQL.setObjects
protected void setObjects(PreparedStatement ps, Object... objects) throws SQLException { int index = 1; for (Object obj : objects) { ps.setObject(index, obj); index++; } }
java
protected void setObjects(PreparedStatement ps, Object... objects) throws SQLException { int index = 1; for (Object obj : objects) { ps.setObject(index, obj); index++; } }
[ "protected", "void", "setObjects", "(", "PreparedStatement", "ps", ",", "Object", "...", "objects", ")", "throws", "SQLException", "{", "int", "index", "=", "1", ";", "for", "(", "Object", "obj", ":", "objects", ")", "{", "ps", ".", "setObject", "(", "in...
Helper function to set the values given, to a {@link PreparedStatement}, in the order in which they are given. @param ps @param objects @throws SQLException
[ "Helper", "function", "to", "set", "the", "values", "given", "to", "a", "{", "@link", "PreparedStatement", "}", "in", "the", "order", "in", "which", "they", "are", "given", "." ]
train
https://github.com/victims/victims-lib-java/blob/ccd0e2fcc409bb6cdfc5de411c3bb202c9095f8b/src/main/java/com/redhat/victims/database/VictimsSQL.java#L143-L150
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java
CSLUtils.readFileToString
public static String readFileToString(File f, String encoding) throws IOException { return readStreamToString(new FileInputStream(f), encoding); }
java
public static String readFileToString(File f, String encoding) throws IOException { return readStreamToString(new FileInputStream(f), encoding); }
[ "public", "static", "String", "readFileToString", "(", "File", "f", ",", "String", "encoding", ")", "throws", "IOException", "{", "return", "readStreamToString", "(", "new", "FileInputStream", "(", "f", ")", ",", "encoding", ")", ";", "}" ]
Reads a string from a file. @param f the file @param encoding the character encoding @return the string @throws IOException if the file contents could not be read
[ "Reads", "a", "string", "from", "a", "file", "." ]
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/CSLUtils.java#L73-L75
SeaCloudsEU/SeaCloudsPlatform
monitor/seaclouds-data-collector/src/main/java/eu/seaclouds/monitor/datacollector/Registry.java
Registry.addResource
public static void addResource(String type, String id, String url){ //add the new resource to the list of the managed resources logger.info("Adding the following new resource to the Data Collector Descriptor: {}, {}", type, id); try { resources.put(new InternalComponent(type,id), new URL(url)); } catch (MalformedURLException e) { logger.error(e.getMessage(), e.getCause()); } logger.info("Currently managed resources..."); for(Resource r: _INSTANCE.getResources()){ logger.info(r.getType() + " " + r.getId() + "\n"); } // re-Build the DCDescriptor DCDescriptor dcDescriptor = new DCDescriptor(); dcDescriptor.addMonitoredResources(_INSTANCE.getProvidedMetrics(), _INSTANCE.getResources()); dcDescriptor.addResources(_INSTANCE.getResources()); dcDescriptor .setConfigSyncPeriod(CONFIG_SYNC_PERIOD != null ? CONFIG_SYNC_PERIOD : DEFAULT_CONFIG_SYNC_PERIOD); dcDescriptor.setKeepAlive(KEEP_ALIVE != null ? KEEP_ALIVE : (DEFAULT_CONFIG_SYNC_PERIOD + 15)); logger.info("Setting the new DCDescriptor..."); _INSTANCE.dcAgent.setDCDescriptor(dcDescriptor); //re-start the monitoring _INSTANCE.monitoringStarted = false; startMonitoring(); }
java
public static void addResource(String type, String id, String url){ //add the new resource to the list of the managed resources logger.info("Adding the following new resource to the Data Collector Descriptor: {}, {}", type, id); try { resources.put(new InternalComponent(type,id), new URL(url)); } catch (MalformedURLException e) { logger.error(e.getMessage(), e.getCause()); } logger.info("Currently managed resources..."); for(Resource r: _INSTANCE.getResources()){ logger.info(r.getType() + " " + r.getId() + "\n"); } // re-Build the DCDescriptor DCDescriptor dcDescriptor = new DCDescriptor(); dcDescriptor.addMonitoredResources(_INSTANCE.getProvidedMetrics(), _INSTANCE.getResources()); dcDescriptor.addResources(_INSTANCE.getResources()); dcDescriptor .setConfigSyncPeriod(CONFIG_SYNC_PERIOD != null ? CONFIG_SYNC_PERIOD : DEFAULT_CONFIG_SYNC_PERIOD); dcDescriptor.setKeepAlive(KEEP_ALIVE != null ? KEEP_ALIVE : (DEFAULT_CONFIG_SYNC_PERIOD + 15)); logger.info("Setting the new DCDescriptor..."); _INSTANCE.dcAgent.setDCDescriptor(dcDescriptor); //re-start the monitoring _INSTANCE.monitoringStarted = false; startMonitoring(); }
[ "public", "static", "void", "addResource", "(", "String", "type", ",", "String", "id", ",", "String", "url", ")", "{", "//add the new resource to the list of the managed resources", "logger", ".", "info", "(", "\"Adding the following new resource to the Data Collector Descrip...
This method allow to add a new monitored resource to the Registry. @param type the Type of the new resource to be added. @param id the id of the new resource to be added. @param url the String representation of the url of the new resource to be added.
[ "This", "method", "allow", "to", "add", "a", "new", "monitored", "resource", "to", "the", "Registry", "." ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/monitor/seaclouds-data-collector/src/main/java/eu/seaclouds/monitor/datacollector/Registry.java#L213-L252
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/managers/AccountManager.java
AccountManager.setAvatar
@CheckReturnValue public AccountManager setAvatar(Icon avatar, String currentPassword) { this.currentPassword = currentPassword; this.avatar = avatar; set |= AVATAR; return this; }
java
@CheckReturnValue public AccountManager setAvatar(Icon avatar, String currentPassword) { this.currentPassword = currentPassword; this.avatar = avatar; set |= AVATAR; return this; }
[ "@", "CheckReturnValue", "public", "AccountManager", "setAvatar", "(", "Icon", "avatar", ",", "String", "currentPassword", ")", "{", "this", ".", "currentPassword", "=", "currentPassword", ";", "this", ".", "avatar", "=", "avatar", ";", "set", "|=", "AVATAR", ...
Sets the avatar for the currently logged in account @param avatar An {@link net.dv8tion.jda.core.entities.Icon Icon} instance representing the new Avatar for the current account, {@code null} to reset the avatar to the default avatar. @param currentPassword The current password for the represented account, this is only required for {@link net.dv8tion.jda.core.AccountType#CLIENT AccountType.CLIENT} @throws IllegalArgumentException If the provided {@code currentPassword} is {@code null} or empty and the currently logged in account is from {@link net.dv8tion.jda.core.AccountType#CLIENT AccountType.CLIENT} @return AccountManager for chaining convenience
[ "Sets", "the", "avatar", "for", "the", "currently", "logged", "in", "account" ]
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/managers/AccountManager.java#L251-L258
opentable/otj-jaxrs
client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java
JaxRsClientFactory.addFeatureToGroup
@SafeVarargs public final synchronized JaxRsClientFactory addFeatureToGroup(JaxRsFeatureGroup group, Class<? extends Feature>... features) { Preconditions.checkState(!started, "Already started building clients"); classFeatureMap.putAll(group, Arrays.asList(features)); LOG.trace("Group {} registers features {}", group, features); return this; }
java
@SafeVarargs public final synchronized JaxRsClientFactory addFeatureToGroup(JaxRsFeatureGroup group, Class<? extends Feature>... features) { Preconditions.checkState(!started, "Already started building clients"); classFeatureMap.putAll(group, Arrays.asList(features)); LOG.trace("Group {} registers features {}", group, features); return this; }
[ "@", "SafeVarargs", "public", "final", "synchronized", "JaxRsClientFactory", "addFeatureToGroup", "(", "JaxRsFeatureGroup", "group", ",", "Class", "<", "?", "extends", "Feature", ">", "...", "features", ")", "{", "Preconditions", ".", "checkState", "(", "!", "star...
Register a list of features to all clients marked with the given group.
[ "Register", "a", "list", "of", "features", "to", "all", "clients", "marked", "with", "the", "given", "group", "." ]
train
https://github.com/opentable/otj-jaxrs/blob/384e7094fe5a56d41b2a9970bfd783fa85cbbcb8/client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java#L159-L165
alibaba/canal
driver/src/main/java/com/alibaba/otter/canal/parse/driver/mysql/packets/server/OKPacket.java
OKPacket.fromBytes
public void fromBytes(byte[] data) throws IOException { int index = 0; // 1. read field count this.fieldCount = data[0]; index++; // 2. read affected rows this.affectedRows = ByteHelper.readBinaryCodedLengthBytes(data, index); index += this.affectedRows.length; // 3. read insert id this.insertId = ByteHelper.readBinaryCodedLengthBytes(data, index); index += this.insertId.length; // 4. read server status this.serverStatus = ByteHelper.readUnsignedShortLittleEndian(data, index); index += 2; // 5. read warning count this.warningCount = ByteHelper.readUnsignedShortLittleEndian(data, index); index += 2; // 6. read message. this.message = new String(ByteHelper.readFixedLengthBytes(data, index, data.length - index)); // end read }
java
public void fromBytes(byte[] data) throws IOException { int index = 0; // 1. read field count this.fieldCount = data[0]; index++; // 2. read affected rows this.affectedRows = ByteHelper.readBinaryCodedLengthBytes(data, index); index += this.affectedRows.length; // 3. read insert id this.insertId = ByteHelper.readBinaryCodedLengthBytes(data, index); index += this.insertId.length; // 4. read server status this.serverStatus = ByteHelper.readUnsignedShortLittleEndian(data, index); index += 2; // 5. read warning count this.warningCount = ByteHelper.readUnsignedShortLittleEndian(data, index); index += 2; // 6. read message. this.message = new String(ByteHelper.readFixedLengthBytes(data, index, data.length - index)); // end read }
[ "public", "void", "fromBytes", "(", "byte", "[", "]", "data", ")", "throws", "IOException", "{", "int", "index", "=", "0", ";", "// 1. read field count", "this", ".", "fieldCount", "=", "data", "[", "0", "]", ";", "index", "++", ";", "// 2. read affected r...
<pre> VERSION 4.1 Bytes Name ----- ---- 1 (Length Coded Binary) field_count, always = 0 1-9 (Length Coded Binary) affected_rows 1-9 (Length Coded Binary) insert_id 2 server_status 2 warning_count n (until end of packet) message </pre> @throws IOException
[ "<pre", ">", "VERSION", "4", ".", "1", "Bytes", "Name", "-----", "----", "1", "(", "Length", "Coded", "Binary", ")", "field_count", "always", "=", "0", "1", "-", "9", "(", "Length", "Coded", "Binary", ")", "affected_rows", "1", "-", "9", "(", "Length...
train
https://github.com/alibaba/canal/blob/8f088cddc0755f4350c5aaae95c6e4002d90a40f/driver/src/main/java/com/alibaba/otter/canal/parse/driver/mysql/packets/server/OKPacket.java#L38-L58
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/AbstractResources.java
AbstractResources.getResourceAsFile
public void getResourceAsFile(String path, String fileType, OutputStream outputStream) throws SmartsheetException { Util.throwIfNull(outputStream, fileType); HttpRequest request; request = createHttpRequest(this.getSmartsheet().getBaseURI().resolve(path), HttpMethod.GET); request.getHeaders().put("Accept", fileType); try { HttpResponse response = getSmartsheet().getHttpClient().request(request); switch (response.getStatusCode()) { case 200: try { copyStream(response.getEntity().getContent(), outputStream); } catch (IOException e) { throw new SmartsheetException(e); } break; default: handleError(response); } } finally { getSmartsheet().getHttpClient().releaseConnection(); } }
java
public void getResourceAsFile(String path, String fileType, OutputStream outputStream) throws SmartsheetException { Util.throwIfNull(outputStream, fileType); HttpRequest request; request = createHttpRequest(this.getSmartsheet().getBaseURI().resolve(path), HttpMethod.GET); request.getHeaders().put("Accept", fileType); try { HttpResponse response = getSmartsheet().getHttpClient().request(request); switch (response.getStatusCode()) { case 200: try { copyStream(response.getEntity().getContent(), outputStream); } catch (IOException e) { throw new SmartsheetException(e); } break; default: handleError(response); } } finally { getSmartsheet().getHttpClient().releaseConnection(); } }
[ "public", "void", "getResourceAsFile", "(", "String", "path", ",", "String", "fileType", ",", "OutputStream", "outputStream", ")", "throws", "SmartsheetException", "{", "Util", ".", "throwIfNull", "(", "outputStream", ",", "fileType", ")", ";", "HttpRequest", "req...
Get a sheet as a file. Exceptions: - InvalidRequestException : if there is any problem with the REST API request - AuthorizationException : if there is any problem with the REST API authorization(access token) - ResourceNotFoundException : if the resource can not be found - ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) - SmartsheetRestException : if there is any other REST API related error occurred during the operation - SmartsheetException : if there is any other error occurred during the operation @param path the path @param fileType the output file type @param outputStream the OutputStream to which the file will be written @return the report as file @throws SmartsheetException the smartsheet exception
[ "Get", "a", "sheet", "as", "a", "file", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/AbstractResources.java#L929-L954
rhuss/jolokia
agent/core/src/main/java/org/jolokia/discovery/AgentDetails.java
AgentDetails.setServerInfo
public void setServerInfo(String pVendor, String pProduct, String pVersion) { checkSeal(); serverVendor = pVendor; serverProduct = pProduct; serverVersion = pVersion; }
java
public void setServerInfo(String pVendor, String pProduct, String pVersion) { checkSeal(); serverVendor = pVendor; serverProduct = pProduct; serverVersion = pVersion; }
[ "public", "void", "setServerInfo", "(", "String", "pVendor", ",", "String", "pProduct", ",", "String", "pVersion", ")", "{", "checkSeal", "(", ")", ";", "serverVendor", "=", "pVendor", ";", "serverProduct", "=", "pProduct", ";", "serverVersion", "=", "pVersion...
Single method for updating the server information when the server has been detected @param pVendor vendor of the deteted container @param pProduct name of the contained @param pVersion server version (not Jolokia's version!)
[ "Single", "method", "for", "updating", "the", "server", "information", "when", "the", "server", "has", "been", "detected" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/discovery/AgentDetails.java#L90-L95
Sciss/abc4j
abc/src/main/java/abc/ui/swing/JTune.java
JTune.getHighestNoteGlyphBetween
private JNoteElementAbstract getHighestNoteGlyphBetween(NoteAbstract start, NoteAbstract end, boolean excludeStartAndEnd) { Collection jnotes = getNoteGlyphesBetween(start, end); JNoteElementAbstract ret = null; boolean first = true; for (Iterator it = jnotes.iterator(); it.hasNext();) { JNoteElementAbstract n = (JNoteElementAbstract) it.next(); if (first && excludeStartAndEnd) { //ignore start ? first = false; continue; } if (!it.hasNext() && excludeStartAndEnd) { //ignore end ? break; } if (ret == null) ret = n; else { if (n.getBoundingBox().getMinY() < ret.getBoundingBox().getMinY()) ret = n; } } return ret; }
java
private JNoteElementAbstract getHighestNoteGlyphBetween(NoteAbstract start, NoteAbstract end, boolean excludeStartAndEnd) { Collection jnotes = getNoteGlyphesBetween(start, end); JNoteElementAbstract ret = null; boolean first = true; for (Iterator it = jnotes.iterator(); it.hasNext();) { JNoteElementAbstract n = (JNoteElementAbstract) it.next(); if (first && excludeStartAndEnd) { //ignore start ? first = false; continue; } if (!it.hasNext() && excludeStartAndEnd) { //ignore end ? break; } if (ret == null) ret = n; else { if (n.getBoundingBox().getMinY() < ret.getBoundingBox().getMinY()) ret = n; } } return ret; }
[ "private", "JNoteElementAbstract", "getHighestNoteGlyphBetween", "(", "NoteAbstract", "start", ",", "NoteAbstract", "end", ",", "boolean", "excludeStartAndEnd", ")", "{", "Collection", "jnotes", "=", "getNoteGlyphesBetween", "(", "start", ",", "end", ")", ";", "JNoteE...
Return the JNote that have the highest bounding box @return a JNote. May return <code>null</code> if exclude is true and no notes between start and end!
[ "Return", "the", "JNote", "that", "have", "the", "highest", "bounding", "box" ]
train
https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/ui/swing/JTune.java#L1453-L1477
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.isAssignableFrom
@GwtIncompatible("incompatible method") public static void isAssignableFrom(final Class<?> superType, final Class<?> type, final String message, final Object... values) { // TODO when breaking BC, consider returning type if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(StringUtils.simpleFormat(message, values)); } }
java
@GwtIncompatible("incompatible method") public static void isAssignableFrom(final Class<?> superType, final Class<?> type, final String message, final Object... values) { // TODO when breaking BC, consider returning type if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(StringUtils.simpleFormat(message, values)); } }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "void", "isAssignableFrom", "(", "final", "Class", "<", "?", ">", "superType", ",", "final", "Class", "<", "?", ">", "type", ",", "final", "String", "message", ",", "final", "Ob...
Validates that the argument can be converted to the specified class, if not throws an exception. <p>This method is useful when validating if there will be no casting errors.</p> <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre> <p>The message of the exception is &quot;The validated object can not be converted to the&quot; followed by the name of the class and &quot;class&quot;</p> @param superType the class the class must be validated against, not null @param type the class to check, not null @param message the {@link String#format(String, Object...)} exception message if invalid, not null @param values the optional values for the formatted exception message, null array not recommended @throws IllegalArgumentException if argument can not be converted to the specified class @see #isAssignableFrom(Class, Class)
[ "Validates", "that", "the", "argument", "can", "be", "converted", "to", "the", "specified", "class", "if", "not", "throws", "an", "exception", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L1345-L1351
micronaut-projects/micronaut-core
tracing/src/main/java/io/micronaut/tracing/instrument/http/AbstractOpenTracingFilter.java
AbstractOpenTracingFilter.setResponseTags
protected void setResponseTags(HttpRequest<?> request, HttpResponse<?> response, Span span) { HttpStatus status = response.getStatus(); int code = status.getCode(); if (code > HTTP_SUCCESS_CODE_UPPER_LIMIT) { span.setTag(TAG_HTTP_STATUS_CODE, code); span.setTag(TAG_ERROR, status.getReason()); } request.getAttribute(HttpAttributes.ERROR, Throwable.class).ifPresent(error -> setErrorTags(span, error) ); }
java
protected void setResponseTags(HttpRequest<?> request, HttpResponse<?> response, Span span) { HttpStatus status = response.getStatus(); int code = status.getCode(); if (code > HTTP_SUCCESS_CODE_UPPER_LIMIT) { span.setTag(TAG_HTTP_STATUS_CODE, code); span.setTag(TAG_ERROR, status.getReason()); } request.getAttribute(HttpAttributes.ERROR, Throwable.class).ifPresent(error -> setErrorTags(span, error) ); }
[ "protected", "void", "setResponseTags", "(", "HttpRequest", "<", "?", ">", "request", ",", "HttpResponse", "<", "?", ">", "response", ",", "Span", "span", ")", "{", "HttpStatus", "status", "=", "response", ".", "getStatus", "(", ")", ";", "int", "code", ...
Sets the response tags. @param request The request @param response The response @param span The span
[ "Sets", "the", "response", "tags", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/tracing/src/main/java/io/micronaut/tracing/instrument/http/AbstractOpenTracingFilter.java#L62-L72
undertow-io/undertow
core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java
Http2PriorityTree.registerStream
public void registerStream(int streamId, int dependency, int weighting, boolean exclusive) { final Http2PriorityNode node = new Http2PriorityNode(streamId, weighting); if(exclusive) { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.exclusive(node); } } else { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.addDependent(node); } } nodesByID.put(streamId, node); }
java
public void registerStream(int streamId, int dependency, int weighting, boolean exclusive) { final Http2PriorityNode node = new Http2PriorityNode(streamId, weighting); if(exclusive) { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.exclusive(node); } } else { Http2PriorityNode existing = nodesByID.get(dependency); if(existing != null) { existing.addDependent(node); } } nodesByID.put(streamId, node); }
[ "public", "void", "registerStream", "(", "int", "streamId", ",", "int", "dependency", ",", "int", "weighting", ",", "boolean", "exclusive", ")", "{", "final", "Http2PriorityNode", "node", "=", "new", "Http2PriorityNode", "(", "streamId", ",", "weighting", ")", ...
Resisters a stream, with its dependency and dependent information @param streamId The stream id @param dependency The stream this stream depends on, if no stream is specified this should be zero @param weighting The weighting. If no weighting is specified this should be 16
[ "Resisters", "a", "stream", "with", "its", "dependency", "and", "dependent", "information" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/protocols/http2/Http2PriorityTree.java#L60-L74
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java
CassandraSchemaManager.onSetKeyValidation
private void onSetKeyValidation(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String keyValidationClass = cfProperties.getProperty(CassandraConstants.KEY_VALIDATION_CLASS); if (keyValidationClass != null) { if (builder != null) { // nothing available. } else { cfDef.setKey_validation_class(keyValidationClass); } } }
java
private void onSetKeyValidation(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String keyValidationClass = cfProperties.getProperty(CassandraConstants.KEY_VALIDATION_CLASS); if (keyValidationClass != null) { if (builder != null) { // nothing available. } else { cfDef.setKey_validation_class(keyValidationClass); } } }
[ "private", "void", "onSetKeyValidation", "(", "CfDef", "cfDef", ",", "Properties", "cfProperties", ",", "StringBuilder", "builder", ")", "{", "String", "keyValidationClass", "=", "cfProperties", ".", "getProperty", "(", "CassandraConstants", ".", "KEY_VALIDATION_CLASS",...
On set key validation. @param cfDef the cf def @param cfProperties the cf properties @param builder the builder
[ "On", "set", "key", "validation", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L2771-L2785
sirthias/parboiled
parboiled-core/src/main/java/org/parboiled/support/ParseTreeUtils.java
ParseTreeUtils.getNodeText
public static String getNodeText(Node<?> node, InputBuffer inputBuffer) { checkArgNotNull(node, "node"); checkArgNotNull(inputBuffer, "inputBuffer"); if (node.hasError()) { // if the node has a parse error we cannot simply cut a string out of the underlying input buffer, since we // would also include illegal characters, so we need to build it constructively StringBuilder sb = new StringBuilder(); for (int i = node.getStartIndex(); i < node.getEndIndex(); i++) { char c = inputBuffer.charAt(i); switch (c) { case Chars.DEL_ERROR: i++; break; case Chars.INS_ERROR: case Chars.EOI: break; case Chars.RESYNC_START: i++; while (inputBuffer.charAt(i) != Chars.RESYNC_END) i++; break; case Chars.RESYNC_END: case Chars.RESYNC_EOI: case Chars.RESYNC: // we should only see proper RESYNC_START / RESYNC_END blocks throw new IllegalStateException(); default: sb.append(c); } } return sb.toString(); } return inputBuffer.extract(node.getStartIndex(), node.getEndIndex()); }
java
public static String getNodeText(Node<?> node, InputBuffer inputBuffer) { checkArgNotNull(node, "node"); checkArgNotNull(inputBuffer, "inputBuffer"); if (node.hasError()) { // if the node has a parse error we cannot simply cut a string out of the underlying input buffer, since we // would also include illegal characters, so we need to build it constructively StringBuilder sb = new StringBuilder(); for (int i = node.getStartIndex(); i < node.getEndIndex(); i++) { char c = inputBuffer.charAt(i); switch (c) { case Chars.DEL_ERROR: i++; break; case Chars.INS_ERROR: case Chars.EOI: break; case Chars.RESYNC_START: i++; while (inputBuffer.charAt(i) != Chars.RESYNC_END) i++; break; case Chars.RESYNC_END: case Chars.RESYNC_EOI: case Chars.RESYNC: // we should only see proper RESYNC_START / RESYNC_END blocks throw new IllegalStateException(); default: sb.append(c); } } return sb.toString(); } return inputBuffer.extract(node.getStartIndex(), node.getEndIndex()); }
[ "public", "static", "String", "getNodeText", "(", "Node", "<", "?", ">", "node", ",", "InputBuffer", "inputBuffer", ")", "{", "checkArgNotNull", "(", "node", ",", "\"node\"", ")", ";", "checkArgNotNull", "(", "inputBuffer", ",", "\"inputBuffer\"", ")", ";", ...
Returns the input text matched by the given node, with error correction. @param node the node @param inputBuffer the underlying inputBuffer @return null if node is null otherwise a string with the matched input text (which can be empty)
[ "Returns", "the", "input", "text", "matched", "by", "the", "given", "node", "with", "error", "correction", "." ]
train
https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/ParseTreeUtils.java#L262-L294
pushbit/sprockets
src/main/java/net/sf/sprockets/sql/Statements.java
Statements.setStrings
public static PreparedStatement setStrings(PreparedStatement stmt, String... params) throws SQLException { return setStrings(1, stmt, params); }
java
public static PreparedStatement setStrings(PreparedStatement stmt, String... params) throws SQLException { return setStrings(1, stmt, params); }
[ "public", "static", "PreparedStatement", "setStrings", "(", "PreparedStatement", "stmt", ",", "String", "...", "params", ")", "throws", "SQLException", "{", "return", "setStrings", "(", "1", ",", "stmt", ",", "params", ")", ";", "}" ]
Set the statement parameters, starting at 1, in the order of the params. @since 3.0.0
[ "Set", "the", "statement", "parameters", "starting", "at", "1", "in", "the", "order", "of", "the", "params", "." ]
train
https://github.com/pushbit/sprockets/blob/5d967317cbb2374c69d33271d3c7b7311e1ea4ac/src/main/java/net/sf/sprockets/sql/Statements.java#L90-L93
BioPAX/Paxtools
sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/SBGNLayoutManager.java
SBGNLayoutManager.connectArcToPort
private void connectArcToPort(SbgnPDNode lPort, Port vPort) { //Iterate over the edges of l level port for (Object e: (lPort.getEdges())) { //Ignore rigid edges if(((LEdge)e).type.equals("rigid edge")) continue; //Determine the if vPort is source or target Arc arc = idToArcs.get(((LEdge)e).label); if( lPort.label.equals(((LEdge)e).getSource().label )) { arc.setSource(vPort); } else if ( lPort.label.equals(((LEdge)e).getTarget().label ) ) { arc.setTarget(vPort); } } }
java
private void connectArcToPort(SbgnPDNode lPort, Port vPort) { //Iterate over the edges of l level port for (Object e: (lPort.getEdges())) { //Ignore rigid edges if(((LEdge)e).type.equals("rigid edge")) continue; //Determine the if vPort is source or target Arc arc = idToArcs.get(((LEdge)e).label); if( lPort.label.equals(((LEdge)e).getSource().label )) { arc.setSource(vPort); } else if ( lPort.label.equals(((LEdge)e).getTarget().label ) ) { arc.setTarget(vPort); } } }
[ "private", "void", "connectArcToPort", "(", "SbgnPDNode", "lPort", ",", "Port", "vPort", ")", "{", "//Iterate over the edges of l level port", "for", "(", "Object", "e", ":", "(", "lPort", ".", "getEdges", "(", ")", ")", ")", "{", "//Ignore rigid edges", "if", ...
This method connects the existing arcs to the newly created ports which are created by ChiLay and SBGNPD Layout. @param lPort l level port object. @param vPort v level port object.
[ "This", "method", "connects", "the", "existing", "arcs", "to", "the", "newly", "created", "ports", "which", "are", "created", "by", "ChiLay", "and", "SBGNPD", "Layout", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/SBGNLayoutManager.java#L185-L205
davidmoten/rxjava-jdbc
src/main/java/com/github/davidmoten/rx/jdbc/Util.java
Util.autoMap
@SuppressWarnings("unchecked") static <T> T autoMap(ResultSet rs, Class<T> cls) { try { if (cls.isInterface()) { return autoMapInterface(rs, cls); } else { int n = rs.getMetaData().getColumnCount(); for (Constructor<?> c : cls.getDeclaredConstructors()) { if (n == c.getParameterTypes().length) { return autoMap(rs, (Constructor<T>) c); } } throw new RuntimeException( "constructor with number of parameters=" + n + " not found in " + cls); } } catch (SQLException e) { throw new SQLRuntimeException(e); } }
java
@SuppressWarnings("unchecked") static <T> T autoMap(ResultSet rs, Class<T> cls) { try { if (cls.isInterface()) { return autoMapInterface(rs, cls); } else { int n = rs.getMetaData().getColumnCount(); for (Constructor<?> c : cls.getDeclaredConstructors()) { if (n == c.getParameterTypes().length) { return autoMap(rs, (Constructor<T>) c); } } throw new RuntimeException( "constructor with number of parameters=" + n + " not found in " + cls); } } catch (SQLException e) { throw new SQLRuntimeException(e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "static", "<", "T", ">", "T", "autoMap", "(", "ResultSet", "rs", ",", "Class", "<", "T", ">", "cls", ")", "{", "try", "{", "if", "(", "cls", ".", "isInterface", "(", ")", ")", "{", "return", "auto...
Converts the ResultSet column values into parameters to the constructor (with number of parameters equals the number of columns) of type <code>T</code> then returns an instance of type <code>T</code>. See See {@link Builder#autoMap(Class)}. @param cls the class of the resultant instance @return an automapped instance
[ "Converts", "the", "ResultSet", "column", "values", "into", "parameters", "to", "the", "constructor", "(", "with", "number", "of", "parameters", "equals", "the", "number", "of", "columns", ")", "of", "type", "<code", ">", "T<", "/", "code", ">", "then", "r...
train
https://github.com/davidmoten/rxjava-jdbc/blob/81e157d7071a825086bde81107b8694684cdff14/src/main/java/com/github/davidmoten/rx/jdbc/Util.java#L275-L293
Erudika/para
para-client/src/main/java/com/erudika/para/client/ParaClient.java
ParaClient.formatDate
public String formatDate(String format, Locale loc) { MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("format", format); params.putSingle("locale", loc == null ? null : loc.toString()); return getEntity(invokeGet("utils/formatdate", params), String.class); }
java
public String formatDate(String format, Locale loc) { MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("format", format); params.putSingle("locale", loc == null ? null : loc.toString()); return getEntity(invokeGet("utils/formatdate", params), String.class); }
[ "public", "String", "formatDate", "(", "String", "format", ",", "Locale", "loc", ")", "{", "MultivaluedMap", "<", "String", ",", "String", ">", "params", "=", "new", "MultivaluedHashMap", "<>", "(", ")", ";", "params", ".", "putSingle", "(", "\"format\"", ...
Formats a date in a specific format. @param format the date format @param loc the locale instance @return a formatted date
[ "Formats", "a", "date", "in", "a", "specific", "format", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L1196-L1201
googleapis/google-cloud-java
google-cloud-clients/google-cloud-container/src/main/java/com/google/cloud/container/v1/ClusterManagerClient.java
ClusterManagerClient.getCluster
public final Cluster getCluster(String projectId, String zone, String clusterId) { GetClusterRequest request = GetClusterRequest.newBuilder() .setProjectId(projectId) .setZone(zone) .setClusterId(clusterId) .build(); return getCluster(request); }
java
public final Cluster getCluster(String projectId, String zone, String clusterId) { GetClusterRequest request = GetClusterRequest.newBuilder() .setProjectId(projectId) .setZone(zone) .setClusterId(clusterId) .build(); return getCluster(request); }
[ "public", "final", "Cluster", "getCluster", "(", "String", "projectId", ",", "String", "zone", ",", "String", "clusterId", ")", "{", "GetClusterRequest", "request", "=", "GetClusterRequest", ".", "newBuilder", "(", ")", ".", "setProjectId", "(", "projectId", ")"...
Gets the details of a specific cluster. <p>Sample code: <pre><code> try (ClusterManagerClient clusterManagerClient = ClusterManagerClient.create()) { String projectId = ""; String zone = ""; String clusterId = ""; Cluster response = clusterManagerClient.getCluster(projectId, zone, clusterId); } </code></pre> @param projectId Deprecated. The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840). This field has been deprecated and replaced by the name field. @param zone Deprecated. The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. This field has been deprecated and replaced by the name field. @param clusterId Deprecated. The name of the cluster to retrieve. This field has been deprecated and replaced by the name field. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Gets", "the", "details", "of", "a", "specific", "cluster", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-container/src/main/java/com/google/cloud/container/v1/ClusterManagerClient.java#L294-L303
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java
XML.addClass
public XML addClass(Class<?> aClass,Attribute[] attributes){ checksClassAbsence(aClass); XmlClass xmlClass = new XmlClass(); xmlClass.name = aClass.getName(); xmlClass.attributes = new ArrayList<XmlAttribute>(); xmlJmapper.classes.add(xmlClass); addAttributes(aClass, attributes); return this; }
java
public XML addClass(Class<?> aClass,Attribute[] attributes){ checksClassAbsence(aClass); XmlClass xmlClass = new XmlClass(); xmlClass.name = aClass.getName(); xmlClass.attributes = new ArrayList<XmlAttribute>(); xmlJmapper.classes.add(xmlClass); addAttributes(aClass, attributes); return this; }
[ "public", "XML", "addClass", "(", "Class", "<", "?", ">", "aClass", ",", "Attribute", "[", "]", "attributes", ")", "{", "checksClassAbsence", "(", "aClass", ")", ";", "XmlClass", "xmlClass", "=", "new", "XmlClass", "(", ")", ";", "xmlClass", ".", "name",...
This method adds aClass with the attributes given as input to XML configuration file.<br> It's mandatory define at least one attribute. @param aClass Class to adds @param attributes attributes of Class @return this instance
[ "This", "method", "adds", "aClass", "with", "the", "attributes", "given", "as", "input", "to", "XML", "configuration", "file", ".", "<br", ">", "It", "s", "mandatory", "define", "at", "least", "one", "attribute", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java#L237-L249
alkacon/opencms-core
src-gwt/org/opencms/ade/publish/client/CmsPublishConfirmationDialog.java
CmsPublishConfirmationDialog.getMessage
protected String getMessage(String key, Object... args) { return Messages.get().getBundle().key(key, args); }
java
protected String getMessage(String key, Object... args) { return Messages.get().getBundle().key(key, args); }
[ "protected", "String", "getMessage", "(", "String", "key", ",", "Object", "...", "args", ")", "{", "return", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "key", ",", "args", ")", ";", "}" ]
Helper method to get a localized message.<p> @param key the message key @param args the message parameters @return the localized message
[ "Helper", "method", "to", "get", "a", "localized", "message", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/publish/client/CmsPublishConfirmationDialog.java#L139-L142
apache/incubator-gobblin
gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java
SalesforceExtractor.fetchResultBatchWithRetry
private void fetchResultBatchWithRetry(RecordSetList<JsonElement> rs) throws AsyncApiException, DataRecordException, IOException { boolean success = false; int retryCount = 0; int recordCountBeforeFetch = this.bulkRecordCount; do { try { // reinitialize the reader to establish a new connection to handle transient network errors if (retryCount > 0) { reinitializeBufferedReader(); } // on retries there may already be records in rs, so pass the number of records as the initial count fetchResultBatch(rs, this.bulkRecordCount - recordCountBeforeFetch); success = true; } catch (IOException e) { if (retryCount < this.fetchRetryLimit) { log.info("Exception while fetching data, retrying: " + e.getMessage(), e); retryCount++; } else { log.error("Exception while fetching data: " + e.getMessage(), e); throw e; } } } while (!success); }
java
private void fetchResultBatchWithRetry(RecordSetList<JsonElement> rs) throws AsyncApiException, DataRecordException, IOException { boolean success = false; int retryCount = 0; int recordCountBeforeFetch = this.bulkRecordCount; do { try { // reinitialize the reader to establish a new connection to handle transient network errors if (retryCount > 0) { reinitializeBufferedReader(); } // on retries there may already be records in rs, so pass the number of records as the initial count fetchResultBatch(rs, this.bulkRecordCount - recordCountBeforeFetch); success = true; } catch (IOException e) { if (retryCount < this.fetchRetryLimit) { log.info("Exception while fetching data, retrying: " + e.getMessage(), e); retryCount++; } else { log.error("Exception while fetching data: " + e.getMessage(), e); throw e; } } } while (!success); }
[ "private", "void", "fetchResultBatchWithRetry", "(", "RecordSetList", "<", "JsonElement", ">", "rs", ")", "throws", "AsyncApiException", ",", "DataRecordException", ",", "IOException", "{", "boolean", "success", "=", "false", ";", "int", "retryCount", "=", "0", ";...
Fetch a result batch with retry for network errors @param rs the {@link RecordSetList} to fetch into
[ "Fetch", "a", "result", "batch", "with", "retry", "for", "network", "errors" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L911-L937
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java
Locale.getInstance
static Locale getInstance(String language, String country, String variant) { return getInstance(language, "", country, variant, null); }
java
static Locale getInstance(String language, String country, String variant) { return getInstance(language, "", country, variant, null); }
[ "static", "Locale", "getInstance", "(", "String", "language", ",", "String", "country", ",", "String", "variant", ")", "{", "return", "getInstance", "(", "language", ",", "\"\"", ",", "country", ",", "variant", ",", "null", ")", ";", "}" ]
Returns a <code>Locale</code> constructed from the given <code>language</code>, <code>country</code> and <code>variant</code>. If the same <code>Locale</code> instance is available in the cache, then that instance is returned. Otherwise, a new <code>Locale</code> instance is created and cached. @param language lowercase 2 to 8 language code. @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code. @param variant vendor and browser specific code. See class description. @return the <code>Locale</code> instance requested @exception NullPointerException if any argument is null.
[ "Returns", "a", "<code", ">", "Locale<", "/", "code", ">", "constructed", "from", "the", "given", "<code", ">", "language<", "/", "code", ">", "<code", ">", "country<", "/", "code", ">", "and", "<code", ">", "variant<", "/", "code", ">", ".", "If", "...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java#L728-L730
sagiegurari/fax4j
src/main/java/org/fax4j/spi/windows/WindowsJNIFaxClientSpi.java
WindowsJNIFaxClientSpi.winGetFaxJobStatus
private String winGetFaxJobStatus(String serverName,int faxJobID) { String status=null; synchronized(WindowsFaxClientSpiHelper.NATIVE_LOCK) { //pre native call this.preNativeCall(); //invoke native status=WindowsJNIFaxClientSpi.getFaxJobStatusNative(serverName,faxJobID); } return status; }
java
private String winGetFaxJobStatus(String serverName,int faxJobID) { String status=null; synchronized(WindowsFaxClientSpiHelper.NATIVE_LOCK) { //pre native call this.preNativeCall(); //invoke native status=WindowsJNIFaxClientSpi.getFaxJobStatusNative(serverName,faxJobID); } return status; }
[ "private", "String", "winGetFaxJobStatus", "(", "String", "serverName", ",", "int", "faxJobID", ")", "{", "String", "status", "=", "null", ";", "synchronized", "(", "WindowsFaxClientSpiHelper", ".", "NATIVE_LOCK", ")", "{", "//pre native call", "this", ".", "preNa...
This function returns the fax job status. @param serverName The fax server name @param faxJobID The fax job ID @return The fax job status
[ "This", "function", "returns", "the", "fax", "job", "status", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/windows/WindowsJNIFaxClientSpi.java#L349-L362
TheBlackChamber/commons-encryption
src/main/java/net/theblackchamber/crypto/implementations/SecureProperties.java
SecureProperties.attemptEncryption
private String attemptEncryption(String key, String property) { try { if (StringUtils.endsWithIgnoreCase(key, UNENCRYPTED_SUFFIX)) { if (encryptionProvider == null) throw new RuntimeCryptoException( "No encryption provider configured"); return encryptionProvider.encrypt(property); } else { return property; } } catch (MissingParameterException mpre) { throw new RuntimeCryptoException("No value to decrypt specified."); } }
java
private String attemptEncryption(String key, String property) { try { if (StringUtils.endsWithIgnoreCase(key, UNENCRYPTED_SUFFIX)) { if (encryptionProvider == null) throw new RuntimeCryptoException( "No encryption provider configured"); return encryptionProvider.encrypt(property); } else { return property; } } catch (MissingParameterException mpre) { throw new RuntimeCryptoException("No value to decrypt specified."); } }
[ "private", "String", "attemptEncryption", "(", "String", "key", ",", "String", "property", ")", "{", "try", "{", "if", "(", "StringUtils", ".", "endsWithIgnoreCase", "(", "key", ",", "UNENCRYPTED_SUFFIX", ")", ")", "{", "if", "(", "encryptionProvider", "==", ...
Utility method which will determine if a requested property needs to be encrypted. If property key ends in -unencrypted and the encryption provider is configured this method will return the encrypted property value. If the key does not include -unencrypted then the property value will be returned. @param key @param property @throws RuntimeCryptoException If not encryption provider is configured. @return
[ "Utility", "method", "which", "will", "determine", "if", "a", "requested", "property", "needs", "to", "be", "encrypted", ".", "If", "property", "key", "ends", "in", "-", "unencrypted", "and", "the", "encryption", "provider", "is", "configured", "this", "method...
train
https://github.com/TheBlackChamber/commons-encryption/blob/0cbbf7c07ae3c133cc82b6dde7ab7af91ddf64d0/src/main/java/net/theblackchamber/crypto/implementations/SecureProperties.java#L585-L598
codelibs/minhash
src/main/java/org/codelibs/minhash/MinHash.java
MinHash.createAnalyzer
public static Analyzer createAnalyzer(final Tokenizer tokenizer, final int hashBit, final int seed, final int num) { final HashFunction[] hashFunctions = MinHash.createHashFunctions(seed, num); final Analyzer minhashAnalyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents( final String fieldName) { final TokenStream stream = new MinHashTokenFilter( tokenizer, hashFunctions, hashBit); return new TokenStreamComponents(tokenizer, stream); } }; return minhashAnalyzer; }
java
public static Analyzer createAnalyzer(final Tokenizer tokenizer, final int hashBit, final int seed, final int num) { final HashFunction[] hashFunctions = MinHash.createHashFunctions(seed, num); final Analyzer minhashAnalyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents( final String fieldName) { final TokenStream stream = new MinHashTokenFilter( tokenizer, hashFunctions, hashBit); return new TokenStreamComponents(tokenizer, stream); } }; return minhashAnalyzer; }
[ "public", "static", "Analyzer", "createAnalyzer", "(", "final", "Tokenizer", "tokenizer", ",", "final", "int", "hashBit", ",", "final", "int", "seed", ",", "final", "int", "num", ")", "{", "final", "HashFunction", "[", "]", "hashFunctions", "=", "MinHash", "...
Create an analyzer to calculate a minhash. @param tokenizer a tokenizer to parse a text @param hashBit the number of hash bits @param seed a base seed for hash function @param num the number of hash functions @return analyzer used by {@link MinHash#calculate(Analyzer, String)}
[ "Create", "an", "analyzer", "to", "calculate", "a", "minhash", "." ]
train
https://github.com/codelibs/minhash/blob/2aaa16e3096461c0f550d0eb462ae9e69d1b7749/src/main/java/org/codelibs/minhash/MinHash.java#L249-L263
Ordinastie/MalisisCore
src/main/java/net/malisis/core/util/Point.java
Point.distanceSquared
public static double distanceSquared(Point p1, Point p2) { double x = p2.x - p1.x; double y = p2.y - p1.y; double z = p2.z - p1.z; return x * x + y * y + z * z; }
java
public static double distanceSquared(Point p1, Point p2) { double x = p2.x - p1.x; double y = p2.y - p1.y; double z = p2.z - p1.z; return x * x + y * y + z * z; }
[ "public", "static", "double", "distanceSquared", "(", "Point", "p1", ",", "Point", "p2", ")", "{", "double", "x", "=", "p2", ".", "x", "-", "p1", ".", "x", ";", "double", "y", "=", "p2", ".", "y", "-", "p1", ".", "y", ";", "double", "z", "=", ...
Calculates the squared distance between two {@link Point points}. @param p1 fist point @param p2 second point @return the distance squared
[ "Calculates", "the", "squared", "distance", "between", "two", "{", "@link", "Point", "points", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/Point.java#L176-L182
apache/incubator-atlas
repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasTypeDefGraphStoreV1.java
AtlasTypeDefGraphStoreV1.updateVertexProperty
private void updateVertexProperty(AtlasVertex vertex, String propertyName, Date newValue) { if (newValue != null) { Number currValue = vertex.getProperty(propertyName, Number.class); if (currValue == null || !currValue.equals(newValue.getTime())) { vertex.setProperty(propertyName, newValue.getTime()); } } }
java
private void updateVertexProperty(AtlasVertex vertex, String propertyName, Date newValue) { if (newValue != null) { Number currValue = vertex.getProperty(propertyName, Number.class); if (currValue == null || !currValue.equals(newValue.getTime())) { vertex.setProperty(propertyName, newValue.getTime()); } } }
[ "private", "void", "updateVertexProperty", "(", "AtlasVertex", "vertex", ",", "String", "propertyName", ",", "Date", "newValue", ")", "{", "if", "(", "newValue", "!=", "null", ")", "{", "Number", "currValue", "=", "vertex", ".", "getProperty", "(", "propertyNa...
/* update the given vertex property, if the new value is not-null
[ "/", "*", "update", "the", "given", "vertex", "property", "if", "the", "new", "value", "is", "not", "-", "null" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasTypeDefGraphStoreV1.java#L441-L449
keenon/loglinear
src/main/java/com/github/keenon/loglinear/model/NDArrayDoubles.java
NDArrayDoubles.valueEquals
public boolean valueEquals(NDArrayDoubles other, double tolerance) { if (!Arrays.equals(dimensions, other.dimensions)) return false; if (dimensions.length != other.dimensions.length) return false; for (int i = 0; i < dimensions.length; i++) { if (Math.abs(dimensions[i] - other.dimensions[i]) > tolerance) return false; } return true; }
java
public boolean valueEquals(NDArrayDoubles other, double tolerance) { if (!Arrays.equals(dimensions, other.dimensions)) return false; if (dimensions.length != other.dimensions.length) return false; for (int i = 0; i < dimensions.length; i++) { if (Math.abs(dimensions[i] - other.dimensions[i]) > tolerance) return false; } return true; }
[ "public", "boolean", "valueEquals", "(", "NDArrayDoubles", "other", ",", "double", "tolerance", ")", "{", "if", "(", "!", "Arrays", ".", "equals", "(", "dimensions", ",", "other", ".", "dimensions", ")", ")", "return", "false", ";", "if", "(", "dimensions"...
Does a deep comparison, using equality with tolerance checks against the vector table of values. @param other the factor to compare to @param tolerance the tolerance to accept in differences @return whether the two factors are within tolerance of one another
[ "Does", "a", "deep", "comparison", "using", "equality", "with", "tolerance", "checks", "against", "the", "vector", "table", "of", "values", "." ]
train
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/model/NDArrayDoubles.java#L164-L171
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_activateSharepoint_POST
public OvhTask organizationName_service_exchangeService_activateSharepoint_POST(String organizationName, String exchangeService, String primaryEmailAddress, String subDomain) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/activateSharepoint"; StringBuilder sb = path(qPath, organizationName, exchangeService); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "primaryEmailAddress", primaryEmailAddress); addBody(o, "subDomain", subDomain); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask organizationName_service_exchangeService_activateSharepoint_POST(String organizationName, String exchangeService, String primaryEmailAddress, String subDomain) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/activateSharepoint"; StringBuilder sb = path(qPath, organizationName, exchangeService); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "primaryEmailAddress", primaryEmailAddress); addBody(o, "subDomain", subDomain); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "organizationName_service_exchangeService_activateSharepoint_POST", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "String", "primaryEmailAddress", ",", "String", "subDomain", ")", "throws", "IOException", "{", "String", "qPath"...
Activate Sharepoint infra connected to this exchange service REST: POST /email/exchange/{organizationName}/service/{exchangeService}/activateSharepoint @param subDomain [required] sub domain that will be used for Your sharepoint infra (You will not be able to change it!) @param primaryEmailAddress [required] primary email address of a user that will be admin of sharepoint (You will not be able to change it!) @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service
[ "Activate", "Sharepoint", "infra", "connected", "to", "this", "exchange", "service" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L1028-L1036
reactor/reactor-netty
src/main/java/reactor/netty/http/client/HttpClient.java
HttpClient.httpResponseDecoder
public final HttpClient httpResponseDecoder(Function<HttpResponseDecoderSpec, HttpResponseDecoderSpec> responseDecoderOptions) { return tcpConfiguration( responseDecoderOptions.apply(new HttpResponseDecoderSpec()) .build()); }
java
public final HttpClient httpResponseDecoder(Function<HttpResponseDecoderSpec, HttpResponseDecoderSpec> responseDecoderOptions) { return tcpConfiguration( responseDecoderOptions.apply(new HttpResponseDecoderSpec()) .build()); }
[ "public", "final", "HttpClient", "httpResponseDecoder", "(", "Function", "<", "HttpResponseDecoderSpec", ",", "HttpResponseDecoderSpec", ">", "responseDecoderOptions", ")", "{", "return", "tcpConfiguration", "(", "responseDecoderOptions", ".", "apply", "(", "new", "HttpRe...
Configure the {@link io.netty.handler.codec.http.HttpClientCodec}'s response decoding options. @param responseDecoderOptions a function to mutate the provided Http response decoder options @return a new {@link HttpClient}
[ "Configure", "the", "{", "@link", "io", ".", "netty", ".", "handler", ".", "codec", ".", "http", ".", "HttpClientCodec", "}", "s", "response", "decoding", "options", "." ]
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L829-L833
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/WidgetUtil.java
WidgetUtil.embedFlashObject
public static HTML embedFlashObject (Panel container, String htmlString) { // Please note: the following is a work-around for an IE7 bug. If we create a Flash object // node *before* attaching it to the DOM tree, IE will silently fail to register // the Flash object's callback functions for access from JavaScript. To make this work, // create an empty node first, add it to the DOM tree, and then initialize it with // the Flash object definition. HTML element = new HTML(); container.add(element); element.setHTML(htmlString); return element; }
java
public static HTML embedFlashObject (Panel container, String htmlString) { // Please note: the following is a work-around for an IE7 bug. If we create a Flash object // node *before* attaching it to the DOM tree, IE will silently fail to register // the Flash object's callback functions for access from JavaScript. To make this work, // create an empty node first, add it to the DOM tree, and then initialize it with // the Flash object definition. HTML element = new HTML(); container.add(element); element.setHTML(htmlString); return element; }
[ "public", "static", "HTML", "embedFlashObject", "(", "Panel", "container", ",", "String", "htmlString", ")", "{", "// Please note: the following is a work-around for an IE7 bug. If we create a Flash object", "// node *before* attaching it to the DOM tree, IE will silently fail to register"...
Given an HTML string that defines a Flash object, creates a new DOM node for it and adds it to the appropriate container. Please note: the container should be added to the page prior to calling this function.
[ "Given", "an", "HTML", "string", "that", "defines", "a", "Flash", "object", "creates", "a", "new", "DOM", "node", "for", "it", "and", "adds", "it", "to", "the", "appropriate", "container", ".", "Please", "note", ":", "the", "container", "should", "be", "...
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/WidgetUtil.java#L203-L214
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/subdoc/LookupInBuilder.java
LookupInBuilder.getCount
public LookupInBuilder getCount(Iterable<String> paths, SubdocOptionsBuilder optionsBuilder) { this.async.getCount(paths, optionsBuilder); return this; }
java
public LookupInBuilder getCount(Iterable<String> paths, SubdocOptionsBuilder optionsBuilder) { this.async.getCount(paths, optionsBuilder); return this; }
[ "public", "LookupInBuilder", "getCount", "(", "Iterable", "<", "String", ">", "paths", ",", "SubdocOptionsBuilder", "optionsBuilder", ")", "{", "this", ".", "async", ".", "getCount", "(", "paths", ",", "optionsBuilder", ")", ";", "return", "this", ";", "}" ]
Get a count of values inside the JSON document. This method is only available with Couchbase Server 5.0 and later. @param paths the paths inside the document where to get the count from. @param optionsBuilder {@link SubdocOptionsBuilder} @return this builder for chaining.
[ "Get", "a", "count", "of", "values", "inside", "the", "JSON", "document", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/LookupInBuilder.java#L292-L295
playn/playn
android/src/playn/android/AndroidAudio.java
AndroidAudio.createSound
public SoundImpl<?> createSound(AssetFileDescriptor fd) { PooledSound sound = new PooledSound(pool.load(fd, 1)); loadingSounds.put(sound.soundId, sound); return sound; }
java
public SoundImpl<?> createSound(AssetFileDescriptor fd) { PooledSound sound = new PooledSound(pool.load(fd, 1)); loadingSounds.put(sound.soundId, sound); return sound; }
[ "public", "SoundImpl", "<", "?", ">", "createSound", "(", "AssetFileDescriptor", "fd", ")", "{", "PooledSound", "sound", "=", "new", "PooledSound", "(", "pool", ".", "load", "(", "fd", ",", "1", ")", ")", ";", "loadingSounds", ".", "put", "(", "sound", ...
Creates a sound instance from the supplied asset file descriptor.
[ "Creates", "a", "sound", "instance", "from", "the", "supplied", "asset", "file", "descriptor", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/android/src/playn/android/AndroidAudio.java#L125-L129
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java
JobOperations.createJob
public void createJob(String jobId, PoolInformation poolInfo, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { JobAddParameter param = new JobAddParameter() .withId(jobId) .withPoolInfo(poolInfo); createJob(param, additionalBehaviors); }
java
public void createJob(String jobId, PoolInformation poolInfo, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { JobAddParameter param = new JobAddParameter() .withId(jobId) .withPoolInfo(poolInfo); createJob(param, additionalBehaviors); }
[ "public", "void", "createJob", "(", "String", "jobId", ",", "PoolInformation", "poolInfo", ",", "Iterable", "<", "BatchClientBehavior", ">", "additionalBehaviors", ")", "throws", "BatchErrorException", ",", "IOException", "{", "JobAddParameter", "param", "=", "new", ...
Adds a job to the Batch account. @param jobId The ID of the job to be added. @param poolInfo Specifies how a job should be assigned to a pool. @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Adds", "a", "job", "to", "the", "Batch", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java#L289-L295
facebook/fresco
drawee-span/src/main/java/com/facebook/drawee/span/SimpleDraweeSpanTextView.java
SimpleDraweeSpanTextView.setDraweeSpanStringBuilder
public void setDraweeSpanStringBuilder(DraweeSpanStringBuilder draweeSpanStringBuilder) { // setText will trigger onTextChanged, which will clean up the old draweeSpanStringBuilder // if necessary setText(draweeSpanStringBuilder, BufferType.SPANNABLE); mDraweeStringBuilder = draweeSpanStringBuilder; if (mDraweeStringBuilder != null && mIsAttached) { mDraweeStringBuilder.onAttachToView(this); } }
java
public void setDraweeSpanStringBuilder(DraweeSpanStringBuilder draweeSpanStringBuilder) { // setText will trigger onTextChanged, which will clean up the old draweeSpanStringBuilder // if necessary setText(draweeSpanStringBuilder, BufferType.SPANNABLE); mDraweeStringBuilder = draweeSpanStringBuilder; if (mDraweeStringBuilder != null && mIsAttached) { mDraweeStringBuilder.onAttachToView(this); } }
[ "public", "void", "setDraweeSpanStringBuilder", "(", "DraweeSpanStringBuilder", "draweeSpanStringBuilder", ")", "{", "// setText will trigger onTextChanged, which will clean up the old draweeSpanStringBuilder", "// if necessary", "setText", "(", "draweeSpanStringBuilder", ",", "BufferTyp...
Bind the given string builder to this view. @param draweeSpanStringBuilder the builder to attach to
[ "Bind", "the", "given", "string", "builder", "to", "this", "view", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee-span/src/main/java/com/facebook/drawee/span/SimpleDraweeSpanTextView.java#L85-L93
knowm/Sundial
src/main/java/org/knowm/sundial/SundialJobScheduler.java
SundialJobScheduler.addJob
public static void addJob( String jobName, Class<? extends Job> jobClass, Map<String, Object> params, boolean isConcurrencyAllowed) throws SundialSchedulerException { try { JobDataMap jobDataMap = new JobDataMap(); if (params != null) { for (Entry<String, Object> entry : params.entrySet()) { jobDataMap.put(entry.getKey(), entry.getValue()); } } JobDetail jobDetail = newJobBuilder(jobClass) .withIdentity(jobName) .usingJobData(jobDataMap) .isConcurrencyAllowed(isConcurrencyAllowed) .build(); getScheduler().addJob(jobDetail); } catch (SchedulerException e) { logger.error("ERROR ADDING JOB!!!", e); throw new SundialSchedulerException("ERROR ADDING JOB!!!", e); } }
java
public static void addJob( String jobName, Class<? extends Job> jobClass, Map<String, Object> params, boolean isConcurrencyAllowed) throws SundialSchedulerException { try { JobDataMap jobDataMap = new JobDataMap(); if (params != null) { for (Entry<String, Object> entry : params.entrySet()) { jobDataMap.put(entry.getKey(), entry.getValue()); } } JobDetail jobDetail = newJobBuilder(jobClass) .withIdentity(jobName) .usingJobData(jobDataMap) .isConcurrencyAllowed(isConcurrencyAllowed) .build(); getScheduler().addJob(jobDetail); } catch (SchedulerException e) { logger.error("ERROR ADDING JOB!!!", e); throw new SundialSchedulerException("ERROR ADDING JOB!!!", e); } }
[ "public", "static", "void", "addJob", "(", "String", "jobName", ",", "Class", "<", "?", "extends", "Job", ">", "jobClass", ",", "Map", "<", "String", ",", "Object", ">", "params", ",", "boolean", "isConcurrencyAllowed", ")", "throws", "SundialSchedulerExceptio...
Adds a Job to the scheduler. Replaces a matching existing Job. @param jobName @param jobClass @param params Set this null if there are no params @param isConcurrencyAllowed
[ "Adds", "a", "Job", "to", "the", "scheduler", ".", "Replaces", "a", "matching", "existing", "Job", "." ]
train
https://github.com/knowm/Sundial/blob/0d61549fdfb8d6f884a1f2eed7e32ad39e2f4c62/src/main/java/org/knowm/sundial/SundialJobScheduler.java#L213-L241
jtrfp/javamod
src/main/java/de/quippy/javamod/multimedia/mp3/id3/ID3v2Tag.java
ID3v2Tag.setUserDefinedURLFrame
public void setUserDefinedURLFrame(String description, String value) { try { byte[] b = new byte[description.length() + value.length() + 2]; int bytesCopied = 0; b[bytesCopied++] = 0; System.arraycopy(description.getBytes(ENC_TYPE), 0, b, bytesCopied, description.length()); bytesCopied += description.length(); b[bytesCopied++] = 0; System.arraycopy(value.getBytes(), 0, b, bytesCopied, value.length()); bytesCopied += value.length(); updateFrameData(ID3v2Frames.USER_DEFINED_URL, b); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
java
public void setUserDefinedURLFrame(String description, String value) { try { byte[] b = new byte[description.length() + value.length() + 2]; int bytesCopied = 0; b[bytesCopied++] = 0; System.arraycopy(description.getBytes(ENC_TYPE), 0, b, bytesCopied, description.length()); bytesCopied += description.length(); b[bytesCopied++] = 0; System.arraycopy(value.getBytes(), 0, b, bytesCopied, value.length()); bytesCopied += value.length(); updateFrameData(ID3v2Frames.USER_DEFINED_URL, b); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
[ "public", "void", "setUserDefinedURLFrame", "(", "String", "description", ",", "String", "value", ")", "{", "try", "{", "byte", "[", "]", "b", "=", "new", "byte", "[", "description", ".", "length", "(", ")", "+", "value", ".", "length", "(", ")", "+", ...
Sets the data contained in the user defined url frame (WXXX). @param description a description of the url @param value the url for the frame
[ "Sets", "the", "data", "contained", "in", "the", "user", "defined", "url", "frame", "(", "WXXX", ")", "." ]
train
https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mp3/id3/ID3v2Tag.java#L368-L387
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/NotificationsApi.java
NotificationsApi.connectWithHttpInfo
public ApiResponse<Void> connectWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = connectValidateBeforeCall(null, null); return apiClient.execute(call); }
java
public ApiResponse<Void> connectWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = connectValidateBeforeCall(null, null); return apiClient.execute(call); }
[ "public", "ApiResponse", "<", "Void", ">", "connectWithHttpInfo", "(", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "connectValidateBeforeCall", "(", "null", ",", "null", ")", ";", "return", "apiClient", ...
CometD connect CometD connect, see https://docs.cometd.org/current/reference/#_bayeux_meta_connect @return ApiResponse&lt;Void&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "CometD", "connect", "CometD", "connect", "see", "https", ":", "//", "docs", ".", "cometd", ".", "org", "/", "current", "/", "reference", "/", "#_bayeux_meta_connect" ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/NotificationsApi.java#L128-L131
edwardcapriolo/teknek-core
src/main/java/io/teknek/driver/DriverFactory.java
DriverFactory.buildOperator
public static Operator buildOperator(OperatorDesc operatorDesc, MetricRegistry metricRegistry, String planPath, FeedPartition feedPartition) { Operator operator = null; NitFactory nitFactory = new NitFactory(); NitDesc nitDesc = nitDescFromDynamic(operatorDesc); try { if (nitDesc.getSpec() == NitDesc.NitSpec.GROOVY_CLOSURE){ operator = new GroovyOperator((Closure) nitFactory.construct(nitDesc)); } else { operator = nitFactory.construct(nitDesc); } } catch (NitException e) { throw new RuntimeException(e); } operator.setProperties(operatorDesc.getParameters()); operator.setMetricRegistry(metricRegistry); operator.setPartitionId(feedPartition.getPartitionId()); String myName = operatorDesc.getName(); if (myName == null){ myName = operatorDesc.getTheClass(); if (myName.indexOf(".") > -1){ String[] parts = myName.split("\\."); myName = parts[parts.length-1]; } } operator.setPath(planPath + "." + myName); return operator; }
java
public static Operator buildOperator(OperatorDesc operatorDesc, MetricRegistry metricRegistry, String planPath, FeedPartition feedPartition) { Operator operator = null; NitFactory nitFactory = new NitFactory(); NitDesc nitDesc = nitDescFromDynamic(operatorDesc); try { if (nitDesc.getSpec() == NitDesc.NitSpec.GROOVY_CLOSURE){ operator = new GroovyOperator((Closure) nitFactory.construct(nitDesc)); } else { operator = nitFactory.construct(nitDesc); } } catch (NitException e) { throw new RuntimeException(e); } operator.setProperties(operatorDesc.getParameters()); operator.setMetricRegistry(metricRegistry); operator.setPartitionId(feedPartition.getPartitionId()); String myName = operatorDesc.getName(); if (myName == null){ myName = operatorDesc.getTheClass(); if (myName.indexOf(".") > -1){ String[] parts = myName.split("\\."); myName = parts[parts.length-1]; } } operator.setPath(planPath + "." + myName); return operator; }
[ "public", "static", "Operator", "buildOperator", "(", "OperatorDesc", "operatorDesc", ",", "MetricRegistry", "metricRegistry", ",", "String", "planPath", ",", "FeedPartition", "feedPartition", ")", "{", "Operator", "operator", "=", "null", ";", "NitFactory", "nitFacto...
OperatorDesc can describe local reasources, URL, loaded resources and dynamic resources like groovy code. This method instantiates an Operator based on the OperatorDesc. @param operatorDesc @return
[ "OperatorDesc", "can", "describe", "local", "reasources", "URL", "loaded", "resources", "and", "dynamic", "resources", "like", "groovy", "code", ".", "This", "method", "instantiates", "an", "Operator", "based", "on", "the", "OperatorDesc", "." ]
train
https://github.com/edwardcapriolo/teknek-core/blob/4fa972d11044dee2954c0cc5e1b53b18fba319b9/src/main/java/io/teknek/driver/DriverFactory.java#L127-L153
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java
Util.generateCacheFileFullPath
public static String generateCacheFileFullPath(Uri fileOriginalUri, File cacheDir, long createdTime) { String source = fileOriginalUri.toString() + Long.toString(createdTime); String fileName = md5(source); File cacheFile = new File(cacheDir, fileName); return cacheFile.getPath(); }
java
public static String generateCacheFileFullPath(Uri fileOriginalUri, File cacheDir, long createdTime) { String source = fileOriginalUri.toString() + Long.toString(createdTime); String fileName = md5(source); File cacheFile = new File(cacheDir, fileName); return cacheFile.getPath(); }
[ "public", "static", "String", "generateCacheFileFullPath", "(", "Uri", "fileOriginalUri", ",", "File", "cacheDir", ",", "long", "createdTime", ")", "{", "String", "source", "=", "fileOriginalUri", ".", "toString", "(", ")", "+", "Long", ".", "toString", "(", "...
/* Generate cached file name use md5 from file originalPath and created time
[ "/", "*", "Generate", "cached", "file", "name", "use", "md5", "from", "file", "originalPath", "and", "created", "time" ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L599-L604
apereo/cas
support/cas-server-support-saml-googleapps-core/src/main/java/org/apereo/cas/support/saml/authentication/principal/GoogleAccountsServiceResponseBuilder.java
GoogleAccountsServiceResponseBuilder.createGoogleAppsPublicKey
protected void createGoogleAppsPublicKey() throws Exception { if (!isValidConfiguration()) { LOGGER.debug("Google Apps public key bean will not be created, because it's not configured"); return; } val bean = new PublicKeyFactoryBean(); if (this.publicKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { bean.setResource(new ClassPathResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX))); } else if (this.publicKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) { bean.setResource(new FileSystemResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.FILE_URL_PREFIX))); } else { bean.setResource(new FileSystemResource(this.publicKeyLocation)); } bean.setAlgorithm(this.keyAlgorithm); LOGGER.debug("Loading Google Apps public key from [{}] with key algorithm [{}]", bean.getResource(), bean.getAlgorithm()); bean.afterPropertiesSet(); LOGGER.debug("Creating Google Apps public key instance via [{}]", this.publicKeyLocation); this.publicKey = bean.getObject(); }
java
protected void createGoogleAppsPublicKey() throws Exception { if (!isValidConfiguration()) { LOGGER.debug("Google Apps public key bean will not be created, because it's not configured"); return; } val bean = new PublicKeyFactoryBean(); if (this.publicKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { bean.setResource(new ClassPathResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX))); } else if (this.publicKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) { bean.setResource(new FileSystemResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.FILE_URL_PREFIX))); } else { bean.setResource(new FileSystemResource(this.publicKeyLocation)); } bean.setAlgorithm(this.keyAlgorithm); LOGGER.debug("Loading Google Apps public key from [{}] with key algorithm [{}]", bean.getResource(), bean.getAlgorithm()); bean.afterPropertiesSet(); LOGGER.debug("Creating Google Apps public key instance via [{}]", this.publicKeyLocation); this.publicKey = bean.getObject(); }
[ "protected", "void", "createGoogleAppsPublicKey", "(", ")", "throws", "Exception", "{", "if", "(", "!", "isValidConfiguration", "(", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"Google Apps public key bean will not be created, because it's not configured\"", ")", ";", ...
Create the public key. @throws Exception if key creation ran into an error
[ "Create", "the", "public", "key", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-googleapps-core/src/main/java/org/apereo/cas/support/saml/authentication/principal/GoogleAccountsServiceResponseBuilder.java#L172-L193
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/logic/Expression.java
Expression.findEndOfSubExpression
public static int findEndOfSubExpression(String expression, int start) { int count = 0; for (int i = start; i < expression.length(); i++) { switch (expression.charAt(i)) { case '(': { count++; break; } case ')': { count--; if (count == 0) { return i; } break; } } } throw new IllegalArgumentException("can't parse expression [" + expression + "]: end of subexpression not found"); }
java
public static int findEndOfSubExpression(String expression, int start) { int count = 0; for (int i = start; i < expression.length(); i++) { switch (expression.charAt(i)) { case '(': { count++; break; } case ')': { count--; if (count == 0) { return i; } break; } } } throw new IllegalArgumentException("can't parse expression [" + expression + "]: end of subexpression not found"); }
[ "public", "static", "int", "findEndOfSubExpression", "(", "String", "expression", ",", "int", "start", ")", "{", "int", "count", "=", "0", ";", "for", "(", "int", "i", "=", "start", ";", "i", "<", "expression", ".", "length", "(", ")", ";", "i", "++"...
Finds the position of the end bracket ')' matching a start bracket '('. @param expression @param start position of the start bracket @return position of the matching end bracket or 0 if it can not be located
[ "Finds", "the", "position", "of", "the", "end", "bracket", ")", "matching", "a", "start", "bracket", "(", "." ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/logic/Expression.java#L290-L308
KyoriPowered/lunar
src/main/java/net/kyori/lunar/graph/MoreGraphs.java
MoreGraphs.topologicalSort
public static <T> @NonNull List<T> topologicalSort(final @NonNull Graph<T> graph) { return topologicalSort(graph, SortType.random()); }
java
public static <T> @NonNull List<T> topologicalSort(final @NonNull Graph<T> graph) { return topologicalSort(graph, SortType.random()); }
[ "public", "static", "<", "T", ">", "@", "NonNull", "List", "<", "T", ">", "topologicalSort", "(", "final", "@", "NonNull", "Graph", "<", "T", ">", "graph", ")", "{", "return", "topologicalSort", "(", "graph", ",", "SortType", ".", "random", "(", ")", ...
Sorts a directed acyclic graph into a list. <p>The particular order of elements without prerequisites is not guaranteed.</p> @param graph the graph to be sorted @param <T> the node type @return the sorted list @throws CyclePresentException if the graph has cycles @throws IllegalArgumentException if the graph is not directed or allows self loops
[ "Sorts", "a", "directed", "acyclic", "graph", "into", "a", "list", "." ]
train
https://github.com/KyoriPowered/lunar/blob/6856747d9034a2fe0c8d0a8a0150986797732b5c/src/main/java/net/kyori/lunar/graph/MoreGraphs.java#L56-L58
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormatSymbols.java
DateFormatSymbols.setMonths
public void setMonths(String[] newMonths, int context, int width) { switch (context) { case FORMAT : switch(width) { case WIDE : months = duplicate(newMonths); break; case ABBREVIATED : shortMonths = duplicate(newMonths); break; case NARROW : narrowMonths = duplicate(newMonths); break; default : // HANDLE SHORT, etc. break; } break; case STANDALONE : switch(width) { case WIDE : standaloneMonths = duplicate(newMonths); break; case ABBREVIATED : standaloneShortMonths = duplicate(newMonths); break; case NARROW : standaloneNarrowMonths = duplicate(newMonths); break; default : // HANDLE SHORT, etc. break; } break; } }
java
public void setMonths(String[] newMonths, int context, int width) { switch (context) { case FORMAT : switch(width) { case WIDE : months = duplicate(newMonths); break; case ABBREVIATED : shortMonths = duplicate(newMonths); break; case NARROW : narrowMonths = duplicate(newMonths); break; default : // HANDLE SHORT, etc. break; } break; case STANDALONE : switch(width) { case WIDE : standaloneMonths = duplicate(newMonths); break; case ABBREVIATED : standaloneShortMonths = duplicate(newMonths); break; case NARROW : standaloneNarrowMonths = duplicate(newMonths); break; default : // HANDLE SHORT, etc. break; } break; } }
[ "public", "void", "setMonths", "(", "String", "[", "]", "newMonths", ",", "int", "context", ",", "int", "width", ")", "{", "switch", "(", "context", ")", "{", "case", "FORMAT", ":", "switch", "(", "width", ")", "{", "case", "WIDE", ":", "months", "="...
Sets month strings. For example: "January", "February", etc. @param newMonths the new month strings. @param context The formatting context, FORMAT or STANDALONE. @param width The width of the month string, either WIDE, ABBREVIATED, or NARROW.
[ "Sets", "month", "strings", ".", "For", "example", ":", "January", "February", "etc", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormatSymbols.java#L824-L857
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java
ImageModerationsImpl.evaluateFileInputWithServiceResponseAsync
public Observable<ServiceResponse<Evaluate>> evaluateFileInputWithServiceResponseAsync(byte[] imageStream, EvaluateFileInputOptionalParameter evaluateFileInputOptionalParameter) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } if (imageStream == null) { throw new IllegalArgumentException("Parameter imageStream is required and cannot be null."); } final Boolean cacheImage = evaluateFileInputOptionalParameter != null ? evaluateFileInputOptionalParameter.cacheImage() : null; return evaluateFileInputWithServiceResponseAsync(imageStream, cacheImage); }
java
public Observable<ServiceResponse<Evaluate>> evaluateFileInputWithServiceResponseAsync(byte[] imageStream, EvaluateFileInputOptionalParameter evaluateFileInputOptionalParameter) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } if (imageStream == null) { throw new IllegalArgumentException("Parameter imageStream is required and cannot be null."); } final Boolean cacheImage = evaluateFileInputOptionalParameter != null ? evaluateFileInputOptionalParameter.cacheImage() : null; return evaluateFileInputWithServiceResponseAsync(imageStream, cacheImage); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Evaluate", ">", ">", "evaluateFileInputWithServiceResponseAsync", "(", "byte", "[", "]", "imageStream", ",", "EvaluateFileInputOptionalParameter", "evaluateFileInputOptionalParameter", ")", "{", "if", "(", "this", ".",...
Returns probabilities of the image containing racy or adult content. @param imageStream The image file. @param evaluateFileInputOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the Evaluate object
[ "Returns", "probabilities", "of", "the", "image", "containing", "racy", "or", "adult", "content", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java#L1468-L1478
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobAgentsInner.java
JobAgentsInner.createOrUpdateAsync
public Observable<JobAgentInner> createOrUpdateAsync(String resourceGroupName, String serverName, String jobAgentName, JobAgentInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, parameters).map(new Func1<ServiceResponse<JobAgentInner>, JobAgentInner>() { @Override public JobAgentInner call(ServiceResponse<JobAgentInner> response) { return response.body(); } }); }
java
public Observable<JobAgentInner> createOrUpdateAsync(String resourceGroupName, String serverName, String jobAgentName, JobAgentInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, parameters).map(new Func1<ServiceResponse<JobAgentInner>, JobAgentInner>() { @Override public JobAgentInner call(ServiceResponse<JobAgentInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "JobAgentInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "jobAgentName", ",", "JobAgentInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(",...
Creates or updates a job agent. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param jobAgentName The name of the job agent to be created or updated. @param parameters The requested job agent resource state. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "job", "agent", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobAgentsInner.java#L362-L369
davetcc/tcMenu
tcMenuCodePluginApi/src/main/java/com/thecoderscorner/menu/pluginapi/AbstractCodeCreator.java
AbstractCodeCreator.addExportVariableIfPresent
protected void addExportVariableIfPresent(String variable, String typeName) { String expVar = findPropertyValue(variable).getLatestValue(); if(expVar != null && !expVar.isEmpty()) { addVariable(new CodeVariableBuilder().exportOnly().variableType(typeName).variableName(expVar)); } }
java
protected void addExportVariableIfPresent(String variable, String typeName) { String expVar = findPropertyValue(variable).getLatestValue(); if(expVar != null && !expVar.isEmpty()) { addVariable(new CodeVariableBuilder().exportOnly().variableType(typeName).variableName(expVar)); } }
[ "protected", "void", "addExportVariableIfPresent", "(", "String", "variable", ",", "String", "typeName", ")", "{", "String", "expVar", "=", "findPropertyValue", "(", "variable", ")", ".", "getLatestValue", "(", ")", ";", "if", "(", "expVar", "!=", "null", "&&"...
Adds a variable for export only when a property is present @param variable the variable name (and also the expected property value) @param typeName the type name
[ "Adds", "a", "variable", "for", "export", "only", "when", "a", "property", "is", "present" ]
train
https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuCodePluginApi/src/main/java/com/thecoderscorner/menu/pluginapi/AbstractCodeCreator.java#L92-L97
osmdroid/osmdroid
OpenStreetMapViewer/src/main/java/org/osmdroid/StarterMapActivity.java
StarterMapActivity.onKeyUp
@Override public boolean onKeyUp (int keyCode, KeyEvent event){ MapView mMapView = getMapView(); if (mMapView==null) return super.onKeyUp(keyCode,event); switch (keyCode) { case KeyEvent.KEYCODE_PAGE_DOWN: mMapView.getController().zoomIn(); return true; case KeyEvent.KEYCODE_PAGE_UP: mMapView.getController().zoomOut(); return true; } return super.onKeyUp(keyCode,event); }
java
@Override public boolean onKeyUp (int keyCode, KeyEvent event){ MapView mMapView = getMapView(); if (mMapView==null) return super.onKeyUp(keyCode,event); switch (keyCode) { case KeyEvent.KEYCODE_PAGE_DOWN: mMapView.getController().zoomIn(); return true; case KeyEvent.KEYCODE_PAGE_UP: mMapView.getController().zoomOut(); return true; } return super.onKeyUp(keyCode,event); }
[ "@", "Override", "public", "boolean", "onKeyUp", "(", "int", "keyCode", ",", "KeyEvent", "event", ")", "{", "MapView", "mMapView", "=", "getMapView", "(", ")", ";", "if", "(", "mMapView", "==", "null", ")", "return", "super", ".", "onKeyUp", "(", "keyCod...
small example of keyboard events on the mapview page up = zoom out page down = zoom in @param keyCode @param event @return
[ "small", "example", "of", "keyboard", "events", "on", "the", "mapview", "page", "up", "=", "zoom", "out", "page", "down", "=", "zoom", "in" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/StarterMapActivity.java#L82-L97
realtime-framework/RealtimeStorage-Android
library/src/main/java/co/realtime/storage/TableRef.java
TableRef.notContains
public TableRef notContains(String attributeName, ItemAttribute value){ filters.add(new Filter(StorageFilter.NOTCONTAINS, attributeName, value, null)); return this; }
java
public TableRef notContains(String attributeName, ItemAttribute value){ filters.add(new Filter(StorageFilter.NOTCONTAINS, attributeName, value, null)); return this; }
[ "public", "TableRef", "notContains", "(", "String", "attributeName", ",", "ItemAttribute", "value", ")", "{", "filters", ".", "add", "(", "new", "Filter", "(", "StorageFilter", ".", "NOTCONTAINS", ",", "attributeName", ",", "value", ",", "null", ")", ")", ";...
Applies a filter to the table. When fetched, it will return the items that does not contains the filter property value. <pre> StorageRef storage = new StorageRef("your_app_key", "your_token"); TableRef tableRef = storage.table("your_table"); // Retrieve all items with property "itemProperty" contains the value "xpto" tableRef.notContains("itemProperty",new ItemAttribute("xpto")).getItems(new OnItemSnapshot() { &#064;Override public void run(ItemSnapshot itemSnapshot) { if (itemSnapshot != null) { Log.d("TableRef", "Item retrieved: " + itemSnapshot.val()); } } }, new OnError() { &#064;Override public void run(Integer code, String errorMessage) { Log.e("TableRef", "Error retrieving items: " + errorMessage); } }); </pre> @param attributeName The name of the property to filter. @param value The value of the property to filter. @return Current table reference
[ "Applies", "a", "filter", "to", "the", "table", ".", "When", "fetched", "it", "will", "return", "the", "items", "that", "does", "not", "contains", "the", "filter", "property", "value", "." ]
train
https://github.com/realtime-framework/RealtimeStorage-Android/blob/05816a6b7a6dcc83f9e7400ac3048494dadca302/library/src/main/java/co/realtime/storage/TableRef.java#L897-L900
alkacon/opencms-core
src/org/opencms/configuration/CmsParameterConfiguration.java
CmsParameterConfiguration.appendToXml
public Element appendToXml(Element parentNode, List<String> parametersToIgnore) { for (Map.Entry<String, Serializable> entry : m_configurationObjects.entrySet()) { String name = entry.getKey(); // check if the parameter should be ignored if ((parametersToIgnore == null) || !parametersToIgnore.contains(name)) { // now serialize the parameter name and value Object value = entry.getValue(); if (value instanceof List) { @SuppressWarnings("unchecked") List<String> values = (List<String>)value; for (String strValue : values) { // use the original String as value Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } else { // use the original String as value String strValue = get(name); Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } } return parentNode; }
java
public Element appendToXml(Element parentNode, List<String> parametersToIgnore) { for (Map.Entry<String, Serializable> entry : m_configurationObjects.entrySet()) { String name = entry.getKey(); // check if the parameter should be ignored if ((parametersToIgnore == null) || !parametersToIgnore.contains(name)) { // now serialize the parameter name and value Object value = entry.getValue(); if (value instanceof List) { @SuppressWarnings("unchecked") List<String> values = (List<String>)value; for (String strValue : values) { // use the original String as value Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } else { // use the original String as value String strValue = get(name); Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } } return parentNode; }
[ "public", "Element", "appendToXml", "(", "Element", "parentNode", ",", "List", "<", "String", ">", "parametersToIgnore", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Serializable", ">", "entry", ":", "m_configurationObjects", ".", "entrySet"...
Serializes this parameter configuration for the OpenCms XML configuration.<p> For each parameter, a XML node like this<br> <code> &lt;param name="theName"&gt;theValue&lt;/param&gt; </code><br> is generated and appended to the provided parent node.<p> @param parentNode the parent node where the parameter nodes are appended to @param parametersToIgnore if not <code>null</code>, all parameters in this list are not written to the XML @return the parent node
[ "Serializes", "this", "parameter", "configuration", "for", "the", "OpenCms", "XML", "configuration", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/configuration/CmsParameterConfiguration.java#L427-L459
alkacon/opencms-core
src/org/opencms/site/CmsSiteManagerImpl.java
CmsSiteManagerImpl.addAliasToConfigSite
public void addAliasToConfigSite(String alias, String redirect, String offset) { long timeOffset = 0; try { timeOffset = Long.parseLong(offset); } catch (Throwable e) { // ignore } CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset); boolean redirectVal = new Boolean(redirect).booleanValue(); siteMatcher.setRedirect(redirectVal); m_aliases.add(siteMatcher); }
java
public void addAliasToConfigSite(String alias, String redirect, String offset) { long timeOffset = 0; try { timeOffset = Long.parseLong(offset); } catch (Throwable e) { // ignore } CmsSiteMatcher siteMatcher = new CmsSiteMatcher(alias, timeOffset); boolean redirectVal = new Boolean(redirect).booleanValue(); siteMatcher.setRedirect(redirectVal); m_aliases.add(siteMatcher); }
[ "public", "void", "addAliasToConfigSite", "(", "String", "alias", ",", "String", "redirect", ",", "String", "offset", ")", "{", "long", "timeOffset", "=", "0", ";", "try", "{", "timeOffset", "=", "Long", ".", "parseLong", "(", "offset", ")", ";", "}", "c...
Adds an alias to the currently configured site. @param alias the URL of the alias server @param redirect <code>true</code> to always redirect to main URL @param offset the optional time offset for this alias
[ "Adds", "an", "alias", "to", "the", "currently", "configured", "site", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/site/CmsSiteManagerImpl.java#L207-L219
riversun/string-grabber
src/main/java/org/riversun/string_grabber/StringGrabber.java
StringGrabber.replaceCaseTo
private StringGrabber replaceCaseTo(int startPos, int endPos, ECase toCase) { StringBuilder sbRange = new StringBuilder(); try { for (int i = startPos; i < endPos; i++) { sbRange.append(String.valueOf(sb.charAt(i))); } } catch (Exception e) { e.printStackTrace(); } final String caseConvertedRangeStr; if (ECase.LOWER == toCase) { caseConvertedRangeStr = sbRange.toString().toLowerCase(); } else { caseConvertedRangeStr = sbRange.toString().toUpperCase(); } try { sb.replace(startPos, endPos, caseConvertedRangeStr); } catch (Exception e) { e.printStackTrace(); } return StringGrabber.this; }
java
private StringGrabber replaceCaseTo(int startPos, int endPos, ECase toCase) { StringBuilder sbRange = new StringBuilder(); try { for (int i = startPos; i < endPos; i++) { sbRange.append(String.valueOf(sb.charAt(i))); } } catch (Exception e) { e.printStackTrace(); } final String caseConvertedRangeStr; if (ECase.LOWER == toCase) { caseConvertedRangeStr = sbRange.toString().toLowerCase(); } else { caseConvertedRangeStr = sbRange.toString().toUpperCase(); } try { sb.replace(startPos, endPos, caseConvertedRangeStr); } catch (Exception e) { e.printStackTrace(); } return StringGrabber.this; }
[ "private", "StringGrabber", "replaceCaseTo", "(", "int", "startPos", ",", "int", "endPos", ",", "ECase", "toCase", ")", "{", "StringBuilder", "sbRange", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "for", "(", "int", "i", "=", "startPos", ";", ...
convert string in the specified position(range) to specified case @param sb @param startPos @param endPos
[ "convert", "string", "in", "the", "specified", "position", "(", "range", ")", "to", "specified", "case" ]
train
https://github.com/riversun/string-grabber/blob/b5aadc21fe15f50d35392188dec6ab81dcf8d464/src/main/java/org/riversun/string_grabber/StringGrabber.java#L327-L352
Stratio/stratio-cassandra
src/java/com/stratio/cassandra/index/service/RowService.java
RowService.cleanExpired
protected ColumnFamily cleanExpired(ColumnFamily columnFamily, long timestamp) { ColumnFamily cleanColumnFamily = ArrayBackedSortedColumns.factory.create(baseCfs.metadata); for (Cell cell : columnFamily) { if (cell.isLive(timestamp)) { cleanColumnFamily.addColumn(cell); } } return cleanColumnFamily; }
java
protected ColumnFamily cleanExpired(ColumnFamily columnFamily, long timestamp) { ColumnFamily cleanColumnFamily = ArrayBackedSortedColumns.factory.create(baseCfs.metadata); for (Cell cell : columnFamily) { if (cell.isLive(timestamp)) { cleanColumnFamily.addColumn(cell); } } return cleanColumnFamily; }
[ "protected", "ColumnFamily", "cleanExpired", "(", "ColumnFamily", "columnFamily", ",", "long", "timestamp", ")", "{", "ColumnFamily", "cleanColumnFamily", "=", "ArrayBackedSortedColumns", ".", "factory", ".", "create", "(", "baseCfs", ".", "metadata", ")", ";", "for...
Returns a {@link ColumnFamily} composed by the non expired {@link Cell}s of the specified {@link ColumnFamily}. @param columnFamily A {@link ColumnFamily}. @param timestamp The max allowed timestamp for the {@link Cell}s. @return A {@link ColumnFamily} composed by the non expired {@link Cell}s of the specified {@link ColumnFamily}.
[ "Returns", "a", "{", "@link", "ColumnFamily", "}", "composed", "by", "the", "non", "expired", "{", "@link", "Cell", "}", "s", "of", "the", "specified", "{", "@link", "ColumnFamily", "}", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/RowService.java#L379-L387
msgpack/msgpack-java
msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java
MessageUnpacker.unpackBigInteger
public BigInteger unpackBigInteger() throws IOException { byte b = readByte(); if (Code.isFixInt(b)) { return BigInteger.valueOf((long) b); } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); return BigInteger.valueOf((long) (u8 & 0xff)); case Code.UINT16: // unsigned int 16 short u16 = readShort(); return BigInteger.valueOf((long) (u16 & 0xffff)); case Code.UINT32: // unsigned int 32 int u32 = readInt(); if (u32 < 0) { return BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L); } else { return BigInteger.valueOf((long) u32); } case Code.UINT64: // unsigned int 64 long u64 = readLong(); if (u64 < 0L) { BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63); return bi; } else { return BigInteger.valueOf(u64); } case Code.INT8: // signed int 8 byte i8 = readByte(); return BigInteger.valueOf((long) i8); case Code.INT16: // signed int 16 short i16 = readShort(); return BigInteger.valueOf((long) i16); case Code.INT32: // signed int 32 int i32 = readInt(); return BigInteger.valueOf((long) i32); case Code.INT64: // signed int 64 long i64 = readLong(); return BigInteger.valueOf(i64); } throw unexpected("Integer", b); }
java
public BigInteger unpackBigInteger() throws IOException { byte b = readByte(); if (Code.isFixInt(b)) { return BigInteger.valueOf((long) b); } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); return BigInteger.valueOf((long) (u8 & 0xff)); case Code.UINT16: // unsigned int 16 short u16 = readShort(); return BigInteger.valueOf((long) (u16 & 0xffff)); case Code.UINT32: // unsigned int 32 int u32 = readInt(); if (u32 < 0) { return BigInteger.valueOf((long) (u32 & 0x7fffffff) + 0x80000000L); } else { return BigInteger.valueOf((long) u32); } case Code.UINT64: // unsigned int 64 long u64 = readLong(); if (u64 < 0L) { BigInteger bi = BigInteger.valueOf(u64 + Long.MAX_VALUE + 1L).setBit(63); return bi; } else { return BigInteger.valueOf(u64); } case Code.INT8: // signed int 8 byte i8 = readByte(); return BigInteger.valueOf((long) i8); case Code.INT16: // signed int 16 short i16 = readShort(); return BigInteger.valueOf((long) i16); case Code.INT32: // signed int 32 int i32 = readInt(); return BigInteger.valueOf((long) i32); case Code.INT64: // signed int 64 long i64 = readLong(); return BigInteger.valueOf(i64); } throw unexpected("Integer", b); }
[ "public", "BigInteger", "unpackBigInteger", "(", ")", "throws", "IOException", "{", "byte", "b", "=", "readByte", "(", ")", ";", "if", "(", "Code", ".", "isFixInt", "(", "b", ")", ")", "{", "return", "BigInteger", ".", "valueOf", "(", "(", "long", ")",...
Reads a BigInteger. @return the read value @throws MessageTypeException when value is not MessagePack Integer type @throws IOException when underlying input throws IOException
[ "Reads", "a", "BigInteger", "." ]
train
https://github.com/msgpack/msgpack-java/blob/16e370e348215a72a14c210b42d448d513aee015/msgpack-core/src/main/java/org/msgpack/core/MessageUnpacker.java#L1023-L1068
alkacon/opencms-core
src/org/opencms/main/CmsSessionManager.java
CmsSessionManager.sendBroadcast
public void sendBroadcast(CmsObject cms, String message, String sessionId) { sendBroadcast(cms, message, sessionId, false); }
java
public void sendBroadcast(CmsObject cms, String message, String sessionId) { sendBroadcast(cms, message, sessionId, false); }
[ "public", "void", "sendBroadcast", "(", "CmsObject", "cms", ",", "String", "message", ",", "String", "sessionId", ")", "{", "sendBroadcast", "(", "cms", ",", "message", ",", "sessionId", ",", "false", ")", ";", "}" ]
Sends a broadcast to the specified user session.<p> @param cms the OpenCms user context of the user sending the broadcast @param message the message to broadcast @param sessionId the OpenCms session uuid target (receiver) of the broadcast
[ "Sends", "a", "broadcast", "to", "the", "specified", "user", "session", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsSessionManager.java#L377-L381
Wadpam/guja
guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java
GeneratedDi18nDaoImpl.queryByUpdatedDate
public Iterable<Di18n> queryByUpdatedDate(java.util.Date updatedDate) { return queryByField(null, Di18nMapper.Field.UPDATEDDATE.getFieldName(), updatedDate); }
java
public Iterable<Di18n> queryByUpdatedDate(java.util.Date updatedDate) { return queryByField(null, Di18nMapper.Field.UPDATEDDATE.getFieldName(), updatedDate); }
[ "public", "Iterable", "<", "Di18n", ">", "queryByUpdatedDate", "(", "java", ".", "util", ".", "Date", "updatedDate", ")", "{", "return", "queryByField", "(", "null", ",", "Di18nMapper", ".", "Field", ".", "UPDATEDDATE", ".", "getFieldName", "(", ")", ",", ...
query-by method for field updatedDate @param updatedDate the specified attribute @return an Iterable of Di18ns for the specified updatedDate
[ "query", "-", "by", "method", "for", "field", "updatedDate" ]
train
https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/i18n/dao/GeneratedDi18nDaoImpl.java#L106-L108
radkovo/CSSBox
src/main/java/org/fit/cssbox/layout/Box.java
Box.applyClip
protected Rectangle applyClip(Shape current, Rectangle newclip) { if (current == null) return newclip; else { if (current instanceof Rectangle) return ((Rectangle) current).intersection(newclip); else return current.getBounds().intersection(newclip); } }
java
protected Rectangle applyClip(Shape current, Rectangle newclip) { if (current == null) return newclip; else { if (current instanceof Rectangle) return ((Rectangle) current).intersection(newclip); else return current.getBounds().intersection(newclip); } }
[ "protected", "Rectangle", "applyClip", "(", "Shape", "current", ",", "Rectangle", "newclip", ")", "{", "if", "(", "current", "==", "null", ")", "return", "newclip", ";", "else", "{", "if", "(", "current", "instanceof", "Rectangle", ")", "return", "(", "(",...
Computes a new clipping region from the current one and the eventual clipping box @param current current clipping region @param newclip new clipping box to be used @return the new clipping rectangle
[ "Computes", "a", "new", "clipping", "region", "from", "the", "current", "one", "and", "the", "eventual", "clipping", "box" ]
train
https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/Box.java#L848-L859
alkacon/opencms-core
src/org/opencms/search/documents/A_CmsVfsDocument.java
A_CmsVfsDocument.getDocumentKey
public static String getDocumentKey(String type, String mimeType) { StringBuffer result = new StringBuffer(16); result.append(I_CmsSearchDocument.VFS_DOCUMENT_KEY_PREFIX); result.append('_'); result.append(type); if (mimeType != null) { result.append(':'); result.append(mimeType); } return result.toString(); }
java
public static String getDocumentKey(String type, String mimeType) { StringBuffer result = new StringBuffer(16); result.append(I_CmsSearchDocument.VFS_DOCUMENT_KEY_PREFIX); result.append('_'); result.append(type); if (mimeType != null) { result.append(':'); result.append(mimeType); } return result.toString(); }
[ "public", "static", "String", "getDocumentKey", "(", "String", "type", ",", "String", "mimeType", ")", "{", "StringBuffer", "result", "=", "new", "StringBuffer", "(", "16", ")", ";", "result", ".", "append", "(", "I_CmsSearchDocument", ".", "VFS_DOCUMENT_KEY_PRE...
Creates a document factory lookup key for the given resource type name / MIME type configuration.<p> If the given <code>mimeType</code> is <code>null</code>, this indicates that the key should match all VFS resource of the given resource type regardless of the MIME type.<p> @param type the resource type name to use @param mimeType the MIME type to use @return a document factory lookup key for the given resource id / MIME type configuration
[ "Creates", "a", "document", "factory", "lookup", "key", "for", "the", "given", "resource", "type", "name", "/", "MIME", "type", "configuration", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/documents/A_CmsVfsDocument.java#L88-L99