repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
albfernandez/itext2
src/main/java/com/lowagie/text/Image.java
Image.getInstance
public static Image getInstance(int width, int height, int components, int bpc, byte data[], int transparency[]) throws BadElementException { """ Gets an instance of an Image in raw mode. @param width the width of the image in pixels @param height the height of the image in pixels @param components 1,3 or 4 for GrayScale, RGB and CMYK @param data the image data @param bpc bits per component @param transparency transparency information in the Mask format of the image dictionary @return an object of type <CODE>ImgRaw</CODE> @throws BadElementException on error """ if (transparency != null && transparency.length != components * 2) throw new BadElementException( "Transparency length must be equal to (componentes * 2)"); if (components == 1 && bpc == 1) { byte g4[] = CCITTG4Encoder.compress(data, width, height); return Image.getInstance(width, height, false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, transparency); } Image img = new ImgRaw(width, height, components, bpc, data); img.transparency = transparency; return img; }
java
public static Image getInstance(int width, int height, int components, int bpc, byte data[], int transparency[]) throws BadElementException { if (transparency != null && transparency.length != components * 2) throw new BadElementException( "Transparency length must be equal to (componentes * 2)"); if (components == 1 && bpc == 1) { byte g4[] = CCITTG4Encoder.compress(data, width, height); return Image.getInstance(width, height, false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, transparency); } Image img = new ImgRaw(width, height, components, bpc, data); img.transparency = transparency; return img; }
[ "public", "static", "Image", "getInstance", "(", "int", "width", ",", "int", "height", ",", "int", "components", ",", "int", "bpc", ",", "byte", "data", "[", "]", ",", "int", "transparency", "[", "]", ")", "throws", "BadElementException", "{", "if", "(", "transparency", "!=", "null", "&&", "transparency", ".", "length", "!=", "components", "*", "2", ")", "throw", "new", "BadElementException", "(", "\"Transparency length must be equal to (componentes * 2)\"", ")", ";", "if", "(", "components", "==", "1", "&&", "bpc", "==", "1", ")", "{", "byte", "g4", "[", "]", "=", "CCITTG4Encoder", ".", "compress", "(", "data", ",", "width", ",", "height", ")", ";", "return", "Image", ".", "getInstance", "(", "width", ",", "height", ",", "false", ",", "Image", ".", "CCITTG4", ",", "Image", ".", "CCITT_BLACKIS1", ",", "g4", ",", "transparency", ")", ";", "}", "Image", "img", "=", "new", "ImgRaw", "(", "width", ",", "height", ",", "components", ",", "bpc", ",", "data", ")", ";", "img", ".", "transparency", "=", "transparency", ";", "return", "img", ";", "}" ]
Gets an instance of an Image in raw mode. @param width the width of the image in pixels @param height the height of the image in pixels @param components 1,3 or 4 for GrayScale, RGB and CMYK @param data the image data @param bpc bits per component @param transparency transparency information in the Mask format of the image dictionary @return an object of type <CODE>ImgRaw</CODE> @throws BadElementException on error
[ "Gets", "an", "instance", "of", "an", "Image", "in", "raw", "mode", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/Image.java#L572-L586
phax/ph-bdve
ph-bdve/src/main/java/com/helger/bdve/execute/ValidationExecutionManager.java
ValidationExecutionManager.executeValidation
@Nonnull public ValidationResultList executeValidation (@Nonnull final IValidationSource aSource) { """ Perform a validation with all the contained executors and the system default locale. @param aSource The source artefact to be validated. May not be <code>null</code>. contained executor a result is added to the result list. @return The validation result list. Never <code>null</code>. For each contained executor a result is added to the result list. @see #executeValidation(IValidationSource, ValidationResultList, Locale) @since 5.1.1 """ return executeValidation (aSource, (Locale) null); }
java
@Nonnull public ValidationResultList executeValidation (@Nonnull final IValidationSource aSource) { return executeValidation (aSource, (Locale) null); }
[ "@", "Nonnull", "public", "ValidationResultList", "executeValidation", "(", "@", "Nonnull", "final", "IValidationSource", "aSource", ")", "{", "return", "executeValidation", "(", "aSource", ",", "(", "Locale", ")", "null", ")", ";", "}" ]
Perform a validation with all the contained executors and the system default locale. @param aSource The source artefact to be validated. May not be <code>null</code>. contained executor a result is added to the result list. @return The validation result list. Never <code>null</code>. For each contained executor a result is added to the result list. @see #executeValidation(IValidationSource, ValidationResultList, Locale) @since 5.1.1
[ "Perform", "a", "validation", "with", "all", "the", "contained", "executors", "and", "the", "system", "default", "locale", "." ]
train
https://github.com/phax/ph-bdve/blob/2438f491174cd8989567fcdf129b273bd217e89f/ph-bdve/src/main/java/com/helger/bdve/execute/ValidationExecutionManager.java#L278-L282
alkacon/opencms-core
src-gwt/org/opencms/ade/galleries/client/ui/CmsResultsTab.java
CmsResultsTab.displayResultCount
private void displayResultCount(int displayed, int total) { """ Displays the result count.<p> @param displayed the displayed result items @param total the total of result items """ String message = Messages.get().key( Messages.GUI_LABEL_NUM_RESULTS_2, new Integer(displayed), new Integer(total)); m_infoLabel.setText(message); }
java
private void displayResultCount(int displayed, int total) { String message = Messages.get().key( Messages.GUI_LABEL_NUM_RESULTS_2, new Integer(displayed), new Integer(total)); m_infoLabel.setText(message); }
[ "private", "void", "displayResultCount", "(", "int", "displayed", ",", "int", "total", ")", "{", "String", "message", "=", "Messages", ".", "get", "(", ")", ".", "key", "(", "Messages", ".", "GUI_LABEL_NUM_RESULTS_2", ",", "new", "Integer", "(", "displayed", ")", ",", "new", "Integer", "(", "total", ")", ")", ";", "m_infoLabel", ".", "setText", "(", "message", ")", ";", "}" ]
Displays the result count.<p> @param displayed the displayed result items @param total the total of result items
[ "Displays", "the", "result", "count", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsResultsTab.java#L707-L714
Activiti/Activiti
activiti-engine/src/main/java/org/activiti/engine/impl/util/json/JSONObject.java
JSONObject.optDouble
public double optDouble(String key, double defaultValue) { """ Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. @param key A key string. @param defaultValue The default. @return An object which is the value. """ try { Object o = opt(key); return o instanceof Number ? ((Number) o).doubleValue() : new Double((String) o).doubleValue(); } catch (Exception e) { return defaultValue; } }
java
public double optDouble(String key, double defaultValue) { try { Object o = opt(key); return o instanceof Number ? ((Number) o).doubleValue() : new Double((String) o).doubleValue(); } catch (Exception e) { return defaultValue; } }
[ "public", "double", "optDouble", "(", "String", "key", ",", "double", "defaultValue", ")", "{", "try", "{", "Object", "o", "=", "opt", "(", "key", ")", ";", "return", "o", "instanceof", "Number", "?", "(", "(", "Number", ")", "o", ")", ".", "doubleValue", "(", ")", ":", "new", "Double", "(", "(", "String", ")", "o", ")", ".", "doubleValue", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "defaultValue", ";", "}", "}" ]
Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. @param key A key string. @param defaultValue The default. @return An object which is the value.
[ "Get", "an", "optional", "double", "associated", "with", "a", "key", "or", "the", "defaultValue", "if", "there", "is", "no", "such", "key", "or", "if", "its", "value", "is", "not", "a", "number", ".", "If", "the", "value", "is", "a", "string", "an", "attempt", "will", "be", "made", "to", "evaluate", "it", "as", "a", "number", "." ]
train
https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/util/json/JSONObject.java#L704-L711
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/component/rabbitmq/DefaultRabbitmqClient.java
DefaultRabbitmqClient.sendAndRetry
private void sendAndRetry(AmqpTemplate template, Object message) throws InterruptedException { """ メッセージを送信する。 @param template キューへのコネクション @param message メッセージ @throws InterruptedException スレッド割り込みが発生した場合 """ try { template.convertAndSend(message); } catch (AmqpException ex) { Thread.sleep(getRetryInterval()); template.convertAndSend(message); } }
java
private void sendAndRetry(AmqpTemplate template, Object message) throws InterruptedException { try { template.convertAndSend(message); } catch (AmqpException ex) { Thread.sleep(getRetryInterval()); template.convertAndSend(message); } }
[ "private", "void", "sendAndRetry", "(", "AmqpTemplate", "template", ",", "Object", "message", ")", "throws", "InterruptedException", "{", "try", "{", "template", ".", "convertAndSend", "(", "message", ")", ";", "}", "catch", "(", "AmqpException", "ex", ")", "{", "Thread", ".", "sleep", "(", "getRetryInterval", "(", ")", ")", ";", "template", ".", "convertAndSend", "(", "message", ")", ";", "}", "}" ]
メッセージを送信する。 @param template キューへのコネクション @param message メッセージ @throws InterruptedException スレッド割り込みが発生した場合
[ "メッセージを送信する。" ]
train
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/component/rabbitmq/DefaultRabbitmqClient.java#L81-L92
Omertron/api-thetvdb
src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java
DOMHelper.getValueFromElement
public static String getValueFromElement(Element element, String tagName) { """ Gets the string value of the tag element name passed @param element @param tagName @return """ NodeList elementNodeList = element.getElementsByTagName(tagName); if (elementNodeList == null) { return ""; } else { Element tagElement = (Element) elementNodeList.item(0); if (tagElement == null) { return ""; } NodeList tagNodeList = tagElement.getChildNodes(); if (tagNodeList == null || tagNodeList.getLength() == 0) { return ""; } return tagNodeList.item(0).getNodeValue(); } }
java
public static String getValueFromElement(Element element, String tagName) { NodeList elementNodeList = element.getElementsByTagName(tagName); if (elementNodeList == null) { return ""; } else { Element tagElement = (Element) elementNodeList.item(0); if (tagElement == null) { return ""; } NodeList tagNodeList = tagElement.getChildNodes(); if (tagNodeList == null || tagNodeList.getLength() == 0) { return ""; } return tagNodeList.item(0).getNodeValue(); } }
[ "public", "static", "String", "getValueFromElement", "(", "Element", "element", ",", "String", "tagName", ")", "{", "NodeList", "elementNodeList", "=", "element", ".", "getElementsByTagName", "(", "tagName", ")", ";", "if", "(", "elementNodeList", "==", "null", ")", "{", "return", "\"\"", ";", "}", "else", "{", "Element", "tagElement", "=", "(", "Element", ")", "elementNodeList", ".", "item", "(", "0", ")", ";", "if", "(", "tagElement", "==", "null", ")", "{", "return", "\"\"", ";", "}", "NodeList", "tagNodeList", "=", "tagElement", ".", "getChildNodes", "(", ")", ";", "if", "(", "tagNodeList", "==", "null", "||", "tagNodeList", ".", "getLength", "(", ")", "==", "0", ")", "{", "return", "\"\"", ";", "}", "return", "tagNodeList", ".", "item", "(", "0", ")", ".", "getNodeValue", "(", ")", ";", "}", "}" ]
Gets the string value of the tag element name passed @param element @param tagName @return
[ "Gets", "the", "string", "value", "of", "the", "tag", "element", "name", "passed" ]
train
https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java#L93-L109
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/pipeline/declarative/utils/DeclarativePipelineUtils.java
DeclarativePipelineUtils.deleteOldBuildDataDirs
static void deleteOldBuildDataDirs(File tmpDir, Log logger) { """ Delete @tmp/artifactory-pipeline-cache/build-number directories older than 1 day. """ if (!tmpDir.exists()) { // Before creation of the @tmp directory return; } File[] buildDataDirs = tmpDir.listFiles(buildDataDir -> { long ageInMilliseconds = new Date().getTime() - buildDataDir.lastModified(); return ageInMilliseconds > TimeUnit.DAYS.toMillis(1); }); if (buildDataDirs == null) { logger.error("Failed while attempting to delete old build data dirs. Could not list files in " + tmpDir); return; } for (File buildDataDir : buildDataDirs) { try { FileUtils.deleteDirectory(buildDataDir); logger.debug(buildDataDir.getAbsolutePath() + " deleted"); } catch (IOException e) { logger.error("Failed while attempting to delete old build data dir: " + buildDataDir.toString(), e); } } }
java
static void deleteOldBuildDataDirs(File tmpDir, Log logger) { if (!tmpDir.exists()) { // Before creation of the @tmp directory return; } File[] buildDataDirs = tmpDir.listFiles(buildDataDir -> { long ageInMilliseconds = new Date().getTime() - buildDataDir.lastModified(); return ageInMilliseconds > TimeUnit.DAYS.toMillis(1); }); if (buildDataDirs == null) { logger.error("Failed while attempting to delete old build data dirs. Could not list files in " + tmpDir); return; } for (File buildDataDir : buildDataDirs) { try { FileUtils.deleteDirectory(buildDataDir); logger.debug(buildDataDir.getAbsolutePath() + " deleted"); } catch (IOException e) { logger.error("Failed while attempting to delete old build data dir: " + buildDataDir.toString(), e); } } }
[ "static", "void", "deleteOldBuildDataDirs", "(", "File", "tmpDir", ",", "Log", "logger", ")", "{", "if", "(", "!", "tmpDir", ".", "exists", "(", ")", ")", "{", "// Before creation of the @tmp directory", "return", ";", "}", "File", "[", "]", "buildDataDirs", "=", "tmpDir", ".", "listFiles", "(", "buildDataDir", "->", "{", "long", "ageInMilliseconds", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "-", "buildDataDir", ".", "lastModified", "(", ")", ";", "return", "ageInMilliseconds", ">", "TimeUnit", ".", "DAYS", ".", "toMillis", "(", "1", ")", ";", "}", ")", ";", "if", "(", "buildDataDirs", "==", "null", ")", "{", "logger", ".", "error", "(", "\"Failed while attempting to delete old build data dirs. Could not list files in \"", "+", "tmpDir", ")", ";", "return", ";", "}", "for", "(", "File", "buildDataDir", ":", "buildDataDirs", ")", "{", "try", "{", "FileUtils", ".", "deleteDirectory", "(", "buildDataDir", ")", ";", "logger", ".", "debug", "(", "buildDataDir", ".", "getAbsolutePath", "(", ")", "+", "\" deleted\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Failed while attempting to delete old build data dir: \"", "+", "buildDataDir", ".", "toString", "(", ")", ",", "e", ")", ";", "}", "}", "}" ]
Delete @tmp/artifactory-pipeline-cache/build-number directories older than 1 day.
[ "Delete" ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/pipeline/declarative/utils/DeclarativePipelineUtils.java#L152-L174
spring-projects/spring-android
spring-android-core/src/main/java/org/springframework/core/convert/converter/ConvertingComparator.java
ConvertingComparator.mapEntryKeys
public static <K, V> ConvertingComparator<Map.Entry<K, V>, K> mapEntryKeys( Comparator<K> comparator) { """ Create a new {@link ConvertingComparator} that compares {@link java.util.Map.Entry map * entries} based on their {@link java.util.Map.Entry#getKey() keys}. @param comparator the underlying comparator used to compare keys @return a new {@link ConvertingComparator} instance """ return new ConvertingComparator<Map.Entry<K,V>, K>(comparator, new Converter<Map.Entry<K, V>, K>() { public K convert(Map.Entry<K, V> source) { return source.getKey(); } }); }
java
public static <K, V> ConvertingComparator<Map.Entry<K, V>, K> mapEntryKeys( Comparator<K> comparator) { return new ConvertingComparator<Map.Entry<K,V>, K>(comparator, new Converter<Map.Entry<K, V>, K>() { public K convert(Map.Entry<K, V> source) { return source.getKey(); } }); }
[ "public", "static", "<", "K", ",", "V", ">", "ConvertingComparator", "<", "Map", ".", "Entry", "<", "K", ",", "V", ">", ",", "K", ">", "mapEntryKeys", "(", "Comparator", "<", "K", ">", "comparator", ")", "{", "return", "new", "ConvertingComparator", "<", "Map", ".", "Entry", "<", "K", ",", "V", ">", ",", "K", ">", "(", "comparator", ",", "new", "Converter", "<", "Map", ".", "Entry", "<", "K", ",", "V", ">", ",", "K", ">", "(", ")", "{", "public", "K", "convert", "(", "Map", ".", "Entry", "<", "K", ",", "V", ">", "source", ")", "{", "return", "source", ".", "getKey", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create a new {@link ConvertingComparator} that compares {@link java.util.Map.Entry map * entries} based on their {@link java.util.Map.Entry#getKey() keys}. @param comparator the underlying comparator used to compare keys @return a new {@link ConvertingComparator} instance
[ "Create", "a", "new", "{", "@link", "ConvertingComparator", "}", "that", "compares", "{", "@link", "java", ".", "util", ".", "Map", ".", "Entry", "map", "*", "entries", "}", "based", "on", "their", "{", "@link", "java", ".", "util", ".", "Map", ".", "Entry#getKey", "()", "keys", "}", "." ]
train
https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/core/convert/converter/ConvertingComparator.java#L93-L101
MTDdk/jawn
jawn-core/src/main/java/net/javapla/jawn/core/templates/ContentTemplateLoader.java
ContentTemplateLoader.locateLayoutTemplate
public T locateLayoutTemplate(String controller, final String layout, final boolean useCache) throws ViewException { """ If found, uses the provided layout within the controller folder. If not found, it looks for the default template within the controller folder then use this to override the root default template """ // first see if we have already looked for the template final String controllerLayoutCombined = controller + '/' + layout; if (useCache && cachedTemplates.containsKey(controllerLayoutCombined)) return engine.clone(cachedTemplates.get(controllerLayoutCombined)); // README: computeIfAbsent does not save the result if null - which it actually might need to do to minimise disk reads T template; if ((template = lookupLayoutWithNonDefaultName(controllerLayoutCombined)) != null) return cacheTemplate(controllerLayoutCombined, template, useCache); // going for defaults if ((template = lookupDefaultLayoutInControllerPathChain(controller)) != null) return cacheTemplate(controllerLayoutCombined, template, useCache); if ((template = lookupDefaultLayout()) != null) return cacheTemplate(controllerLayoutCombined, template, useCache); throw new ViewException(TemplateEngine.LAYOUT_DEFAULT + engine.getSuffixOfTemplatingEngine() + " is not to be found anywhere"); }
java
public T locateLayoutTemplate(String controller, final String layout, final boolean useCache) throws ViewException { // first see if we have already looked for the template final String controllerLayoutCombined = controller + '/' + layout; if (useCache && cachedTemplates.containsKey(controllerLayoutCombined)) return engine.clone(cachedTemplates.get(controllerLayoutCombined)); // README: computeIfAbsent does not save the result if null - which it actually might need to do to minimise disk reads T template; if ((template = lookupLayoutWithNonDefaultName(controllerLayoutCombined)) != null) return cacheTemplate(controllerLayoutCombined, template, useCache); // going for defaults if ((template = lookupDefaultLayoutInControllerPathChain(controller)) != null) return cacheTemplate(controllerLayoutCombined, template, useCache); if ((template = lookupDefaultLayout()) != null) return cacheTemplate(controllerLayoutCombined, template, useCache); throw new ViewException(TemplateEngine.LAYOUT_DEFAULT + engine.getSuffixOfTemplatingEngine() + " is not to be found anywhere"); }
[ "public", "T", "locateLayoutTemplate", "(", "String", "controller", ",", "final", "String", "layout", ",", "final", "boolean", "useCache", ")", "throws", "ViewException", "{", "// first see if we have already looked for the template", "final", "String", "controllerLayoutCombined", "=", "controller", "+", "'", "'", "+", "layout", ";", "if", "(", "useCache", "&&", "cachedTemplates", ".", "containsKey", "(", "controllerLayoutCombined", ")", ")", "return", "engine", ".", "clone", "(", "cachedTemplates", ".", "get", "(", "controllerLayoutCombined", ")", ")", ";", "// README: computeIfAbsent does not save the result if null - which it actually might need to do to minimise disk reads", "T", "template", ";", "if", "(", "(", "template", "=", "lookupLayoutWithNonDefaultName", "(", "controllerLayoutCombined", ")", ")", "!=", "null", ")", "return", "cacheTemplate", "(", "controllerLayoutCombined", ",", "template", ",", "useCache", ")", ";", "// going for defaults", "if", "(", "(", "template", "=", "lookupDefaultLayoutInControllerPathChain", "(", "controller", ")", ")", "!=", "null", ")", "return", "cacheTemplate", "(", "controllerLayoutCombined", ",", "template", ",", "useCache", ")", ";", "if", "(", "(", "template", "=", "lookupDefaultLayout", "(", ")", ")", "!=", "null", ")", "return", "cacheTemplate", "(", "controllerLayoutCombined", ",", "template", ",", "useCache", ")", ";", "throw", "new", "ViewException", "(", "TemplateEngine", ".", "LAYOUT_DEFAULT", "+", "engine", ".", "getSuffixOfTemplatingEngine", "(", ")", "+", "\" is not to be found anywhere\"", ")", ";", "}" ]
If found, uses the provided layout within the controller folder. If not found, it looks for the default template within the controller folder then use this to override the root default template
[ "If", "found", "uses", "the", "provided", "layout", "within", "the", "controller", "folder", ".", "If", "not", "found", "it", "looks", "for", "the", "default", "template", "within", "the", "controller", "folder", "then", "use", "this", "to", "override", "the", "root", "default", "template" ]
train
https://github.com/MTDdk/jawn/blob/4ec2d09b97d413efdead7487e6075e5bfd13b925/jawn-core/src/main/java/net/javapla/jawn/core/templates/ContentTemplateLoader.java#L103-L122
classgraph/classgraph
src/main/java/nonapi/io/github/classgraph/fastzipfilereader/NestedJarHandler.java
NestedJarHandler.makeTempFile
private File makeTempFile(final String filePath, final boolean onlyUseLeafname) throws IOException { """ Create a temporary file, and mark it for deletion on exit. @param filePath The path to derive the temporary filename from. @param onlyUseLeafname If true, only use the leafname of filePath to derive the temporary filename. @return The temporary {@link File}. @throws IOException If the temporary file could not be created. """ final File tempFile = File.createTempFile("ClassGraph--", TEMP_FILENAME_LEAF_SEPARATOR + sanitizeFilename(onlyUseLeafname ? leafname(filePath) : filePath)); tempFile.deleteOnExit(); tempFiles.add(tempFile); return tempFile; }
java
private File makeTempFile(final String filePath, final boolean onlyUseLeafname) throws IOException { final File tempFile = File.createTempFile("ClassGraph--", TEMP_FILENAME_LEAF_SEPARATOR + sanitizeFilename(onlyUseLeafname ? leafname(filePath) : filePath)); tempFile.deleteOnExit(); tempFiles.add(tempFile); return tempFile; }
[ "private", "File", "makeTempFile", "(", "final", "String", "filePath", ",", "final", "boolean", "onlyUseLeafname", ")", "throws", "IOException", "{", "final", "File", "tempFile", "=", "File", ".", "createTempFile", "(", "\"ClassGraph--\"", ",", "TEMP_FILENAME_LEAF_SEPARATOR", "+", "sanitizeFilename", "(", "onlyUseLeafname", "?", "leafname", "(", "filePath", ")", ":", "filePath", ")", ")", ";", "tempFile", ".", "deleteOnExit", "(", ")", ";", "tempFiles", ".", "add", "(", "tempFile", ")", ";", "return", "tempFile", ";", "}" ]
Create a temporary file, and mark it for deletion on exit. @param filePath The path to derive the temporary filename from. @param onlyUseLeafname If true, only use the leafname of filePath to derive the temporary filename. @return The temporary {@link File}. @throws IOException If the temporary file could not be created.
[ "Create", "a", "temporary", "file", "and", "mark", "it", "for", "deletion", "on", "exit", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/fastzipfilereader/NestedJarHandler.java#L505-L511
operasoftware/operaprestodriver
src/com/opera/core/systems/runner/launcher/OperaLauncherProtocol.java
OperaLauncherProtocol.sendRequestWithoutResponse
public void sendRequestWithoutResponse(MessageType type, byte[] body) throws IOException { """ Send a request without a response. Used for shutdown. @param type the request type to be sent @param body the serialized request payload @throws IOException if socket read error or protocol parse error """ sendRequestHeader(type, (body != null) ? body.length : 0); if (body != null) { os.write(body); } }
java
public void sendRequestWithoutResponse(MessageType type, byte[] body) throws IOException { sendRequestHeader(type, (body != null) ? body.length : 0); if (body != null) { os.write(body); } }
[ "public", "void", "sendRequestWithoutResponse", "(", "MessageType", "type", ",", "byte", "[", "]", "body", ")", "throws", "IOException", "{", "sendRequestHeader", "(", "type", ",", "(", "body", "!=", "null", ")", "?", "body", ".", "length", ":", "0", ")", ";", "if", "(", "body", "!=", "null", ")", "{", "os", ".", "write", "(", "body", ")", ";", "}", "}" ]
Send a request without a response. Used for shutdown. @param type the request type to be sent @param body the serialized request payload @throws IOException if socket read error or protocol parse error
[ "Send", "a", "request", "without", "a", "response", ".", "Used", "for", "shutdown", "." ]
train
https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/runner/launcher/OperaLauncherProtocol.java#L163-L168
baratine/baratine
framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java
XmlWriter.writeElement
public void writeElement(String name, Object text) { """ Convenience method, same as doing a startElement(), writeText(text), endElement(). """ startElement(name); writeText(text); endElement(name); }
java
public void writeElement(String name, Object text) { startElement(name); writeText(text); endElement(name); }
[ "public", "void", "writeElement", "(", "String", "name", ",", "Object", "text", ")", "{", "startElement", "(", "name", ")", ";", "writeText", "(", "text", ")", ";", "endElement", "(", "name", ")", ";", "}" ]
Convenience method, same as doing a startElement(), writeText(text), endElement().
[ "Convenience", "method", "same", "as", "doing", "a", "startElement", "()", "writeText", "(", "text", ")", "endElement", "()", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/vfs/XmlWriter.java#L257-L262
lessthanoptimal/BoofCV
main/boofcv-simulation/src/main/java/boofcv/simulation/SimulatePlanarWorld.java
SimulatePlanarWorld.computeProjectionTable
void computeProjectionTable( int width , int height ) { """ Computes 3D pointing vector for every pixel in the simulated camera frame @param width width of simulated camera @param height height of simulated camera """ output.reshape(width,height); depthMap.reshape(width,height); ImageMiscOps.fill(depthMap,-1); pointing = new float[width*height*3]; for (int y = 0; y < output.height; y++) { for (int x = 0; x < output.width; x++) { // Should this add 0.5 so that the ray goes out of the pixel's center? Seems to increase reprojection // error in calibration tests if I do... pixelTo3.compute(x, y, p3); if(UtilEjml.isUncountable(p3.x)) { depthMap.unsafe_set(x,y,Float.NaN); } else { pointing[(y*output.width+x)*3 ] = (float)p3.x; pointing[(y*output.width+x)*3+1 ] = (float)p3.y; pointing[(y*output.width+x)*3+2 ] = (float)p3.z; } } } }
java
void computeProjectionTable( int width , int height ) { output.reshape(width,height); depthMap.reshape(width,height); ImageMiscOps.fill(depthMap,-1); pointing = new float[width*height*3]; for (int y = 0; y < output.height; y++) { for (int x = 0; x < output.width; x++) { // Should this add 0.5 so that the ray goes out of the pixel's center? Seems to increase reprojection // error in calibration tests if I do... pixelTo3.compute(x, y, p3); if(UtilEjml.isUncountable(p3.x)) { depthMap.unsafe_set(x,y,Float.NaN); } else { pointing[(y*output.width+x)*3 ] = (float)p3.x; pointing[(y*output.width+x)*3+1 ] = (float)p3.y; pointing[(y*output.width+x)*3+2 ] = (float)p3.z; } } } }
[ "void", "computeProjectionTable", "(", "int", "width", ",", "int", "height", ")", "{", "output", ".", "reshape", "(", "width", ",", "height", ")", ";", "depthMap", ".", "reshape", "(", "width", ",", "height", ")", ";", "ImageMiscOps", ".", "fill", "(", "depthMap", ",", "-", "1", ")", ";", "pointing", "=", "new", "float", "[", "width", "*", "height", "*", "3", "]", ";", "for", "(", "int", "y", "=", "0", ";", "y", "<", "output", ".", "height", ";", "y", "++", ")", "{", "for", "(", "int", "x", "=", "0", ";", "x", "<", "output", ".", "width", ";", "x", "++", ")", "{", "// Should this add 0.5 so that the ray goes out of the pixel's center? Seems to increase reprojection", "// error in calibration tests if I do...", "pixelTo3", ".", "compute", "(", "x", ",", "y", ",", "p3", ")", ";", "if", "(", "UtilEjml", ".", "isUncountable", "(", "p3", ".", "x", ")", ")", "{", "depthMap", ".", "unsafe_set", "(", "x", ",", "y", ",", "Float", ".", "NaN", ")", ";", "}", "else", "{", "pointing", "[", "(", "y", "*", "output", ".", "width", "+", "x", ")", "*", "3", "]", "=", "(", "float", ")", "p3", ".", "x", ";", "pointing", "[", "(", "y", "*", "output", ".", "width", "+", "x", ")", "*", "3", "+", "1", "]", "=", "(", "float", ")", "p3", ".", "y", ";", "pointing", "[", "(", "y", "*", "output", ".", "width", "+", "x", ")", "*", "3", "+", "2", "]", "=", "(", "float", ")", "p3", ".", "z", ";", "}", "}", "}", "}" ]
Computes 3D pointing vector for every pixel in the simulated camera frame @param width width of simulated camera @param height height of simulated camera
[ "Computes", "3D", "pointing", "vector", "for", "every", "pixel", "in", "the", "simulated", "camera", "frame" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-simulation/src/main/java/boofcv/simulation/SimulatePlanarWorld.java#L120-L142
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/stereo/StereoElementFactory.java
StereoElementFactory.using2DCoordinates
public static StereoElementFactory using2DCoordinates(IAtomContainer container) { """ Create a stereo element factory for creating stereo elements using 2D coordinates and depiction labels (up/down, wedge/hatch). @param container the structure to create the factory for @return the factory instance """ EdgeToBondMap bondMap = EdgeToBondMap.withSpaceFor(container); int[][] graph = GraphUtil.toAdjList(container, bondMap); return new StereoElementFactory2D(container, graph, bondMap); }
java
public static StereoElementFactory using2DCoordinates(IAtomContainer container) { EdgeToBondMap bondMap = EdgeToBondMap.withSpaceFor(container); int[][] graph = GraphUtil.toAdjList(container, bondMap); return new StereoElementFactory2D(container, graph, bondMap); }
[ "public", "static", "StereoElementFactory", "using2DCoordinates", "(", "IAtomContainer", "container", ")", "{", "EdgeToBondMap", "bondMap", "=", "EdgeToBondMap", ".", "withSpaceFor", "(", "container", ")", ";", "int", "[", "]", "[", "]", "graph", "=", "GraphUtil", ".", "toAdjList", "(", "container", ",", "bondMap", ")", ";", "return", "new", "StereoElementFactory2D", "(", "container", ",", "graph", ",", "bondMap", ")", ";", "}" ]
Create a stereo element factory for creating stereo elements using 2D coordinates and depiction labels (up/down, wedge/hatch). @param container the structure to create the factory for @return the factory instance
[ "Create", "a", "stereo", "element", "factory", "for", "creating", "stereo", "elements", "using", "2D", "coordinates", "and", "depiction", "labels", "(", "up", "/", "down", "wedge", "/", "hatch", ")", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/stereo/StereoElementFactory.java#L483-L487
GerdHolz/TOVAL
src/de/invation/code/toval/graphic/util/GraphicUtils.java
GraphicUtils.fillCircle
public static void fillCircle(Graphics g, Point center, int diameter, Color color) { """ Draws a circle with the specified diameter using the given point as center and fills it with the given color. @param g Graphics context @param center Circle center @param diameter Circle diameter """ fillCircle(g, (int) center.x, (int) center.y, diameter, color); }
java
public static void fillCircle(Graphics g, Point center, int diameter, Color color){ fillCircle(g, (int) center.x, (int) center.y, diameter, color); }
[ "public", "static", "void", "fillCircle", "(", "Graphics", "g", ",", "Point", "center", ",", "int", "diameter", ",", "Color", "color", ")", "{", "fillCircle", "(", "g", ",", "(", "int", ")", "center", ".", "x", ",", "(", "int", ")", "center", ".", "y", ",", "diameter", ",", "color", ")", ";", "}" ]
Draws a circle with the specified diameter using the given point as center and fills it with the given color. @param g Graphics context @param center Circle center @param diameter Circle diameter
[ "Draws", "a", "circle", "with", "the", "specified", "diameter", "using", "the", "given", "point", "as", "center", "and", "fills", "it", "with", "the", "given", "color", "." ]
train
https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/graphic/util/GraphicUtils.java#L64-L66
canoo/dolphin-platform
platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/commons/lang/TypeUtils.java
TypeUtils.substituteTypeVariables
private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) { """ <p>Find the mapping for {@code type} in {@code typeVarAssigns}.</p> @param type the type to be replaced @param typeVarAssigns the map with type variables @return the replaced type @throws IllegalArgumentException if the type cannot be substituted """ if (type instanceof TypeVariable<?> && typeVarAssigns != null) { final Type replacementType = typeVarAssigns.get(type); if (replacementType == null) { throw new IllegalArgumentException("missing assignment type for type variable " + type); } return replacementType; } return type; }
java
private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) { if (type instanceof TypeVariable<?> && typeVarAssigns != null) { final Type replacementType = typeVarAssigns.get(type); if (replacementType == null) { throw new IllegalArgumentException("missing assignment type for type variable " + type); } return replacementType; } return type; }
[ "private", "static", "Type", "substituteTypeVariables", "(", "final", "Type", "type", ",", "final", "Map", "<", "TypeVariable", "<", "?", ">", ",", "Type", ">", "typeVarAssigns", ")", "{", "if", "(", "type", "instanceof", "TypeVariable", "<", "?", ">", "&&", "typeVarAssigns", "!=", "null", ")", "{", "final", "Type", "replacementType", "=", "typeVarAssigns", ".", "get", "(", "type", ")", ";", "if", "(", "replacementType", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"missing assignment type for type variable \"", "+", "type", ")", ";", "}", "return", "replacementType", ";", "}", "return", "type", ";", "}" ]
<p>Find the mapping for {@code type} in {@code typeVarAssigns}.</p> @param type the type to be replaced @param typeVarAssigns the map with type variables @return the replaced type @throws IllegalArgumentException if the type cannot be substituted
[ "<p", ">", "Find", "the", "mapping", "for", "{", "@code", "type", "}", "in", "{", "@code", "typeVarAssigns", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/commons/lang/TypeUtils.java#L654-L665
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java
InvalidationAuditDaemon.wakeUp
public void wakeUp(long startDaemonTime, long startWakeUpTime) { """ This is the method in the RealTimeDaemon base class. It is called periodically (period is timeHoldingInvalidations). @param startDaemonTime The absolute time when this daemon was first started. @param startWakeUpTime The absolute time when this wakeUp call was made. """ lastTimeCleared = startWakeUpTime; for (Map.Entry<String, InvalidationTableList> entry : cacheinvalidationTables.entrySet()) { InvalidationTableList invalidationTableList = entry.getValue(); try { invalidationTableList.readWriteLock.writeLock().lock(); invalidationTableList.pastIdSet.clear(); Map<Object, InvalidationEvent> temp = invalidationTableList.pastIdSet; invalidationTableList.pastIdSet = invalidationTableList.presentIdSet; invalidationTableList.presentIdSet = invalidationTableList.futureIdSet; invalidationTableList.futureIdSet = temp; invalidationTableList.pastTemplateSet.clear(); temp = invalidationTableList.pastTemplateSet; invalidationTableList.pastTemplateSet = invalidationTableList.presentTemplateSet; invalidationTableList.presentTemplateSet = invalidationTableList.futureTemplateSet; invalidationTableList.futureTemplateSet = temp; } finally { invalidationTableList.readWriteLock.writeLock().unlock(); } } }
java
public void wakeUp(long startDaemonTime, long startWakeUpTime) { lastTimeCleared = startWakeUpTime; for (Map.Entry<String, InvalidationTableList> entry : cacheinvalidationTables.entrySet()) { InvalidationTableList invalidationTableList = entry.getValue(); try { invalidationTableList.readWriteLock.writeLock().lock(); invalidationTableList.pastIdSet.clear(); Map<Object, InvalidationEvent> temp = invalidationTableList.pastIdSet; invalidationTableList.pastIdSet = invalidationTableList.presentIdSet; invalidationTableList.presentIdSet = invalidationTableList.futureIdSet; invalidationTableList.futureIdSet = temp; invalidationTableList.pastTemplateSet.clear(); temp = invalidationTableList.pastTemplateSet; invalidationTableList.pastTemplateSet = invalidationTableList.presentTemplateSet; invalidationTableList.presentTemplateSet = invalidationTableList.futureTemplateSet; invalidationTableList.futureTemplateSet = temp; } finally { invalidationTableList.readWriteLock.writeLock().unlock(); } } }
[ "public", "void", "wakeUp", "(", "long", "startDaemonTime", ",", "long", "startWakeUpTime", ")", "{", "lastTimeCleared", "=", "startWakeUpTime", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "InvalidationTableList", ">", "entry", ":", "cacheinvalidationTables", ".", "entrySet", "(", ")", ")", "{", "InvalidationTableList", "invalidationTableList", "=", "entry", ".", "getValue", "(", ")", ";", "try", "{", "invalidationTableList", ".", "readWriteLock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "invalidationTableList", ".", "pastIdSet", ".", "clear", "(", ")", ";", "Map", "<", "Object", ",", "InvalidationEvent", ">", "temp", "=", "invalidationTableList", ".", "pastIdSet", ";", "invalidationTableList", ".", "pastIdSet", "=", "invalidationTableList", ".", "presentIdSet", ";", "invalidationTableList", ".", "presentIdSet", "=", "invalidationTableList", ".", "futureIdSet", ";", "invalidationTableList", ".", "futureIdSet", "=", "temp", ";", "invalidationTableList", ".", "pastTemplateSet", ".", "clear", "(", ")", ";", "temp", "=", "invalidationTableList", ".", "pastTemplateSet", ";", "invalidationTableList", ".", "pastTemplateSet", "=", "invalidationTableList", ".", "presentTemplateSet", ";", "invalidationTableList", ".", "presentTemplateSet", "=", "invalidationTableList", ".", "futureTemplateSet", ";", "invalidationTableList", ".", "futureTemplateSet", "=", "temp", ";", "}", "finally", "{", "invalidationTableList", ".", "readWriteLock", ".", "writeLock", "(", ")", ".", "unlock", "(", ")", ";", "}", "}", "}" ]
This is the method in the RealTimeDaemon base class. It is called periodically (period is timeHoldingInvalidations). @param startDaemonTime The absolute time when this daemon was first started. @param startWakeUpTime The absolute time when this wakeUp call was made.
[ "This", "is", "the", "method", "in", "the", "RealTimeDaemon", "base", "class", ".", "It", "is", "called", "periodically", "(", "period", "is", "timeHoldingInvalidations", ")", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/InvalidationAuditDaemon.java#L67-L92
Waikato/jclasslocator
src/main/java/nz/ac/waikato/cms/locator/ClassPathTraversal.java
ClassPathTraversal.traverseManifest
protected void traverseManifest(Manifest manifest, TraversalState state) { """ Analyzes the MANIFEST.MF file of a jar whether additional jars are listed in the "Class-Path" key. @param manifest the manifest to analyze @param state the traversal state """ Attributes atts; String cp; String[] parts; if (manifest == null) return; atts = manifest.getMainAttributes(); cp = atts.getValue("Class-Path"); if (cp == null) return; parts = cp.split(" "); for (String part: parts) { if (part.trim().length() == 0) return; if (part.toLowerCase().endsWith(".jar") || !part.equals(".")) traverseClasspathPart(part, state); } }
java
protected void traverseManifest(Manifest manifest, TraversalState state) { Attributes atts; String cp; String[] parts; if (manifest == null) return; atts = manifest.getMainAttributes(); cp = atts.getValue("Class-Path"); if (cp == null) return; parts = cp.split(" "); for (String part: parts) { if (part.trim().length() == 0) return; if (part.toLowerCase().endsWith(".jar") || !part.equals(".")) traverseClasspathPart(part, state); } }
[ "protected", "void", "traverseManifest", "(", "Manifest", "manifest", ",", "TraversalState", "state", ")", "{", "Attributes", "atts", ";", "String", "cp", ";", "String", "[", "]", "parts", ";", "if", "(", "manifest", "==", "null", ")", "return", ";", "atts", "=", "manifest", ".", "getMainAttributes", "(", ")", ";", "cp", "=", "atts", ".", "getValue", "(", "\"Class-Path\"", ")", ";", "if", "(", "cp", "==", "null", ")", "return", ";", "parts", "=", "cp", ".", "split", "(", "\" \"", ")", ";", "for", "(", "String", "part", ":", "parts", ")", "{", "if", "(", "part", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", ")", "return", ";", "if", "(", "part", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".jar\"", ")", "||", "!", "part", ".", "equals", "(", "\".\"", ")", ")", "traverseClasspathPart", "(", "part", ",", "state", ")", ";", "}", "}" ]
Analyzes the MANIFEST.MF file of a jar whether additional jars are listed in the "Class-Path" key. @param manifest the manifest to analyze @param state the traversal state
[ "Analyzes", "the", "MANIFEST", ".", "MF", "file", "of", "a", "jar", "whether", "additional", "jars", "are", "listed", "in", "the", "Class", "-", "Path", "key", "." ]
train
https://github.com/Waikato/jclasslocator/blob/c899072fff607a56ee7f8c2d01fbeb15157ad144/src/main/java/nz/ac/waikato/cms/locator/ClassPathTraversal.java#L205-L225
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/util/ScriptUtil.java
ScriptUtil.getScriptFromResourceExpression
public static ExecutableScript getScriptFromResourceExpression(String language, Expression resourceExpression, ScriptFactory scriptFactory) { """ Creates a new {@link ExecutableScript} from a dynamic resource. Dynamic means that the source is an expression which will be evaluated during execution. @param language the language of the script @param resourceExpression the expression which evaluates to the resource path @param scriptFactory the script factory used to create the script @return the newly created script @throws NotValidException if language is null or empty or resourceExpression is null """ ensureNotEmpty(NotValidException.class, "Script language", language); ensureNotNull(NotValidException.class, "Script resource expression", resourceExpression); return scriptFactory.createScriptFromResource(language, resourceExpression); }
java
public static ExecutableScript getScriptFromResourceExpression(String language, Expression resourceExpression, ScriptFactory scriptFactory) { ensureNotEmpty(NotValidException.class, "Script language", language); ensureNotNull(NotValidException.class, "Script resource expression", resourceExpression); return scriptFactory.createScriptFromResource(language, resourceExpression); }
[ "public", "static", "ExecutableScript", "getScriptFromResourceExpression", "(", "String", "language", ",", "Expression", "resourceExpression", ",", "ScriptFactory", "scriptFactory", ")", "{", "ensureNotEmpty", "(", "NotValidException", ".", "class", ",", "\"Script language\"", ",", "language", ")", ";", "ensureNotNull", "(", "NotValidException", ".", "class", ",", "\"Script resource expression\"", ",", "resourceExpression", ")", ";", "return", "scriptFactory", ".", "createScriptFromResource", "(", "language", ",", "resourceExpression", ")", ";", "}" ]
Creates a new {@link ExecutableScript} from a dynamic resource. Dynamic means that the source is an expression which will be evaluated during execution. @param language the language of the script @param resourceExpression the expression which evaluates to the resource path @param scriptFactory the script factory used to create the script @return the newly created script @throws NotValidException if language is null or empty or resourceExpression is null
[ "Creates", "a", "new", "{", "@link", "ExecutableScript", "}", "from", "a", "dynamic", "resource", ".", "Dynamic", "means", "that", "the", "source", "is", "an", "expression", "which", "will", "be", "evaluated", "during", "execution", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/util/ScriptUtil.java#L179-L183
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.sla_id_services_GET
public ArrayList<OvhSlaOperationService> sla_id_services_GET(Long id) throws IOException { """ Get services impacted by this SLA REST: GET /me/sla/{id}/services @param id [required] Id of the object """ String qPath = "/me/sla/{id}/services"; StringBuilder sb = path(qPath, id); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
java
public ArrayList<OvhSlaOperationService> sla_id_services_GET(Long id) throws IOException { String qPath = "/me/sla/{id}/services"; StringBuilder sb = path(qPath, id); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
[ "public", "ArrayList", "<", "OvhSlaOperationService", ">", "sla_id_services_GET", "(", "Long", "id", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/sla/{id}/services\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "id", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t4", ")", ";", "}" ]
Get services impacted by this SLA REST: GET /me/sla/{id}/services @param id [required] Id of the object
[ "Get", "services", "impacted", "by", "this", "SLA" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L1175-L1180
OpenLiberty/open-liberty
dev/com.ibm.ws.injection.core/src/com/ibm/wsspi/injectionengine/InjectionBinding.java
InjectionBinding.setObjects
public void setObjects(Object injectionObject, Reference bindingObject) throws InjectionException { """ Sets the object to use for injection and the Reference to use for binding. Usually, the injection object is null. @param injectionObject the object to inject, or null if the object should be obtained from the binding object instead @param bindingObject the object to bind, or null if injectionObject should be bound directly if is non-null @throws InjectionException if a problem occurs while creating the instance to be injected """ final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "setObjects", injectionObject, bindingObjectToString(bindingObject)); ivInjectedObject = injectionObject; // d392996.3 if (bindingObject != null) { ivBindingObject = bindingObject; ivObjectFactoryClassName = bindingObject.getFactoryClassName(); // F48603.4 if (ivObjectFactoryClassName == null) // F54050 { throw new IllegalArgumentException("expected non-null getFactoryClassName"); } } else { ivBindingObject = injectionObject; } }
java
public void setObjects(Object injectionObject, Reference bindingObject) throws InjectionException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isDebugEnabled()) Tr.debug(tc, "setObjects", injectionObject, bindingObjectToString(bindingObject)); ivInjectedObject = injectionObject; // d392996.3 if (bindingObject != null) { ivBindingObject = bindingObject; ivObjectFactoryClassName = bindingObject.getFactoryClassName(); // F48603.4 if (ivObjectFactoryClassName == null) // F54050 { throw new IllegalArgumentException("expected non-null getFactoryClassName"); } } else { ivBindingObject = injectionObject; } }
[ "public", "void", "setObjects", "(", "Object", "injectionObject", ",", "Reference", "bindingObject", ")", "throws", "InjectionException", "{", "final", "boolean", "isTraceOn", "=", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", ";", "if", "(", "isTraceOn", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "Tr", ".", "debug", "(", "tc", ",", "\"setObjects\"", ",", "injectionObject", ",", "bindingObjectToString", "(", "bindingObject", ")", ")", ";", "ivInjectedObject", "=", "injectionObject", ";", "// d392996.3", "if", "(", "bindingObject", "!=", "null", ")", "{", "ivBindingObject", "=", "bindingObject", ";", "ivObjectFactoryClassName", "=", "bindingObject", ".", "getFactoryClassName", "(", ")", ";", "// F48603.4", "if", "(", "ivObjectFactoryClassName", "==", "null", ")", "// F54050", "{", "throw", "new", "IllegalArgumentException", "(", "\"expected non-null getFactoryClassName\"", ")", ";", "}", "}", "else", "{", "ivBindingObject", "=", "injectionObject", ";", "}", "}" ]
Sets the object to use for injection and the Reference to use for binding. Usually, the injection object is null. @param injectionObject the object to inject, or null if the object should be obtained from the binding object instead @param bindingObject the object to bind, or null if injectionObject should be bound directly if is non-null @throws InjectionException if a problem occurs while creating the instance to be injected
[ "Sets", "the", "object", "to", "use", "for", "injection", "and", "the", "Reference", "to", "use", "for", "binding", ".", "Usually", "the", "injection", "object", "is", "null", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.injection.core/src/com/ibm/wsspi/injectionengine/InjectionBinding.java#L1283-L1305
nmorel/gwt-jackson
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonSerializationContext.java
JsonSerializationContext.traceError
public JsonSerializationException traceError( Object value, String message ) { """ Trace an error and returns a corresponding exception. @param value current value @param message error message @return a {@link JsonSerializationException} with the given message """ getLogger().log( Level.SEVERE, message ); return new JsonSerializationException( message ); }
java
public JsonSerializationException traceError( Object value, String message ) { getLogger().log( Level.SEVERE, message ); return new JsonSerializationException( message ); }
[ "public", "JsonSerializationException", "traceError", "(", "Object", "value", ",", "String", "message", ")", "{", "getLogger", "(", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "message", ")", ";", "return", "new", "JsonSerializationException", "(", "message", ")", ";", "}" ]
Trace an error and returns a corresponding exception. @param value current value @param message error message @return a {@link JsonSerializationException} with the given message
[ "Trace", "an", "error", "and", "returns", "a", "corresponding", "exception", "." ]
train
https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/JsonSerializationContext.java#L505-L508
phax/ph-web
ph-servlet/src/main/java/com/helger/servlet/request/RequestHelper.java
RequestHelper.getRequestClientCertificates
@Nullable public static X509Certificate [] getRequestClientCertificates (@Nonnull final HttpServletRequest aHttpRequest) { """ Get the client certificates provided by a HTTP servlet request. @param aHttpRequest The HTTP servlet request to extract the information from. May not be <code>null</code>. @return <code>null</code> if the passed request does not contain any client certificate """ return _getRequestAttr (aHttpRequest, SERVLET_ATTR_CLIENT_CERTIFICATE, X509Certificate [].class); }
java
@Nullable public static X509Certificate [] getRequestClientCertificates (@Nonnull final HttpServletRequest aHttpRequest) { return _getRequestAttr (aHttpRequest, SERVLET_ATTR_CLIENT_CERTIFICATE, X509Certificate [].class); }
[ "@", "Nullable", "public", "static", "X509Certificate", "[", "]", "getRequestClientCertificates", "(", "@", "Nonnull", "final", "HttpServletRequest", "aHttpRequest", ")", "{", "return", "_getRequestAttr", "(", "aHttpRequest", ",", "SERVLET_ATTR_CLIENT_CERTIFICATE", ",", "X509Certificate", "[", "]", ".", "class", ")", ";", "}" ]
Get the client certificates provided by a HTTP servlet request. @param aHttpRequest The HTTP servlet request to extract the information from. May not be <code>null</code>. @return <code>null</code> if the passed request does not contain any client certificate
[ "Get", "the", "client", "certificates", "provided", "by", "a", "HTTP", "servlet", "request", "." ]
train
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-servlet/src/main/java/com/helger/servlet/request/RequestHelper.java#L668-L672
Omertron/api-rottentomatoes
src/main/java/com/omertron/rottentomatoesapi/RottenTomatoesApi.java
RottenTomatoesApi.getNewReleaseDvds
public List<RTMovie> getNewReleaseDvds(String country) throws RottenTomatoesException { """ Retrieves new release DVDs @param country Provides localized data for the selected country @return @throws RottenTomatoesException """ return getNewReleaseDvds(country, DEFAULT_PAGE, DEFAULT_PAGE_LIMIT); }
java
public List<RTMovie> getNewReleaseDvds(String country) throws RottenTomatoesException { return getNewReleaseDvds(country, DEFAULT_PAGE, DEFAULT_PAGE_LIMIT); }
[ "public", "List", "<", "RTMovie", ">", "getNewReleaseDvds", "(", "String", "country", ")", "throws", "RottenTomatoesException", "{", "return", "getNewReleaseDvds", "(", "country", ",", "DEFAULT_PAGE", ",", "DEFAULT_PAGE_LIMIT", ")", ";", "}" ]
Retrieves new release DVDs @param country Provides localized data for the selected country @return @throws RottenTomatoesException
[ "Retrieves", "new", "release", "DVDs" ]
train
https://github.com/Omertron/api-rottentomatoes/blob/abaf1833acafc6ada593d52b14ff1bacb4e441ee/src/main/java/com/omertron/rottentomatoesapi/RottenTomatoesApi.java#L439-L441
FINRAOS/DataGenerator
dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLGapper.java
SCXMLGapper.reproduce
public Frontier reproduce(Map<String, String> decomposition, List<CustomTagExtension> tagExtensionList) { """ Produces an SCXMLFrontier by reversing a decomposition; the model text is bundled into the decomposition. @param decomposition the decomposition, assembled back into a map @param tagExtensionList custom tags to use in the model @return a rebuilt SCXMLFrontier """ tagExtensionList = new LinkedList<>(tagExtensionList); tagExtensionList.add(new SetAssignExtension()); tagExtensionList.add(new SingleValueAssignExtension()); tagExtensionList.add(new FileExtension()); tagExtensionList.add(new RangeExtension()); setModel(decomposition.get("model"), tagExtensionList); TransitionTarget target = (TransitionTarget) model.getTargets().get(decomposition.get("target")); Map<String, String> variables = new HashMap<>(); String[] assignments = decomposition.get("variables").split(";"); for (int i = 0; i < assignments.length; i++) { String[] a = assignments[i].split("::"); if (a.length == 2) { variables.put(a[0], a[1]); } else { variables.put(a[0], ""); } } return new SCXMLFrontier(new PossibleState(target, variables), model, tagExtensionList); }
java
public Frontier reproduce(Map<String, String> decomposition, List<CustomTagExtension> tagExtensionList) { tagExtensionList = new LinkedList<>(tagExtensionList); tagExtensionList.add(new SetAssignExtension()); tagExtensionList.add(new SingleValueAssignExtension()); tagExtensionList.add(new FileExtension()); tagExtensionList.add(new RangeExtension()); setModel(decomposition.get("model"), tagExtensionList); TransitionTarget target = (TransitionTarget) model.getTargets().get(decomposition.get("target")); Map<String, String> variables = new HashMap<>(); String[] assignments = decomposition.get("variables").split(";"); for (int i = 0; i < assignments.length; i++) { String[] a = assignments[i].split("::"); if (a.length == 2) { variables.put(a[0], a[1]); } else { variables.put(a[0], ""); } } return new SCXMLFrontier(new PossibleState(target, variables), model, tagExtensionList); }
[ "public", "Frontier", "reproduce", "(", "Map", "<", "String", ",", "String", ">", "decomposition", ",", "List", "<", "CustomTagExtension", ">", "tagExtensionList", ")", "{", "tagExtensionList", "=", "new", "LinkedList", "<>", "(", "tagExtensionList", ")", ";", "tagExtensionList", ".", "add", "(", "new", "SetAssignExtension", "(", ")", ")", ";", "tagExtensionList", ".", "add", "(", "new", "SingleValueAssignExtension", "(", ")", ")", ";", "tagExtensionList", ".", "add", "(", "new", "FileExtension", "(", ")", ")", ";", "tagExtensionList", ".", "add", "(", "new", "RangeExtension", "(", ")", ")", ";", "setModel", "(", "decomposition", ".", "get", "(", "\"model\"", ")", ",", "tagExtensionList", ")", ";", "TransitionTarget", "target", "=", "(", "TransitionTarget", ")", "model", ".", "getTargets", "(", ")", ".", "get", "(", "decomposition", ".", "get", "(", "\"target\"", ")", ")", ";", "Map", "<", "String", ",", "String", ">", "variables", "=", "new", "HashMap", "<>", "(", ")", ";", "String", "[", "]", "assignments", "=", "decomposition", ".", "get", "(", "\"variables\"", ")", ".", "split", "(", "\";\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "assignments", ".", "length", ";", "i", "++", ")", "{", "String", "[", "]", "a", "=", "assignments", "[", "i", "]", ".", "split", "(", "\"::\"", ")", ";", "if", "(", "a", ".", "length", "==", "2", ")", "{", "variables", ".", "put", "(", "a", "[", "0", "]", ",", "a", "[", "1", "]", ")", ";", "}", "else", "{", "variables", ".", "put", "(", "a", "[", "0", "]", ",", "\"\"", ")", ";", "}", "}", "return", "new", "SCXMLFrontier", "(", "new", "PossibleState", "(", "target", ",", "variables", ")", ",", "model", ",", "tagExtensionList", ")", ";", "}" ]
Produces an SCXMLFrontier by reversing a decomposition; the model text is bundled into the decomposition. @param decomposition the decomposition, assembled back into a map @param tagExtensionList custom tags to use in the model @return a rebuilt SCXMLFrontier
[ "Produces", "an", "SCXMLFrontier", "by", "reversing", "a", "decomposition", ";", "the", "model", "text", "is", "bundled", "into", "the", "decomposition", "." ]
train
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/SCXMLGapper.java#L117-L139
joniles/mpxj
src/main/java/net/sf/mpxj/primavera/p3/P3DatabaseReader.java
P3DatabaseReader.listProjectNames
public static final List<String> listProjectNames(File directory) { """ Retrieve a list of the available P3 project names from a directory. @param directory directory containing P3 files @return list of project names """ List<String> result = new ArrayList<String>(); File[] files = directory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toUpperCase().endsWith("STR.P3"); } }); if (files != null) { for (File file : files) { String fileName = file.getName(); String prefix = fileName.substring(0, fileName.length() - 6); result.add(prefix); } } Collections.sort(result); return result; }
java
public static final List<String> listProjectNames(File directory) { List<String> result = new ArrayList<String>(); File[] files = directory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toUpperCase().endsWith("STR.P3"); } }); if (files != null) { for (File file : files) { String fileName = file.getName(); String prefix = fileName.substring(0, fileName.length() - 6); result.add(prefix); } } Collections.sort(result); return result; }
[ "public", "static", "final", "List", "<", "String", ">", "listProjectNames", "(", "File", "directory", ")", "{", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "File", "[", "]", "files", "=", "directory", ".", "listFiles", "(", "new", "FilenameFilter", "(", ")", "{", "@", "Override", "public", "boolean", "accept", "(", "File", "dir", ",", "String", "name", ")", "{", "return", "name", ".", "toUpperCase", "(", ")", ".", "endsWith", "(", "\"STR.P3\"", ")", ";", "}", "}", ")", ";", "if", "(", "files", "!=", "null", ")", "{", "for", "(", "File", "file", ":", "files", ")", "{", "String", "fileName", "=", "file", ".", "getName", "(", ")", ";", "String", "prefix", "=", "fileName", ".", "substring", "(", "0", ",", "fileName", ".", "length", "(", ")", "-", "6", ")", ";", "result", ".", "add", "(", "prefix", ")", ";", "}", "}", "Collections", ".", "sort", "(", "result", ")", ";", "return", "result", ";", "}" ]
Retrieve a list of the available P3 project names from a directory. @param directory directory containing P3 files @return list of project names
[ "Retrieve", "a", "list", "of", "the", "available", "P3", "project", "names", "from", "a", "directory", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/p3/P3DatabaseReader.java#L118-L143
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java
KerasTokenizer.reverseSortByValues
private static HashMap reverseSortByValues(HashMap map) { """ Sort HashMap by values in reverse order @param map input HashMap @return sorted HashMap """ List list = new LinkedList(map.entrySet()); Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; }
java
private static HashMap reverseSortByValues(HashMap map) { List list = new LinkedList(map.entrySet()); Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()) .compareTo(((Map.Entry) (o2)).getValue()); } }); HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; }
[ "private", "static", "HashMap", "reverseSortByValues", "(", "HashMap", "map", ")", "{", "List", "list", "=", "new", "LinkedList", "(", "map", ".", "entrySet", "(", ")", ")", ";", "Collections", ".", "sort", "(", "list", ",", "new", "Comparator", "(", ")", "{", "public", "int", "compare", "(", "Object", "o1", ",", "Object", "o2", ")", "{", "return", "(", "(", "Comparable", ")", "(", "(", "Map", ".", "Entry", ")", "(", "o1", ")", ")", ".", "getValue", "(", ")", ")", ".", "compareTo", "(", "(", "(", "Map", ".", "Entry", ")", "(", "o2", ")", ")", ".", "getValue", "(", ")", ")", ";", "}", "}", ")", ";", "HashMap", "sortedHashMap", "=", "new", "LinkedHashMap", "(", ")", ";", "for", "(", "Iterator", "it", "=", "list", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "Map", ".", "Entry", "entry", "=", "(", "Map", ".", "Entry", ")", "it", ".", "next", "(", ")", ";", "sortedHashMap", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "return", "sortedHashMap", ";", "}" ]
Sort HashMap by values in reverse order @param map input HashMap @return sorted HashMap
[ "Sort", "HashMap", "by", "values", "in", "reverse", "order" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/preprocessing/text/KerasTokenizer.java#L229-L243
jbundle/jbundle
base/remote/src/main/java/org/jbundle/base/remote/proxy/ProxyServlet.java
ProxyServlet.doProcess
public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { """ Process an HTML get or post. @exception ServletException From inherited class. @exception IOException From inherited class. """ try { res.setDateHeader("Expires", 0); // Make sure the browser never caches these requests res.setHeader("Pragma", "No-cache"); res.setHeader("Cache-Control", "no-cache"); m_servletTask.doProcess(this, req, res, null); } catch (Throwable ex) { ex.printStackTrace(); } }
java
public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setDateHeader("Expires", 0); // Make sure the browser never caches these requests res.setHeader("Pragma", "No-cache"); res.setHeader("Cache-Control", "no-cache"); m_servletTask.doProcess(this, req, res, null); } catch (Throwable ex) { ex.printStackTrace(); } }
[ "public", "void", "doProcess", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ")", "throws", "ServletException", ",", "IOException", "{", "try", "{", "res", ".", "setDateHeader", "(", "\"Expires\"", ",", "0", ")", ";", "// Make sure the browser never caches these requests", "res", ".", "setHeader", "(", "\"Pragma\"", ",", "\"No-cache\"", ")", ";", "res", ".", "setHeader", "(", "\"Cache-Control\"", ",", "\"no-cache\"", ")", ";", "m_servletTask", ".", "doProcess", "(", "this", ",", "req", ",", "res", ",", "null", ")", ";", "}", "catch", "(", "Throwable", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Process an HTML get or post. @exception ServletException From inherited class. @exception IOException From inherited class.
[ "Process", "an", "HTML", "get", "or", "post", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/remote/src/main/java/org/jbundle/base/remote/proxy/ProxyServlet.java#L115-L126
ow2-chameleon/fuchsia
bases/knx/calimero/src/main/java/tuwien/auto/calimero/link/KNXNetworkLinkIP.java
KNXNetworkLinkIP.sendRequestWait
public void sendRequestWait(KNXAddress dst, Priority p, byte[] nsdu) throws KNXTimeoutException, KNXLinkClosedException { """ {@inheritDoc} When communicating with a KNX network which uses open medium, messages are broadcasted within domain (as opposite to system broadcast) by default. Specify <code>dst null</code> for system broadcast. """ send(dst, p, nsdu, true); }
java
public void sendRequestWait(KNXAddress dst, Priority p, byte[] nsdu) throws KNXTimeoutException, KNXLinkClosedException { send(dst, p, nsdu, true); }
[ "public", "void", "sendRequestWait", "(", "KNXAddress", "dst", ",", "Priority", "p", ",", "byte", "[", "]", "nsdu", ")", "throws", "KNXTimeoutException", ",", "KNXLinkClosedException", "{", "send", "(", "dst", ",", "p", ",", "nsdu", ",", "true", ")", ";", "}" ]
{@inheritDoc} When communicating with a KNX network which uses open medium, messages are broadcasted within domain (as opposite to system broadcast) by default. Specify <code>dst null</code> for system broadcast.
[ "{" ]
train
https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/link/KNXNetworkLinkIP.java#L363-L367
landawn/AbacusUtil
src/com/landawn/abacus/util/JdbcUtil.java
JdbcUtil.prepareQuery
public static PreparedQuery prepareQuery(final Connection conn, final Try.Function<Connection, PreparedStatement, SQLException> stmtCreator) throws SQLException { """ Never write below code because it will definitely cause {@code Connection} leak: <pre> <code> JdbcUtil.prepareQuery(dataSource.getConnection(), stmtCreator); </code> </pre> @param conn the specified {@code conn} won't be close after this query is executed. @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code PreparedQuery/PreparedCallableQuery} is called. An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/list/execute/.... @return @throws SQLException @see {@link JdbcUtil#prepareStatement(Connection, String, Object...)} """ return new PreparedQuery(stmtCreator.apply(conn)); }
java
public static PreparedQuery prepareQuery(final Connection conn, final Try.Function<Connection, PreparedStatement, SQLException> stmtCreator) throws SQLException { return new PreparedQuery(stmtCreator.apply(conn)); }
[ "public", "static", "PreparedQuery", "prepareQuery", "(", "final", "Connection", "conn", ",", "final", "Try", ".", "Function", "<", "Connection", ",", "PreparedStatement", ",", "SQLException", ">", "stmtCreator", ")", "throws", "SQLException", "{", "return", "new", "PreparedQuery", "(", "stmtCreator", ".", "apply", "(", "conn", ")", ")", ";", "}" ]
Never write below code because it will definitely cause {@code Connection} leak: <pre> <code> JdbcUtil.prepareQuery(dataSource.getConnection(), stmtCreator); </code> </pre> @param conn the specified {@code conn} won't be close after this query is executed. @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code PreparedQuery/PreparedCallableQuery} is called. An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/list/execute/.... @return @throws SQLException @see {@link JdbcUtil#prepareStatement(Connection, String, Object...)}
[ "Never", "write", "below", "code", "because", "it", "will", "definitely", "cause", "{", "@code", "Connection", "}", "leak", ":", "<pre", ">", "<code", ">", "JdbcUtil", ".", "prepareQuery", "(", "dataSource", ".", "getConnection", "()", "stmtCreator", ")", ";", "<", "/", "code", ">", "<", "/", "pre", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L1337-L1340
Samsung/GearVRf
GVRf/Extensions/gvrf-particlesystem/src/main/java/org/gearvrf/particlesystem/GVREmitter.java
GVREmitter.setVelocityRange
public void setVelocityRange( final Vector3f minV, final Vector3f maxV ) { """ The range of velocities that a particle generated from this emitter can have. @param minV Minimum velocity that a particle can have @param maxV Maximum velocity that a particle can have """ if (null != mGVRContext) { mGVRContext.runOnGlThread(new Runnable() { @Override public void run() { minVelocity = minV; maxVelocity = maxV; } }); } }
java
public void setVelocityRange( final Vector3f minV, final Vector3f maxV ) { if (null != mGVRContext) { mGVRContext.runOnGlThread(new Runnable() { @Override public void run() { minVelocity = minV; maxVelocity = maxV; } }); } }
[ "public", "void", "setVelocityRange", "(", "final", "Vector3f", "minV", ",", "final", "Vector3f", "maxV", ")", "{", "if", "(", "null", "!=", "mGVRContext", ")", "{", "mGVRContext", ".", "runOnGlThread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "minVelocity", "=", "minV", ";", "maxVelocity", "=", "maxV", ";", "}", "}", ")", ";", "}", "}" ]
The range of velocities that a particle generated from this emitter can have. @param minV Minimum velocity that a particle can have @param maxV Maximum velocity that a particle can have
[ "The", "range", "of", "velocities", "that", "a", "particle", "generated", "from", "this", "emitter", "can", "have", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/gvrf-particlesystem/src/main/java/org/gearvrf/particlesystem/GVREmitter.java#L294-L306
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/AbstractBlobClob.java
AbstractBlobClob.truncate
public synchronized void truncate(long len) throws SQLException { """ For Blobs this should be in bytes while for Clobs it should be in characters. Since we really haven't figured out how to handle character sets for Clobs the current implementation uses bytes for both Blobs and Clobs. @param len maximum length @throws SQLException if operation fails """ checkFreed(); if (!conn.haveMinimumServerVersion(ServerVersion.v8_3)) { throw new PSQLException( GT.tr("Truncation of large objects is only implemented in 8.3 and later servers."), PSQLState.NOT_IMPLEMENTED); } if (len < 0) { throw new PSQLException(GT.tr("Cannot truncate LOB to a negative length."), PSQLState.INVALID_PARAMETER_VALUE); } if (len > Integer.MAX_VALUE) { if (support64bit) { getLo(true).truncate64(len); } else { throw new PSQLException(GT.tr("PostgreSQL LOBs can only index to: {0}", Integer.MAX_VALUE), PSQLState.INVALID_PARAMETER_VALUE); } } else { getLo(true).truncate((int) len); } }
java
public synchronized void truncate(long len) throws SQLException { checkFreed(); if (!conn.haveMinimumServerVersion(ServerVersion.v8_3)) { throw new PSQLException( GT.tr("Truncation of large objects is only implemented in 8.3 and later servers."), PSQLState.NOT_IMPLEMENTED); } if (len < 0) { throw new PSQLException(GT.tr("Cannot truncate LOB to a negative length."), PSQLState.INVALID_PARAMETER_VALUE); } if (len > Integer.MAX_VALUE) { if (support64bit) { getLo(true).truncate64(len); } else { throw new PSQLException(GT.tr("PostgreSQL LOBs can only index to: {0}", Integer.MAX_VALUE), PSQLState.INVALID_PARAMETER_VALUE); } } else { getLo(true).truncate((int) len); } }
[ "public", "synchronized", "void", "truncate", "(", "long", "len", ")", "throws", "SQLException", "{", "checkFreed", "(", ")", ";", "if", "(", "!", "conn", ".", "haveMinimumServerVersion", "(", "ServerVersion", ".", "v8_3", ")", ")", "{", "throw", "new", "PSQLException", "(", "GT", ".", "tr", "(", "\"Truncation of large objects is only implemented in 8.3 and later servers.\"", ")", ",", "PSQLState", ".", "NOT_IMPLEMENTED", ")", ";", "}", "if", "(", "len", "<", "0", ")", "{", "throw", "new", "PSQLException", "(", "GT", ".", "tr", "(", "\"Cannot truncate LOB to a negative length.\"", ")", ",", "PSQLState", ".", "INVALID_PARAMETER_VALUE", ")", ";", "}", "if", "(", "len", ">", "Integer", ".", "MAX_VALUE", ")", "{", "if", "(", "support64bit", ")", "{", "getLo", "(", "true", ")", ".", "truncate64", "(", "len", ")", ";", "}", "else", "{", "throw", "new", "PSQLException", "(", "GT", ".", "tr", "(", "\"PostgreSQL LOBs can only index to: {0}\"", ",", "Integer", ".", "MAX_VALUE", ")", ",", "PSQLState", ".", "INVALID_PARAMETER_VALUE", ")", ";", "}", "}", "else", "{", "getLo", "(", "true", ")", ".", "truncate", "(", "(", "int", ")", "len", ")", ";", "}", "}" ]
For Blobs this should be in bytes while for Clobs it should be in characters. Since we really haven't figured out how to handle character sets for Clobs the current implementation uses bytes for both Blobs and Clobs. @param len maximum length @throws SQLException if operation fails
[ "For", "Blobs", "this", "should", "be", "in", "bytes", "while", "for", "Clobs", "it", "should", "be", "in", "characters", ".", "Since", "we", "really", "haven", "t", "figured", "out", "how", "to", "handle", "character", "sets", "for", "Clobs", "the", "current", "implementation", "uses", "bytes", "for", "both", "Blobs", "and", "Clobs", "." ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/AbstractBlobClob.java#L73-L95
johnkil/Print
print/src/main/java/com/github/johnkil/print/PrintConfig.java
PrintConfig.initDefault
public static void initDefault(AssetManager assets, String defaultFontPath) { """ Define the default iconic font. @param assets The application's asset manager. @param defaultFontPath The file name of the font in the assets directory, e.g. "fonts/iconic-font.ttf". @see #initDefault(Typeface) """ Typeface defaultFont = TypefaceManager.load(assets, defaultFontPath); initDefault(defaultFont); }
java
public static void initDefault(AssetManager assets, String defaultFontPath) { Typeface defaultFont = TypefaceManager.load(assets, defaultFontPath); initDefault(defaultFont); }
[ "public", "static", "void", "initDefault", "(", "AssetManager", "assets", ",", "String", "defaultFontPath", ")", "{", "Typeface", "defaultFont", "=", "TypefaceManager", ".", "load", "(", "assets", ",", "defaultFontPath", ")", ";", "initDefault", "(", "defaultFont", ")", ";", "}" ]
Define the default iconic font. @param assets The application's asset manager. @param defaultFontPath The file name of the font in the assets directory, e.g. "fonts/iconic-font.ttf". @see #initDefault(Typeface)
[ "Define", "the", "default", "iconic", "font", "." ]
train
https://github.com/johnkil/Print/blob/535f3ca466289c491b8c29f41c32e72f0bb95127/print/src/main/java/com/github/johnkil/print/PrintConfig.java#L34-L37
liaochong/spring-boot-starter-converter
src/main/java/com/github/liaochong/converter/core/BeanConvertStrategy.java
BeanConvertStrategy.convertBean
public static <T, U> U convertBean(T source, Class<U> targetClass) { """ 单个Bean转换,无指定异常提供 @throws ConvertException 转换异常 @param source 被转换对象 @param targetClass 需要转换到的类型 @param <T> 转换前的类型 @param <U> 转换后的类型 @return 结果 """ return convertBean(source, targetClass, null); }
java
public static <T, U> U convertBean(T source, Class<U> targetClass) { return convertBean(source, targetClass, null); }
[ "public", "static", "<", "T", ",", "U", ">", "U", "convertBean", "(", "T", "source", ",", "Class", "<", "U", ">", "targetClass", ")", "{", "return", "convertBean", "(", "source", ",", "targetClass", ",", "null", ")", ";", "}" ]
单个Bean转换,无指定异常提供 @throws ConvertException 转换异常 @param source 被转换对象 @param targetClass 需要转换到的类型 @param <T> 转换前的类型 @param <U> 转换后的类型 @return 结果
[ "单个Bean转换,无指定异常提供" ]
train
https://github.com/liaochong/spring-boot-starter-converter/blob/a36bea44bd23330a6f43b0372906a804a09285c5/src/main/java/com/github/liaochong/converter/core/BeanConvertStrategy.java#L48-L50
yan74/afplib
org.afplib/src/main/java/org/afplib/base/util/BaseValidator.java
BaseValidator.validateModcaString32_MaxLength
public boolean validateModcaString32_MaxLength(String modcaString32, DiagnosticChain diagnostics, Map<Object, Object> context) { """ Validates the MaxLength constraint of '<em>Modca String32</em>'. <!-- begin-user-doc --> <!-- end-user-doc --> @generated """ int length = modcaString32.length(); boolean result = length <= 32; if (!result && diagnostics != null) reportMaxLengthViolation(BasePackage.Literals.MODCA_STRING32, modcaString32, length, 32, diagnostics, context); return result; }
java
public boolean validateModcaString32_MaxLength(String modcaString32, DiagnosticChain diagnostics, Map<Object, Object> context) { int length = modcaString32.length(); boolean result = length <= 32; if (!result && diagnostics != null) reportMaxLengthViolation(BasePackage.Literals.MODCA_STRING32, modcaString32, length, 32, diagnostics, context); return result; }
[ "public", "boolean", "validateModcaString32_MaxLength", "(", "String", "modcaString32", ",", "DiagnosticChain", "diagnostics", ",", "Map", "<", "Object", ",", "Object", ">", "context", ")", "{", "int", "length", "=", "modcaString32", ".", "length", "(", ")", ";", "boolean", "result", "=", "length", "<=", "32", ";", "if", "(", "!", "result", "&&", "diagnostics", "!=", "null", ")", "reportMaxLengthViolation", "(", "BasePackage", ".", "Literals", ".", "MODCA_STRING32", ",", "modcaString32", ",", "length", ",", "32", ",", "diagnostics", ",", "context", ")", ";", "return", "result", ";", "}" ]
Validates the MaxLength constraint of '<em>Modca String32</em>'. <!-- begin-user-doc --> <!-- end-user-doc --> @generated
[ "Validates", "the", "MaxLength", "constraint", "of", "<em", ">", "Modca", "String32<", "/", "em", ">", ".", "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "<!", "--", "end", "-", "user", "-", "doc", "--", ">" ]
train
https://github.com/yan74/afplib/blob/9ff0513f9448bdf8c0b0e31dc4910c094c48fb2f/org.afplib/src/main/java/org/afplib/base/util/BaseValidator.java#L278-L284
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java
Client.buildRMST
@SuppressWarnings("WeakerAccess") public static NumberField buildRMST(int requestingPlayer, Message.MenuIdentifier targetMenu, CdjStatus.TrackSourceSlot slot) { """ <p>Build the <em>R:M:S:T</em> parameter that begins many queries, when T=1.</p> <p>Many request messages take, as their first argument, a 4-byte value where each byte has a special meaning. The first byte is the player number of the requesting player. The second identifies the menu into which the response is being loaded, as described by {@link Message.MenuIdentifier}. The third specifies the media slot from which information is desired, as described by {@link CdjStatus.TrackSourceSlot}, and the fourth byte identifies the type of track about which information is being requested; in most requests this has the value 1, which corresponds to rekordbox tracks, and this version of the function assumes that.</p> @param requestingPlayer the player number that is asking the question @param targetMenu the destination for the response to this query @param slot the media library of interest for this query @return the first argument to send with the query in order to obtain the desired information """ return buildRMST(requestingPlayer, targetMenu, slot, CdjStatus.TrackType.REKORDBOX); }
java
@SuppressWarnings("WeakerAccess") public static NumberField buildRMST(int requestingPlayer, Message.MenuIdentifier targetMenu, CdjStatus.TrackSourceSlot slot) { return buildRMST(requestingPlayer, targetMenu, slot, CdjStatus.TrackType.REKORDBOX); }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "public", "static", "NumberField", "buildRMST", "(", "int", "requestingPlayer", ",", "Message", ".", "MenuIdentifier", "targetMenu", ",", "CdjStatus", ".", "TrackSourceSlot", "slot", ")", "{", "return", "buildRMST", "(", "requestingPlayer", ",", "targetMenu", ",", "slot", ",", "CdjStatus", ".", "TrackType", ".", "REKORDBOX", ")", ";", "}" ]
<p>Build the <em>R:M:S:T</em> parameter that begins many queries, when T=1.</p> <p>Many request messages take, as their first argument, a 4-byte value where each byte has a special meaning. The first byte is the player number of the requesting player. The second identifies the menu into which the response is being loaded, as described by {@link Message.MenuIdentifier}. The third specifies the media slot from which information is desired, as described by {@link CdjStatus.TrackSourceSlot}, and the fourth byte identifies the type of track about which information is being requested; in most requests this has the value 1, which corresponds to rekordbox tracks, and this version of the function assumes that.</p> @param requestingPlayer the player number that is asking the question @param targetMenu the destination for the response to this query @param slot the media library of interest for this query @return the first argument to send with the query in order to obtain the desired information
[ "<p", ">", "Build", "the", "<em", ">", "R", ":", "M", ":", "S", ":", "T<", "/", "em", ">", "parameter", "that", "begins", "many", "queries", "when", "T", "=", "1", ".", "<", "/", "p", ">" ]
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java#L262-L266
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java
ParagraphVectors.inferVectorBatched
public Future<Pair<String, INDArray>> inferVectorBatched(@NonNull LabelledDocument document) { """ This method implements batched inference, based on Java Future parallelism model. PLEASE NOTE: In order to use this method, LabelledDocument being passed in should have Id field defined. @param document @return """ if (countSubmitted == null) initInference(); if (this.vocab == null || this.vocab.numWords() == 0) reassignExistingModel(); // we block execution until queued amount of documents gets below acceptable level, to avoid memory exhaust while (countSubmitted.get() - countFinished.get() > 1024) { ThreadUtils.uncheckedSleep(50); } InferenceCallable callable = new InferenceCallable(vocab, tokenizerFactory, document); Future<Pair<String, INDArray>> future = inferenceExecutor.submit(callable); countSubmitted.incrementAndGet(); return future; }
java
public Future<Pair<String, INDArray>> inferVectorBatched(@NonNull LabelledDocument document) { if (countSubmitted == null) initInference(); if (this.vocab == null || this.vocab.numWords() == 0) reassignExistingModel(); // we block execution until queued amount of documents gets below acceptable level, to avoid memory exhaust while (countSubmitted.get() - countFinished.get() > 1024) { ThreadUtils.uncheckedSleep(50); } InferenceCallable callable = new InferenceCallable(vocab, tokenizerFactory, document); Future<Pair<String, INDArray>> future = inferenceExecutor.submit(callable); countSubmitted.incrementAndGet(); return future; }
[ "public", "Future", "<", "Pair", "<", "String", ",", "INDArray", ">", ">", "inferVectorBatched", "(", "@", "NonNull", "LabelledDocument", "document", ")", "{", "if", "(", "countSubmitted", "==", "null", ")", "initInference", "(", ")", ";", "if", "(", "this", ".", "vocab", "==", "null", "||", "this", ".", "vocab", ".", "numWords", "(", ")", "==", "0", ")", "reassignExistingModel", "(", ")", ";", "// we block execution until queued amount of documents gets below acceptable level, to avoid memory exhaust", "while", "(", "countSubmitted", ".", "get", "(", ")", "-", "countFinished", ".", "get", "(", ")", ">", "1024", ")", "{", "ThreadUtils", ".", "uncheckedSleep", "(", "50", ")", ";", "}", "InferenceCallable", "callable", "=", "new", "InferenceCallable", "(", "vocab", ",", "tokenizerFactory", ",", "document", ")", ";", "Future", "<", "Pair", "<", "String", ",", "INDArray", ">", ">", "future", "=", "inferenceExecutor", ".", "submit", "(", "callable", ")", ";", "countSubmitted", ".", "incrementAndGet", "(", ")", ";", "return", "future", ";", "}" ]
This method implements batched inference, based on Java Future parallelism model. PLEASE NOTE: In order to use this method, LabelledDocument being passed in should have Id field defined. @param document @return
[ "This", "method", "implements", "batched", "inference", "based", "on", "Java", "Future", "parallelism", "model", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/paragraphvectors/ParagraphVectors.java#L326-L343
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/A_CmsGroupEditor.java
A_CmsGroupEditor.addInputField
protected void addInputField(String label, Widget inputWidget) { """ Adds an input field with the given label to the dialog.<p> @param label the label @param inputWidget the input widget """ FlowPanel row = new FlowPanel(); row.setStyleName(I_CmsLayoutBundle.INSTANCE.groupcontainerCss().inputRow()); CmsLabel labelWidget = new CmsLabel(label); labelWidget.setStyleName(I_CmsLayoutBundle.INSTANCE.groupcontainerCss().inputLabel()); row.add(labelWidget); inputWidget.addStyleName(I_CmsLayoutBundle.INSTANCE.groupcontainerCss().inputBox()); row.add(inputWidget); m_dialogContent.add(row); }
java
protected void addInputField(String label, Widget inputWidget) { FlowPanel row = new FlowPanel(); row.setStyleName(I_CmsLayoutBundle.INSTANCE.groupcontainerCss().inputRow()); CmsLabel labelWidget = new CmsLabel(label); labelWidget.setStyleName(I_CmsLayoutBundle.INSTANCE.groupcontainerCss().inputLabel()); row.add(labelWidget); inputWidget.addStyleName(I_CmsLayoutBundle.INSTANCE.groupcontainerCss().inputBox()); row.add(inputWidget); m_dialogContent.add(row); }
[ "protected", "void", "addInputField", "(", "String", "label", ",", "Widget", "inputWidget", ")", "{", "FlowPanel", "row", "=", "new", "FlowPanel", "(", ")", ";", "row", ".", "setStyleName", "(", "I_CmsLayoutBundle", ".", "INSTANCE", ".", "groupcontainerCss", "(", ")", ".", "inputRow", "(", ")", ")", ";", "CmsLabel", "labelWidget", "=", "new", "CmsLabel", "(", "label", ")", ";", "labelWidget", ".", "setStyleName", "(", "I_CmsLayoutBundle", ".", "INSTANCE", ".", "groupcontainerCss", "(", ")", ".", "inputLabel", "(", ")", ")", ";", "row", ".", "add", "(", "labelWidget", ")", ";", "inputWidget", ".", "addStyleName", "(", "I_CmsLayoutBundle", ".", "INSTANCE", ".", "groupcontainerCss", "(", ")", ".", "inputBox", "(", ")", ")", ";", "row", ".", "add", "(", "inputWidget", ")", ";", "m_dialogContent", ".", "add", "(", "row", ")", ";", "}" ]
Adds an input field with the given label to the dialog.<p> @param label the label @param inputWidget the input widget
[ "Adds", "an", "input", "field", "with", "the", "given", "label", "to", "the", "dialog", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/A_CmsGroupEditor.java#L343-L353
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java
KeyValueAuthHandler.channelRead0
@Override protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception { """ Dispatches incoming SASL responses to the appropriate handler methods. @param ctx the handler context. @param msg the incoming message to investigate. @throws Exception if something goes wrong during negotiation. """ if (msg.getOpcode() == SASL_LIST_MECHS_OPCODE) { handleListMechsResponse(ctx, msg); } else if (msg.getOpcode() == SASL_AUTH_OPCODE) { handleAuthResponse(ctx, msg); } else if (msg.getOpcode() == SASL_STEP_OPCODE) { checkIsAuthed(msg); } }
java
@Override protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception { if (msg.getOpcode() == SASL_LIST_MECHS_OPCODE) { handleListMechsResponse(ctx, msg); } else if (msg.getOpcode() == SASL_AUTH_OPCODE) { handleAuthResponse(ctx, msg); } else if (msg.getOpcode() == SASL_STEP_OPCODE) { checkIsAuthed(msg); } }
[ "@", "Override", "protected", "void", "channelRead0", "(", "ChannelHandlerContext", "ctx", ",", "FullBinaryMemcacheResponse", "msg", ")", "throws", "Exception", "{", "if", "(", "msg", ".", "getOpcode", "(", ")", "==", "SASL_LIST_MECHS_OPCODE", ")", "{", "handleListMechsResponse", "(", "ctx", ",", "msg", ")", ";", "}", "else", "if", "(", "msg", ".", "getOpcode", "(", ")", "==", "SASL_AUTH_OPCODE", ")", "{", "handleAuthResponse", "(", "ctx", ",", "msg", ")", ";", "}", "else", "if", "(", "msg", ".", "getOpcode", "(", ")", "==", "SASL_STEP_OPCODE", ")", "{", "checkIsAuthed", "(", "msg", ")", ";", "}", "}" ]
Dispatches incoming SASL responses to the appropriate handler methods. @param ctx the handler context. @param msg the incoming message to investigate. @throws Exception if something goes wrong during negotiation.
[ "Dispatches", "incoming", "SASL", "responses", "to", "the", "appropriate", "handler", "methods", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java#L173-L182
alkacon/opencms-core
src/org/opencms/search/solr/CmsSolrIndex.java
CmsSolrIndex.getDocument
public synchronized I_CmsSearchDocument getDocument(String fieldname, String term, String[] fls) { """ Version of {@link org.opencms.search.CmsSearchIndex#getDocument(java.lang.String, java.lang.String)} where the returned fields can be restricted. @param fieldname the field to query in @param term the query @param fls the returned fields. @return the document. """ try { SolrQuery query = new SolrQuery(); if (CmsSearchField.FIELD_PATH.equals(fieldname)) { query.setQuery(fieldname + ":\"" + term + "\""); } else { query.setQuery(fieldname + ":" + term); } query.addFilterQuery("{!collapse field=" + fieldname + "}"); if (null != fls) { query.setFields(fls); } QueryResponse res = m_solr.query(query); if (res != null) { SolrDocumentList sdl = m_solr.query(query).getResults(); if ((sdl.getNumFound() > 0L) && (sdl.get(0) != null)) { return new CmsSolrDocument(sdl.get(0)); } } } catch (Exception e) { // ignore and assume that the document could not be found LOG.error(e.getMessage(), e); } return null; }
java
public synchronized I_CmsSearchDocument getDocument(String fieldname, String term, String[] fls) { try { SolrQuery query = new SolrQuery(); if (CmsSearchField.FIELD_PATH.equals(fieldname)) { query.setQuery(fieldname + ":\"" + term + "\""); } else { query.setQuery(fieldname + ":" + term); } query.addFilterQuery("{!collapse field=" + fieldname + "}"); if (null != fls) { query.setFields(fls); } QueryResponse res = m_solr.query(query); if (res != null) { SolrDocumentList sdl = m_solr.query(query).getResults(); if ((sdl.getNumFound() > 0L) && (sdl.get(0) != null)) { return new CmsSolrDocument(sdl.get(0)); } } } catch (Exception e) { // ignore and assume that the document could not be found LOG.error(e.getMessage(), e); } return null; }
[ "public", "synchronized", "I_CmsSearchDocument", "getDocument", "(", "String", "fieldname", ",", "String", "term", ",", "String", "[", "]", "fls", ")", "{", "try", "{", "SolrQuery", "query", "=", "new", "SolrQuery", "(", ")", ";", "if", "(", "CmsSearchField", ".", "FIELD_PATH", ".", "equals", "(", "fieldname", ")", ")", "{", "query", ".", "setQuery", "(", "fieldname", "+", "\":\\\"\"", "+", "term", "+", "\"\\\"\"", ")", ";", "}", "else", "{", "query", ".", "setQuery", "(", "fieldname", "+", "\":\"", "+", "term", ")", ";", "}", "query", ".", "addFilterQuery", "(", "\"{!collapse field=\"", "+", "fieldname", "+", "\"}\"", ")", ";", "if", "(", "null", "!=", "fls", ")", "{", "query", ".", "setFields", "(", "fls", ")", ";", "}", "QueryResponse", "res", "=", "m_solr", ".", "query", "(", "query", ")", ";", "if", "(", "res", "!=", "null", ")", "{", "SolrDocumentList", "sdl", "=", "m_solr", ".", "query", "(", "query", ")", ".", "getResults", "(", ")", ";", "if", "(", "(", "sdl", ".", "getNumFound", "(", ")", ">", "0L", ")", "&&", "(", "sdl", ".", "get", "(", "0", ")", "!=", "null", ")", ")", "{", "return", "new", "CmsSolrDocument", "(", "sdl", ".", "get", "(", "0", ")", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// ignore and assume that the document could not be found\r", "LOG", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Version of {@link org.opencms.search.CmsSearchIndex#getDocument(java.lang.String, java.lang.String)} where the returned fields can be restricted. @param fieldname the field to query in @param term the query @param fls the returned fields. @return the document.
[ "Version", "of", "{", "@link", "org", ".", "opencms", ".", "search", ".", "CmsSearchIndex#getDocument", "(", "java", ".", "lang", ".", "String", "java", ".", "lang", ".", "String", ")", "}", "where", "the", "returned", "fields", "can", "be", "restricted", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/solr/CmsSolrIndex.java#L536-L561
eiichiro/gig
gig-appengine/src/main/java/org/eiichiro/gig/appengine/GeoPtConverter.java
GeoPtConverter.convertToType
@SuppressWarnings("rawtypes") @Override protected Object convertToType(Class type, Object value) throws Throwable { """ Converts the specified value to {@code com.google.appengine.api.datastore.GeoPt}. @see org.apache.commons.beanutils.converters.AbstractConverter#convertToType(java.lang.Class, java.lang.Object) """ String[] strings = value.toString().split(","); if (strings.length != 2) { throw new ConversionException( "GeoPt 'value' must be able to be splitted into 2 float values " + "by ',' (latitude,longitude)"); } try { float latitude = new BigDecimal(strings[0].trim()).floatValue(); float longitude = new BigDecimal(strings[1].trim()).floatValue(); return new GeoPt(latitude, longitude); } catch (Exception e) { throw new ConversionException( "Cannot parse GeoPt value into 2 float values: " + "latitude [" + strings[0].trim() + "], longitude [" + strings[1].trim() + "]"); } }
java
@SuppressWarnings("rawtypes") @Override protected Object convertToType(Class type, Object value) throws Throwable { String[] strings = value.toString().split(","); if (strings.length != 2) { throw new ConversionException( "GeoPt 'value' must be able to be splitted into 2 float values " + "by ',' (latitude,longitude)"); } try { float latitude = new BigDecimal(strings[0].trim()).floatValue(); float longitude = new BigDecimal(strings[1].trim()).floatValue(); return new GeoPt(latitude, longitude); } catch (Exception e) { throw new ConversionException( "Cannot parse GeoPt value into 2 float values: " + "latitude [" + strings[0].trim() + "], longitude [" + strings[1].trim() + "]"); } }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "@", "Override", "protected", "Object", "convertToType", "(", "Class", "type", ",", "Object", "value", ")", "throws", "Throwable", "{", "String", "[", "]", "strings", "=", "value", ".", "toString", "(", ")", ".", "split", "(", "\",\"", ")", ";", "if", "(", "strings", ".", "length", "!=", "2", ")", "{", "throw", "new", "ConversionException", "(", "\"GeoPt 'value' must be able to be splitted into 2 float values \"", "+", "\"by ',' (latitude,longitude)\"", ")", ";", "}", "try", "{", "float", "latitude", "=", "new", "BigDecimal", "(", "strings", "[", "0", "]", ".", "trim", "(", ")", ")", ".", "floatValue", "(", ")", ";", "float", "longitude", "=", "new", "BigDecimal", "(", "strings", "[", "1", "]", ".", "trim", "(", ")", ")", ".", "floatValue", "(", ")", ";", "return", "new", "GeoPt", "(", "latitude", ",", "longitude", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "ConversionException", "(", "\"Cannot parse GeoPt value into 2 float values: \"", "+", "\"latitude [\"", "+", "strings", "[", "0", "]", ".", "trim", "(", ")", "+", "\"], longitude [\"", "+", "strings", "[", "1", "]", ".", "trim", "(", ")", "+", "\"]\"", ")", ";", "}", "}" ]
Converts the specified value to {@code com.google.appengine.api.datastore.GeoPt}. @see org.apache.commons.beanutils.converters.AbstractConverter#convertToType(java.lang.Class, java.lang.Object)
[ "Converts", "the", "specified", "value", "to", "{", "@code", "com", ".", "google", ".", "appengine", ".", "api", ".", "datastore", ".", "GeoPt", "}", "." ]
train
https://github.com/eiichiro/gig/blob/21181fb36a17d2154f989e5e8c6edbb39fc81900/gig-appengine/src/main/java/org/eiichiro/gig/appengine/GeoPtConverter.java#L41-L62
jenkinsci/jenkins
core/src/main/java/jenkins/model/lazy/SortedIntList.java
SortedIntList.binarySearch
private static int binarySearch(int[] a, int start, int end, int key) { """ Switch to {@code java.util.Arrays.binarySearch} when we depend on Java6. """ int lo = start, hi = end-1; // search range is [lo,hi] // invariant lo<=hi while (lo <= hi) { int pivot = (lo + hi)/2; int v = a[pivot]; if (v < key) // needs to search upper half lo = pivot+1; else if (v > key) // needs to search lower half hi = pivot-1; else // eureka! return pivot; } return -(lo + 1); // insertion point }
java
private static int binarySearch(int[] a, int start, int end, int key) { int lo = start, hi = end-1; // search range is [lo,hi] // invariant lo<=hi while (lo <= hi) { int pivot = (lo + hi)/2; int v = a[pivot]; if (v < key) // needs to search upper half lo = pivot+1; else if (v > key) // needs to search lower half hi = pivot-1; else // eureka! return pivot; } return -(lo + 1); // insertion point }
[ "private", "static", "int", "binarySearch", "(", "int", "[", "]", "a", ",", "int", "start", ",", "int", "end", ",", "int", "key", ")", "{", "int", "lo", "=", "start", ",", "hi", "=", "end", "-", "1", ";", "// search range is [lo,hi]", "// invariant lo<=hi", "while", "(", "lo", "<=", "hi", ")", "{", "int", "pivot", "=", "(", "lo", "+", "hi", ")", "/", "2", ";", "int", "v", "=", "a", "[", "pivot", "]", ";", "if", "(", "v", "<", "key", ")", "// needs to search upper half", "lo", "=", "pivot", "+", "1", ";", "else", "if", "(", "v", ">", "key", ")", "// needs to search lower half", "hi", "=", "pivot", "-", "1", ";", "else", "// eureka!", "return", "pivot", ";", "}", "return", "-", "(", "lo", "+", "1", ")", ";", "// insertion point", "}" ]
Switch to {@code java.util.Arrays.binarySearch} when we depend on Java6.
[ "Switch", "to", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/lazy/SortedIntList.java#L159-L175
synchronoss/cpo-api
cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java
CassandraCpoAdapter.retrieveBeans
@Override public <T, C> List<T> retrieveBeans(String name, C criteria, T result) throws CpoException { """ Retrieves the bean from the datasource. The assumption is that the bean exists in the datasource. @param name The filter name which tells the datasource which beans should be returned. The name also signifies what data in the bean will be populated. @param criteria This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the arguments used to retrieve the collection of beans. @param result This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the bean type that will be returned in the collection. @return A collection of beans will be returned that meet the criteria specified by obj. The beans will be of the same type as the bean that was passed in. If no beans match the criteria, an empty collection will be returned @throws CpoException Thrown if there are errors accessing the datasource """ return processSelectGroup(name, criteria, result, null, null, null, false); }
java
@Override public <T, C> List<T> retrieveBeans(String name, C criteria, T result) throws CpoException { return processSelectGroup(name, criteria, result, null, null, null, false); }
[ "@", "Override", "public", "<", "T", ",", "C", ">", "List", "<", "T", ">", "retrieveBeans", "(", "String", "name", ",", "C", "criteria", ",", "T", "result", ")", "throws", "CpoException", "{", "return", "processSelectGroup", "(", "name", ",", "criteria", ",", "result", ",", "null", ",", "null", ",", "null", ",", "false", ")", ";", "}" ]
Retrieves the bean from the datasource. The assumption is that the bean exists in the datasource. @param name The filter name which tells the datasource which beans should be returned. The name also signifies what data in the bean will be populated. @param criteria This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the arguments used to retrieve the collection of beans. @param result This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the bean type that will be returned in the collection. @return A collection of beans will be returned that meet the criteria specified by obj. The beans will be of the same type as the bean that was passed in. If no beans match the criteria, an empty collection will be returned @throws CpoException Thrown if there are errors accessing the datasource
[ "Retrieves", "the", "bean", "from", "the", "datasource", ".", "The", "assumption", "is", "that", "the", "bean", "exists", "in", "the", "datasource", "." ]
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L1531-L1534
jbundle/jbundle
thin/opt/location/src/main/java/org/jbundle/thin/opt/location/DynamicTreeNode.java
DynamicTreeNode.loadChildren
protected void loadChildren() { """ Messaged the first time getChildCount is messaged. Creates children with random names from names. """ DynamicTreeNode newNode; // Font font; // int randomIndex; NodeData dataParent = (NodeData)this.getUserObject(); FieldList fieldList = dataParent.makeRecord(); FieldTable fieldTable = fieldList.getTable(); m_fNameCount = 0; try { fieldTable.close(); // while (fieldTable.hasNext()) while (fieldTable.next() != null) { String objID = fieldList.getField(0).toString(); String strDescription = fieldList.getField(3).toString(); NodeData data = new NodeData(dataParent.getBaseApplet(), dataParent.getRemoteSession(), strDescription, objID, dataParent.getSubRecordClassName()); newNode = new DynamicTreeNode(data); /** Don't use add() here, add calls insert(newNode, getChildCount()) so if you want to use add, just be sure to set hasLoaded = true first. */ this.insert(newNode, (int)m_fNameCount); m_fNameCount++; } } catch (Exception ex) { ex.printStackTrace(); } /** This node has now been loaded, mark it so. */ m_bHasLoaded = true; }
java
protected void loadChildren() { DynamicTreeNode newNode; // Font font; // int randomIndex; NodeData dataParent = (NodeData)this.getUserObject(); FieldList fieldList = dataParent.makeRecord(); FieldTable fieldTable = fieldList.getTable(); m_fNameCount = 0; try { fieldTable.close(); // while (fieldTable.hasNext()) while (fieldTable.next() != null) { String objID = fieldList.getField(0).toString(); String strDescription = fieldList.getField(3).toString(); NodeData data = new NodeData(dataParent.getBaseApplet(), dataParent.getRemoteSession(), strDescription, objID, dataParent.getSubRecordClassName()); newNode = new DynamicTreeNode(data); /** Don't use add() here, add calls insert(newNode, getChildCount()) so if you want to use add, just be sure to set hasLoaded = true first. */ this.insert(newNode, (int)m_fNameCount); m_fNameCount++; } } catch (Exception ex) { ex.printStackTrace(); } /** This node has now been loaded, mark it so. */ m_bHasLoaded = true; }
[ "protected", "void", "loadChildren", "(", ")", "{", "DynamicTreeNode", "newNode", ";", "// Font font;", "// int randomIndex;", "NodeData", "dataParent", "=", "(", "NodeData", ")", "this", ".", "getUserObject", "(", ")", ";", "FieldList", "fieldList", "=", "dataParent", ".", "makeRecord", "(", ")", ";", "FieldTable", "fieldTable", "=", "fieldList", ".", "getTable", "(", ")", ";", "m_fNameCount", "=", "0", ";", "try", "{", "fieldTable", ".", "close", "(", ")", ";", "// while (fieldTable.hasNext())", "while", "(", "fieldTable", ".", "next", "(", ")", "!=", "null", ")", "{", "String", "objID", "=", "fieldList", ".", "getField", "(", "0", ")", ".", "toString", "(", ")", ";", "String", "strDescription", "=", "fieldList", ".", "getField", "(", "3", ")", ".", "toString", "(", ")", ";", "NodeData", "data", "=", "new", "NodeData", "(", "dataParent", ".", "getBaseApplet", "(", ")", ",", "dataParent", ".", "getRemoteSession", "(", ")", ",", "strDescription", ",", "objID", ",", "dataParent", ".", "getSubRecordClassName", "(", ")", ")", ";", "newNode", "=", "new", "DynamicTreeNode", "(", "data", ")", ";", "/** Don't use add() here, add calls insert(newNode, getChildCount())\n so if you want to use add, just be sure to set hasLoaded = true first. */", "this", ".", "insert", "(", "newNode", ",", "(", "int", ")", "m_fNameCount", ")", ";", "m_fNameCount", "++", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "/** This node has now been loaded, mark it so. */", "m_bHasLoaded", "=", "true", ";", "}" ]
Messaged the first time getChildCount is messaged. Creates children with random names from names.
[ "Messaged", "the", "first", "time", "getChildCount", "is", "messaged", ".", "Creates", "children", "with", "random", "names", "from", "names", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/opt/location/src/main/java/org/jbundle/thin/opt/location/DynamicTreeNode.java#L67-L97
ecclesia/kipeto
kipeto-common/src/main/java/de/ecclesia/kipeto/common/util/Files.java
Files.copyFile
public static void copyFile(File sourceFile, File destinationFile) throws FileNotFoundException, IOException { """ Kopiert eine Datei @param sourceFile Quelldatei @param destinationFile Zieldatei @throws IOException @throws FileNotFoundException """ Streams.copyStream(new FileInputStream(sourceFile), new FileOutputStream(destinationFile), true); }
java
public static void copyFile(File sourceFile, File destinationFile) throws FileNotFoundException, IOException { Streams.copyStream(new FileInputStream(sourceFile), new FileOutputStream(destinationFile), true); }
[ "public", "static", "void", "copyFile", "(", "File", "sourceFile", ",", "File", "destinationFile", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "Streams", ".", "copyStream", "(", "new", "FileInputStream", "(", "sourceFile", ")", ",", "new", "FileOutputStream", "(", "destinationFile", ")", ",", "true", ")", ";", "}" ]
Kopiert eine Datei @param sourceFile Quelldatei @param destinationFile Zieldatei @throws IOException @throws FileNotFoundException
[ "Kopiert", "eine", "Datei" ]
train
https://github.com/ecclesia/kipeto/blob/ea39a10ae4eaa550f71a856ab2f2845270a64913/kipeto-common/src/main/java/de/ecclesia/kipeto/common/util/Files.java#L77-L79
JOML-CI/JOML
src/org/joml/sampling/SpiralSampling.java
SpiralSampling.createEquiAngle
public void createEquiAngle(float radius, int numRotations, int numSamples, Callback2d callback) { """ Create <code>numSamples</code> number of samples on a spiral with maximum radius <code>radius</code> around the center using <code>numRotations</code> number of rotations along the spiral, and call the given <code>callback</code> for each sample generated. <p> The generated sample points are distributed with equal angle differences around the spiral, so they concentrate towards the center. @param radius the maximum radius of the spiral @param numRotations the number of rotations of the spiral @param numSamples the number of samples to generate @param callback will be called for each sample generated """ for (int sample = 0; sample < numSamples; sample++) { float angle = 2.0f * (float) Math.PI * (sample * numRotations) / numSamples; float r = radius * sample / (numSamples - 1); float x = (float) Math.sin_roquen_9(angle + 0.5f * (float) Math.PI) * r; float y = (float) Math.sin_roquen_9(angle) * r; callback.onNewSample(x, y); } }
java
public void createEquiAngle(float radius, int numRotations, int numSamples, Callback2d callback) { for (int sample = 0; sample < numSamples; sample++) { float angle = 2.0f * (float) Math.PI * (sample * numRotations) / numSamples; float r = radius * sample / (numSamples - 1); float x = (float) Math.sin_roquen_9(angle + 0.5f * (float) Math.PI) * r; float y = (float) Math.sin_roquen_9(angle) * r; callback.onNewSample(x, y); } }
[ "public", "void", "createEquiAngle", "(", "float", "radius", ",", "int", "numRotations", ",", "int", "numSamples", ",", "Callback2d", "callback", ")", "{", "for", "(", "int", "sample", "=", "0", ";", "sample", "<", "numSamples", ";", "sample", "++", ")", "{", "float", "angle", "=", "2.0f", "*", "(", "float", ")", "Math", ".", "PI", "*", "(", "sample", "*", "numRotations", ")", "/", "numSamples", ";", "float", "r", "=", "radius", "*", "sample", "/", "(", "numSamples", "-", "1", ")", ";", "float", "x", "=", "(", "float", ")", "Math", ".", "sin_roquen_9", "(", "angle", "+", "0.5f", "*", "(", "float", ")", "Math", ".", "PI", ")", "*", "r", ";", "float", "y", "=", "(", "float", ")", "Math", ".", "sin_roquen_9", "(", "angle", ")", "*", "r", ";", "callback", ".", "onNewSample", "(", "x", ",", "y", ")", ";", "}", "}" ]
Create <code>numSamples</code> number of samples on a spiral with maximum radius <code>radius</code> around the center using <code>numRotations</code> number of rotations along the spiral, and call the given <code>callback</code> for each sample generated. <p> The generated sample points are distributed with equal angle differences around the spiral, so they concentrate towards the center. @param radius the maximum radius of the spiral @param numRotations the number of rotations of the spiral @param numSamples the number of samples to generate @param callback will be called for each sample generated
[ "Create", "<code", ">", "numSamples<", "/", "code", ">", "number", "of", "samples", "on", "a", "spiral", "with", "maximum", "radius", "<code", ">", "radius<", "/", "code", ">", "around", "the", "center", "using", "<code", ">", "numRotations<", "/", "code", ">", "number", "of", "rotations", "along", "the", "spiral", "and", "call", "the", "given", "<code", ">", "callback<", "/", "code", ">", "for", "each", "sample", "generated", ".", "<p", ">", "The", "generated", "sample", "points", "are", "distributed", "with", "equal", "angle", "differences", "around", "the", "spiral", "so", "they", "concentrate", "towards", "the", "center", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/sampling/SpiralSampling.java#L61-L69
fuinorg/srcgen4javassist
src/main/java/org/fuin/srcgen4javassist/ByteCodeGenerator.java
ByteCodeGenerator.createWithCurrentThreadContextClassLoader
public static ByteCodeGenerator createWithCurrentThreadContextClassLoader() { """ Creates a generator initialized with default class pool and the context class loader of the current thread. @return New byte code generator instance. """ final ClassPool pool = ClassPool.getDefault(); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); pool.appendClassPath(new LoaderClassPath(classLoader)); return new ByteCodeGenerator(pool, classLoader); }
java
public static ByteCodeGenerator createWithCurrentThreadContextClassLoader() { final ClassPool pool = ClassPool.getDefault(); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); pool.appendClassPath(new LoaderClassPath(classLoader)); return new ByteCodeGenerator(pool, classLoader); }
[ "public", "static", "ByteCodeGenerator", "createWithCurrentThreadContextClassLoader", "(", ")", "{", "final", "ClassPool", "pool", "=", "ClassPool", ".", "getDefault", "(", ")", ";", "final", "ClassLoader", "classLoader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "pool", ".", "appendClassPath", "(", "new", "LoaderClassPath", "(", "classLoader", ")", ")", ";", "return", "new", "ByteCodeGenerator", "(", "pool", ",", "classLoader", ")", ";", "}" ]
Creates a generator initialized with default class pool and the context class loader of the current thread. @return New byte code generator instance.
[ "Creates", "a", "generator", "initialized", "with", "default", "class", "pool", "and", "the", "context", "class", "loader", "of", "the", "current", "thread", "." ]
train
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/ByteCodeGenerator.java#L351-L356
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java
JobOperations.getJob
public CloudJob getJob(String jobId, DetailLevel detailLevel) throws BatchErrorException, IOException { """ Gets the specified {@link CloudJob}. @param jobId The ID of the job to get. @param detailLevel A {@link DetailLevel} used for controlling which properties are retrieved from the service. @return A {@link CloudJob} containing information about the specified Azure Batch job. @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. """ return getJob(jobId, detailLevel, null); }
java
public CloudJob getJob(String jobId, DetailLevel detailLevel) throws BatchErrorException, IOException { return getJob(jobId, detailLevel, null); }
[ "public", "CloudJob", "getJob", "(", "String", "jobId", ",", "DetailLevel", "detailLevel", ")", "throws", "BatchErrorException", ",", "IOException", "{", "return", "getJob", "(", "jobId", ",", "detailLevel", ",", "null", ")", ";", "}" ]
Gets the specified {@link CloudJob}. @param jobId The ID of the job to get. @param detailLevel A {@link DetailLevel} used for controlling which properties are retrieved from the service. @return A {@link CloudJob} containing information about the specified Azure Batch job. @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.
[ "Gets", "the", "specified", "{", "@link", "CloudJob", "}", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/JobOperations.java#L127-L129
sporniket/core
sporniket-core-ui/src/main/java/com/sporniket/libre/ui/swing/FluidFlowPanelModel.java
FluidFlowPanelModel.createFluidFlowPanel
public static final FluidFlowPanelModel createFluidFlowPanel(FlowLayout flowLayout) { """ The macro that create a scrollable panel with a fluid flow layout. @param flowLayout the flow layout to use by this panel. @return the component. """ JPanel _panel = new JPanel(flowLayout); PanelSizeUpdaterOnViewPortResize _updater = new PanelSizeUpdaterOnViewPortResize(_panel); _panel.addContainerListener(_updater); JScrollPane _scroller = new JScrollPane(_panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); _scroller.addComponentListener(_updater); return new FluidFlowPanelModel(_panel, _scroller); }
java
public static final FluidFlowPanelModel createFluidFlowPanel(FlowLayout flowLayout) { JPanel _panel = new JPanel(flowLayout); PanelSizeUpdaterOnViewPortResize _updater = new PanelSizeUpdaterOnViewPortResize(_panel); _panel.addContainerListener(_updater); JScrollPane _scroller = new JScrollPane(_panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); _scroller.addComponentListener(_updater); return new FluidFlowPanelModel(_panel, _scroller); }
[ "public", "static", "final", "FluidFlowPanelModel", "createFluidFlowPanel", "(", "FlowLayout", "flowLayout", ")", "{", "JPanel", "_panel", "=", "new", "JPanel", "(", "flowLayout", ")", ";", "PanelSizeUpdaterOnViewPortResize", "_updater", "=", "new", "PanelSizeUpdaterOnViewPortResize", "(", "_panel", ")", ";", "_panel", ".", "addContainerListener", "(", "_updater", ")", ";", "JScrollPane", "_scroller", "=", "new", "JScrollPane", "(", "_panel", ",", "JScrollPane", ".", "VERTICAL_SCROLLBAR_ALWAYS", ",", "JScrollPane", ".", "HORIZONTAL_SCROLLBAR_NEVER", ")", ";", "_scroller", ".", "addComponentListener", "(", "_updater", ")", ";", "return", "new", "FluidFlowPanelModel", "(", "_panel", ",", "_scroller", ")", ";", "}" ]
The macro that create a scrollable panel with a fluid flow layout. @param flowLayout the flow layout to use by this panel. @return the component.
[ "The", "macro", "that", "create", "a", "scrollable", "panel", "with", "a", "fluid", "flow", "layout", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-ui/src/main/java/com/sporniket/libre/ui/swing/FluidFlowPanelModel.java#L204-L213
RestComm/sip-servlets
sip-servlets-examples/click-to-call-servlet3/src/main/java/org/mobicents/servlet/sip/example/StatusServlet.java
StatusServlet.doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { """ /* doGet will will start an AsyncContext, store the new AsyncContext in order for this to get processed later and last update the client's page with the current data. Also sets a timeout in the AsyncContext, and registers an AsyncListener in order to handle the events needed. """ PrintWriter writer = response.getWriter(); writer.write(JUNK); writer.flush(); if(!request.isAsyncSupported()){ PrintWriter out = response.getWriter(); out.println("Asynchronous request processing is not supported"); out.flush(); out.close(); return; } final AsyncContext ac = request.startAsync(); ac.setTimeout(10 * 60 * 1000); StatusServletAsyncListener asyncListener = new StatusServletAsyncListener(ac, queue, data); ac.addListener(asyncListener); //Add this to the queue for further processing when there is a response to dispatch queue.add(ac); //First time request will get the current data firstTimeReq(ac); }
java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); writer.write(JUNK); writer.flush(); if(!request.isAsyncSupported()){ PrintWriter out = response.getWriter(); out.println("Asynchronous request processing is not supported"); out.flush(); out.close(); return; } final AsyncContext ac = request.startAsync(); ac.setTimeout(10 * 60 * 1000); StatusServletAsyncListener asyncListener = new StatusServletAsyncListener(ac, queue, data); ac.addListener(asyncListener); //Add this to the queue for further processing when there is a response to dispatch queue.add(ac); //First time request will get the current data firstTimeReq(ac); }
[ "protected", "void", "doGet", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "PrintWriter", "writer", "=", "response", ".", "getWriter", "(", ")", ";", "writer", ".", "write", "(", "JUNK", ")", ";", "writer", ".", "flush", "(", ")", ";", "if", "(", "!", "request", ".", "isAsyncSupported", "(", ")", ")", "{", "PrintWriter", "out", "=", "response", ".", "getWriter", "(", ")", ";", "out", ".", "println", "(", "\"Asynchronous request processing is not supported\"", ")", ";", "out", ".", "flush", "(", ")", ";", "out", ".", "close", "(", ")", ";", "return", ";", "}", "final", "AsyncContext", "ac", "=", "request", ".", "startAsync", "(", ")", ";", "ac", ".", "setTimeout", "(", "10", "*", "60", "*", "1000", ")", ";", "StatusServletAsyncListener", "asyncListener", "=", "new", "StatusServletAsyncListener", "(", "ac", ",", "queue", ",", "data", ")", ";", "ac", ".", "addListener", "(", "asyncListener", ")", ";", "//Add this to the queue for further processing when there is a response to dispatch", "queue", ".", "add", "(", "ac", ")", ";", "//First time request will get the current data", "firstTimeReq", "(", "ac", ")", ";", "}" ]
/* doGet will will start an AsyncContext, store the new AsyncContext in order for this to get processed later and last update the client's page with the current data. Also sets a timeout in the AsyncContext, and registers an AsyncListener in order to handle the events needed.
[ "/", "*", "doGet", "will", "will", "start", "an", "AsyncContext", "store", "the", "new", "AsyncContext", "in", "order", "for", "this", "to", "get", "processed", "later", "and", "last", "update", "the", "client", "s", "page", "with", "the", "current", "data", ".", "Also", "sets", "a", "timeout", "in", "the", "AsyncContext", "and", "registers", "an", "AsyncListener", "in", "order", "to", "handle", "the", "events", "needed", "." ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/click-to-call-servlet3/src/main/java/org/mobicents/servlet/sip/example/StatusServlet.java#L56-L79
aws/aws-sdk-java
aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/GetStageResult.java
GetStageResult.withRouteSettings
public GetStageResult withRouteSettings(java.util.Map<String, RouteSettings> routeSettings) { """ <p> Route settings for the stage. </p> @param routeSettings Route settings for the stage. @return Returns a reference to this object so that method calls can be chained together. """ setRouteSettings(routeSettings); return this; }
java
public GetStageResult withRouteSettings(java.util.Map<String, RouteSettings> routeSettings) { setRouteSettings(routeSettings); return this; }
[ "public", "GetStageResult", "withRouteSettings", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "RouteSettings", ">", "routeSettings", ")", "{", "setRouteSettings", "(", "routeSettings", ")", ";", "return", "this", ";", "}" ]
<p> Route settings for the stage. </p> @param routeSettings Route settings for the stage. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Route", "settings", "for", "the", "stage", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/GetStageResult.java#L398-L401
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.getType
public JSType getType( StaticTypedScope scope, String jsTypeName, String sourceName, int lineno, int charno) { """ Looks up a type by name. To allow for forward references to types, an unrecognized string has to be bound to a NamedType object that will be resolved later. @param scope A scope for doing type name resolution. @param jsTypeName The name string. @param sourceName The name of the source file where this reference appears. @param lineno The line number of the reference. @return a NamedType if the string argument is not one of the known types, otherwise the corresponding JSType object. """ return getType(scope, jsTypeName, sourceName, lineno, charno, true); }
java
public JSType getType( StaticTypedScope scope, String jsTypeName, String sourceName, int lineno, int charno) { return getType(scope, jsTypeName, sourceName, lineno, charno, true); }
[ "public", "JSType", "getType", "(", "StaticTypedScope", "scope", ",", "String", "jsTypeName", ",", "String", "sourceName", ",", "int", "lineno", ",", "int", "charno", ")", "{", "return", "getType", "(", "scope", ",", "jsTypeName", ",", "sourceName", ",", "lineno", ",", "charno", ",", "true", ")", ";", "}" ]
Looks up a type by name. To allow for forward references to types, an unrecognized string has to be bound to a NamedType object that will be resolved later. @param scope A scope for doing type name resolution. @param jsTypeName The name string. @param sourceName The name of the source file where this reference appears. @param lineno The line number of the reference. @return a NamedType if the string argument is not one of the known types, otherwise the corresponding JSType object.
[ "Looks", "up", "a", "type", "by", "name", ".", "To", "allow", "for", "forward", "references", "to", "types", "an", "unrecognized", "string", "has", "to", "be", "bound", "to", "a", "NamedType", "object", "that", "will", "be", "resolved", "later", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1361-L1364
interedition/collatex
collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java
ActivePoint.fixActiveEdgeAfterSuffixLink
private void fixActiveEdgeAfterSuffixLink(Suffix<T, S> suffix) { """ Deal with the case when we follow a suffix link but the active length is greater than the new active edge length. In this situation we must walk down the tree updating the entire active point. """ while (activeEdge != null && activeLength > activeEdge.getLength()) { activeLength = activeLength - activeEdge.getLength(); activeNode = activeEdge.getTerminal(); Object item = suffix.getItemXFromEnd(activeLength + 1); activeEdge = activeNode.getEdgeStarting(item); } resetActivePointToTerminal(); }
java
private void fixActiveEdgeAfterSuffixLink(Suffix<T, S> suffix) { while (activeEdge != null && activeLength > activeEdge.getLength()) { activeLength = activeLength - activeEdge.getLength(); activeNode = activeEdge.getTerminal(); Object item = suffix.getItemXFromEnd(activeLength + 1); activeEdge = activeNode.getEdgeStarting(item); } resetActivePointToTerminal(); }
[ "private", "void", "fixActiveEdgeAfterSuffixLink", "(", "Suffix", "<", "T", ",", "S", ">", "suffix", ")", "{", "while", "(", "activeEdge", "!=", "null", "&&", "activeLength", ">", "activeEdge", ".", "getLength", "(", ")", ")", "{", "activeLength", "=", "activeLength", "-", "activeEdge", ".", "getLength", "(", ")", ";", "activeNode", "=", "activeEdge", ".", "getTerminal", "(", ")", ";", "Object", "item", "=", "suffix", ".", "getItemXFromEnd", "(", "activeLength", "+", "1", ")", ";", "activeEdge", "=", "activeNode", ".", "getEdgeStarting", "(", "item", ")", ";", "}", "resetActivePointToTerminal", "(", ")", ";", "}" ]
Deal with the case when we follow a suffix link but the active length is greater than the new active edge length. In this situation we must walk down the tree updating the entire active point.
[ "Deal", "with", "the", "case", "when", "we", "follow", "a", "suffix", "link", "but", "the", "active", "length", "is", "greater", "than", "the", "new", "active", "edge", "length", ".", "In", "this", "situation", "we", "must", "walk", "down", "the", "tree", "updating", "the", "entire", "active", "point", "." ]
train
https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java#L157-L165
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java
CPInstancePersistenceImpl.removeByC_NotST
@Override public void removeByC_NotST(long CPDefinitionId, int status) { """ Removes all the cp instances where CPDefinitionId = &#63; and status &ne; &#63; from the database. @param CPDefinitionId the cp definition ID @param status the status """ for (CPInstance cpInstance : findByC_NotST(CPDefinitionId, status, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpInstance); } }
java
@Override public void removeByC_NotST(long CPDefinitionId, int status) { for (CPInstance cpInstance : findByC_NotST(CPDefinitionId, status, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpInstance); } }
[ "@", "Override", "public", "void", "removeByC_NotST", "(", "long", "CPDefinitionId", ",", "int", "status", ")", "{", "for", "(", "CPInstance", "cpInstance", ":", "findByC_NotST", "(", "CPDefinitionId", ",", "status", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ")", "{", "remove", "(", "cpInstance", ")", ";", "}", "}" ]
Removes all the cp instances where CPDefinitionId = &#63; and status &ne; &#63; from the database. @param CPDefinitionId the cp definition ID @param status the status
[ "Removes", "all", "the", "cp", "instances", "where", "CPDefinitionId", "=", "&#63", ";", "and", "status", "&ne", ";", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java#L5568-L5574
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/mps_ssl_certkey.java
mps_ssl_certkey.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ mps_ssl_certkey_responses result = (mps_ssl_certkey_responses) service.get_payload_formatter().string_to_resource(mps_ssl_certkey_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.mps_ssl_certkey_response_array); } mps_ssl_certkey[] result_mps_ssl_certkey = new mps_ssl_certkey[result.mps_ssl_certkey_response_array.length]; for(int i = 0; i < result.mps_ssl_certkey_response_array.length; i++) { result_mps_ssl_certkey[i] = result.mps_ssl_certkey_response_array[i].mps_ssl_certkey[0]; } return result_mps_ssl_certkey; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { mps_ssl_certkey_responses result = (mps_ssl_certkey_responses) service.get_payload_formatter().string_to_resource(mps_ssl_certkey_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.mps_ssl_certkey_response_array); } mps_ssl_certkey[] result_mps_ssl_certkey = new mps_ssl_certkey[result.mps_ssl_certkey_response_array.length]; for(int i = 0; i < result.mps_ssl_certkey_response_array.length; i++) { result_mps_ssl_certkey[i] = result.mps_ssl_certkey_response_array[i].mps_ssl_certkey[0]; } return result_mps_ssl_certkey; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "mps_ssl_certkey_responses", "result", "=", "(", "mps_ssl_certkey_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "mps_ssl_certkey_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "mps_ssl_certkey_response_array", ")", ";", "}", "mps_ssl_certkey", "[", "]", "result_mps_ssl_certkey", "=", "new", "mps_ssl_certkey", "[", "result", ".", "mps_ssl_certkey_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "mps_ssl_certkey_response_array", ".", "length", ";", "i", "++", ")", "{", "result_mps_ssl_certkey", "[", "i", "]", "=", "result", ".", "mps_ssl_certkey_response_array", "[", "i", "]", ".", "mps_ssl_certkey", "[", "0", "]", ";", "}", "return", "result_mps_ssl_certkey", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/mps_ssl_certkey.java#L442-L459
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/SheetUpdateRequestResourcesImpl.java
SheetUpdateRequestResourcesImpl.createUpdateRequest
public UpdateRequest createUpdateRequest(long sheetId, UpdateRequest updateRequest) throws SmartsheetException { """ Creates an Update Request for the specified Row(s) within the Sheet. An email notification (containing a link to the update request) will be asynchronously sent to the specified recipient(s). It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/updaterequests @param sheetId the Id of the sheet @param updateRequest the update request object @return the update request resource. @throws IllegalArgumentException if any argument is null or empty string @throws InvalidRequestException if there is any problem with the REST API request @throws AuthorizationException if there is any problem with the REST API authorization (access token) @throws ResourceNotFoundException if the resource cannot be found @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting) @throws SmartsheetException if there is any other error during the operation """ return this.createResource("sheets/" + sheetId + "/updaterequests", UpdateRequest.class, updateRequest); }
java
public UpdateRequest createUpdateRequest(long sheetId, UpdateRequest updateRequest) throws SmartsheetException { return this.createResource("sheets/" + sheetId + "/updaterequests", UpdateRequest.class, updateRequest); }
[ "public", "UpdateRequest", "createUpdateRequest", "(", "long", "sheetId", ",", "UpdateRequest", "updateRequest", ")", "throws", "SmartsheetException", "{", "return", "this", ".", "createResource", "(", "\"sheets/\"", "+", "sheetId", "+", "\"/updaterequests\"", ",", "UpdateRequest", ".", "class", ",", "updateRequest", ")", ";", "}" ]
Creates an Update Request for the specified Row(s) within the Sheet. An email notification (containing a link to the update request) will be asynchronously sent to the specified recipient(s). It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/updaterequests @param sheetId the Id of the sheet @param updateRequest the update request object @return the update request resource. @throws IllegalArgumentException if any argument is null or empty string @throws InvalidRequestException if there is any problem with the REST API request @throws AuthorizationException if there is any problem with the REST API authorization (access token) @throws ResourceNotFoundException if the resource cannot be found @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting) @throws SmartsheetException if there is any other error during the operation
[ "Creates", "an", "Update", "Request", "for", "the", "specified", "Row", "(", "s", ")", "within", "the", "Sheet", ".", "An", "email", "notification", "(", "containing", "a", "link", "to", "the", "update", "request", ")", "will", "be", "asynchronously", "sent", "to", "the", "specified", "recipient", "(", "s", ")", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetUpdateRequestResourcesImpl.java#L112-L114
signalapp/libsignal-service-java
java/src/main/java/org/whispersystems/signalservice/api/SignalServiceAccountManager.java
SignalServiceAccountManager.setPreKeys
public void setPreKeys(IdentityKey identityKey, SignedPreKeyRecord signedPreKey, List<PreKeyRecord> oneTimePreKeys) throws IOException { """ Register an identity key, signed prekey, and list of one time prekeys with the server. @param identityKey The client's long-term identity keypair. @param signedPreKey The client's signed prekey. @param oneTimePreKeys The client's list of one-time prekeys. @throws IOException """ this.pushServiceSocket.registerPreKeys(identityKey, signedPreKey, oneTimePreKeys); }
java
public void setPreKeys(IdentityKey identityKey, SignedPreKeyRecord signedPreKey, List<PreKeyRecord> oneTimePreKeys) throws IOException { this.pushServiceSocket.registerPreKeys(identityKey, signedPreKey, oneTimePreKeys); }
[ "public", "void", "setPreKeys", "(", "IdentityKey", "identityKey", ",", "SignedPreKeyRecord", "signedPreKey", ",", "List", "<", "PreKeyRecord", ">", "oneTimePreKeys", ")", "throws", "IOException", "{", "this", ".", "pushServiceSocket", ".", "registerPreKeys", "(", "identityKey", ",", "signedPreKey", ",", "oneTimePreKeys", ")", ";", "}" ]
Register an identity key, signed prekey, and list of one time prekeys with the server. @param identityKey The client's long-term identity keypair. @param signedPreKey The client's signed prekey. @param oneTimePreKeys The client's list of one-time prekeys. @throws IOException
[ "Register", "an", "identity", "key", "signed", "prekey", "and", "list", "of", "one", "time", "prekeys", "with", "the", "server", "." ]
train
https://github.com/signalapp/libsignal-service-java/blob/64f1150c5e4062d67d31c9a2a9c3a0237d022902/java/src/main/java/org/whispersystems/signalservice/api/SignalServiceAccountManager.java#L206-L210
super-csv/super-csv
super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrRegEx.java
StrRegEx.execute
public Object execute(final Object value, final CsvContext context) { """ {@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if value doesn't match the regular expression """ validateInputNotNull(value, context); final boolean matches = regexPattern.matcher((String) value).matches(); if( !matches ) { final String msg = REGEX_MSGS.get(regex); if( msg == null ) { throw new SuperCsvConstraintViolationException(String.format( "'%s' does not match the regular expression '%s'", value, regex), context, this); } else { throw new SuperCsvConstraintViolationException( String.format("'%s' does not match the constraint '%s' defined by the regular expression '%s'", value, msg, regex), context, this); } } return next.execute(value, context); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); final boolean matches = regexPattern.matcher((String) value).matches(); if( !matches ) { final String msg = REGEX_MSGS.get(regex); if( msg == null ) { throw new SuperCsvConstraintViolationException(String.format( "'%s' does not match the regular expression '%s'", value, regex), context, this); } else { throw new SuperCsvConstraintViolationException( String.format("'%s' does not match the constraint '%s' defined by the regular expression '%s'", value, msg, regex), context, this); } } return next.execute(value, context); }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "final", "boolean", "matches", "=", "regexPattern", ".", "matcher", "(", "(", "String", ")", "value", ")", ".", "matches", "(", ")", ";", "if", "(", "!", "matches", ")", "{", "final", "String", "msg", "=", "REGEX_MSGS", ".", "get", "(", "regex", ")", ";", "if", "(", "msg", "==", "null", ")", "{", "throw", "new", "SuperCsvConstraintViolationException", "(", "String", ".", "format", "(", "\"'%s' does not match the regular expression '%s'\"", ",", "value", ",", "regex", ")", ",", "context", ",", "this", ")", ";", "}", "else", "{", "throw", "new", "SuperCsvConstraintViolationException", "(", "String", ".", "format", "(", "\"'%s' does not match the constraint '%s' defined by the regular expression '%s'\"", ",", "value", ",", "msg", ",", "regex", ")", ",", "context", ",", "this", ")", ";", "}", "}", "return", "next", ".", "execute", "(", "value", ",", "context", ")", ";", "}" ]
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null @throws SuperCsvConstraintViolationException if value doesn't match the regular expression
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/StrRegEx.java#L111-L127
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/dsl/converters/FromInstances.java
FromInstances.buildFileDefinition
public FileDefinition buildFileDefinition( Collection<Instance> rootInstances, File targetFile, boolean addComment, boolean saveRuntimeInformation ) { """ Builds a file definition from a collection of instances. @param rootInstances the root instances (not null) @param targetFile the target file (will not be written) @param addComment true to insert generated comments @param saveRuntimeInformation true to save runtime information (such as IP...), false otherwise @return a non-null file definition """ FileDefinition result = new FileDefinition( targetFile ); result.setFileType( FileDefinition.INSTANCE ); if( addComment ) { String s = "# File created from an in-memory model,\n# without a binding to existing files."; BlockComment initialComment = new BlockComment( result, s ); result.getBlocks().add( initialComment ); result.getBlocks().add( new BlockBlank( result, "\n" )); } for( Instance rootInstance : rootInstances ) result.getBlocks().addAll( buildInstanceOf( result, rootInstance, addComment, saveRuntimeInformation )); return result; }
java
public FileDefinition buildFileDefinition( Collection<Instance> rootInstances, File targetFile, boolean addComment, boolean saveRuntimeInformation ) { FileDefinition result = new FileDefinition( targetFile ); result.setFileType( FileDefinition.INSTANCE ); if( addComment ) { String s = "# File created from an in-memory model,\n# without a binding to existing files."; BlockComment initialComment = new BlockComment( result, s ); result.getBlocks().add( initialComment ); result.getBlocks().add( new BlockBlank( result, "\n" )); } for( Instance rootInstance : rootInstances ) result.getBlocks().addAll( buildInstanceOf( result, rootInstance, addComment, saveRuntimeInformation )); return result; }
[ "public", "FileDefinition", "buildFileDefinition", "(", "Collection", "<", "Instance", ">", "rootInstances", ",", "File", "targetFile", ",", "boolean", "addComment", ",", "boolean", "saveRuntimeInformation", ")", "{", "FileDefinition", "result", "=", "new", "FileDefinition", "(", "targetFile", ")", ";", "result", ".", "setFileType", "(", "FileDefinition", ".", "INSTANCE", ")", ";", "if", "(", "addComment", ")", "{", "String", "s", "=", "\"# File created from an in-memory model,\\n# without a binding to existing files.\"", ";", "BlockComment", "initialComment", "=", "new", "BlockComment", "(", "result", ",", "s", ")", ";", "result", ".", "getBlocks", "(", ")", ".", "add", "(", "initialComment", ")", ";", "result", ".", "getBlocks", "(", ")", ".", "add", "(", "new", "BlockBlank", "(", "result", ",", "\"\\n\"", ")", ")", ";", "}", "for", "(", "Instance", "rootInstance", ":", "rootInstances", ")", "result", ".", "getBlocks", "(", ")", ".", "addAll", "(", "buildInstanceOf", "(", "result", ",", "rootInstance", ",", "addComment", ",", "saveRuntimeInformation", ")", ")", ";", "return", "result", ";", "}" ]
Builds a file definition from a collection of instances. @param rootInstances the root instances (not null) @param targetFile the target file (will not be written) @param addComment true to insert generated comments @param saveRuntimeInformation true to save runtime information (such as IP...), false otherwise @return a non-null file definition
[ "Builds", "a", "file", "definition", "from", "a", "collection", "of", "instances", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/dsl/converters/FromInstances.java#L60-L75
DataArt/CalculationEngine
calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DependencyExtractors.java
DependencyExtractors.toDataModel
static IDataModel toDataModel(final Workbook book, final ICellAddress address) { """ Extracts {@link IDataModel} from {@link Workbook} at given {@link ICellAddress}. Useful for formula. If given {@link ICellAddress} contains formula it can be parsed. Based on this parsed information a new {@link IDataModel} might be created. """ if (book == null || address == null) { return null; } if (address instanceof A1RangeAddress) { throw new CalculationEngineException("A1RangeAddress is not supported, only one cell can be converted to DataModel."); } Sheet s = book.getSheetAt(0); /* TODO: only one sheet is supported */ Row r = s.getRow(address.a1Address().row()); if (r == null) { return null; } Cell c = r.getCell(address.a1Address().column()); if (c == null || CELL_TYPE_FORMULA != c.getCellType()) { return null; } return createDataModelFromCell(s, create((XSSFWorkbook) book), fromRowColumn(c.getRowIndex(), c.getColumnIndex())); }
java
static IDataModel toDataModel(final Workbook book, final ICellAddress address) { if (book == null || address == null) { return null; } if (address instanceof A1RangeAddress) { throw new CalculationEngineException("A1RangeAddress is not supported, only one cell can be converted to DataModel."); } Sheet s = book.getSheetAt(0); /* TODO: only one sheet is supported */ Row r = s.getRow(address.a1Address().row()); if (r == null) { return null; } Cell c = r.getCell(address.a1Address().column()); if (c == null || CELL_TYPE_FORMULA != c.getCellType()) { return null; } return createDataModelFromCell(s, create((XSSFWorkbook) book), fromRowColumn(c.getRowIndex(), c.getColumnIndex())); }
[ "static", "IDataModel", "toDataModel", "(", "final", "Workbook", "book", ",", "final", "ICellAddress", "address", ")", "{", "if", "(", "book", "==", "null", "||", "address", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "address", "instanceof", "A1RangeAddress", ")", "{", "throw", "new", "CalculationEngineException", "(", "\"A1RangeAddress is not supported, only one cell can be converted to DataModel.\"", ")", ";", "}", "Sheet", "s", "=", "book", ".", "getSheetAt", "(", "0", ")", ";", "/* TODO: only one sheet is supported */", "Row", "r", "=", "s", ".", "getRow", "(", "address", ".", "a1Address", "(", ")", ".", "row", "(", ")", ")", ";", "if", "(", "r", "==", "null", ")", "{", "return", "null", ";", "}", "Cell", "c", "=", "r", ".", "getCell", "(", "address", ".", "a1Address", "(", ")", ".", "column", "(", ")", ")", ";", "if", "(", "c", "==", "null", "||", "CELL_TYPE_FORMULA", "!=", "c", ".", "getCellType", "(", ")", ")", "{", "return", "null", ";", "}", "return", "createDataModelFromCell", "(", "s", ",", "create", "(", "(", "XSSFWorkbook", ")", "book", ")", ",", "fromRowColumn", "(", "c", ".", "getRowIndex", "(", ")", ",", "c", ".", "getColumnIndex", "(", ")", ")", ")", ";", "}" ]
Extracts {@link IDataModel} from {@link Workbook} at given {@link ICellAddress}. Useful for formula. If given {@link ICellAddress} contains formula it can be parsed. Based on this parsed information a new {@link IDataModel} might be created.
[ "Extracts", "{" ]
train
https://github.com/DataArt/CalculationEngine/blob/34ce1d9c1f9b57a502906b274311d28580b134e5/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DependencyExtractors.java#L76-L87
OpenLiberty/open-liberty
dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/webapp/UIComponentTag.java
UIComponentTag.createComponent
@Override protected UIComponent createComponent(FacesContext context, String id) { """ Create a UIComponent. Abstract method getComponentType is invoked to determine the actual type name for the component to be created. If this tag has a "binding" attribute, then that is immediately evaluated to store the created component in the specified property. """ String componentType = getComponentType(); if (componentType == null) { throw new NullPointerException("componentType"); } if (_binding != null) { Application application = context.getApplication(); ValueBinding componentBinding = application.createValueBinding(_binding); UIComponent component = application.createComponent(componentBinding, context, componentType); component.setId(id); component.setValueBinding("binding", componentBinding); setProperties(component); return component; } UIComponent component = context.getApplication().createComponent(componentType); component.setId(id); setProperties(component); return component; }
java
@Override protected UIComponent createComponent(FacesContext context, String id) { String componentType = getComponentType(); if (componentType == null) { throw new NullPointerException("componentType"); } if (_binding != null) { Application application = context.getApplication(); ValueBinding componentBinding = application.createValueBinding(_binding); UIComponent component = application.createComponent(componentBinding, context, componentType); component.setId(id); component.setValueBinding("binding", componentBinding); setProperties(component); return component; } UIComponent component = context.getApplication().createComponent(componentType); component.setId(id); setProperties(component); return component; }
[ "@", "Override", "protected", "UIComponent", "createComponent", "(", "FacesContext", "context", ",", "String", "id", ")", "{", "String", "componentType", "=", "getComponentType", "(", ")", ";", "if", "(", "componentType", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"componentType\"", ")", ";", "}", "if", "(", "_binding", "!=", "null", ")", "{", "Application", "application", "=", "context", ".", "getApplication", "(", ")", ";", "ValueBinding", "componentBinding", "=", "application", ".", "createValueBinding", "(", "_binding", ")", ";", "UIComponent", "component", "=", "application", ".", "createComponent", "(", "componentBinding", ",", "context", ",", "componentType", ")", ";", "component", ".", "setId", "(", "id", ")", ";", "component", ".", "setValueBinding", "(", "\"binding\"", ",", "componentBinding", ")", ";", "setProperties", "(", "component", ")", ";", "return", "component", ";", "}", "UIComponent", "component", "=", "context", ".", "getApplication", "(", ")", ".", "createComponent", "(", "componentType", ")", ";", "component", ".", "setId", "(", "id", ")", ";", "setProperties", "(", "component", ")", ";", "return", "component", ";", "}" ]
Create a UIComponent. Abstract method getComponentType is invoked to determine the actual type name for the component to be created. If this tag has a "binding" attribute, then that is immediately evaluated to store the created component in the specified property.
[ "Create", "a", "UIComponent", ".", "Abstract", "method", "getComponentType", "is", "invoked", "to", "determine", "the", "actual", "type", "name", "for", "the", "component", "to", "be", "created", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/webapp/UIComponentTag.java#L126-L154
couchbaselabs/couchbase-lite-java-forestdb
src/main/java/com/couchbase/lite/store/ForestDBViewStore.java
ForestDBViewStore.openIndex
private View openIndex(int flags, boolean dryRun) throws ForestException { """ Opens the index, specifying ForestDB database flags in CBLView.m - (MapReduceIndex*) openIndexWithOptions: (Database::openFlags)options """ if (_view == null) { // Flags: if (_dbStore.getAutoCompact()) flags |= Database.AutoCompact; // Encryption: SymmetricKey encryptionKey = _dbStore.getEncryptionKey(); int enAlgorithm = Database.NoEncryption; byte[] enKey = null; if (encryptionKey != null) { enAlgorithm = Database.AES256Encryption; enKey = encryptionKey.getKey(); } _view = new View(_dbStore.forest, _path, flags, enAlgorithm, enKey, name, dryRun ? "0" : delegate.getMapVersion()); if (dryRun) { closeIndex(); } } return _view; }
java
private View openIndex(int flags, boolean dryRun) throws ForestException { if (_view == null) { // Flags: if (_dbStore.getAutoCompact()) flags |= Database.AutoCompact; // Encryption: SymmetricKey encryptionKey = _dbStore.getEncryptionKey(); int enAlgorithm = Database.NoEncryption; byte[] enKey = null; if (encryptionKey != null) { enAlgorithm = Database.AES256Encryption; enKey = encryptionKey.getKey(); } _view = new View(_dbStore.forest, _path, flags, enAlgorithm, enKey, name, dryRun ? "0" : delegate.getMapVersion()); if (dryRun) { closeIndex(); } } return _view; }
[ "private", "View", "openIndex", "(", "int", "flags", ",", "boolean", "dryRun", ")", "throws", "ForestException", "{", "if", "(", "_view", "==", "null", ")", "{", "// Flags:", "if", "(", "_dbStore", ".", "getAutoCompact", "(", ")", ")", "flags", "|=", "Database", ".", "AutoCompact", ";", "// Encryption:", "SymmetricKey", "encryptionKey", "=", "_dbStore", ".", "getEncryptionKey", "(", ")", ";", "int", "enAlgorithm", "=", "Database", ".", "NoEncryption", ";", "byte", "[", "]", "enKey", "=", "null", ";", "if", "(", "encryptionKey", "!=", "null", ")", "{", "enAlgorithm", "=", "Database", ".", "AES256Encryption", ";", "enKey", "=", "encryptionKey", ".", "getKey", "(", ")", ";", "}", "_view", "=", "new", "View", "(", "_dbStore", ".", "forest", ",", "_path", ",", "flags", ",", "enAlgorithm", ",", "enKey", ",", "name", ",", "dryRun", "?", "\"0\"", ":", "delegate", ".", "getMapVersion", "(", ")", ")", ";", "if", "(", "dryRun", ")", "{", "closeIndex", "(", ")", ";", "}", "}", "return", "_view", ";", "}" ]
Opens the index, specifying ForestDB database flags in CBLView.m - (MapReduceIndex*) openIndexWithOptions: (Database::openFlags)options
[ "Opens", "the", "index", "specifying", "ForestDB", "database", "flags", "in", "CBLView", ".", "m", "-", "(", "MapReduceIndex", "*", ")", "openIndexWithOptions", ":", "(", "Database", "::", "openFlags", ")", "options" ]
train
https://github.com/couchbaselabs/couchbase-lite-java-forestdb/blob/fd806b251dd7dcc7a76ab7a8db618e30c3419f06/src/main/java/com/couchbase/lite/store/ForestDBViewStore.java#L583-L605
yavijava/yavijava
src/main/java/com/vmware/vim25/mo/IoFilterManager.java
IoFilterManager.resolveInstallationErrorsOnHost_Task
public Task resolveInstallationErrorsOnHost_Task(String filterId, HostSystem host) throws NotFound, RuntimeFault, RemoteException { """ Resolve the errors occured during an installation/uninstallation/upgrade operation of an IO Filter on a host. Depending on the nature of the installation failure, vCenter will take the appropriate actions to resolve it. For example, retry or resume installation. @param filterId - ID of the filter. @param host - The host to fix the issues on. @return - This method returns a Task object with which to monitor the operation. The task is set to success if all the errors related to the filter are resolved on the cluster. If the task fails, first check error to see the error. If the error indicates that issues persist on the cluster, use QueryIoFilterIssues to get the detailed errors on the hosts in the cluster. The dynamic privilege check will ensure that the appropriate privileges must be acquired for all the hosts in the cluster based on the remediation actions. For example, Host.Config.Maintenance privilege and Host.Config.Patch privileges must be required for upgrading a VIB. @throws RuntimeFault - Thrown if any type of runtime fault is thrown that is not covered by the other faults; for example, a communication error. @throws NotFound @throws RemoteException """ return new Task(getServerConnection(), getVimService().resolveInstallationErrorsOnHost_Task(getMOR(), filterId, host.getMOR())); }
java
public Task resolveInstallationErrorsOnHost_Task(String filterId, HostSystem host) throws NotFound, RuntimeFault, RemoteException { return new Task(getServerConnection(), getVimService().resolveInstallationErrorsOnHost_Task(getMOR(), filterId, host.getMOR())); }
[ "public", "Task", "resolveInstallationErrorsOnHost_Task", "(", "String", "filterId", ",", "HostSystem", "host", ")", "throws", "NotFound", ",", "RuntimeFault", ",", "RemoteException", "{", "return", "new", "Task", "(", "getServerConnection", "(", ")", ",", "getVimService", "(", ")", ".", "resolveInstallationErrorsOnHost_Task", "(", "getMOR", "(", ")", ",", "filterId", ",", "host", ".", "getMOR", "(", ")", ")", ")", ";", "}" ]
Resolve the errors occured during an installation/uninstallation/upgrade operation of an IO Filter on a host. Depending on the nature of the installation failure, vCenter will take the appropriate actions to resolve it. For example, retry or resume installation. @param filterId - ID of the filter. @param host - The host to fix the issues on. @return - This method returns a Task object with which to monitor the operation. The task is set to success if all the errors related to the filter are resolved on the cluster. If the task fails, first check error to see the error. If the error indicates that issues persist on the cluster, use QueryIoFilterIssues to get the detailed errors on the hosts in the cluster. The dynamic privilege check will ensure that the appropriate privileges must be acquired for all the hosts in the cluster based on the remediation actions. For example, Host.Config.Maintenance privilege and Host.Config.Patch privileges must be required for upgrading a VIB. @throws RuntimeFault - Thrown if any type of runtime fault is thrown that is not covered by the other faults; for example, a communication error. @throws NotFound @throws RemoteException
[ "Resolve", "the", "errors", "occured", "during", "an", "installation", "/", "uninstallation", "/", "upgrade", "operation", "of", "an", "IO", "Filter", "on", "a", "host", ".", "Depending", "on", "the", "nature", "of", "the", "installation", "failure", "vCenter", "will", "take", "the", "appropriate", "actions", "to", "resolve", "it", ".", "For", "example", "retry", "or", "resume", "installation", "." ]
train
https://github.com/yavijava/yavijava/blob/27fd2c5826115782d5eeb934f86e3e39240179cd/src/main/java/com/vmware/vim25/mo/IoFilterManager.java#L177-L179
jparsec/jparsec
jparsec/src/main/java/org/jparsec/Scanners.java
Scanners.nestableBlockComment
public static Parser<Void> nestableBlockComment(String begin, String end) { """ A scanner for a nestable block comment that starts with {@code begin} and ends with {@code end}. @param begin begins a block comment @param end ends a block comment @return the block comment scanner. """ return nestableBlockComment(begin, end, Patterns.isChar(CharPredicates.ALWAYS)); }
java
public static Parser<Void> nestableBlockComment(String begin, String end) { return nestableBlockComment(begin, end, Patterns.isChar(CharPredicates.ALWAYS)); }
[ "public", "static", "Parser", "<", "Void", ">", "nestableBlockComment", "(", "String", "begin", ",", "String", "end", ")", "{", "return", "nestableBlockComment", "(", "begin", ",", "end", ",", "Patterns", ".", "isChar", "(", "CharPredicates", ".", "ALWAYS", ")", ")", ";", "}" ]
A scanner for a nestable block comment that starts with {@code begin} and ends with {@code end}. @param begin begins a block comment @param end ends a block comment @return the block comment scanner.
[ "A", "scanner", "for", "a", "nestable", "block", "comment", "that", "starts", "with", "{", "@code", "begin", "}", "and", "ends", "with", "{", "@code", "end", "}", "." ]
train
https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/Scanners.java#L472-L474
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.newCloseShieldZipInputStream
private static ZipInputStream newCloseShieldZipInputStream(final InputStream is, Charset charset) { """ Creates a new {@link ZipInputStream} based on the given {@link InputStream}. It will be buffered and close-shielded. Closing the result stream flushes the buffers and frees up resources of the {@link ZipInputStream}. However the source stream itself remains open. """ InputStream in = new BufferedInputStream(new CloseShieldInputStream(is)); if (charset == null) { return new ZipInputStream(in); } return ZipFileUtil.createZipInputStream(in, charset); }
java
private static ZipInputStream newCloseShieldZipInputStream(final InputStream is, Charset charset) { InputStream in = new BufferedInputStream(new CloseShieldInputStream(is)); if (charset == null) { return new ZipInputStream(in); } return ZipFileUtil.createZipInputStream(in, charset); }
[ "private", "static", "ZipInputStream", "newCloseShieldZipInputStream", "(", "final", "InputStream", "is", ",", "Charset", "charset", ")", "{", "InputStream", "in", "=", "new", "BufferedInputStream", "(", "new", "CloseShieldInputStream", "(", "is", ")", ")", ";", "if", "(", "charset", "==", "null", ")", "{", "return", "new", "ZipInputStream", "(", "in", ")", ";", "}", "return", "ZipFileUtil", ".", "createZipInputStream", "(", "in", ",", "charset", ")", ";", "}" ]
Creates a new {@link ZipInputStream} based on the given {@link InputStream}. It will be buffered and close-shielded. Closing the result stream flushes the buffers and frees up resources of the {@link ZipInputStream}. However the source stream itself remains open.
[ "Creates", "a", "new", "{" ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L825-L831
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/microdom/AbstractMicroNode.java
AbstractMicroNode.onInsertAfter
@OverrideOnDemand protected void onInsertAfter (@Nonnull final AbstractMicroNode aChildNode, @Nonnull final IMicroNode aPredecessor) { """ Callback that is invoked once a child is to be inserted after another child. @param aChildNode The new child node to be inserted. @param aPredecessor The node after which the new node will be inserted. """ throw new MicroException ("Cannot insert children in class " + getClass ().getName ()); }
java
@OverrideOnDemand protected void onInsertAfter (@Nonnull final AbstractMicroNode aChildNode, @Nonnull final IMicroNode aPredecessor) { throw new MicroException ("Cannot insert children in class " + getClass ().getName ()); }
[ "@", "OverrideOnDemand", "protected", "void", "onInsertAfter", "(", "@", "Nonnull", "final", "AbstractMicroNode", "aChildNode", ",", "@", "Nonnull", "final", "IMicroNode", "aPredecessor", ")", "{", "throw", "new", "MicroException", "(", "\"Cannot insert children in class \"", "+", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}" ]
Callback that is invoked once a child is to be inserted after another child. @param aChildNode The new child node to be inserted. @param aPredecessor The node after which the new node will be inserted.
[ "Callback", "that", "is", "invoked", "once", "a", "child", "is", "to", "be", "inserted", "after", "another", "child", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/microdom/AbstractMicroNode.java#L89-L93
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/service/nitro_service.java
nitro_service.clear_config
public base_response clear_config(Boolean force, String level) throws Exception { """ Use this API to clear configuration on netscaler. @param force clear confirmation without prompting. @param level clear config according to the level. eg: basic, extended, full @return status of the operation performed. @throws Exception Nitro exception is thrown. """ base_response result = null; nsconfig resource = new nsconfig(); if (force) resource.set_force(force); resource.set_level(level); options option = new options(); option.set_action("clear"); result = resource.perform_operation(this, option); return result; }
java
public base_response clear_config(Boolean force, String level) throws Exception { base_response result = null; nsconfig resource = new nsconfig(); if (force) resource.set_force(force); resource.set_level(level); options option = new options(); option.set_action("clear"); result = resource.perform_operation(this, option); return result; }
[ "public", "base_response", "clear_config", "(", "Boolean", "force", ",", "String", "level", ")", "throws", "Exception", "{", "base_response", "result", "=", "null", ";", "nsconfig", "resource", "=", "new", "nsconfig", "(", ")", ";", "if", "(", "force", ")", "resource", ".", "set_force", "(", "force", ")", ";", "resource", ".", "set_level", "(", "level", ")", ";", "options", "option", "=", "new", "options", "(", ")", ";", "option", ".", "set_action", "(", "\"clear\"", ")", ";", "result", "=", "resource", ".", "perform_operation", "(", "this", ",", "option", ")", ";", "return", "result", ";", "}" ]
Use this API to clear configuration on netscaler. @param force clear confirmation without prompting. @param level clear config according to the level. eg: basic, extended, full @return status of the operation performed. @throws Exception Nitro exception is thrown.
[ "Use", "this", "API", "to", "clear", "configuration", "on", "netscaler", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/service/nitro_service.java#L369-L381
JOML-CI/JOML
src/org/joml/Matrix3x2f.java
Matrix3x2f.scaleAroundLocal
public Matrix3x2f scaleAroundLocal(float sx, float sy, float ox, float oy, Matrix3x2f dest) { """ /* (non-Javadoc) @see org.joml.Matrix3x2fc#scaleAroundLocal(float, float, float, float, float, float, org.joml.Matrix3x2f) """ dest.m00 = sx * m00; dest.m01 = sy * m01; dest.m10 = sx * m10; dest.m11 = sy * m11; dest.m20 = sx * m20 - sx * ox + ox; dest.m21 = sy * m21 - sy * oy + oy; return dest; }
java
public Matrix3x2f scaleAroundLocal(float sx, float sy, float ox, float oy, Matrix3x2f dest) { dest.m00 = sx * m00; dest.m01 = sy * m01; dest.m10 = sx * m10; dest.m11 = sy * m11; dest.m20 = sx * m20 - sx * ox + ox; dest.m21 = sy * m21 - sy * oy + oy; return dest; }
[ "public", "Matrix3x2f", "scaleAroundLocal", "(", "float", "sx", ",", "float", "sy", ",", "float", "ox", ",", "float", "oy", ",", "Matrix3x2f", "dest", ")", "{", "dest", ".", "m00", "=", "sx", "*", "m00", ";", "dest", ".", "m01", "=", "sy", "*", "m01", ";", "dest", ".", "m10", "=", "sx", "*", "m10", ";", "dest", ".", "m11", "=", "sy", "*", "m11", ";", "dest", ".", "m20", "=", "sx", "*", "m20", "-", "sx", "*", "ox", "+", "ox", ";", "dest", ".", "m21", "=", "sy", "*", "m21", "-", "sy", "*", "oy", "+", "oy", ";", "return", "dest", ";", "}" ]
/* (non-Javadoc) @see org.joml.Matrix3x2fc#scaleAroundLocal(float, float, float, float, float, float, org.joml.Matrix3x2f)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2f.java#L1487-L1495
VoltDB/voltdb
src/frontend/org/voltdb/client/HashinatorLite.java
HashinatorLite.getHashedPartitionForParameter
public int getHashedPartitionForParameter(int partitionParameterType, Object partitionValue) throws VoltTypeException { """ Given the type of the targeting partition parameter and an object, coerce the object to the correct type and hash it. NOTE NOTE NOTE NOTE! THIS SHOULD BE THE ONLY WAY THAT YOU FIGURE OUT THE PARTITIONING FOR A PARAMETER! THIS IS SHARED BY SERVER AND CLIENT CLIENT USES direct instance method as it initializes its own per connection Hashinator. @return The partition best set up to execute the procedure. @throws VoltTypeException """ final VoltType partitionParamType = VoltType.get((byte) partitionParameterType); // Special cases: // 1) if the user supplied a string for a number column, // try to do the conversion. This makes it substantially easier to // load CSV data or other untyped inputs that match DDL without // requiring the loader to know precise the schema. // 2) For legacy hashinators, if we have a numeric column but the param is in a byte // array, convert the byte array back to the numeric value if (partitionValue != null && partitionParamType.isAnyIntegerType()) { if (partitionValue.getClass() == String.class) { try { partitionValue = Long.parseLong((String) partitionValue); } catch (NumberFormatException nfe) { throw new VoltTypeException( "getHashedPartitionForParameter: Unable to convert string " + ((String) partitionValue) + " to " + partitionParamType.getMostCompatibleJavaTypeName() + " target parameter "); } } else if (partitionValue.getClass() == byte[].class) { partitionValue = partitionParamType.bytesToValue((byte[]) partitionValue); } } return hashToPartition(partitionParamType, partitionValue); }
java
public int getHashedPartitionForParameter(int partitionParameterType, Object partitionValue) throws VoltTypeException { final VoltType partitionParamType = VoltType.get((byte) partitionParameterType); // Special cases: // 1) if the user supplied a string for a number column, // try to do the conversion. This makes it substantially easier to // load CSV data or other untyped inputs that match DDL without // requiring the loader to know precise the schema. // 2) For legacy hashinators, if we have a numeric column but the param is in a byte // array, convert the byte array back to the numeric value if (partitionValue != null && partitionParamType.isAnyIntegerType()) { if (partitionValue.getClass() == String.class) { try { partitionValue = Long.parseLong((String) partitionValue); } catch (NumberFormatException nfe) { throw new VoltTypeException( "getHashedPartitionForParameter: Unable to convert string " + ((String) partitionValue) + " to " + partitionParamType.getMostCompatibleJavaTypeName() + " target parameter "); } } else if (partitionValue.getClass() == byte[].class) { partitionValue = partitionParamType.bytesToValue((byte[]) partitionValue); } } return hashToPartition(partitionParamType, partitionValue); }
[ "public", "int", "getHashedPartitionForParameter", "(", "int", "partitionParameterType", ",", "Object", "partitionValue", ")", "throws", "VoltTypeException", "{", "final", "VoltType", "partitionParamType", "=", "VoltType", ".", "get", "(", "(", "byte", ")", "partitionParameterType", ")", ";", "// Special cases:", "// 1) if the user supplied a string for a number column,", "// try to do the conversion. This makes it substantially easier to", "// load CSV data or other untyped inputs that match DDL without", "// requiring the loader to know precise the schema.", "// 2) For legacy hashinators, if we have a numeric column but the param is in a byte", "// array, convert the byte array back to the numeric value", "if", "(", "partitionValue", "!=", "null", "&&", "partitionParamType", ".", "isAnyIntegerType", "(", ")", ")", "{", "if", "(", "partitionValue", ".", "getClass", "(", ")", "==", "String", ".", "class", ")", "{", "try", "{", "partitionValue", "=", "Long", ".", "parseLong", "(", "(", "String", ")", "partitionValue", ")", ";", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "throw", "new", "VoltTypeException", "(", "\"getHashedPartitionForParameter: Unable to convert string \"", "+", "(", "(", "String", ")", "partitionValue", ")", "+", "\" to \"", "+", "partitionParamType", ".", "getMostCompatibleJavaTypeName", "(", ")", "+", "\" target parameter \"", ")", ";", "}", "}", "else", "if", "(", "partitionValue", ".", "getClass", "(", ")", "==", "byte", "[", "]", ".", "class", ")", "{", "partitionValue", "=", "partitionParamType", ".", "bytesToValue", "(", "(", "byte", "[", "]", ")", "partitionValue", ")", ";", "}", "}", "return", "hashToPartition", "(", "partitionParamType", ",", "partitionValue", ")", ";", "}" ]
Given the type of the targeting partition parameter and an object, coerce the object to the correct type and hash it. NOTE NOTE NOTE NOTE! THIS SHOULD BE THE ONLY WAY THAT YOU FIGURE OUT THE PARTITIONING FOR A PARAMETER! THIS IS SHARED BY SERVER AND CLIENT CLIENT USES direct instance method as it initializes its own per connection Hashinator. @return The partition best set up to execute the procedure. @throws VoltTypeException
[ "Given", "the", "type", "of", "the", "targeting", "partition", "parameter", "and", "an", "object", "coerce", "the", "object", "to", "the", "correct", "type", "and", "hash", "it", ".", "NOTE", "NOTE", "NOTE", "NOTE!", "THIS", "SHOULD", "BE", "THE", "ONLY", "WAY", "THAT", "YOU", "FIGURE", "OUT", "THE", "PARTITIONING", "FOR", "A", "PARAMETER!", "THIS", "IS", "SHARED", "BY", "SERVER", "AND", "CLIENT", "CLIENT", "USES", "direct", "instance", "method", "as", "it", "initializes", "its", "own", "per", "connection", "Hashinator", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/HashinatorLite.java#L241-L271
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java
BigDecimal.movePointLeft
public BigDecimal movePointLeft(int n) { """ Returns a {@code BigDecimal} which is equivalent to this one with the decimal point moved {@code n} places to the left. If {@code n} is non-negative, the call merely adds {@code n} to the scale. If {@code n} is negative, the call is equivalent to {@code movePointRight(-n)}. The {@code BigDecimal} returned by this call has value <tt>(this &times; 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n, 0)}. @param n number of places to move the decimal point to the left. @return a {@code BigDecimal} which is equivalent to this one with the decimal point moved {@code n} places to the left. @throws ArithmeticException if scale overflows. """ // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE int newScale = checkScale((long)scale + n); BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; }
java
public BigDecimal movePointLeft(int n) { // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE int newScale = checkScale((long)scale + n); BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; }
[ "public", "BigDecimal", "movePointLeft", "(", "int", "n", ")", "{", "// Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE", "int", "newScale", "=", "checkScale", "(", "(", "long", ")", "scale", "+", "n", ")", ";", "BigDecimal", "num", "=", "new", "BigDecimal", "(", "intVal", ",", "intCompact", ",", "newScale", ",", "0", ")", ";", "return", "num", ".", "scale", "<", "0", "?", "num", ".", "setScale", "(", "0", ",", "ROUND_UNNECESSARY", ")", ":", "num", ";", "}" ]
Returns a {@code BigDecimal} which is equivalent to this one with the decimal point moved {@code n} places to the left. If {@code n} is non-negative, the call merely adds {@code n} to the scale. If {@code n} is negative, the call is equivalent to {@code movePointRight(-n)}. The {@code BigDecimal} returned by this call has value <tt>(this &times; 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n, 0)}. @param n number of places to move the decimal point to the left. @return a {@code BigDecimal} which is equivalent to this one with the decimal point moved {@code n} places to the left. @throws ArithmeticException if scale overflows.
[ "Returns", "a", "{", "@code", "BigDecimal", "}", "which", "is", "equivalent", "to", "this", "one", "with", "the", "decimal", "point", "moved", "{", "@code", "n", "}", "places", "to", "the", "left", ".", "If", "{", "@code", "n", "}", "is", "non", "-", "negative", "the", "call", "merely", "adds", "{", "@code", "n", "}", "to", "the", "scale", ".", "If", "{", "@code", "n", "}", "is", "negative", "the", "call", "is", "equivalent", "to", "{", "@code", "movePointRight", "(", "-", "n", ")", "}", ".", "The", "{", "@code", "BigDecimal", "}", "returned", "by", "this", "call", "has", "value", "<tt", ">", "(", "this", "&times", ";", "10<sup", ">", "-", "n<", "/", "sup", ">", ")", "<", "/", "tt", ">", "and", "scale", "{", "@code", "max", "(", "this", ".", "scale", "()", "+", "n", "0", ")", "}", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L2534-L2539
jamesagnew/hapi-fhir
hapi-fhir-base/src/main/java/ca/uhn/fhir/util/DateUtils.java
DateUtils.parseDate
public static Date parseDate(final String dateValue, final String[] dateFormats) { """ Parses the date value using the given date formats. @param dateValue the date value to parse @param dateFormats the date formats to use @return the parsed date or null if input could not be parsed """ return parseDate(dateValue, dateFormats, null); }
java
public static Date parseDate(final String dateValue, final String[] dateFormats) { return parseDate(dateValue, dateFormats, null); }
[ "public", "static", "Date", "parseDate", "(", "final", "String", "dateValue", ",", "final", "String", "[", "]", "dateFormats", ")", "{", "return", "parseDate", "(", "dateValue", ",", "dateFormats", ",", "null", ")", ";", "}" ]
Parses the date value using the given date formats. @param dateValue the date value to parse @param dateFormats the date formats to use @return the parsed date or null if input could not be parsed
[ "Parses", "the", "date", "value", "using", "the", "given", "date", "formats", "." ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/DateUtils.java#L121-L123
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Index.java
Index.updateApiKey
public JSONObject updateApiKey(String key, JSONObject params) throws AlgoliaException { """ Update a new api key @param params the list of parameters for this key. Defined by a JSONObject that can contains the following values: - acl: array of string - indices: array of string - validity: int - referers: array of string - description: string - maxHitsPerQuery: integer - queryParameters: string - maxQueriesPerIPPerHour: integer """ return this.updateApiKey(key, params, RequestOptions.empty); }
java
public JSONObject updateApiKey(String key, JSONObject params) throws AlgoliaException { return this.updateApiKey(key, params, RequestOptions.empty); }
[ "public", "JSONObject", "updateApiKey", "(", "String", "key", ",", "JSONObject", "params", ")", "throws", "AlgoliaException", "{", "return", "this", ".", "updateApiKey", "(", "key", ",", "params", ",", "RequestOptions", ".", "empty", ")", ";", "}" ]
Update a new api key @param params the list of parameters for this key. Defined by a JSONObject that can contains the following values: - acl: array of string - indices: array of string - validity: int - referers: array of string - description: string - maxHitsPerQuery: integer - queryParameters: string - maxQueriesPerIPPerHour: integer
[ "Update", "a", "new", "api", "key" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1116-L1118
headius/invokebinder
src/main/java/com/headius/invokebinder/transform/Transform.java
Transform.buildClass
private static void buildClass(StringBuilder builder, Class cls) { """ Build Java code to represent a type reference to the given class. This will be of the form "pkg.Cls1" or "pkc.Cls2[]" or "primtype". @param builder the builder in which to build the type reference @param cls the type for the reference """ int arrayDims = 0; Class tmp = cls; while (tmp.isArray()) { arrayDims++; tmp = tmp.getComponentType(); } builder.append(tmp.getName()); if (arrayDims > 0) { for (; arrayDims > 0 ; arrayDims--) { builder.append("[]"); } } }
java
private static void buildClass(StringBuilder builder, Class cls) { int arrayDims = 0; Class tmp = cls; while (tmp.isArray()) { arrayDims++; tmp = tmp.getComponentType(); } builder.append(tmp.getName()); if (arrayDims > 0) { for (; arrayDims > 0 ; arrayDims--) { builder.append("[]"); } } }
[ "private", "static", "void", "buildClass", "(", "StringBuilder", "builder", ",", "Class", "cls", ")", "{", "int", "arrayDims", "=", "0", ";", "Class", "tmp", "=", "cls", ";", "while", "(", "tmp", ".", "isArray", "(", ")", ")", "{", "arrayDims", "++", ";", "tmp", "=", "tmp", ".", "getComponentType", "(", ")", ";", "}", "builder", ".", "append", "(", "tmp", ".", "getName", "(", ")", ")", ";", "if", "(", "arrayDims", ">", "0", ")", "{", "for", "(", ";", "arrayDims", ">", "0", ";", "arrayDims", "--", ")", "{", "builder", ".", "append", "(", "\"[]\"", ")", ";", "}", "}", "}" ]
Build Java code to represent a type reference to the given class. This will be of the form "pkg.Cls1" or "pkc.Cls2[]" or "primtype". @param builder the builder in which to build the type reference @param cls the type for the reference
[ "Build", "Java", "code", "to", "represent", "a", "type", "reference", "to", "the", "given", "class", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/transform/Transform.java#L123-L136
opencypher/openCypher
tools/grammar/src/main/java/org/opencypher/grammar/Description.java
Description.findStart
private static int findStart( char[] buffer, int start, int end ) { """ Find the beginning of the first line that isn't all whitespace. """ int pos, cp; for ( pos = start; pos < end && isWhitespace( cp = codePointAt( buffer, pos ) ); pos += charCount( cp ) ) { if ( cp == '\n' ) { start = pos + 1; } } return pos >= end ? end : start; }
java
private static int findStart( char[] buffer, int start, int end ) { int pos, cp; for ( pos = start; pos < end && isWhitespace( cp = codePointAt( buffer, pos ) ); pos += charCount( cp ) ) { if ( cp == '\n' ) { start = pos + 1; } } return pos >= end ? end : start; }
[ "private", "static", "int", "findStart", "(", "char", "[", "]", "buffer", ",", "int", "start", ",", "int", "end", ")", "{", "int", "pos", ",", "cp", ";", "for", "(", "pos", "=", "start", ";", "pos", "<", "end", "&&", "isWhitespace", "(", "cp", "=", "codePointAt", "(", "buffer", ",", "pos", ")", ")", ";", "pos", "+=", "charCount", "(", "cp", ")", ")", "{", "if", "(", "cp", "==", "'", "'", ")", "{", "start", "=", "pos", "+", "1", ";", "}", "}", "return", "pos", ">=", "end", "?", "end", ":", "start", ";", "}" ]
Find the beginning of the first line that isn't all whitespace.
[ "Find", "the", "beginning", "of", "the", "first", "line", "that", "isn", "t", "all", "whitespace", "." ]
train
https://github.com/opencypher/openCypher/blob/eb780caea625900ddbedd28a1eac9a5dbe09c5f0/tools/grammar/src/main/java/org/opencypher/grammar/Description.java#L210-L221
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSetDTM.java
NodeSetDTM.addNode
public void addNode(int n) { """ Add a node to the NodeSetDTM. Not all types of NodeSetDTMs support this operation @param n Node to be added @throws RuntimeException thrown if this NodeSetDTM is not of a mutable type. """ if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE, null)); //"This NodeSetDTM is not mutable!"); this.addElement(n); }
java
public void addNode(int n) { if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE, null)); //"This NodeSetDTM is not mutable!"); this.addElement(n); }
[ "public", "void", "addNode", "(", "int", "n", ")", "{", "if", "(", "!", "m_mutable", ")", "throw", "new", "RuntimeException", "(", "XSLMessages", ".", "createXPATHMessage", "(", "XPATHErrorResources", ".", "ER_NODESETDTM_NOT_MUTABLE", ",", "null", ")", ")", ";", "//\"This NodeSetDTM is not mutable!\");", "this", ".", "addElement", "(", "n", ")", ";", "}" ]
Add a node to the NodeSetDTM. Not all types of NodeSetDTMs support this operation @param n Node to be added @throws RuntimeException thrown if this NodeSetDTM is not of a mutable type.
[ "Add", "a", "node", "to", "the", "NodeSetDTM", ".", "Not", "all", "types", "of", "NodeSetDTMs", "support", "this", "operation" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSetDTM.java#L535-L542
geomajas/geomajas-project-client-gwt2
plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java
TileBasedLayerClient.createDefaultOsmLayer
public OsmLayer createDefaultOsmLayer(String id, int nrOfLevels) { """ Create a new OSM layer with the given ID and tile configuration. The layer will be configured with the default OSM tile services so you don't have to specify these URLs yourself. @param id The unique ID of the layer. @param conf The tile configuration. @return A new OSM layer. @since 2.2.1 """ OsmLayer layer = new OsmLayer(id, createOsmTileConfiguration(nrOfLevels)); layer.addUrls(Arrays.asList(DEFAULT_OSM_URLS)); return layer; }
java
public OsmLayer createDefaultOsmLayer(String id, int nrOfLevels) { OsmLayer layer = new OsmLayer(id, createOsmTileConfiguration(nrOfLevels)); layer.addUrls(Arrays.asList(DEFAULT_OSM_URLS)); return layer; }
[ "public", "OsmLayer", "createDefaultOsmLayer", "(", "String", "id", ",", "int", "nrOfLevels", ")", "{", "OsmLayer", "layer", "=", "new", "OsmLayer", "(", "id", ",", "createOsmTileConfiguration", "(", "nrOfLevels", ")", ")", ";", "layer", ".", "addUrls", "(", "Arrays", ".", "asList", "(", "DEFAULT_OSM_URLS", ")", ")", ";", "return", "layer", ";", "}" ]
Create a new OSM layer with the given ID and tile configuration. The layer will be configured with the default OSM tile services so you don't have to specify these URLs yourself. @param id The unique ID of the layer. @param conf The tile configuration. @return A new OSM layer. @since 2.2.1
[ "Create", "a", "new", "OSM", "layer", "with", "the", "given", "ID", "and", "tile", "configuration", ".", "The", "layer", "will", "be", "configured", "with", "the", "default", "OSM", "tile", "services", "so", "you", "don", "t", "have", "to", "specify", "these", "URLs", "yourself", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java#L117-L121
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/DescribePointSift.java
DescribePointSift.computeRawDescriptor
void computeRawDescriptor(double c_x, double c_y, double sigma, double orientation, TupleDesc_F64 descriptor) { """ Computes the descriptor by sampling the input image. This is raw because the descriptor hasn't been massaged yet. """ double c = Math.cos(orientation); double s = Math.sin(orientation); float fwidthSubregion = widthSubregion; int sampleWidth = widthGrid*widthSubregion; double sampleRadius = sampleWidth/2; double sampleToPixels = sigma*sigmaToPixels; Deriv image = (Deriv)imageDerivX.getImage(); for (int sampleY = 0; sampleY < sampleWidth; sampleY++) { float subY = sampleY/fwidthSubregion; double y = sampleToPixels*(sampleY-sampleRadius); for (int sampleX = 0; sampleX < sampleWidth; sampleX++) { // coordinate of samples in terms of sub-region. Center of sample point, hence + 0.5f float subX = sampleX/fwidthSubregion; // recentered local pixel sample coordinate double x = sampleToPixels*(sampleX-sampleRadius); // pixel coordinate in the image that is to be sampled. Note the rounding // If the pixel coordinate is -1 < x < 0 then it will round to 0 instead of -1, but the rounding // method below is WAY faster than Math.round() so this is a small loss. int pixelX = (int)(x*c - y*s + c_x + 0.5); int pixelY = (int)(x*s + y*c + c_y + 0.5); // skip pixels outside of the image if( image.isInBounds(pixelX,pixelY) ) { // spacial image derivative at this point float spacialDX = imageDerivX.unsafe_getF(pixelX, pixelY); float spacialDY = imageDerivY.unsafe_getF(pixelX, pixelY); double adjDX = c*spacialDX + s*spacialDY; double adjDY = -s*spacialDX + c*spacialDY; double angle = UtilAngle.domain2PI(Math.atan2(adjDY,adjDX)); float weightGaussian = gaussianWeight[sampleY*sampleWidth+sampleX]; float weightGradient = (float)Math.sqrt(spacialDX*spacialDX + spacialDY*spacialDY); // trilinear interpolation intro descriptor trilinearInterpolation(weightGaussian*weightGradient,subX,subY,angle, descriptor); } } } }
java
void computeRawDescriptor(double c_x, double c_y, double sigma, double orientation, TupleDesc_F64 descriptor) { double c = Math.cos(orientation); double s = Math.sin(orientation); float fwidthSubregion = widthSubregion; int sampleWidth = widthGrid*widthSubregion; double sampleRadius = sampleWidth/2; double sampleToPixels = sigma*sigmaToPixels; Deriv image = (Deriv)imageDerivX.getImage(); for (int sampleY = 0; sampleY < sampleWidth; sampleY++) { float subY = sampleY/fwidthSubregion; double y = sampleToPixels*(sampleY-sampleRadius); for (int sampleX = 0; sampleX < sampleWidth; sampleX++) { // coordinate of samples in terms of sub-region. Center of sample point, hence + 0.5f float subX = sampleX/fwidthSubregion; // recentered local pixel sample coordinate double x = sampleToPixels*(sampleX-sampleRadius); // pixel coordinate in the image that is to be sampled. Note the rounding // If the pixel coordinate is -1 < x < 0 then it will round to 0 instead of -1, but the rounding // method below is WAY faster than Math.round() so this is a small loss. int pixelX = (int)(x*c - y*s + c_x + 0.5); int pixelY = (int)(x*s + y*c + c_y + 0.5); // skip pixels outside of the image if( image.isInBounds(pixelX,pixelY) ) { // spacial image derivative at this point float spacialDX = imageDerivX.unsafe_getF(pixelX, pixelY); float spacialDY = imageDerivY.unsafe_getF(pixelX, pixelY); double adjDX = c*spacialDX + s*spacialDY; double adjDY = -s*spacialDX + c*spacialDY; double angle = UtilAngle.domain2PI(Math.atan2(adjDY,adjDX)); float weightGaussian = gaussianWeight[sampleY*sampleWidth+sampleX]; float weightGradient = (float)Math.sqrt(spacialDX*spacialDX + spacialDY*spacialDY); // trilinear interpolation intro descriptor trilinearInterpolation(weightGaussian*weightGradient,subX,subY,angle, descriptor); } } } }
[ "void", "computeRawDescriptor", "(", "double", "c_x", ",", "double", "c_y", ",", "double", "sigma", ",", "double", "orientation", ",", "TupleDesc_F64", "descriptor", ")", "{", "double", "c", "=", "Math", ".", "cos", "(", "orientation", ")", ";", "double", "s", "=", "Math", ".", "sin", "(", "orientation", ")", ";", "float", "fwidthSubregion", "=", "widthSubregion", ";", "int", "sampleWidth", "=", "widthGrid", "*", "widthSubregion", ";", "double", "sampleRadius", "=", "sampleWidth", "/", "2", ";", "double", "sampleToPixels", "=", "sigma", "*", "sigmaToPixels", ";", "Deriv", "image", "=", "(", "Deriv", ")", "imageDerivX", ".", "getImage", "(", ")", ";", "for", "(", "int", "sampleY", "=", "0", ";", "sampleY", "<", "sampleWidth", ";", "sampleY", "++", ")", "{", "float", "subY", "=", "sampleY", "/", "fwidthSubregion", ";", "double", "y", "=", "sampleToPixels", "*", "(", "sampleY", "-", "sampleRadius", ")", ";", "for", "(", "int", "sampleX", "=", "0", ";", "sampleX", "<", "sampleWidth", ";", "sampleX", "++", ")", "{", "// coordinate of samples in terms of sub-region. Center of sample point, hence + 0.5f", "float", "subX", "=", "sampleX", "/", "fwidthSubregion", ";", "// recentered local pixel sample coordinate", "double", "x", "=", "sampleToPixels", "*", "(", "sampleX", "-", "sampleRadius", ")", ";", "// pixel coordinate in the image that is to be sampled. Note the rounding", "// If the pixel coordinate is -1 < x < 0 then it will round to 0 instead of -1, but the rounding", "// method below is WAY faster than Math.round() so this is a small loss.", "int", "pixelX", "=", "(", "int", ")", "(", "x", "*", "c", "-", "y", "*", "s", "+", "c_x", "+", "0.5", ")", ";", "int", "pixelY", "=", "(", "int", ")", "(", "x", "*", "s", "+", "y", "*", "c", "+", "c_y", "+", "0.5", ")", ";", "// skip pixels outside of the image", "if", "(", "image", ".", "isInBounds", "(", "pixelX", ",", "pixelY", ")", ")", "{", "// spacial image derivative at this point", "float", "spacialDX", "=", "imageDerivX", ".", "unsafe_getF", "(", "pixelX", ",", "pixelY", ")", ";", "float", "spacialDY", "=", "imageDerivY", ".", "unsafe_getF", "(", "pixelX", ",", "pixelY", ")", ";", "double", "adjDX", "=", "c", "*", "spacialDX", "+", "s", "*", "spacialDY", ";", "double", "adjDY", "=", "-", "s", "*", "spacialDX", "+", "c", "*", "spacialDY", ";", "double", "angle", "=", "UtilAngle", ".", "domain2PI", "(", "Math", ".", "atan2", "(", "adjDY", ",", "adjDX", ")", ")", ";", "float", "weightGaussian", "=", "gaussianWeight", "[", "sampleY", "*", "sampleWidth", "+", "sampleX", "]", ";", "float", "weightGradient", "=", "(", "float", ")", "Math", ".", "sqrt", "(", "spacialDX", "*", "spacialDX", "+", "spacialDY", "*", "spacialDY", ")", ";", "// trilinear interpolation intro descriptor", "trilinearInterpolation", "(", "weightGaussian", "*", "weightGradient", ",", "subX", ",", "subY", ",", "angle", ",", "descriptor", ")", ";", "}", "}", "}", "}" ]
Computes the descriptor by sampling the input image. This is raw because the descriptor hasn't been massaged yet.
[ "Computes", "the", "descriptor", "by", "sampling", "the", "input", "image", ".", "This", "is", "raw", "because", "the", "descriptor", "hasn", "t", "been", "massaged", "yet", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/describe/DescribePointSift.java#L118-L165
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/DFSClient.java
DFSClient.setQuota
void setQuota(String src, long namespaceQuota, long diskspaceQuota) throws IOException { """ Sets or resets quotas for a directory. @see org.apache.hadoop.hdfs.protocol.ClientProtocol#setQuota(String, long, long) """ // sanity check if ((namespaceQuota <= 0 && namespaceQuota != FSConstants.QUOTA_DONT_SET && namespaceQuota != FSConstants.QUOTA_RESET) || (diskspaceQuota <= 0 && diskspaceQuota != FSConstants.QUOTA_DONT_SET && diskspaceQuota != FSConstants.QUOTA_RESET)) { throw new IllegalArgumentException("Invalid values for quota : " + namespaceQuota + " and " + diskspaceQuota); } try { namenode.setQuota(src, namespaceQuota, diskspaceQuota); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } }
java
void setQuota(String src, long namespaceQuota, long diskspaceQuota) throws IOException { // sanity check if ((namespaceQuota <= 0 && namespaceQuota != FSConstants.QUOTA_DONT_SET && namespaceQuota != FSConstants.QUOTA_RESET) || (diskspaceQuota <= 0 && diskspaceQuota != FSConstants.QUOTA_DONT_SET && diskspaceQuota != FSConstants.QUOTA_RESET)) { throw new IllegalArgumentException("Invalid values for quota : " + namespaceQuota + " and " + diskspaceQuota); } try { namenode.setQuota(src, namespaceQuota, diskspaceQuota); } catch(RemoteException re) { throw re.unwrapRemoteException(AccessControlException.class, FileNotFoundException.class, NSQuotaExceededException.class, DSQuotaExceededException.class); } }
[ "void", "setQuota", "(", "String", "src", ",", "long", "namespaceQuota", ",", "long", "diskspaceQuota", ")", "throws", "IOException", "{", "// sanity check", "if", "(", "(", "namespaceQuota", "<=", "0", "&&", "namespaceQuota", "!=", "FSConstants", ".", "QUOTA_DONT_SET", "&&", "namespaceQuota", "!=", "FSConstants", ".", "QUOTA_RESET", ")", "||", "(", "diskspaceQuota", "<=", "0", "&&", "diskspaceQuota", "!=", "FSConstants", ".", "QUOTA_DONT_SET", "&&", "diskspaceQuota", "!=", "FSConstants", ".", "QUOTA_RESET", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid values for quota : \"", "+", "namespaceQuota", "+", "\" and \"", "+", "diskspaceQuota", ")", ";", "}", "try", "{", "namenode", ".", "setQuota", "(", "src", ",", "namespaceQuota", ",", "diskspaceQuota", ")", ";", "}", "catch", "(", "RemoteException", "re", ")", "{", "throw", "re", ".", "unwrapRemoteException", "(", "AccessControlException", ".", "class", ",", "FileNotFoundException", ".", "class", ",", "NSQuotaExceededException", ".", "class", ",", "DSQuotaExceededException", ".", "class", ")", ";", "}", "}" ]
Sets or resets quotas for a directory. @see org.apache.hadoop.hdfs.protocol.ClientProtocol#setQuota(String, long, long)
[ "Sets", "or", "resets", "quotas", "for", "a", "directory", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/DFSClient.java#L2525-L2546
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/FileUtils.java
FileUtils.convertPathToFile
public static File convertPathToFile(String filePath, BootstrapConfig bootProps) { """ Convert the file path string to a file. If the filePath starts with a wlp pre-defined location symbol, will translate it to an absolute file path; If the filePath is a relative path, the File returned will be relative to the server's directory (as provided by {@link com.ibm.ws.kernel.boot.BootstrapConfig#getConfigFile(String) BootstrapConfig.getSeverFile(filePath)} If an unknown location symbol is used in the filePath, an IllegalArgument Exception will be thrown. @param filePath @return @exception IllegalArgumentException if the location symbol could not be resolved """ if (filePath == null) { throw new NullPointerException(); } File resolvedFile = null; String resolvedPath = normalizeFilePath(bootProps.replaceSymbols(filePath)); resolvedFile = new File(resolvedPath); if (!resolvedFile.isAbsolute()) { resolvedFile = bootProps.getConfigFile(resolvedPath); } return resolvedFile; }
java
public static File convertPathToFile(String filePath, BootstrapConfig bootProps) { if (filePath == null) { throw new NullPointerException(); } File resolvedFile = null; String resolvedPath = normalizeFilePath(bootProps.replaceSymbols(filePath)); resolvedFile = new File(resolvedPath); if (!resolvedFile.isAbsolute()) { resolvedFile = bootProps.getConfigFile(resolvedPath); } return resolvedFile; }
[ "public", "static", "File", "convertPathToFile", "(", "String", "filePath", ",", "BootstrapConfig", "bootProps", ")", "{", "if", "(", "filePath", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "File", "resolvedFile", "=", "null", ";", "String", "resolvedPath", "=", "normalizeFilePath", "(", "bootProps", ".", "replaceSymbols", "(", "filePath", ")", ")", ";", "resolvedFile", "=", "new", "File", "(", "resolvedPath", ")", ";", "if", "(", "!", "resolvedFile", ".", "isAbsolute", "(", ")", ")", "{", "resolvedFile", "=", "bootProps", ".", "getConfigFile", "(", "resolvedPath", ")", ";", "}", "return", "resolvedFile", ";", "}" ]
Convert the file path string to a file. If the filePath starts with a wlp pre-defined location symbol, will translate it to an absolute file path; If the filePath is a relative path, the File returned will be relative to the server's directory (as provided by {@link com.ibm.ws.kernel.boot.BootstrapConfig#getConfigFile(String) BootstrapConfig.getSeverFile(filePath)} If an unknown location symbol is used in the filePath, an IllegalArgument Exception will be thrown. @param filePath @return @exception IllegalArgumentException if the location symbol could not be resolved
[ "Convert", "the", "file", "path", "string", "to", "a", "file", ".", "If", "the", "filePath", "starts", "with", "a", "wlp", "pre", "-", "defined", "location", "symbol", "will", "translate", "it", "to", "an", "absolute", "file", "path", ";", "If", "the", "filePath", "is", "a", "relative", "path", "the", "File", "returned", "will", "be", "relative", "to", "the", "server", "s", "directory", "(", "as", "provided", "by", "{", "@link", "com", ".", "ibm", ".", "ws", ".", "kernel", ".", "boot", ".", "BootstrapConfig#getConfigFile", "(", "String", ")", "BootstrapConfig", ".", "getSeverFile", "(", "filePath", ")", "}", "If", "an", "unknown", "location", "symbol", "is", "used", "in", "the", "filePath", "an", "IllegalArgument", "Exception", "will", "be", "thrown", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/internal/FileUtils.java#L252-L264
apache/spark
launcher/src/main/java/org/apache/spark/launcher/CommandBuilderUtils.java
CommandBuilderUtils.firstNonEmptyValue
static String firstNonEmptyValue(String key, Map<?, ?>... maps) { """ Returns the first non-empty value mapped to the given key in the given maps, or null otherwise. """ for (Map<?, ?> map : maps) { String value = (String) map.get(key); if (!isEmpty(value)) { return value; } } return null; }
java
static String firstNonEmptyValue(String key, Map<?, ?>... maps) { for (Map<?, ?> map : maps) { String value = (String) map.get(key); if (!isEmpty(value)) { return value; } } return null; }
[ "static", "String", "firstNonEmptyValue", "(", "String", "key", ",", "Map", "<", "?", ",", "?", ">", "...", "maps", ")", "{", "for", "(", "Map", "<", "?", ",", "?", ">", "map", ":", "maps", ")", "{", "String", "value", "=", "(", "String", ")", "map", ".", "get", "(", "key", ")", ";", "if", "(", "!", "isEmpty", "(", "value", ")", ")", "{", "return", "value", ";", "}", "}", "return", "null", ";", "}" ]
Returns the first non-empty value mapped to the given key in the given maps, or null otherwise.
[ "Returns", "the", "first", "non", "-", "empty", "value", "mapped", "to", "the", "given", "key", "in", "the", "given", "maps", "or", "null", "otherwise", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/launcher/src/main/java/org/apache/spark/launcher/CommandBuilderUtils.java#L70-L78
JM-Lab/utils-java8
src/main/java/kr/jm/utils/helper/JMRandom.java
JMRandom.buildRandomIntStream
public static IntStream buildRandomIntStream(int streamSize, long seed, int exclusiveBound) { """ Build random int stream int stream. @param streamSize the stream size @param seed the seed @param exclusiveBound the exclusive bound @return the int stream """ return buildRandomIntStream(streamSize, new Random(seed), exclusiveBound); }
java
public static IntStream buildRandomIntStream(int streamSize, long seed, int exclusiveBound) { return buildRandomIntStream(streamSize, new Random(seed), exclusiveBound); }
[ "public", "static", "IntStream", "buildRandomIntStream", "(", "int", "streamSize", ",", "long", "seed", ",", "int", "exclusiveBound", ")", "{", "return", "buildRandomIntStream", "(", "streamSize", ",", "new", "Random", "(", "seed", ")", ",", "exclusiveBound", ")", ";", "}" ]
Build random int stream int stream. @param streamSize the stream size @param seed the seed @param exclusiveBound the exclusive bound @return the int stream
[ "Build", "random", "int", "stream", "int", "stream", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMRandom.java#L167-L171
zerodhatech/javakiteconnect
kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java
KiteRequestHandler.createGetRequest
public Request createGetRequest(String url, Map<String, Object> params, String apiKey, String accessToken) { """ Creates a GET request. @param url is the endpoint to which request has to be done. @param apiKey is the api key of the Kite Connect app. @param accessToken is the access token obtained after successful login process. @param params is the map of data that has to be sent in query params. """ HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); for(Map.Entry<String, Object> entry: params.entrySet()){ httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); } return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); }
java
public Request createGetRequest(String url, Map<String, Object> params, String apiKey, String accessToken) { HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder(); for(Map.Entry<String, Object> entry: params.entrySet()){ httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString()); } return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build(); }
[ "public", "Request", "createGetRequest", "(", "String", "url", ",", "Map", "<", "String", ",", "Object", ">", "params", ",", "String", "apiKey", ",", "String", "accessToken", ")", "{", "HttpUrl", ".", "Builder", "httpBuilder", "=", "HttpUrl", ".", "parse", "(", "url", ")", ".", "newBuilder", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "params", ".", "entrySet", "(", ")", ")", "{", "httpBuilder", ".", "addQueryParameter", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "return", "new", "Request", ".", "Builder", "(", ")", ".", "url", "(", "httpBuilder", ".", "build", "(", ")", ")", ".", "header", "(", "\"User-Agent\"", ",", "USER_AGENT", ")", ".", "header", "(", "\"X-Kite-Version\"", ",", "\"3\"", ")", ".", "header", "(", "\"Authorization\"", ",", "\"token \"", "+", "apiKey", "+", "\":\"", "+", "accessToken", ")", ".", "build", "(", ")", ";", "}" ]
Creates a GET request. @param url is the endpoint to which request has to be done. @param apiKey is the api key of the Kite Connect app. @param accessToken is the access token obtained after successful login process. @param params is the map of data that has to be sent in query params.
[ "Creates", "a", "GET", "request", "." ]
train
https://github.com/zerodhatech/javakiteconnect/blob/4a3f15ff2c8a1b3b6ec61799f8bb047e4dfeb92d/kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java#L169-L175
eliwan/ew-profiling
profiling-core/src/main/java/be/eliwan/profiling/jdbc/ProfilingDriver.java
ProfilingDriver.registerQuery
static void registerQuery(String group, String query, long durationMillis) { """ Register a duration in milliseconds for running a JDBC method with specific query. <p> When a query is known, {@link #register(String, long)} is called first. </p> @param group indication of type of command. @param query the SQL query which is used @param durationMillis duration in milliseconds """ for (ProfilingListener listener : LISTENERS) { listener.registerQuery(group, query, durationMillis); } }
java
static void registerQuery(String group, String query, long durationMillis) { for (ProfilingListener listener : LISTENERS) { listener.registerQuery(group, query, durationMillis); } }
[ "static", "void", "registerQuery", "(", "String", "group", ",", "String", "query", ",", "long", "durationMillis", ")", "{", "for", "(", "ProfilingListener", "listener", ":", "LISTENERS", ")", "{", "listener", ".", "registerQuery", "(", "group", ",", "query", ",", "durationMillis", ")", ";", "}", "}" ]
Register a duration in milliseconds for running a JDBC method with specific query. <p> When a query is known, {@link #register(String, long)} is called first. </p> @param group indication of type of command. @param query the SQL query which is used @param durationMillis duration in milliseconds
[ "Register", "a", "duration", "in", "milliseconds", "for", "running", "a", "JDBC", "method", "with", "specific", "query", ".", "<p", ">", "When", "a", "query", "is", "known", "{", "@link", "#register", "(", "String", "long", ")", "}", "is", "called", "first", ".", "<", "/", "p", ">" ]
train
https://github.com/eliwan/ew-profiling/blob/3315a0038de967fceb2f4be3c29393857d7b15a2/profiling-core/src/main/java/be/eliwan/profiling/jdbc/ProfilingDriver.java#L72-L76
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/collection/BiInt2ObjectMap.java
BiInt2ObjectMap.get
public V get(final int keyPartA, final int keyPartB) { """ Retrieve a value from the map. @param keyPartA for the key @param keyPartB for the key @return value matching the key if found or null if not found. """ final long key = compoundKey(keyPartA, keyPartB); return map.get(key); }
java
public V get(final int keyPartA, final int keyPartB) { final long key = compoundKey(keyPartA, keyPartB); return map.get(key); }
[ "public", "V", "get", "(", "final", "int", "keyPartA", ",", "final", "int", "keyPartB", ")", "{", "final", "long", "key", "=", "compoundKey", "(", "keyPartA", ",", "keyPartB", ")", ";", "return", "map", ".", "get", "(", "key", ")", ";", "}" ]
Retrieve a value from the map. @param keyPartA for the key @param keyPartB for the key @return value matching the key if found or null if not found.
[ "Retrieve", "a", "value", "from", "the", "map", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/collection/BiInt2ObjectMap.java#L109-L113
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/KunderaCoreUtils.java
KunderaCoreUtils.prepareCompositeKey
public static String prepareCompositeKey(final EntityMetadata m, final Object compositeKey) { """ Prepares composite key . @param m entity metadata @param compositeKey composite key instance @return redis key """ Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields(); StringBuilder stringBuilder = new StringBuilder(); for (Field f : fields) { if (!ReflectUtils.isTransientOrStatic(f)) { try { String fieldValue = PropertyAccessorHelper.getString(compositeKey, f); // what if field value is null???? stringBuilder.append(fieldValue); stringBuilder.append(COMPOSITE_KEY_SEPERATOR); } catch (IllegalArgumentException e) { logger.error("Error during prepare composite key, Caused by {}.", e); throw new PersistenceException(e); } } } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(COMPOSITE_KEY_SEPERATOR)); } return stringBuilder.toString(); }
java
public static String prepareCompositeKey(final EntityMetadata m, final Object compositeKey) { Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields(); StringBuilder stringBuilder = new StringBuilder(); for (Field f : fields) { if (!ReflectUtils.isTransientOrStatic(f)) { try { String fieldValue = PropertyAccessorHelper.getString(compositeKey, f); // what if field value is null???? stringBuilder.append(fieldValue); stringBuilder.append(COMPOSITE_KEY_SEPERATOR); } catch (IllegalArgumentException e) { logger.error("Error during prepare composite key, Caused by {}.", e); throw new PersistenceException(e); } } } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(COMPOSITE_KEY_SEPERATOR)); } return stringBuilder.toString(); }
[ "public", "static", "String", "prepareCompositeKey", "(", "final", "EntityMetadata", "m", ",", "final", "Object", "compositeKey", ")", "{", "Field", "[", "]", "fields", "=", "m", ".", "getIdAttribute", "(", ")", ".", "getBindableJavaType", "(", ")", ".", "getDeclaredFields", "(", ")", ";", "StringBuilder", "stringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Field", "f", ":", "fields", ")", "{", "if", "(", "!", "ReflectUtils", ".", "isTransientOrStatic", "(", "f", ")", ")", "{", "try", "{", "String", "fieldValue", "=", "PropertyAccessorHelper", ".", "getString", "(", "compositeKey", ",", "f", ")", ";", "// what if field value is null????", "stringBuilder", ".", "append", "(", "fieldValue", ")", ";", "stringBuilder", ".", "append", "(", "COMPOSITE_KEY_SEPERATOR", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "logger", ".", "error", "(", "\"Error during prepare composite key, Caused by {}.\"", ",", "e", ")", ";", "throw", "new", "PersistenceException", "(", "e", ")", ";", "}", "}", "}", "if", "(", "stringBuilder", ".", "length", "(", ")", ">", "0", ")", "{", "stringBuilder", ".", "deleteCharAt", "(", "stringBuilder", ".", "lastIndexOf", "(", "COMPOSITE_KEY_SEPERATOR", ")", ")", ";", "}", "return", "stringBuilder", ".", "toString", "(", ")", ";", "}" ]
Prepares composite key . @param m entity metadata @param compositeKey composite key instance @return redis key
[ "Prepares", "composite", "key", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/KunderaCoreUtils.java#L148-L178
Stratio/deep-spark
deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java
MongoNativeExtractor.getSplitData
private BasicDBList getSplitData(DBCollection collection) { """ Gets split data. @param collection the collection @return the split data """ final DBObject cmd = BasicDBObjectBuilder.start("splitVector", collection.getFullName()) .add("keyPattern", new BasicDBObject(MONGO_DEFAULT_ID, 1)) .add("force", false) .add("maxChunkSize", splitSize) .get(); CommandResult splitVectorResult = collection.getDB().getSisterDB("admin").command(cmd); return (BasicDBList) splitVectorResult.get(SPLIT_KEYS); }
java
private BasicDBList getSplitData(DBCollection collection) { final DBObject cmd = BasicDBObjectBuilder.start("splitVector", collection.getFullName()) .add("keyPattern", new BasicDBObject(MONGO_DEFAULT_ID, 1)) .add("force", false) .add("maxChunkSize", splitSize) .get(); CommandResult splitVectorResult = collection.getDB().getSisterDB("admin").command(cmd); return (BasicDBList) splitVectorResult.get(SPLIT_KEYS); }
[ "private", "BasicDBList", "getSplitData", "(", "DBCollection", "collection", ")", "{", "final", "DBObject", "cmd", "=", "BasicDBObjectBuilder", ".", "start", "(", "\"splitVector\"", ",", "collection", ".", "getFullName", "(", ")", ")", ".", "add", "(", "\"keyPattern\"", ",", "new", "BasicDBObject", "(", "MONGO_DEFAULT_ID", ",", "1", ")", ")", ".", "add", "(", "\"force\"", ",", "false", ")", ".", "add", "(", "\"maxChunkSize\"", ",", "splitSize", ")", ".", "get", "(", ")", ";", "CommandResult", "splitVectorResult", "=", "collection", ".", "getDB", "(", ")", ".", "getSisterDB", "(", "\"admin\"", ")", ".", "command", "(", "cmd", ")", ";", "return", "(", "BasicDBList", ")", "splitVectorResult", ".", "get", "(", "SPLIT_KEYS", ")", ";", "}" ]
Gets split data. @param collection the collection @return the split data
[ "Gets", "split", "data", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java#L237-L248
kaazing/gateway
mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java
NTLMResponses.getNTLMResponse
public static byte[] getNTLMResponse(String password, byte[] challenge) throws Exception { """ Calculates the NTLM Response for the given challenge, using the specified password. @param password The user's password. @param challenge The Type 2 challenge from the server. @return The NTLM Response. """ byte[] ntlmHash = ntlmHash(password); return lmResponse(ntlmHash, challenge); }
java
public static byte[] getNTLMResponse(String password, byte[] challenge) throws Exception { byte[] ntlmHash = ntlmHash(password); return lmResponse(ntlmHash, challenge); }
[ "public", "static", "byte", "[", "]", "getNTLMResponse", "(", "String", "password", ",", "byte", "[", "]", "challenge", ")", "throws", "Exception", "{", "byte", "[", "]", "ntlmHash", "=", "ntlmHash", "(", "password", ")", ";", "return", "lmResponse", "(", "ntlmHash", ",", "challenge", ")", ";", "}" ]
Calculates the NTLM Response for the given challenge, using the specified password. @param password The user's password. @param challenge The Type 2 challenge from the server. @return The NTLM Response.
[ "Calculates", "the", "NTLM", "Response", "for", "the", "given", "challenge", "using", "the", "specified", "password", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java#L76-L80
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FSOutputSummer.java
FSOutputSummer.writeChecksumChunk
private void writeChecksumChunk(byte b[], int off, int len, boolean keep) throws IOException { """ Generate checksum for the data chunk and output data chunk & checksum to the underlying output stream. If keep is true then keep the current checksum intact, do not reset it. """ int tempChecksum = (int)sum.getValue(); if (!keep) { sum.reset(); } int2byte(tempChecksum, checksum); writeChunk(b, off, len, checksum); }
java
private void writeChecksumChunk(byte b[], int off, int len, boolean keep) throws IOException { int tempChecksum = (int)sum.getValue(); if (!keep) { sum.reset(); } int2byte(tempChecksum, checksum); writeChunk(b, off, len, checksum); }
[ "private", "void", "writeChecksumChunk", "(", "byte", "b", "[", "]", ",", "int", "off", ",", "int", "len", ",", "boolean", "keep", ")", "throws", "IOException", "{", "int", "tempChecksum", "=", "(", "int", ")", "sum", ".", "getValue", "(", ")", ";", "if", "(", "!", "keep", ")", "{", "sum", ".", "reset", "(", ")", ";", "}", "int2byte", "(", "tempChecksum", ",", "checksum", ")", ";", "writeChunk", "(", "b", ",", "off", ",", "len", ",", "checksum", ")", ";", "}" ]
Generate checksum for the data chunk and output data chunk & checksum to the underlying output stream. If keep is true then keep the current checksum intact, do not reset it.
[ "Generate", "checksum", "for", "the", "data", "chunk", "and", "output", "data", "chunk", "&", "checksum", "to", "the", "underlying", "output", "stream", ".", "If", "keep", "is", "true", "then", "keep", "the", "current", "checksum", "intact", "do", "not", "reset", "it", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FSOutputSummer.java#L175-L183
SourcePond/fileobserver
fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/Directory.java
Directory.informDiscard
public void informDiscard(final EventDispatcher pDispatcher, final Path pFile) { """ Iterates over the listeners specified and informs them that the file specified has been discarded through their {@link PathChangeListener#discard(DispatchKey)} method. The listeners will be called asynchronously sometime in the future. @param pFile Discarded file, must be {@code null} """ // Remove the checksum resource to save memory resources.remove(pFile); if (pDispatcher.hasListeners()) { final Collection<DispatchKey> keys = createKeys(pFile); keys.forEach(k -> pDispatcher.discard(k)); } }
java
public void informDiscard(final EventDispatcher pDispatcher, final Path pFile) { // Remove the checksum resource to save memory resources.remove(pFile); if (pDispatcher.hasListeners()) { final Collection<DispatchKey> keys = createKeys(pFile); keys.forEach(k -> pDispatcher.discard(k)); } }
[ "public", "void", "informDiscard", "(", "final", "EventDispatcher", "pDispatcher", ",", "final", "Path", "pFile", ")", "{", "// Remove the checksum resource to save memory", "resources", ".", "remove", "(", "pFile", ")", ";", "if", "(", "pDispatcher", ".", "hasListeners", "(", ")", ")", "{", "final", "Collection", "<", "DispatchKey", ">", "keys", "=", "createKeys", "(", "pFile", ")", ";", "keys", ".", "forEach", "(", "k", "->", "pDispatcher", ".", "discard", "(", "k", ")", ")", ";", "}", "}" ]
Iterates over the listeners specified and informs them that the file specified has been discarded through their {@link PathChangeListener#discard(DispatchKey)} method. The listeners will be called asynchronously sometime in the future. @param pFile Discarded file, must be {@code null}
[ "Iterates", "over", "the", "listeners", "specified", "and", "informs", "them", "that", "the", "file", "specified", "has", "been", "discarded", "through", "their", "{", "@link", "PathChangeListener#discard", "(", "DispatchKey", ")", "}", "method", ".", "The", "listeners", "will", "be", "called", "asynchronously", "sometime", "in", "the", "future", "." ]
train
https://github.com/SourcePond/fileobserver/blob/dfb3055ed35759a47f52f6cfdea49879c415fd6b/fileobserver-impl/src/main/java/ch/sourcepond/io/fileobserver/impl/directory/Directory.java#L262-L270
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java
PathUtils.isAncestor
public static boolean isAncestor(Path possibleAncestor, Path fullPath) { """ Checks whether possibleAncestor is an ancestor of fullPath. @param possibleAncestor Possible ancestor of fullPath. @param fullPath path to check. @return true if possibleAncestor is an ancestor of fullPath. """ return !relativizePath(fullPath, possibleAncestor).equals(getPathWithoutSchemeAndAuthority(fullPath)); }
java
public static boolean isAncestor(Path possibleAncestor, Path fullPath) { return !relativizePath(fullPath, possibleAncestor).equals(getPathWithoutSchemeAndAuthority(fullPath)); }
[ "public", "static", "boolean", "isAncestor", "(", "Path", "possibleAncestor", ",", "Path", "fullPath", ")", "{", "return", "!", "relativizePath", "(", "fullPath", ",", "possibleAncestor", ")", ".", "equals", "(", "getPathWithoutSchemeAndAuthority", "(", "fullPath", ")", ")", ";", "}" ]
Checks whether possibleAncestor is an ancestor of fullPath. @param possibleAncestor Possible ancestor of fullPath. @param fullPath path to check. @return true if possibleAncestor is an ancestor of fullPath.
[ "Checks", "whether", "possibleAncestor", "is", "an", "ancestor", "of", "fullPath", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L57-L59
structr/structr
structr-core/src/main/java/org/structr/core/graph/NodeServiceCommand.java
NodeServiceCommand.bulkGraphOperation
public <T> long bulkGraphOperation(final SecurityContext securityContext, final Iterator<T> iterator, final long commitCount, String description, final BulkGraphOperation<T> operation) { """ Executes the given operation on all nodes in the given list. @param <T> @param securityContext @param iterator the iterator that provides the nodes to operate on @param commitCount @param description @param operation the operation to execute @return the number of nodes processed """ return bulkGraphOperation(securityContext, iterator, commitCount, description, operation, true); }
java
public <T> long bulkGraphOperation(final SecurityContext securityContext, final Iterator<T> iterator, final long commitCount, String description, final BulkGraphOperation<T> operation) { return bulkGraphOperation(securityContext, iterator, commitCount, description, operation, true); }
[ "public", "<", "T", ">", "long", "bulkGraphOperation", "(", "final", "SecurityContext", "securityContext", ",", "final", "Iterator", "<", "T", ">", "iterator", ",", "final", "long", "commitCount", ",", "String", "description", ",", "final", "BulkGraphOperation", "<", "T", ">", "operation", ")", "{", "return", "bulkGraphOperation", "(", "securityContext", ",", "iterator", ",", "commitCount", ",", "description", ",", "operation", ",", "true", ")", ";", "}" ]
Executes the given operation on all nodes in the given list. @param <T> @param securityContext @param iterator the iterator that provides the nodes to operate on @param commitCount @param description @param operation the operation to execute @return the number of nodes processed
[ "Executes", "the", "given", "operation", "on", "all", "nodes", "in", "the", "given", "list", "." ]
train
https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/core/graph/NodeServiceCommand.java#L72-L74
ThreeTen/threeten-extra
src/main/java/org/threeten/extra/PeriodDuration.java
PeriodDuration.of
public static PeriodDuration of(Period period) { """ Obtains an instance based on a period. <p> The duration will be zero. @param period the period, not null @return the combined period-duration, not null """ Objects.requireNonNull(period, "The period must not be null"); return new PeriodDuration(period, Duration.ZERO); }
java
public static PeriodDuration of(Period period) { Objects.requireNonNull(period, "The period must not be null"); return new PeriodDuration(period, Duration.ZERO); }
[ "public", "static", "PeriodDuration", "of", "(", "Period", "period", ")", "{", "Objects", ".", "requireNonNull", "(", "period", ",", "\"The period must not be null\"", ")", ";", "return", "new", "PeriodDuration", "(", "period", ",", "Duration", ".", "ZERO", ")", ";", "}" ]
Obtains an instance based on a period. <p> The duration will be zero. @param period the period, not null @return the combined period-duration, not null
[ "Obtains", "an", "instance", "based", "on", "a", "period", ".", "<p", ">", "The", "duration", "will", "be", "zero", "." ]
train
https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/PeriodDuration.java#L139-L142
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java
SARLOperationHelper._hasSideEffects
protected Boolean _hasSideEffects(XSwitchExpression expression, ISideEffectContext context) { """ Test if the given expression has side effects. @param expression the expression. @param context the list of context expressions. @return {@code true} if the expression has side effects. """ context.open(); if (hasSideEffects(expression.getSwitch(), context)) { return true; } final List<Map<String, List<XExpression>>> buffers = new ArrayList<>(); for (final XCasePart ex : expression.getCases()) { context.open(); if (hasSideEffects(ex.getCase(), context)) { return true; } final Map<String, List<XExpression>> buffer = context.createVariableAssignmentBufferForBranch(); if (hasSideEffects(ex.getThen(), context.branch(buffer))) { return true; } buffers.add(buffer); context.close(); } final Map<String, List<XExpression>> buffer = context.createVariableAssignmentBufferForBranch(); if (hasSideEffects(expression.getDefault(), context.branch(buffer))) { return true; } buffers.add(buffer); context.mergeBranchVariableAssignments(buffers); context.close(); return false; }
java
protected Boolean _hasSideEffects(XSwitchExpression expression, ISideEffectContext context) { context.open(); if (hasSideEffects(expression.getSwitch(), context)) { return true; } final List<Map<String, List<XExpression>>> buffers = new ArrayList<>(); for (final XCasePart ex : expression.getCases()) { context.open(); if (hasSideEffects(ex.getCase(), context)) { return true; } final Map<String, List<XExpression>> buffer = context.createVariableAssignmentBufferForBranch(); if (hasSideEffects(ex.getThen(), context.branch(buffer))) { return true; } buffers.add(buffer); context.close(); } final Map<String, List<XExpression>> buffer = context.createVariableAssignmentBufferForBranch(); if (hasSideEffects(expression.getDefault(), context.branch(buffer))) { return true; } buffers.add(buffer); context.mergeBranchVariableAssignments(buffers); context.close(); return false; }
[ "protected", "Boolean", "_hasSideEffects", "(", "XSwitchExpression", "expression", ",", "ISideEffectContext", "context", ")", "{", "context", ".", "open", "(", ")", ";", "if", "(", "hasSideEffects", "(", "expression", ".", "getSwitch", "(", ")", ",", "context", ")", ")", "{", "return", "true", ";", "}", "final", "List", "<", "Map", "<", "String", ",", "List", "<", "XExpression", ">", ">", ">", "buffers", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "final", "XCasePart", "ex", ":", "expression", ".", "getCases", "(", ")", ")", "{", "context", ".", "open", "(", ")", ";", "if", "(", "hasSideEffects", "(", "ex", ".", "getCase", "(", ")", ",", "context", ")", ")", "{", "return", "true", ";", "}", "final", "Map", "<", "String", ",", "List", "<", "XExpression", ">", ">", "buffer", "=", "context", ".", "createVariableAssignmentBufferForBranch", "(", ")", ";", "if", "(", "hasSideEffects", "(", "ex", ".", "getThen", "(", ")", ",", "context", ".", "branch", "(", "buffer", ")", ")", ")", "{", "return", "true", ";", "}", "buffers", ".", "add", "(", "buffer", ")", ";", "context", ".", "close", "(", ")", ";", "}", "final", "Map", "<", "String", ",", "List", "<", "XExpression", ">", ">", "buffer", "=", "context", ".", "createVariableAssignmentBufferForBranch", "(", ")", ";", "if", "(", "hasSideEffects", "(", "expression", ".", "getDefault", "(", ")", ",", "context", ".", "branch", "(", "buffer", ")", ")", ")", "{", "return", "true", ";", "}", "buffers", ".", "add", "(", "buffer", ")", ";", "context", ".", "mergeBranchVariableAssignments", "(", "buffers", ")", ";", "context", ".", "close", "(", ")", ";", "return", "false", ";", "}" ]
Test if the given expression has side effects. @param expression the expression. @param context the list of context expressions. @return {@code true} if the expression has side effects.
[ "Test", "if", "the", "given", "expression", "has", "side", "effects", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/typesystem/SARLOperationHelper.java#L430-L456
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java
Convolution.convn
public static INDArray convn(INDArray input, INDArray kernel, Type type, int[] axes) { """ ND Convolution @param input the input to op @param kernel the kerrnel to op with @param type the opType of convolution @param axes the axes to do the convolution along @return the convolution of the given input and kernel """ return Nd4j.getConvolution().convn(input, kernel, type, axes); }
java
public static INDArray convn(INDArray input, INDArray kernel, Type type, int[] axes) { return Nd4j.getConvolution().convn(input, kernel, type, axes); }
[ "public", "static", "INDArray", "convn", "(", "INDArray", "input", ",", "INDArray", "kernel", ",", "Type", "type", ",", "int", "[", "]", "axes", ")", "{", "return", "Nd4j", ".", "getConvolution", "(", ")", ".", "convn", "(", "input", ",", "kernel", ",", "type", ",", "axes", ")", ";", "}" ]
ND Convolution @param input the input to op @param kernel the kerrnel to op with @param type the opType of convolution @param axes the axes to do the convolution along @return the convolution of the given input and kernel
[ "ND", "Convolution" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/convolution/Convolution.java#L368-L370
ralscha/extdirectspring
src/main/java/ch/ralscha/extdirectspring/util/JsonHandler.java
JsonHandler.readValue
public <T> T readValue(String json, Class<T> clazz) { """ Converts a JSON string into an object. In case of an exception returns null and logs the exception. @param <T> type of the object to create @param json string with the JSON @param clazz class of object to create @return the converted object, null if there is an exception """ try { return this.mapper.readValue(json, clazz); } catch (Exception e) { LogFactory.getLog(JsonHandler.class).info("deserialize json to object", e); return null; } }
java
public <T> T readValue(String json, Class<T> clazz) { try { return this.mapper.readValue(json, clazz); } catch (Exception e) { LogFactory.getLog(JsonHandler.class).info("deserialize json to object", e); return null; } }
[ "public", "<", "T", ">", "T", "readValue", "(", "String", "json", ",", "Class", "<", "T", ">", "clazz", ")", "{", "try", "{", "return", "this", ".", "mapper", ".", "readValue", "(", "json", ",", "clazz", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LogFactory", ".", "getLog", "(", "JsonHandler", ".", "class", ")", ".", "info", "(", "\"deserialize json to object\"", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Converts a JSON string into an object. In case of an exception returns null and logs the exception. @param <T> type of the object to create @param json string with the JSON @param clazz class of object to create @return the converted object, null if there is an exception
[ "Converts", "a", "JSON", "string", "into", "an", "object", ".", "In", "case", "of", "an", "exception", "returns", "null", "and", "logs", "the", "exception", "." ]
train
https://github.com/ralscha/extdirectspring/blob/4b018497c4e7503033f91d0491b4e74bf8291d2c/src/main/java/ch/ralscha/extdirectspring/util/JsonHandler.java#L124-L132
google/gson
gson/src/main/java/com/google/gson/TypeAdapter.java
TypeAdapter.nullSafe
public final TypeAdapter<T> nullSafe() { """ This wrapper method is used to make a type adapter null tolerant. In general, a type adapter is required to handle nulls in write and read methods. Here is how this is typically done:<br> <pre> {@code Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, new TypeAdapter<Foo>() { public Foo read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } // read a Foo from in and return it } public void write(JsonWriter out, Foo src) throws IOException { if (src == null) { out.nullValue(); return; } // write src as JSON to out } }).create(); }</pre> You can avoid this boilerplate handling of nulls by wrapping your type adapter with this method. Here is how we will rewrite the above example: <pre> {@code Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, new TypeAdapter<Foo>() { public Foo read(JsonReader in) throws IOException { // read a Foo from in and return it } public void write(JsonWriter out, Foo src) throws IOException { // write src as JSON to out } }.nullSafe()).create(); }</pre> Note that we didn't need to check for nulls in our type adapter after we used nullSafe. """ return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { TypeAdapter.this.write(out, value); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } return TypeAdapter.this.read(reader); } }; }
java
public final TypeAdapter<T> nullSafe() { return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { TypeAdapter.this.write(out, value); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } return TypeAdapter.this.read(reader); } }; }
[ "public", "final", "TypeAdapter", "<", "T", ">", "nullSafe", "(", ")", "{", "return", "new", "TypeAdapter", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "write", "(", "JsonWriter", "out", ",", "T", "value", ")", "throws", "IOException", "{", "if", "(", "value", "==", "null", ")", "{", "out", ".", "nullValue", "(", ")", ";", "}", "else", "{", "TypeAdapter", ".", "this", ".", "write", "(", "out", ",", "value", ")", ";", "}", "}", "@", "Override", "public", "T", "read", "(", "JsonReader", "reader", ")", "throws", "IOException", "{", "if", "(", "reader", ".", "peek", "(", ")", "==", "JsonToken", ".", "NULL", ")", "{", "reader", ".", "nextNull", "(", ")", ";", "return", "null", ";", "}", "return", "TypeAdapter", ".", "this", ".", "read", "(", "reader", ")", ";", "}", "}", ";", "}" ]
This wrapper method is used to make a type adapter null tolerant. In general, a type adapter is required to handle nulls in write and read methods. Here is how this is typically done:<br> <pre> {@code Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, new TypeAdapter<Foo>() { public Foo read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } // read a Foo from in and return it } public void write(JsonWriter out, Foo src) throws IOException { if (src == null) { out.nullValue(); return; } // write src as JSON to out } }).create(); }</pre> You can avoid this boilerplate handling of nulls by wrapping your type adapter with this method. Here is how we will rewrite the above example: <pre> {@code Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, new TypeAdapter<Foo>() { public Foo read(JsonReader in) throws IOException { // read a Foo from in and return it } public void write(JsonWriter out, Foo src) throws IOException { // write src as JSON to out } }.nullSafe()).create(); }</pre> Note that we didn't need to check for nulls in our type adapter after we used nullSafe.
[ "This", "wrapper", "method", "is", "used", "to", "make", "a", "type", "adapter", "null", "tolerant", ".", "In", "general", "a", "type", "adapter", "is", "required", "to", "handle", "nulls", "in", "write", "and", "read", "methods", ".", "Here", "is", "how", "this", "is", "typically", "done", ":", "<br", ">", "<pre", ">", "{", "@code" ]
train
https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/TypeAdapter.java#L185-L202
alkacon/opencms-core
src/org/opencms/ui/apps/lists/CmsListManager.java
CmsListManager.executeSearch
private void executeSearch(CmsSearchController controller, CmsSolrQuery query) { """ Executes a search.<p> @param controller the search controller @param query the SOLR query """ CmsObject cms = A_CmsUI.getCmsObject(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr( cms.getRequestContext().getCurrentProject().isOnlineProject() ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE); try { CmsSolrResultList solrResultList = index.search(cms, query, true, CmsResourceFilter.IGNORE_EXPIRATION); displayResult(solrResultList); m_resultFacets.displayFacetResult( solrResultList, new CmsSearchResultWrapper(controller, solrResultList, query, cms, null)); } catch (CmsSearchException e) { CmsErrorDialog.showErrorDialog(e); LOG.error("Error executing search.", e); } }
java
private void executeSearch(CmsSearchController controller, CmsSolrQuery query) { CmsObject cms = A_CmsUI.getCmsObject(); CmsSolrIndex index = OpenCms.getSearchManager().getIndexSolr( cms.getRequestContext().getCurrentProject().isOnlineProject() ? CmsSolrIndex.DEFAULT_INDEX_NAME_ONLINE : CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE); try { CmsSolrResultList solrResultList = index.search(cms, query, true, CmsResourceFilter.IGNORE_EXPIRATION); displayResult(solrResultList); m_resultFacets.displayFacetResult( solrResultList, new CmsSearchResultWrapper(controller, solrResultList, query, cms, null)); } catch (CmsSearchException e) { CmsErrorDialog.showErrorDialog(e); LOG.error("Error executing search.", e); } }
[ "private", "void", "executeSearch", "(", "CmsSearchController", "controller", ",", "CmsSolrQuery", "query", ")", "{", "CmsObject", "cms", "=", "A_CmsUI", ".", "getCmsObject", "(", ")", ";", "CmsSolrIndex", "index", "=", "OpenCms", ".", "getSearchManager", "(", ")", ".", "getIndexSolr", "(", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentProject", "(", ")", ".", "isOnlineProject", "(", ")", "?", "CmsSolrIndex", ".", "DEFAULT_INDEX_NAME_ONLINE", ":", "CmsSolrIndex", ".", "DEFAULT_INDEX_NAME_OFFLINE", ")", ";", "try", "{", "CmsSolrResultList", "solrResultList", "=", "index", ".", "search", "(", "cms", ",", "query", ",", "true", ",", "CmsResourceFilter", ".", "IGNORE_EXPIRATION", ")", ";", "displayResult", "(", "solrResultList", ")", ";", "m_resultFacets", ".", "displayFacetResult", "(", "solrResultList", ",", "new", "CmsSearchResultWrapper", "(", "controller", ",", "solrResultList", ",", "query", ",", "cms", ",", "null", ")", ")", ";", "}", "catch", "(", "CmsSearchException", "e", ")", "{", "CmsErrorDialog", ".", "showErrorDialog", "(", "e", ")", ";", "LOG", ".", "error", "(", "\"Error executing search.\"", ",", "e", ")", ";", "}", "}" ]
Executes a search.<p> @param controller the search controller @param query the SOLR query
[ "Executes", "a", "search", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/lists/CmsListManager.java#L2106-L2124
intuit/QuickBooks-V3-Java-SDK
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/PrepareRequestInterceptor.java
PrepareRequestInterceptor.isDownloadPDF
private boolean isDownloadPDF(Map<String, String> map) { """ Method returns true if this request expects PDF as response @param map @return """ return StringUtils.hasText(map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR)) && map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR).equalsIgnoreCase(ContentTypes.PDF.name()); }
java
private boolean isDownloadPDF(Map<String, String> map) { return StringUtils.hasText(map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR)) && map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR).equalsIgnoreCase(ContentTypes.PDF.name()); }
[ "private", "boolean", "isDownloadPDF", "(", "Map", "<", "String", ",", "String", ">", "map", ")", "{", "return", "StringUtils", ".", "hasText", "(", "map", ".", "get", "(", "RequestElements", ".", "REQ_PARAM_ENTITY_SELECTOR", ")", ")", "&&", "map", ".", "get", "(", "RequestElements", ".", "REQ_PARAM_ENTITY_SELECTOR", ")", ".", "equalsIgnoreCase", "(", "ContentTypes", ".", "PDF", ".", "name", "(", ")", ")", ";", "}" ]
Method returns true if this request expects PDF as response @param map @return
[ "Method", "returns", "true", "if", "this", "request", "expects", "PDF", "as", "response" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/interceptors/PrepareRequestInterceptor.java#L576-L579
geomajas/geomajas-project-server
plugin/layer-geotools/geotools/src/main/java/org/geomajas/layer/geotools/GeoToolsTransactionSynchronization.java
GeoToolsTransactionSynchronization.afterCompletion
@Override public void afterCompletion(int status) { """ Called when the transaction manager has committed/rolled back. We should copy this behavior at the geotools level, except for the JDBC case, which has already been handled. """ // clean up transactions that aren't managed by Spring for (DataAccess<SimpleFeatureType, SimpleFeature> dataStore : transactions.keySet()) { // we must manage transaction ourselves for non-JDBC ! if (!(dataStore instanceof JDBCDataStore)) { Transaction transaction = transactions.get(dataStore); try { switch (status) { case TransactionSynchronization.STATUS_COMMITTED: transaction.commit(); break; case TransactionSynchronization.STATUS_ROLLED_BACK: transaction.rollback(); break; case TransactionSynchronization.STATUS_UNKNOWN: } } catch (IOException e) { try { transaction.rollback(); } catch (IOException e1) { log.debug("Could not rollback geotools transaction", e1); } } finally { try { transaction.close(); } catch (IOException e) { log.debug("Could not close geotools transaction", e); } } } } transactions.clear(); }
java
@Override public void afterCompletion(int status) { // clean up transactions that aren't managed by Spring for (DataAccess<SimpleFeatureType, SimpleFeature> dataStore : transactions.keySet()) { // we must manage transaction ourselves for non-JDBC ! if (!(dataStore instanceof JDBCDataStore)) { Transaction transaction = transactions.get(dataStore); try { switch (status) { case TransactionSynchronization.STATUS_COMMITTED: transaction.commit(); break; case TransactionSynchronization.STATUS_ROLLED_BACK: transaction.rollback(); break; case TransactionSynchronization.STATUS_UNKNOWN: } } catch (IOException e) { try { transaction.rollback(); } catch (IOException e1) { log.debug("Could not rollback geotools transaction", e1); } } finally { try { transaction.close(); } catch (IOException e) { log.debug("Could not close geotools transaction", e); } } } } transactions.clear(); }
[ "@", "Override", "public", "void", "afterCompletion", "(", "int", "status", ")", "{", "// clean up transactions that aren't managed by Spring", "for", "(", "DataAccess", "<", "SimpleFeatureType", ",", "SimpleFeature", ">", "dataStore", ":", "transactions", ".", "keySet", "(", ")", ")", "{", "// we must manage transaction ourselves for non-JDBC !", "if", "(", "!", "(", "dataStore", "instanceof", "JDBCDataStore", ")", ")", "{", "Transaction", "transaction", "=", "transactions", ".", "get", "(", "dataStore", ")", ";", "try", "{", "switch", "(", "status", ")", "{", "case", "TransactionSynchronization", ".", "STATUS_COMMITTED", ":", "transaction", ".", "commit", "(", ")", ";", "break", ";", "case", "TransactionSynchronization", ".", "STATUS_ROLLED_BACK", ":", "transaction", ".", "rollback", "(", ")", ";", "break", ";", "case", "TransactionSynchronization", ".", "STATUS_UNKNOWN", ":", "}", "}", "catch", "(", "IOException", "e", ")", "{", "try", "{", "transaction", ".", "rollback", "(", ")", ";", "}", "catch", "(", "IOException", "e1", ")", "{", "log", ".", "debug", "(", "\"Could not rollback geotools transaction\"", ",", "e1", ")", ";", "}", "}", "finally", "{", "try", "{", "transaction", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "log", ".", "debug", "(", "\"Could not close geotools transaction\"", ",", "e", ")", ";", "}", "}", "}", "}", "transactions", ".", "clear", "(", ")", ";", "}" ]
Called when the transaction manager has committed/rolled back. We should copy this behavior at the geotools level, except for the JDBC case, which has already been handled.
[ "Called", "when", "the", "transaction", "manager", "has", "committed", "/", "rolled", "back", ".", "We", "should", "copy", "this", "behavior", "at", "the", "geotools", "level", "except", "for", "the", "JDBC", "case", "which", "has", "already", "been", "handled", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/layer-geotools/geotools/src/main/java/org/geomajas/layer/geotools/GeoToolsTransactionSynchronization.java#L128-L161
gallandarakhneorg/afc
core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/Transform1D.java
Transform1D.toTransform2D
@Pure public final Transform2D toTransform2D(double startX, double startY, double endX, double endY) { """ Replies a 2D transformation that is corresponding to this transformation. <p>The used coordinate system is replied by {@link CoordinateSystem2D#getDefaultCoordinateSystem()}. @param startX is the 2D x coordinate of the start point of the segment. @param startY is the 2D y coordinate of the start point of the segment. @param endX is the 2D x coordinate of the end point of the segment @param endY is the 2D y coordinate of the end point of the segment @return the 2D transformation. """ final Transform2D trans = new Transform2D(); final Vector2d direction = new Vector2d(endX - startX, endY - startY); final Vector2d shiftVector = direction.toOrthogonalVector(); double c = this.curvilineTranslation; double j = this.shiftTranslation; if (!this.firstSegmentDirection.isSegmentDirection()) { c = -c; j = -j; } shiftVector.scale(j); direction.normalize(); direction.scale(c); direction.add(shiftVector); trans.setTranslation(direction); return trans; }
java
@Pure public final Transform2D toTransform2D(double startX, double startY, double endX, double endY) { final Transform2D trans = new Transform2D(); final Vector2d direction = new Vector2d(endX - startX, endY - startY); final Vector2d shiftVector = direction.toOrthogonalVector(); double c = this.curvilineTranslation; double j = this.shiftTranslation; if (!this.firstSegmentDirection.isSegmentDirection()) { c = -c; j = -j; } shiftVector.scale(j); direction.normalize(); direction.scale(c); direction.add(shiftVector); trans.setTranslation(direction); return trans; }
[ "@", "Pure", "public", "final", "Transform2D", "toTransform2D", "(", "double", "startX", ",", "double", "startY", ",", "double", "endX", ",", "double", "endY", ")", "{", "final", "Transform2D", "trans", "=", "new", "Transform2D", "(", ")", ";", "final", "Vector2d", "direction", "=", "new", "Vector2d", "(", "endX", "-", "startX", ",", "endY", "-", "startY", ")", ";", "final", "Vector2d", "shiftVector", "=", "direction", ".", "toOrthogonalVector", "(", ")", ";", "double", "c", "=", "this", ".", "curvilineTranslation", ";", "double", "j", "=", "this", ".", "shiftTranslation", ";", "if", "(", "!", "this", ".", "firstSegmentDirection", ".", "isSegmentDirection", "(", ")", ")", "{", "c", "=", "-", "c", ";", "j", "=", "-", "j", ";", "}", "shiftVector", ".", "scale", "(", "j", ")", ";", "direction", ".", "normalize", "(", ")", ";", "direction", ".", "scale", "(", "c", ")", ";", "direction", ".", "add", "(", "shiftVector", ")", ";", "trans", ".", "setTranslation", "(", "direction", ")", ";", "return", "trans", ";", "}" ]
Replies a 2D transformation that is corresponding to this transformation. <p>The used coordinate system is replied by {@link CoordinateSystem2D#getDefaultCoordinateSystem()}. @param startX is the 2D x coordinate of the start point of the segment. @param startY is the 2D y coordinate of the start point of the segment. @param endX is the 2D x coordinate of the end point of the segment @param endY is the 2D y coordinate of the end point of the segment @return the 2D transformation.
[ "Replies", "a", "2D", "transformation", "that", "is", "corresponding", "to", "this", "transformation", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/Transform1D.java#L651-L676