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
jboss/jboss-el-api_spec
src/main/java/javax/el/ELContext.java
ELContext.notifyPropertyResolved
public void notifyPropertyResolved(Object base, Object property) { """ Notifies the listeners when the (base, property) pair is resolved @param base The base object @param property The property Object """ if (getEvaluationListeners() == null) return; for (EvaluationListener listener: getEvaluationListeners()) { listener.propertyResolved(this, base, property); } }
java
public void notifyPropertyResolved(Object base, Object property) { if (getEvaluationListeners() == null) return; for (EvaluationListener listener: getEvaluationListeners()) { listener.propertyResolved(this, base, property); } }
[ "public", "void", "notifyPropertyResolved", "(", "Object", "base", ",", "Object", "property", ")", "{", "if", "(", "getEvaluationListeners", "(", ")", "==", "null", ")", "return", ";", "for", "(", "EvaluationListener", "listener", ":", "getEvaluationListeners", "(", ")", ")", "{", "listener", ".", "propertyResolved", "(", "this", ",", "base", ",", "property", ")", ";", "}", "}" ]
Notifies the listeners when the (base, property) pair is resolved @param base The base object @param property The property Object
[ "Notifies", "the", "listeners", "when", "the", "(", "base", "property", ")", "pair", "is", "resolved" ]
train
https://github.com/jboss/jboss-el-api_spec/blob/4cef117cae3ccf9f76439845687a8d219ad2eb43/src/main/java/javax/el/ELContext.java#L361-L367
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/jaxbref/JAXBResourceFactory.java
JAXBResourceFactory.getOnce
public <T> T getOnce(final Class<T> clazz, final String name) { """ Resolve the JAXB resource once without caching anything @param clazz @param name @param <T> @return """ return new JAXBNamedResourceFactory<T>(this.config, this.factory, name, clazz).get(); }
java
public <T> T getOnce(final Class<T> clazz, final String name) { return new JAXBNamedResourceFactory<T>(this.config, this.factory, name, clazz).get(); }
[ "public", "<", "T", ">", "T", "getOnce", "(", "final", "Class", "<", "T", ">", "clazz", ",", "final", "String", "name", ")", "{", "return", "new", "JAXBNamedResourceFactory", "<", "T", ">", "(", "this", ".", "config", ",", "this", ".", "factory", ",", "name", ",", "clazz", ")", ".", "get", "(", ")", ";", "}" ]
Resolve the JAXB resource once without caching anything @param clazz @param name @param <T> @return
[ "Resolve", "the", "JAXB", "resource", "once", "without", "caching", "anything" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/jaxbref/JAXBResourceFactory.java#L89-L92
spring-projects/spring-data-solr
src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java
EmbeddedSolrServerFactory.createCoreContainer
private CoreContainer createCoreContainer(String solrHomeDirectory, File solrXmlFile) { """ Create {@link CoreContainer} for Solr version 4.4+ and handle changes in . @param solrHomeDirectory @param solrXmlFile @return """ Method createAndLoadMethod = ClassUtils.getStaticMethod(CoreContainer.class, "createAndLoad", String.class, File.class); if (createAndLoadMethod != null) { return (CoreContainer) ReflectionUtils.invokeMethod(createAndLoadMethod, null, solrHomeDirectory, solrXmlFile); } createAndLoadMethod = ClassUtils.getStaticMethod(CoreContainer.class, "createAndLoad", Path.class, Path.class); return (CoreContainer) ReflectionUtils.invokeMethod(createAndLoadMethod, null, FileSystems.getDefault().getPath(solrHomeDirectory), FileSystems.getDefault().getPath(solrXmlFile.getPath())); }
java
private CoreContainer createCoreContainer(String solrHomeDirectory, File solrXmlFile) { Method createAndLoadMethod = ClassUtils.getStaticMethod(CoreContainer.class, "createAndLoad", String.class, File.class); if (createAndLoadMethod != null) { return (CoreContainer) ReflectionUtils.invokeMethod(createAndLoadMethod, null, solrHomeDirectory, solrXmlFile); } createAndLoadMethod = ClassUtils.getStaticMethod(CoreContainer.class, "createAndLoad", Path.class, Path.class); return (CoreContainer) ReflectionUtils.invokeMethod(createAndLoadMethod, null, FileSystems.getDefault().getPath(solrHomeDirectory), FileSystems.getDefault().getPath(solrXmlFile.getPath())); }
[ "private", "CoreContainer", "createCoreContainer", "(", "String", "solrHomeDirectory", ",", "File", "solrXmlFile", ")", "{", "Method", "createAndLoadMethod", "=", "ClassUtils", ".", "getStaticMethod", "(", "CoreContainer", ".", "class", ",", "\"createAndLoad\"", ",", "String", ".", "class", ",", "File", ".", "class", ")", ";", "if", "(", "createAndLoadMethod", "!=", "null", ")", "{", "return", "(", "CoreContainer", ")", "ReflectionUtils", ".", "invokeMethod", "(", "createAndLoadMethod", ",", "null", ",", "solrHomeDirectory", ",", "solrXmlFile", ")", ";", "}", "createAndLoadMethod", "=", "ClassUtils", ".", "getStaticMethod", "(", "CoreContainer", ".", "class", ",", "\"createAndLoad\"", ",", "Path", ".", "class", ",", "Path", ".", "class", ")", ";", "return", "(", "CoreContainer", ")", "ReflectionUtils", ".", "invokeMethod", "(", "createAndLoadMethod", ",", "null", ",", "FileSystems", ".", "getDefault", "(", ")", ".", "getPath", "(", "solrHomeDirectory", ")", ",", "FileSystems", ".", "getDefault", "(", ")", ".", "getPath", "(", "solrXmlFile", ".", "getPath", "(", ")", ")", ")", ";", "}" ]
Create {@link CoreContainer} for Solr version 4.4+ and handle changes in . @param solrHomeDirectory @param solrXmlFile @return
[ "Create", "{", "@link", "CoreContainer", "}", "for", "Solr", "version", "4", ".", "4", "+", "and", "handle", "changes", "in", "." ]
train
https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java#L140-L152
TakahikoKawasaki/nv-websocket-client
src/main/java/com/neovisionaries/ws/client/WebSocketFactory.java
WebSocketFactory.createSocket
public WebSocket createSocket(URL url, int timeout) throws IOException { """ Create a WebSocket. <p> This method is an alias of {@link #createSocket(URI, int) createSocket}{@code (url.}{@link URL#toURI() toURI()}{@code , timeout)}. </p> @param url The URL of the WebSocket endpoint on the server side. @param timeout The timeout value in milliseconds for socket connection. @return A WebSocket. @throws IllegalArgumentException The given URL is {@code null} or failed to be converted into a URI, or the given timeout value is negative. @throws IOException Failed to create a socket. Or, HTTP proxy handshake or SSL handshake failed. @since 1.10 """ if (url == null) { throw new IllegalArgumentException("The given URL is null."); } if (timeout < 0) { throw new IllegalArgumentException("The given timeout value is negative."); } try { return createSocket(url.toURI(), timeout); } catch (URISyntaxException e) { throw new IllegalArgumentException("Failed to convert the given URL into a URI."); } }
java
public WebSocket createSocket(URL url, int timeout) throws IOException { if (url == null) { throw new IllegalArgumentException("The given URL is null."); } if (timeout < 0) { throw new IllegalArgumentException("The given timeout value is negative."); } try { return createSocket(url.toURI(), timeout); } catch (URISyntaxException e) { throw new IllegalArgumentException("Failed to convert the given URL into a URI."); } }
[ "public", "WebSocket", "createSocket", "(", "URL", "url", ",", "int", "timeout", ")", "throws", "IOException", "{", "if", "(", "url", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The given URL is null.\"", ")", ";", "}", "if", "(", "timeout", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The given timeout value is negative.\"", ")", ";", "}", "try", "{", "return", "createSocket", "(", "url", ".", "toURI", "(", ")", ",", "timeout", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Failed to convert the given URL into a URI.\"", ")", ";", "}", "}" ]
Create a WebSocket. <p> This method is an alias of {@link #createSocket(URI, int) createSocket}{@code (url.}{@link URL#toURI() toURI()}{@code , timeout)}. </p> @param url The URL of the WebSocket endpoint on the server side. @param timeout The timeout value in milliseconds for socket connection. @return A WebSocket. @throws IllegalArgumentException The given URL is {@code null} or failed to be converted into a URI, or the given timeout value is negative. @throws IOException Failed to create a socket. Or, HTTP proxy handshake or SSL handshake failed. @since 1.10
[ "Create", "a", "WebSocket", "." ]
train
https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocketFactory.java#L445-L465
jankotek/mapdb
src/main/java/org/mapdb/io/DataIO.java
DataIO.packRecid
static public void packRecid(DataOutput2 out, long value) throws IOException { """ Pack RECID into output stream with 3 bit checksum. It will occupy 1-10 bytes depending on value (lower values occupy smaller space) @param out String to put value into @param value to be serialized, must be non-negative @throws java.io.IOException in case of IO error """ value = DataIO.parity1Set(value<<1); out.writePackedLong(value); }
java
static public void packRecid(DataOutput2 out, long value) throws IOException { value = DataIO.parity1Set(value<<1); out.writePackedLong(value); }
[ "static", "public", "void", "packRecid", "(", "DataOutput2", "out", ",", "long", "value", ")", "throws", "IOException", "{", "value", "=", "DataIO", ".", "parity1Set", "(", "value", "<<", "1", ")", ";", "out", ".", "writePackedLong", "(", "value", ")", ";", "}" ]
Pack RECID into output stream with 3 bit checksum. It will occupy 1-10 bytes depending on value (lower values occupy smaller space) @param out String to put value into @param value to be serialized, must be non-negative @throws java.io.IOException in case of IO error
[ "Pack", "RECID", "into", "output", "stream", "with", "3", "bit", "checksum", ".", "It", "will", "occupy", "1", "-", "10", "bytes", "depending", "on", "value", "(", "lower", "values", "occupy", "smaller", "space", ")" ]
train
https://github.com/jankotek/mapdb/blob/dfd873b2b9cc4e299228839c100adf93a98f1903/src/main/java/org/mapdb/io/DataIO.java#L186-L189
DataArt/CalculationEngine
calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataSetConverters.java
DataSetConverters.toWorkbook
static Workbook toWorkbook(final IDataSet dataSet, final Workbook formatting) { """ Converts {@link IDataSet} to {@link Workbook}. The result {@link Workbook} is created from @param formatting. """ Workbook result = formatting == null ? ConverterUtils.newWorkbook() : ConverterUtils.clearContent(formatting); Sheet sheet = result.createSheet(dataSet.getName()); for (IDsRow row : dataSet) { Row wbRow = sheet.createRow(row.index() - 1); for (IDsCell cell : row) { Cell wbCell = wbRow.createCell(cell.index() - 1); ConverterUtils.populateCellValue(wbCell, cell.getValue()); } } return result; }
java
static Workbook toWorkbook(final IDataSet dataSet, final Workbook formatting) { Workbook result = formatting == null ? ConverterUtils.newWorkbook() : ConverterUtils.clearContent(formatting); Sheet sheet = result.createSheet(dataSet.getName()); for (IDsRow row : dataSet) { Row wbRow = sheet.createRow(row.index() - 1); for (IDsCell cell : row) { Cell wbCell = wbRow.createCell(cell.index() - 1); ConverterUtils.populateCellValue(wbCell, cell.getValue()); } } return result; }
[ "static", "Workbook", "toWorkbook", "(", "final", "IDataSet", "dataSet", ",", "final", "Workbook", "formatting", ")", "{", "Workbook", "result", "=", "formatting", "==", "null", "?", "ConverterUtils", ".", "newWorkbook", "(", ")", ":", "ConverterUtils", ".", "clearContent", "(", "formatting", ")", ";", "Sheet", "sheet", "=", "result", ".", "createSheet", "(", "dataSet", ".", "getName", "(", ")", ")", ";", "for", "(", "IDsRow", "row", ":", "dataSet", ")", "{", "Row", "wbRow", "=", "sheet", ".", "createRow", "(", "row", ".", "index", "(", ")", "-", "1", ")", ";", "for", "(", "IDsCell", "cell", ":", "row", ")", "{", "Cell", "wbCell", "=", "wbRow", ".", "createCell", "(", "cell", ".", "index", "(", ")", "-", "1", ")", ";", "ConverterUtils", ".", "populateCellValue", "(", "wbCell", ",", "cell", ".", "getValue", "(", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Converts {@link IDataSet} to {@link Workbook}. The result {@link Workbook} is created from @param formatting.
[ "Converts", "{" ]
train
https://github.com/DataArt/CalculationEngine/blob/34ce1d9c1f9b57a502906b274311d28580b134e5/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataSetConverters.java#L133-L146
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java
HttpHeaders.setDateHeader
@Deprecated public static void setDateHeader(HttpMessage message, CharSequence name, Date value) { """ @deprecated Use {@link #set(CharSequence, Object)} instead. Sets a new date header with the specified name and value. If there is an existing header with the same name, the existing header is removed. The specified value is formatted as defined in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a> """ if (value != null) { message.headers().set(name, DateFormatter.format(value)); } else { message.headers().set(name, null); } }
java
@Deprecated public static void setDateHeader(HttpMessage message, CharSequence name, Date value) { if (value != null) { message.headers().set(name, DateFormatter.format(value)); } else { message.headers().set(name, null); } }
[ "@", "Deprecated", "public", "static", "void", "setDateHeader", "(", "HttpMessage", "message", ",", "CharSequence", "name", ",", "Date", "value", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "message", ".", "headers", "(", ")", ".", "set", "(", "name", ",", "DateFormatter", ".", "format", "(", "value", ")", ")", ";", "}", "else", "{", "message", ".", "headers", "(", ")", ".", "set", "(", "name", ",", "null", ")", ";", "}", "}" ]
@deprecated Use {@link #set(CharSequence, Object)} instead. Sets a new date header with the specified name and value. If there is an existing header with the same name, the existing header is removed. The specified value is formatted as defined in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">RFC2616</a>
[ "@deprecated", "Use", "{", "@link", "#set", "(", "CharSequence", "Object", ")", "}", "instead", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java#L900-L907
alipay/sofa-rpc
extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/http/Http2ClientInitializer.java
Http2ClientInitializer.configureClearTextWithHttpUpgrade
private void configureClearTextWithHttpUpgrade(SocketChannel ch) { """ Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2. """ HttpClientCodec sourceCodec = new HttpClientCodec(); Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler); HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536); ch.pipeline().addLast(sourceCodec, upgradeHandler, new UpgradeRequestHandler(), new UserEventLogger()); }
java
private void configureClearTextWithHttpUpgrade(SocketChannel ch) { HttpClientCodec sourceCodec = new HttpClientCodec(); Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler); HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536); ch.pipeline().addLast(sourceCodec, upgradeHandler, new UpgradeRequestHandler(), new UserEventLogger()); }
[ "private", "void", "configureClearTextWithHttpUpgrade", "(", "SocketChannel", "ch", ")", "{", "HttpClientCodec", "sourceCodec", "=", "new", "HttpClientCodec", "(", ")", ";", "Http2ClientUpgradeCodec", "upgradeCodec", "=", "new", "Http2ClientUpgradeCodec", "(", "connectionHandler", ")", ";", "HttpClientUpgradeHandler", "upgradeHandler", "=", "new", "HttpClientUpgradeHandler", "(", "sourceCodec", ",", "upgradeCodec", ",", "65536", ")", ";", "ch", ".", "pipeline", "(", ")", ".", "addLast", "(", "sourceCodec", ",", "upgradeHandler", ",", "new", "UpgradeRequestHandler", "(", ")", ",", "new", "UserEventLogger", "(", ")", ")", ";", "}" ]
Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
[ "Configure", "the", "pipeline", "for", "a", "cleartext", "upgrade", "from", "HTTP", "to", "HTTP", "/", "2", "." ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/http/Http2ClientInitializer.java#L133-L142
ReactiveX/RxJavaString
src/main/java/rx/observables/StringObservable.java
StringObservable.byLine
public static Observable<String> byLine(Observable<String> source) { """ Splits the {@link Observable} of Strings by line ending characters in a platform independent way. It is equivalent to <pre>split(src, "(\\r\\n)|\\n|\\r|\\u0085|\\u2028|\\u2029")</pre> <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.byLine.png" alt=""> @param source @return the Observable conaining the split lines of the source @see StringObservable#split(Observable, Pattern) """ return split(source, ByLinePatternHolder.BY_LINE); }
java
public static Observable<String> byLine(Observable<String> source) { return split(source, ByLinePatternHolder.BY_LINE); }
[ "public", "static", "Observable", "<", "String", ">", "byLine", "(", "Observable", "<", "String", ">", "source", ")", "{", "return", "split", "(", "source", ",", "ByLinePatternHolder", ".", "BY_LINE", ")", ";", "}" ]
Splits the {@link Observable} of Strings by line ending characters in a platform independent way. It is equivalent to <pre>split(src, "(\\r\\n)|\\n|\\r|\\u0085|\\u2028|\\u2029")</pre> <p> <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.byLine.png" alt=""> @param source @return the Observable conaining the split lines of the source @see StringObservable#split(Observable, Pattern)
[ "Splits", "the", "{", "@link", "Observable", "}", "of", "Strings", "by", "line", "ending", "characters", "in", "a", "platform", "independent", "way", ".", "It", "is", "equivalent", "to", "<pre", ">", "split", "(", "src", "(", "\\\\", "r", "\\\\", "n", ")", "|", "\\\\", "n|", "\\\\", "r|", "\\\\", "u0085|", "\\\\", "u2028|", "\\\\", "u2029", ")", "<", "/", "pre", ">", "<p", ">", "<img", "width", "=", "640", "src", "=", "https", ":", "//", "raw", ".", "github", ".", "com", "/", "wiki", "/", "ReactiveX", "/", "RxJava", "/", "images", "/", "rx", "-", "operators", "/", "St", ".", "byLine", ".", "png", "alt", "=", ">" ]
train
https://github.com/ReactiveX/RxJavaString/blob/3e73b759ff7bffd5d2e1c753630c5408cb5f9e5e/src/main/java/rx/observables/StringObservable.java#L492-L494
flow/caustic
api/src/main/java/com/flowpowered/caustic/api/util/CausticUtil.java
CausticUtil.getImageData
public static ByteBuffer getImageData(BufferedImage image, Format format) { """ Gets the {@link java.awt.image.BufferedImage}'s data as a {@link java.nio.ByteBuffer}. The image data reading is done according to the {@link com.flowpowered.caustic.api.gl.Texture.Format}. The returned buffer is flipped an ready for reading. @param image The image to extract the data from @param format The format of the image data @return The flipped buffer containing the decoded image data """ final int width = image.getWidth(); final int height = image.getHeight(); final int type = image.getType(); final int[] pixels; if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) { pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); } else { pixels = new int[width * height]; image.getRGB(0, 0, width, height, pixels, 0, width); } return getImageData(pixels, format, width, height); }
java
public static ByteBuffer getImageData(BufferedImage image, Format format) { final int width = image.getWidth(); final int height = image.getHeight(); final int type = image.getType(); final int[] pixels; if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) { pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); } else { pixels = new int[width * height]; image.getRGB(0, 0, width, height, pixels, 0, width); } return getImageData(pixels, format, width, height); }
[ "public", "static", "ByteBuffer", "getImageData", "(", "BufferedImage", "image", ",", "Format", "format", ")", "{", "final", "int", "width", "=", "image", ".", "getWidth", "(", ")", ";", "final", "int", "height", "=", "image", ".", "getHeight", "(", ")", ";", "final", "int", "type", "=", "image", ".", "getType", "(", ")", ";", "final", "int", "[", "]", "pixels", ";", "if", "(", "type", "==", "BufferedImage", ".", "TYPE_INT_ARGB", "||", "type", "==", "BufferedImage", ".", "TYPE_INT_RGB", ")", "{", "pixels", "=", "(", "(", "DataBufferInt", ")", "image", ".", "getRaster", "(", ")", ".", "getDataBuffer", "(", ")", ")", ".", "getData", "(", ")", ";", "}", "else", "{", "pixels", "=", "new", "int", "[", "width", "*", "height", "]", ";", "image", ".", "getRGB", "(", "0", ",", "0", ",", "width", ",", "height", ",", "pixels", ",", "0", ",", "width", ")", ";", "}", "return", "getImageData", "(", "pixels", ",", "format", ",", "width", ",", "height", ")", ";", "}" ]
Gets the {@link java.awt.image.BufferedImage}'s data as a {@link java.nio.ByteBuffer}. The image data reading is done according to the {@link com.flowpowered.caustic.api.gl.Texture.Format}. The returned buffer is flipped an ready for reading. @param image The image to extract the data from @param format The format of the image data @return The flipped buffer containing the decoded image data
[ "Gets", "the", "{", "@link", "java", ".", "awt", ".", "image", ".", "BufferedImage", "}", "s", "data", "as", "a", "{", "@link", "java", ".", "nio", ".", "ByteBuffer", "}", ".", "The", "image", "data", "reading", "is", "done", "according", "to", "the", "{", "@link", "com", ".", "flowpowered", ".", "caustic", ".", "api", ".", "gl", ".", "Texture", ".", "Format", "}", ".", "The", "returned", "buffer", "is", "flipped", "an", "ready", "for", "reading", "." ]
train
https://github.com/flow/caustic/blob/88652fcf0621ce158a0e92ce4c570ed6b1f6fca9/api/src/main/java/com/flowpowered/caustic/api/util/CausticUtil.java#L144-L156
sangupta/jerry-services
src/main/java/com/sangupta/jerry/quartz/service/impl/DefaultQuartzServiceImpl.java
DefaultQuartzServiceImpl.executeJob
public boolean executeJob(String jobName, String jobGroupName) { """ Fire the given job in given group. @param jobName the name of the job @param jobGroupName the group name of the job @return <code>true</code> if job was fired, <code>false</code> otherwise @see QuartzService#executeJob(String, String) """ try { this.scheduler.triggerJob(new JobKey(jobName, jobGroupName)); return true; } catch (SchedulerException e) { logger.error("error executing job: " + jobName + " in group: " + jobGroupName, e); } return false; }
java
public boolean executeJob(String jobName, String jobGroupName) { try { this.scheduler.triggerJob(new JobKey(jobName, jobGroupName)); return true; } catch (SchedulerException e) { logger.error("error executing job: " + jobName + " in group: " + jobGroupName, e); } return false; }
[ "public", "boolean", "executeJob", "(", "String", "jobName", ",", "String", "jobGroupName", ")", "{", "try", "{", "this", ".", "scheduler", ".", "triggerJob", "(", "new", "JobKey", "(", "jobName", ",", "jobGroupName", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "SchedulerException", "e", ")", "{", "logger", ".", "error", "(", "\"error executing job: \"", "+", "jobName", "+", "\" in group: \"", "+", "jobGroupName", ",", "e", ")", ";", "}", "return", "false", ";", "}" ]
Fire the given job in given group. @param jobName the name of the job @param jobGroupName the group name of the job @return <code>true</code> if job was fired, <code>false</code> otherwise @see QuartzService#executeJob(String, String)
[ "Fire", "the", "given", "job", "in", "given", "group", "." ]
train
https://github.com/sangupta/jerry-services/blob/25ff6577445850916425c72068d654c08eba9bcc/src/main/java/com/sangupta/jerry/quartz/service/impl/DefaultQuartzServiceImpl.java#L197-L205
btaz/data-util
src/main/java/com/btaz/util/unit/ResourceUtil.java
ResourceUtil.writeStringToTempFile
public static File writeStringToTempFile(String prefix, String suffix, String data) throws IOException { """ This method writes all data from a string to a temp file. The file will be automatically deleted on JVM shutdown. @param prefix file prefix i.e. "abc" in abc.txt @param suffix file suffix i.e. ".txt" in abc.txt @param data string containing the data to write to the file @return <code>File</code> object @throws IOException IO exception """ File testFile = File.createTempFile(prefix, suffix); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( testFile.getAbsoluteFile(), false),DataUtilDefaults.charSet)); writer.write(data); writer.flush(); writer.close(); return testFile; }
java
public static File writeStringToTempFile(String prefix, String suffix, String data) throws IOException { File testFile = File.createTempFile(prefix, suffix); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( testFile.getAbsoluteFile(), false),DataUtilDefaults.charSet)); writer.write(data); writer.flush(); writer.close(); return testFile; }
[ "public", "static", "File", "writeStringToTempFile", "(", "String", "prefix", ",", "String", "suffix", ",", "String", "data", ")", "throws", "IOException", "{", "File", "testFile", "=", "File", ".", "createTempFile", "(", "prefix", ",", "suffix", ")", ";", "BufferedWriter", "writer", "=", "new", "BufferedWriter", "(", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "testFile", ".", "getAbsoluteFile", "(", ")", ",", "false", ")", ",", "DataUtilDefaults", ".", "charSet", ")", ")", ";", "writer", ".", "write", "(", "data", ")", ";", "writer", ".", "flush", "(", ")", ";", "writer", ".", "close", "(", ")", ";", "return", "testFile", ";", "}" ]
This method writes all data from a string to a temp file. The file will be automatically deleted on JVM shutdown. @param prefix file prefix i.e. "abc" in abc.txt @param suffix file suffix i.e. ".txt" in abc.txt @param data string containing the data to write to the file @return <code>File</code> object @throws IOException IO exception
[ "This", "method", "writes", "all", "data", "from", "a", "string", "to", "a", "temp", "file", ".", "The", "file", "will", "be", "automatically", "deleted", "on", "JVM", "shutdown", "." ]
train
https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/unit/ResourceUtil.java#L94-L103
Jasig/uPortal
uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java
PropertiesManager.getPropertyAsByte
public static byte getPropertyAsByte(String name) throws MissingPropertyException, BadPropertyException { """ Returns the value of a property for a given name as a <code>byte</code> @param name the name of the requested property @return value the property's value as a <code>byte</code> @throws MissingPropertyException - if the property is not set @throws BadPropertyException - if the property cannot be parsed as a byte """ if (PropertiesManager.props == null) loadProps(); try { return Byte.parseByte(getProperty(name)); } catch (NumberFormatException nfe) { throw new BadPropertyException(name, getProperty(name), "byte"); } }
java
public static byte getPropertyAsByte(String name) throws MissingPropertyException, BadPropertyException { if (PropertiesManager.props == null) loadProps(); try { return Byte.parseByte(getProperty(name)); } catch (NumberFormatException nfe) { throw new BadPropertyException(name, getProperty(name), "byte"); } }
[ "public", "static", "byte", "getPropertyAsByte", "(", "String", "name", ")", "throws", "MissingPropertyException", ",", "BadPropertyException", "{", "if", "(", "PropertiesManager", ".", "props", "==", "null", ")", "loadProps", "(", ")", ";", "try", "{", "return", "Byte", ".", "parseByte", "(", "getProperty", "(", "name", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "nfe", ")", "{", "throw", "new", "BadPropertyException", "(", "name", ",", "getProperty", "(", "name", ")", ",", "\"byte\"", ")", ";", "}", "}" ]
Returns the value of a property for a given name as a <code>byte</code> @param name the name of the requested property @return value the property's value as a <code>byte</code> @throws MissingPropertyException - if the property is not set @throws BadPropertyException - if the property cannot be parsed as a byte
[ "Returns", "the", "value", "of", "a", "property", "for", "a", "given", "name", "as", "a", "<code", ">", "byte<", "/", "code", ">" ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-core/src/main/java/org/apereo/portal/properties/PropertiesManager.java#L201-L209
jamesagnew/hapi-fhir
hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java
UrlUtil.constructAbsoluteUrl
public static String constructAbsoluteUrl(String theBase, String theEndpoint) { """ Resolve a relative URL - THIS METHOD WILL NOT FAIL but will log a warning and return theEndpoint if the input is invalid. """ if (theEndpoint == null) { return null; } if (isAbsolute(theEndpoint)) { return theEndpoint; } if (theBase == null) { return theEndpoint; } try { return new URL(new URL(theBase), theEndpoint).toString(); } catch (MalformedURLException e) { ourLog.warn("Failed to resolve relative URL[" + theEndpoint + "] against absolute base[" + theBase + "]", e); return theEndpoint; } }
java
public static String constructAbsoluteUrl(String theBase, String theEndpoint) { if (theEndpoint == null) { return null; } if (isAbsolute(theEndpoint)) { return theEndpoint; } if (theBase == null) { return theEndpoint; } try { return new URL(new URL(theBase), theEndpoint).toString(); } catch (MalformedURLException e) { ourLog.warn("Failed to resolve relative URL[" + theEndpoint + "] against absolute base[" + theBase + "]", e); return theEndpoint; } }
[ "public", "static", "String", "constructAbsoluteUrl", "(", "String", "theBase", ",", "String", "theEndpoint", ")", "{", "if", "(", "theEndpoint", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "isAbsolute", "(", "theEndpoint", ")", ")", "{", "return", "theEndpoint", ";", "}", "if", "(", "theBase", "==", "null", ")", "{", "return", "theEndpoint", ";", "}", "try", "{", "return", "new", "URL", "(", "new", "URL", "(", "theBase", ")", ",", "theEndpoint", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "ourLog", ".", "warn", "(", "\"Failed to resolve relative URL[\"", "+", "theEndpoint", "+", "\"] against absolute base[\"", "+", "theBase", "+", "\"]\"", ",", "e", ")", ";", "return", "theEndpoint", ";", "}", "}" ]
Resolve a relative URL - THIS METHOD WILL NOT FAIL but will log a warning and return theEndpoint if the input is invalid.
[ "Resolve", "a", "relative", "URL", "-", "THIS", "METHOD", "WILL", "NOT", "FAIL", "but", "will", "log", "a", "warning", "and", "return", "theEndpoint", "if", "the", "input", "is", "invalid", "." ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java#L53-L70
alkacon/opencms-core
src-gwt/org/opencms/ade/upload/client/ui/CmsDialogUploadButtonHandler.java
CmsDialogUploadButtonHandler.openDialogWithFiles
public void openDialogWithFiles(List<CmsFileInfo> files) { """ Opens the upload dialog for the given file references.<p> @param files the file references """ if (m_uploadDialog == null) { try { m_uploadDialog = GWT.create(CmsUploadDialogImpl.class); I_CmsUploadContext context = m_contextFactory.get(); m_uploadDialog.setContext(context); updateDialog(); if (m_button != null) { // the current upload button is located outside the dialog, reinitialize it with a new button handler instance m_button.reinitButton( new CmsDialogUploadButtonHandler(m_contextFactory, m_targetFolder, m_isTargetRootPath)); } } catch (Exception e) { CmsErrorDialog.handleException( new Exception( "Deserialization of dialog data failed. This may be caused by expired java-script resources, please clear your browser cache and try again.", e)); return; } } m_uploadDialog.addFiles(files); if (m_button != null) { m_button.createFileInput(); } }
java
public void openDialogWithFiles(List<CmsFileInfo> files) { if (m_uploadDialog == null) { try { m_uploadDialog = GWT.create(CmsUploadDialogImpl.class); I_CmsUploadContext context = m_contextFactory.get(); m_uploadDialog.setContext(context); updateDialog(); if (m_button != null) { // the current upload button is located outside the dialog, reinitialize it with a new button handler instance m_button.reinitButton( new CmsDialogUploadButtonHandler(m_contextFactory, m_targetFolder, m_isTargetRootPath)); } } catch (Exception e) { CmsErrorDialog.handleException( new Exception( "Deserialization of dialog data failed. This may be caused by expired java-script resources, please clear your browser cache and try again.", e)); return; } } m_uploadDialog.addFiles(files); if (m_button != null) { m_button.createFileInput(); } }
[ "public", "void", "openDialogWithFiles", "(", "List", "<", "CmsFileInfo", ">", "files", ")", "{", "if", "(", "m_uploadDialog", "==", "null", ")", "{", "try", "{", "m_uploadDialog", "=", "GWT", ".", "create", "(", "CmsUploadDialogImpl", ".", "class", ")", ";", "I_CmsUploadContext", "context", "=", "m_contextFactory", ".", "get", "(", ")", ";", "m_uploadDialog", ".", "setContext", "(", "context", ")", ";", "updateDialog", "(", ")", ";", "if", "(", "m_button", "!=", "null", ")", "{", "// the current upload button is located outside the dialog, reinitialize it with a new button handler instance\r", "m_button", ".", "reinitButton", "(", "new", "CmsDialogUploadButtonHandler", "(", "m_contextFactory", ",", "m_targetFolder", ",", "m_isTargetRootPath", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "CmsErrorDialog", ".", "handleException", "(", "new", "Exception", "(", "\"Deserialization of dialog data failed. This may be caused by expired java-script resources, please clear your browser cache and try again.\"", ",", "e", ")", ")", ";", "return", ";", "}", "}", "m_uploadDialog", ".", "addFiles", "(", "files", ")", ";", "if", "(", "m_button", "!=", "null", ")", "{", "m_button", ".", "createFileInput", "(", ")", ";", "}", "}" ]
Opens the upload dialog for the given file references.<p> @param files the file references
[ "Opens", "the", "upload", "dialog", "for", "the", "given", "file", "references", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/upload/client/ui/CmsDialogUploadButtonHandler.java#L144-L169
JOML-CI/JOML
src/org/joml/Quaternionf.java
Quaternionf.rotateAxis
public Quaternionf rotateAxis(float angle, float axisX, float axisY, float axisZ) { """ Apply a rotation to <code>this</code> quaternion rotating the given radians about the specified axis. <p> If <code>Q</code> is <code>this</code> quaternion and <code>R</code> the quaternion representing the specified rotation, then the new quaternion will be <code>Q * R</code>. So when transforming a vector <code>v</code> with the new quaternion by using <code>Q * R * v</code>, the rotation added by this method will be applied first! @see #rotateAxis(float, float, float, float, Quaternionf) @param angle the angle in radians to rotate about the specified axis @param axisX the x coordinate of the rotation axis @param axisY the y coordinate of the rotation axis @param axisZ the z coordinate of the rotation axis @return this """ return rotateAxis(angle, axisX, axisY, axisZ, this); }
java
public Quaternionf rotateAxis(float angle, float axisX, float axisY, float axisZ) { return rotateAxis(angle, axisX, axisY, axisZ, this); }
[ "public", "Quaternionf", "rotateAxis", "(", "float", "angle", ",", "float", "axisX", ",", "float", "axisY", ",", "float", "axisZ", ")", "{", "return", "rotateAxis", "(", "angle", ",", "axisX", ",", "axisY", ",", "axisZ", ",", "this", ")", ";", "}" ]
Apply a rotation to <code>this</code> quaternion rotating the given radians about the specified axis. <p> If <code>Q</code> is <code>this</code> quaternion and <code>R</code> the quaternion representing the specified rotation, then the new quaternion will be <code>Q * R</code>. So when transforming a vector <code>v</code> with the new quaternion by using <code>Q * R * v</code>, the rotation added by this method will be applied first! @see #rotateAxis(float, float, float, float, Quaternionf) @param angle the angle in radians to rotate about the specified axis @param axisX the x coordinate of the rotation axis @param axisY the y coordinate of the rotation axis @param axisZ the z coordinate of the rotation axis @return this
[ "Apply", "a", "rotation", "to", "<code", ">", "this<", "/", "code", ">", "quaternion", "rotating", "the", "given", "radians", "about", "the", "specified", "axis", ".", "<p", ">", "If", "<code", ">", "Q<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "quaternion", "and", "<code", ">", "R<", "/", "code", ">", "the", "quaternion", "representing", "the", "specified", "rotation", "then", "the", "new", "quaternion", "will", "be", "<code", ">", "Q", "*", "R<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "quaternion", "by", "using", "<code", ">", "Q", "*", "R", "*", "v<", "/", "code", ">", "the", "rotation", "added", "by", "this", "method", "will", "be", "applied", "first!" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L2601-L2603
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/spout/CheckpointSpout.java
CheckpointSpout.loadCheckpointState
private KeyValueState<String, CheckPointState> loadCheckpointState(Map conf, TopologyContext ctx) { """ Loads the last saved checkpoint state the from persistent storage. """ String namespace = ctx.getThisComponentId() + "-" + ctx.getThisTaskId(); KeyValueState<String, CheckPointState> state = (KeyValueState<String, CheckPointState>) StateFactory.getState(namespace, conf, ctx); if (state.get(TX_STATE_KEY) == null) { CheckPointState txState = new CheckPointState(-1, CheckPointState.State.COMMITTED); state.put(TX_STATE_KEY, txState); state.commit(); LOG.debug("Initialized checkpoint spout state with txState {}", txState); } else { LOG.debug("Got checkpoint spout state {}", state.get(TX_STATE_KEY)); } return state; }
java
private KeyValueState<String, CheckPointState> loadCheckpointState(Map conf, TopologyContext ctx) { String namespace = ctx.getThisComponentId() + "-" + ctx.getThisTaskId(); KeyValueState<String, CheckPointState> state = (KeyValueState<String, CheckPointState>) StateFactory.getState(namespace, conf, ctx); if (state.get(TX_STATE_KEY) == null) { CheckPointState txState = new CheckPointState(-1, CheckPointState.State.COMMITTED); state.put(TX_STATE_KEY, txState); state.commit(); LOG.debug("Initialized checkpoint spout state with txState {}", txState); } else { LOG.debug("Got checkpoint spout state {}", state.get(TX_STATE_KEY)); } return state; }
[ "private", "KeyValueState", "<", "String", ",", "CheckPointState", ">", "loadCheckpointState", "(", "Map", "conf", ",", "TopologyContext", "ctx", ")", "{", "String", "namespace", "=", "ctx", ".", "getThisComponentId", "(", ")", "+", "\"-\"", "+", "ctx", ".", "getThisTaskId", "(", ")", ";", "KeyValueState", "<", "String", ",", "CheckPointState", ">", "state", "=", "(", "KeyValueState", "<", "String", ",", "CheckPointState", ">", ")", "StateFactory", ".", "getState", "(", "namespace", ",", "conf", ",", "ctx", ")", ";", "if", "(", "state", ".", "get", "(", "TX_STATE_KEY", ")", "==", "null", ")", "{", "CheckPointState", "txState", "=", "new", "CheckPointState", "(", "-", "1", ",", "CheckPointState", ".", "State", ".", "COMMITTED", ")", ";", "state", ".", "put", "(", "TX_STATE_KEY", ",", "txState", ")", ";", "state", ".", "commit", "(", ")", ";", "LOG", ".", "debug", "(", "\"Initialized checkpoint spout state with txState {}\"", ",", "txState", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Got checkpoint spout state {}\"", ",", "state", ".", "get", "(", "TX_STATE_KEY", ")", ")", ";", "}", "return", "state", ";", "}" ]
Loads the last saved checkpoint state the from persistent storage.
[ "Loads", "the", "last", "saved", "checkpoint", "state", "the", "from", "persistent", "storage", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/spout/CheckpointSpout.java#L134-L147
undertow-io/undertow
core/src/main/java/io/undertow/predicate/PredicatesHandler.java
PredicatesHandler.addPredicatedHandler
public PredicatesHandler addPredicatedHandler(final Predicate predicate, final HandlerWrapper handlerWrapper, final HandlerWrapper elseBranch) { """ Adds a new predicated handler. <p> @param predicate @param handlerWrapper """ Holder[] old = handlers; Holder[] handlers = new Holder[old.length + 1]; System.arraycopy(old, 0, handlers, 0, old.length); HttpHandler elseHandler = elseBranch != null ? elseBranch.wrap(this) : null; handlers[old.length] = new Holder(predicate, handlerWrapper.wrap(this), elseHandler); this.handlers = handlers; return this; }
java
public PredicatesHandler addPredicatedHandler(final Predicate predicate, final HandlerWrapper handlerWrapper, final HandlerWrapper elseBranch) { Holder[] old = handlers; Holder[] handlers = new Holder[old.length + 1]; System.arraycopy(old, 0, handlers, 0, old.length); HttpHandler elseHandler = elseBranch != null ? elseBranch.wrap(this) : null; handlers[old.length] = new Holder(predicate, handlerWrapper.wrap(this), elseHandler); this.handlers = handlers; return this; }
[ "public", "PredicatesHandler", "addPredicatedHandler", "(", "final", "Predicate", "predicate", ",", "final", "HandlerWrapper", "handlerWrapper", ",", "final", "HandlerWrapper", "elseBranch", ")", "{", "Holder", "[", "]", "old", "=", "handlers", ";", "Holder", "[", "]", "handlers", "=", "new", "Holder", "[", "old", ".", "length", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "old", ",", "0", ",", "handlers", ",", "0", ",", "old", ".", "length", ")", ";", "HttpHandler", "elseHandler", "=", "elseBranch", "!=", "null", "?", "elseBranch", ".", "wrap", "(", "this", ")", ":", "null", ";", "handlers", "[", "old", ".", "length", "]", "=", "new", "Holder", "(", "predicate", ",", "handlerWrapper", ".", "wrap", "(", "this", ")", ",", "elseHandler", ")", ";", "this", ".", "handlers", "=", "handlers", ";", "return", "this", ";", "}" ]
Adds a new predicated handler. <p> @param predicate @param handlerWrapper
[ "Adds", "a", "new", "predicated", "handler", ".", "<p", ">" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/predicate/PredicatesHandler.java#L125-L133
perwendel/spark
src/main/java/spark/CustomErrorPages.java
CustomErrorPages.getFor
public static Object getFor(int status, Request request, Response response) { """ Gets the custom error page for a given status code. If the custom error page is a route, the output of its handle method is returned. If the custom error page is a String, it is returned as an Object. @param status @param request @param response @return Object representing the custom error page """ Object customRenderer = CustomErrorPages.getInstance().customPages.get(status); Object customPage = CustomErrorPages.getInstance().getDefaultFor(status); if (customRenderer instanceof String) { customPage = customRenderer; } else if (customRenderer instanceof Route) { try { customPage = ((Route) customRenderer).handle(request, response); } catch (Exception e) { // The custom page renderer is causing an internal server error. Log exception as a warning and use default page instead LOG.warn("Custom error page handler for status code {} has thrown an exception: {}. Using default page instead.", status, e.getMessage()); } } return customPage; }
java
public static Object getFor(int status, Request request, Response response) { Object customRenderer = CustomErrorPages.getInstance().customPages.get(status); Object customPage = CustomErrorPages.getInstance().getDefaultFor(status); if (customRenderer instanceof String) { customPage = customRenderer; } else if (customRenderer instanceof Route) { try { customPage = ((Route) customRenderer).handle(request, response); } catch (Exception e) { // The custom page renderer is causing an internal server error. Log exception as a warning and use default page instead LOG.warn("Custom error page handler for status code {} has thrown an exception: {}. Using default page instead.", status, e.getMessage()); } } return customPage; }
[ "public", "static", "Object", "getFor", "(", "int", "status", ",", "Request", "request", ",", "Response", "response", ")", "{", "Object", "customRenderer", "=", "CustomErrorPages", ".", "getInstance", "(", ")", ".", "customPages", ".", "get", "(", "status", ")", ";", "Object", "customPage", "=", "CustomErrorPages", ".", "getInstance", "(", ")", ".", "getDefaultFor", "(", "status", ")", ";", "if", "(", "customRenderer", "instanceof", "String", ")", "{", "customPage", "=", "customRenderer", ";", "}", "else", "if", "(", "customRenderer", "instanceof", "Route", ")", "{", "try", "{", "customPage", "=", "(", "(", "Route", ")", "customRenderer", ")", ".", "handle", "(", "request", ",", "response", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// The custom page renderer is causing an internal server error. Log exception as a warning and use default page instead", "LOG", ".", "warn", "(", "\"Custom error page handler for status code {} has thrown an exception: {}. Using default page instead.\"", ",", "status", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "return", "customPage", ";", "}" ]
Gets the custom error page for a given status code. If the custom error page is a route, the output of its handle method is returned. If the custom error page is a String, it is returned as an Object. @param status @param request @param response @return Object representing the custom error page
[ "Gets", "the", "custom", "error", "page", "for", "a", "given", "status", "code", ".", "If", "the", "custom", "error", "page", "is", "a", "route", "the", "output", "of", "its", "handle", "method", "is", "returned", ".", "If", "the", "custom", "error", "page", "is", "a", "String", "it", "is", "returned", "as", "an", "Object", "." ]
train
https://github.com/perwendel/spark/blob/080fb1f9d6e580f6742e9589044c7420d3157b8b/src/main/java/spark/CustomErrorPages.java#L54-L71
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
FormLayout.setColumnSpec
public void setColumnSpec(int columnIndex, ColumnSpec columnSpec) { """ Sets the ColumnSpec at the specified column index. @param columnIndex the index of the column to be changed @param columnSpec the ColumnSpec to be set @throws NullPointerException if {@code columnSpec} is {@code null} @throws IndexOutOfBoundsException if the column index is out of range """ checkNotNull(columnSpec, "The column spec must not be null."); colSpecs.set(columnIndex - 1, columnSpec); }
java
public void setColumnSpec(int columnIndex, ColumnSpec columnSpec) { checkNotNull(columnSpec, "The column spec must not be null."); colSpecs.set(columnIndex - 1, columnSpec); }
[ "public", "void", "setColumnSpec", "(", "int", "columnIndex", ",", "ColumnSpec", "columnSpec", ")", "{", "checkNotNull", "(", "columnSpec", ",", "\"The column spec must not be null.\"", ")", ";", "colSpecs", ".", "set", "(", "columnIndex", "-", "1", ",", "columnSpec", ")", ";", "}" ]
Sets the ColumnSpec at the specified column index. @param columnIndex the index of the column to be changed @param columnSpec the ColumnSpec to be set @throws NullPointerException if {@code columnSpec} is {@code null} @throws IndexOutOfBoundsException if the column index is out of range
[ "Sets", "the", "ColumnSpec", "at", "the", "specified", "column", "index", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java#L458-L461
mguymon/naether
src/main/java/com/tobedevoured/naether/maven/Project.java
Project.loadPOM
public static Model loadPOM(String pomPath, String localRepo, Collection<RemoteRepository> repositories) throws ProjectException { """ Load Maven pom @param pomPath String path @param localRepo String @param repositories {@link Collection} @return {@link Model} @throws ProjectException if fails to open, read, or parse the POM """ RepositoryClient repoClient = new RepositoryClient(localRepo); NaetherModelResolver resolver = new NaetherModelResolver(repoClient, repositories); ModelBuildingRequest req = new DefaultModelBuildingRequest(); req.setProcessPlugins( false ); req.setPomFile( new File(pomPath) ); req.setModelResolver( resolver ); req.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); DefaultModelBuilder builder = (new DefaultModelBuilderFactory()).newInstance(); try { return builder.build( req ).getEffectiveModel(); } catch ( ModelBuildingException e ) { throw new ProjectException("Failed to build project from pom", e); } }
java
public static Model loadPOM(String pomPath, String localRepo, Collection<RemoteRepository> repositories) throws ProjectException { RepositoryClient repoClient = new RepositoryClient(localRepo); NaetherModelResolver resolver = new NaetherModelResolver(repoClient, repositories); ModelBuildingRequest req = new DefaultModelBuildingRequest(); req.setProcessPlugins( false ); req.setPomFile( new File(pomPath) ); req.setModelResolver( resolver ); req.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL ); DefaultModelBuilder builder = (new DefaultModelBuilderFactory()).newInstance(); try { return builder.build( req ).getEffectiveModel(); } catch ( ModelBuildingException e ) { throw new ProjectException("Failed to build project from pom", e); } }
[ "public", "static", "Model", "loadPOM", "(", "String", "pomPath", ",", "String", "localRepo", ",", "Collection", "<", "RemoteRepository", ">", "repositories", ")", "throws", "ProjectException", "{", "RepositoryClient", "repoClient", "=", "new", "RepositoryClient", "(", "localRepo", ")", ";", "NaetherModelResolver", "resolver", "=", "new", "NaetherModelResolver", "(", "repoClient", ",", "repositories", ")", ";", "ModelBuildingRequest", "req", "=", "new", "DefaultModelBuildingRequest", "(", ")", ";", "req", ".", "setProcessPlugins", "(", "false", ")", ";", "req", ".", "setPomFile", "(", "new", "File", "(", "pomPath", ")", ")", ";", "req", ".", "setModelResolver", "(", "resolver", ")", ";", "req", ".", "setValidationLevel", "(", "ModelBuildingRequest", ".", "VALIDATION_LEVEL_MINIMAL", ")", ";", "DefaultModelBuilder", "builder", "=", "(", "new", "DefaultModelBuilderFactory", "(", ")", ")", ".", "newInstance", "(", ")", ";", "try", "{", "return", "builder", ".", "build", "(", "req", ")", ".", "getEffectiveModel", "(", ")", ";", "}", "catch", "(", "ModelBuildingException", "e", ")", "{", "throw", "new", "ProjectException", "(", "\"Failed to build project from pom\"", ",", "e", ")", ";", "}", "}" ]
Load Maven pom @param pomPath String path @param localRepo String @param repositories {@link Collection} @return {@link Model} @throws ProjectException if fails to open, read, or parse the POM
[ "Load", "Maven", "pom" ]
train
https://github.com/mguymon/naether/blob/218d8fd36c0b8b6e16d66e5715975570b4560ec4/src/main/java/com/tobedevoured/naether/maven/Project.java#L132-L148
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManager.java
SlotManager.updateSlot
private boolean updateSlot(SlotID slotId, AllocationID allocationId, JobID jobId) { """ Updates a slot with the given allocation id. @param slotId to update @param allocationId specifying the current allocation of the slot @param jobId specifying the job to which the slot is allocated @return True if the slot could be updated; otherwise false """ final TaskManagerSlot slot = slots.get(slotId); if (slot != null) { final TaskManagerRegistration taskManagerRegistration = taskManagerRegistrations.get(slot.getInstanceId()); if (taskManagerRegistration != null) { updateSlotState(slot, taskManagerRegistration, allocationId, jobId); return true; } else { throw new IllegalStateException("Trying to update a slot from a TaskManager " + slot.getInstanceId() + " which has not been registered."); } } else { LOG.debug("Trying to update unknown slot with slot id {}.", slotId); return false; } }
java
private boolean updateSlot(SlotID slotId, AllocationID allocationId, JobID jobId) { final TaskManagerSlot slot = slots.get(slotId); if (slot != null) { final TaskManagerRegistration taskManagerRegistration = taskManagerRegistrations.get(slot.getInstanceId()); if (taskManagerRegistration != null) { updateSlotState(slot, taskManagerRegistration, allocationId, jobId); return true; } else { throw new IllegalStateException("Trying to update a slot from a TaskManager " + slot.getInstanceId() + " which has not been registered."); } } else { LOG.debug("Trying to update unknown slot with slot id {}.", slotId); return false; } }
[ "private", "boolean", "updateSlot", "(", "SlotID", "slotId", ",", "AllocationID", "allocationId", ",", "JobID", "jobId", ")", "{", "final", "TaskManagerSlot", "slot", "=", "slots", ".", "get", "(", "slotId", ")", ";", "if", "(", "slot", "!=", "null", ")", "{", "final", "TaskManagerRegistration", "taskManagerRegistration", "=", "taskManagerRegistrations", ".", "get", "(", "slot", ".", "getInstanceId", "(", ")", ")", ";", "if", "(", "taskManagerRegistration", "!=", "null", ")", "{", "updateSlotState", "(", "slot", ",", "taskManagerRegistration", ",", "allocationId", ",", "jobId", ")", ";", "return", "true", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Trying to update a slot from a TaskManager \"", "+", "slot", ".", "getInstanceId", "(", ")", "+", "\" which has not been registered.\"", ")", ";", "}", "}", "else", "{", "LOG", ".", "debug", "(", "\"Trying to update unknown slot with slot id {}.\"", ",", "slotId", ")", ";", "return", "false", ";", "}", "}" ]
Updates a slot with the given allocation id. @param slotId to update @param allocationId specifying the current allocation of the slot @param jobId specifying the job to which the slot is allocated @return True if the slot could be updated; otherwise false
[ "Updates", "a", "slot", "with", "the", "given", "allocation", "id", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManager.java#L604-L623
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java
ScriptingUtils.getObjectInstanceFromGroovyResource
public static <T> T getObjectInstanceFromGroovyResource(final Resource resource, final Class<T> expectedType) { """ Gets object instance from groovy resource. @param <T> the type parameter @param resource the resource @param expectedType the expected type @return the object instance from groovy resource """ return getObjectInstanceFromGroovyResource(resource, ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_OBJECT_ARRAY, expectedType); }
java
public static <T> T getObjectInstanceFromGroovyResource(final Resource resource, final Class<T> expectedType) { return getObjectInstanceFromGroovyResource(resource, ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_OBJECT_ARRAY, expectedType); }
[ "public", "static", "<", "T", ">", "T", "getObjectInstanceFromGroovyResource", "(", "final", "Resource", "resource", ",", "final", "Class", "<", "T", ">", "expectedType", ")", "{", "return", "getObjectInstanceFromGroovyResource", "(", "resource", ",", "ArrayUtils", ".", "EMPTY_CLASS_ARRAY", ",", "ArrayUtils", ".", "EMPTY_OBJECT_ARRAY", ",", "expectedType", ")", ";", "}" ]
Gets object instance from groovy resource. @param <T> the type parameter @param resource the resource @param expectedType the expected type @return the object instance from groovy resource
[ "Gets", "object", "instance", "from", "groovy", "resource", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java#L408-L411
pressgang-ccms/PressGangCCMSDatasourceProviders
rest-provider/src/main/java/org/jboss/pressgang/ccms/provider/RESTProviderFactory.java
RESTProviderFactory.registerProvider
public <T extends RESTDataProvider> void registerProvider(Class<T> providerClass, Class<?> providerInterface) { """ Register an external provider with the provider factory. @param providerClass The Class of the Provider. @param providerInterface The Class that the Provider implements. @param <T> The Provider class type. """ try { final Constructor<T> constructor = providerClass.getConstructor(RESTProviderFactory.class); final T instance = constructor.newInstance(this); providerMap.put(providerClass, instance); if (providerInterface != null) { providerMap.put(providerInterface, instance); } } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
java
public <T extends RESTDataProvider> void registerProvider(Class<T> providerClass, Class<?> providerInterface) { try { final Constructor<T> constructor = providerClass.getConstructor(RESTProviderFactory.class); final T instance = constructor.newInstance(this); providerMap.put(providerClass, instance); if (providerInterface != null) { providerMap.put(providerInterface, instance); } } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
[ "public", "<", "T", "extends", "RESTDataProvider", ">", "void", "registerProvider", "(", "Class", "<", "T", ">", "providerClass", ",", "Class", "<", "?", ">", "providerInterface", ")", "{", "try", "{", "final", "Constructor", "<", "T", ">", "constructor", "=", "providerClass", ".", "getConstructor", "(", "RESTProviderFactory", ".", "class", ")", ";", "final", "T", "instance", "=", "constructor", ".", "newInstance", "(", "this", ")", ";", "providerMap", ".", "put", "(", "providerClass", ",", "instance", ")", ";", "if", "(", "providerInterface", "!=", "null", ")", "{", "providerMap", ".", "put", "(", "providerInterface", ",", "instance", ")", ";", "}", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Register an external provider with the provider factory. @param providerClass The Class of the Provider. @param providerInterface The Class that the Provider implements. @param <T> The Provider class type.
[ "Register", "an", "external", "provider", "with", "the", "provider", "factory", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSDatasourceProviders/blob/e47588adad0dcd55608b197b37825a512bc8fd25/rest-provider/src/main/java/org/jboss/pressgang/ccms/provider/RESTProviderFactory.java#L223-L241
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java
PathsDocument.apply
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, PathsDocument.Parameters params) { """ Builds the paths MarkupDocument. @return the paths MarkupDocument """ Map<String, Path> paths = params.paths; if (MapUtils.isNotEmpty(paths)) { applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildPathsTitle(markupDocBuilder); applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildsPathsSection(markupDocBuilder, paths); applyPathsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyPathsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); } return markupDocBuilder; }
java
@Override public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, PathsDocument.Parameters params) { Map<String, Path> paths = params.paths; if (MapUtils.isNotEmpty(paths)) { applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder)); buildPathsTitle(markupDocBuilder); applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder)); buildsPathsSection(markupDocBuilder, paths); applyPathsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder)); applyPathsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder)); } return markupDocBuilder; }
[ "@", "Override", "public", "MarkupDocBuilder", "apply", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "PathsDocument", ".", "Parameters", "params", ")", "{", "Map", "<", "String", ",", "Path", ">", "paths", "=", "params", ".", "paths", ";", "if", "(", "MapUtils", ".", "isNotEmpty", "(", "paths", ")", ")", "{", "applyPathsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEFORE", ",", "markupDocBuilder", ")", ")", ";", "buildPathsTitle", "(", "markupDocBuilder", ")", ";", "applyPathsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_BEGIN", ",", "markupDocBuilder", ")", ")", ";", "buildsPathsSection", "(", "markupDocBuilder", ",", "paths", ")", ";", "applyPathsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_END", ",", "markupDocBuilder", ")", ")", ";", "applyPathsDocumentExtension", "(", "new", "Context", "(", "Position", ".", "DOCUMENT_AFTER", ",", "markupDocBuilder", ")", ")", ";", "}", "return", "markupDocBuilder", ";", "}" ]
Builds the paths MarkupDocument. @return the paths MarkupDocument
[ "Builds", "the", "paths", "MarkupDocument", "." ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java#L96-L108
ironjacamar/ironjacamar
common/src/main/java/org/ironjacamar/common/metadata/MetadataFactory.java
MetadataFactory.getStandardMetaData
public Connector getStandardMetaData(File root) throws Exception { """ Get the JCA standard metadata @param root The root of the deployment @return The metadata @exception Exception Thrown if an error occurs """ Connector result = null; File metadataFile = new File(root, "/META-INF/ra.xml"); if (metadataFile.exists()) { InputStream input = null; String url = metadataFile.getAbsolutePath(); try { long start = System.currentTimeMillis(); input = new FileInputStream(metadataFile); XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(input); result = (new RaParser()).parse(xsr); log.debugf("Total parse for %s took %d ms", url, (System.currentTimeMillis() - start)); } catch (Exception e) { log.parsingErrorRaXml(url, e); throw e; } finally { if (input != null) input.close(); } } else { log.tracef("metadata file %s does not exist", metadataFile.toString()); } return result; }
java
public Connector getStandardMetaData(File root) throws Exception { Connector result = null; File metadataFile = new File(root, "/META-INF/ra.xml"); if (metadataFile.exists()) { InputStream input = null; String url = metadataFile.getAbsolutePath(); try { long start = System.currentTimeMillis(); input = new FileInputStream(metadataFile); XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(input); result = (new RaParser()).parse(xsr); log.debugf("Total parse for %s took %d ms", url, (System.currentTimeMillis() - start)); } catch (Exception e) { log.parsingErrorRaXml(url, e); throw e; } finally { if (input != null) input.close(); } } else { log.tracef("metadata file %s does not exist", metadataFile.toString()); } return result; }
[ "public", "Connector", "getStandardMetaData", "(", "File", "root", ")", "throws", "Exception", "{", "Connector", "result", "=", "null", ";", "File", "metadataFile", "=", "new", "File", "(", "root", ",", "\"/META-INF/ra.xml\"", ")", ";", "if", "(", "metadataFile", ".", "exists", "(", ")", ")", "{", "InputStream", "input", "=", "null", ";", "String", "url", "=", "metadataFile", ".", "getAbsolutePath", "(", ")", ";", "try", "{", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "input", "=", "new", "FileInputStream", "(", "metadataFile", ")", ";", "XMLStreamReader", "xsr", "=", "XMLInputFactory", ".", "newInstance", "(", ")", ".", "createXMLStreamReader", "(", "input", ")", ";", "result", "=", "(", "new", "RaParser", "(", ")", ")", ".", "parse", "(", "xsr", ")", ";", "log", ".", "debugf", "(", "\"Total parse for %s took %d ms\"", ",", "url", ",", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "start", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "parsingErrorRaXml", "(", "url", ",", "e", ")", ";", "throw", "e", ";", "}", "finally", "{", "if", "(", "input", "!=", "null", ")", "input", ".", "close", "(", ")", ";", "}", "}", "else", "{", "log", ".", "tracef", "(", "\"metadata file %s does not exist\"", ",", "metadataFile", ".", "toString", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Get the JCA standard metadata @param root The root of the deployment @return The metadata @exception Exception Thrown if an error occurs
[ "Get", "the", "JCA", "standard", "metadata" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/common/src/main/java/org/ironjacamar/common/metadata/MetadataFactory.java#L62-L100
bwkimmel/java-util
src/main/java/ca/eandb/util/io/StreamUtil.java
StreamUtil.writeBytes
public static void writeBytes(ByteBuffer bytes, OutputStream out) throws IOException { """ Writes the contents of a <code>ByteBuffer</code> to the provided <code>OutputStream</code>. @param bytes The <code>ByteBuffer</code> containing the bytes to write. @param out The <code>OutputStream</code> to write to. @throws IOException If unable to write to the <code>OutputStream</code>. """ final int BUFFER_LENGTH = 1024; byte[] buffer; if (bytes.remaining() >= BUFFER_LENGTH) { buffer = new byte[BUFFER_LENGTH]; do { bytes.get(buffer); out.write(buffer); } while (bytes.remaining() >= BUFFER_LENGTH); } else { buffer = new byte[bytes.remaining()]; } int remaining = bytes.remaining(); if (remaining > 0) { bytes.get(buffer, 0, remaining); out.write(buffer, 0, remaining); } }
java
public static void writeBytes(ByteBuffer bytes, OutputStream out) throws IOException { final int BUFFER_LENGTH = 1024; byte[] buffer; if (bytes.remaining() >= BUFFER_LENGTH) { buffer = new byte[BUFFER_LENGTH]; do { bytes.get(buffer); out.write(buffer); } while (bytes.remaining() >= BUFFER_LENGTH); } else { buffer = new byte[bytes.remaining()]; } int remaining = bytes.remaining(); if (remaining > 0) { bytes.get(buffer, 0, remaining); out.write(buffer, 0, remaining); } }
[ "public", "static", "void", "writeBytes", "(", "ByteBuffer", "bytes", ",", "OutputStream", "out", ")", "throws", "IOException", "{", "final", "int", "BUFFER_LENGTH", "=", "1024", ";", "byte", "[", "]", "buffer", ";", "if", "(", "bytes", ".", "remaining", "(", ")", ">=", "BUFFER_LENGTH", ")", "{", "buffer", "=", "new", "byte", "[", "BUFFER_LENGTH", "]", ";", "do", "{", "bytes", ".", "get", "(", "buffer", ")", ";", "out", ".", "write", "(", "buffer", ")", ";", "}", "while", "(", "bytes", ".", "remaining", "(", ")", ">=", "BUFFER_LENGTH", ")", ";", "}", "else", "{", "buffer", "=", "new", "byte", "[", "bytes", ".", "remaining", "(", ")", "]", ";", "}", "int", "remaining", "=", "bytes", ".", "remaining", "(", ")", ";", "if", "(", "remaining", ">", "0", ")", "{", "bytes", ".", "get", "(", "buffer", ",", "0", ",", "remaining", ")", ";", "out", ".", "write", "(", "buffer", ",", "0", ",", "remaining", ")", ";", "}", "}" ]
Writes the contents of a <code>ByteBuffer</code> to the provided <code>OutputStream</code>. @param bytes The <code>ByteBuffer</code> containing the bytes to write. @param out The <code>OutputStream</code> to write to. @throws IOException If unable to write to the <code>OutputStream</code>.
[ "Writes", "the", "contents", "of", "a", "<code", ">", "ByteBuffer<", "/", "code", ">", "to", "the", "provided", "<code", ">", "OutputStream<", "/", "code", ">", "." ]
train
https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/io/StreamUtil.java#L98-L117
Stratio/bdt
src/main/java/com/stratio/qa/specs/DatabaseSpec.java
DatabaseSpec.connectDatabasePostgres
@Given("^I connect with JDBC and security type '(TLS|MD5|TRUST|CERT|LDAP|tls|md5|trust|cert|ldap)' to database '(.+?)' on host '(.+?)' and port '(.+?)' with user '(.+?)'( and password '(.+?)')?( and root ca '(.+?)')?(, crt '(.+?)')?( and key '(.+?)' certificates)?$") public void connectDatabasePostgres(String securityType, String database, String host, String port, String user, String foo1, String password, String foo2, String ca, String foo3, String crt, String foo4, String key) throws Exception { """ Connect to JDBC secured/not secured database @param database database connection string @param host database host @param port database port @param user database user @param password database password @param ca database self signed certs @param crt: database certificate @param key: database private key @throws Exception exception * """ this.commonspec.getExceptions().clear(); if ("TLS".equals(securityType) || "tls".equals(securityType) || "CERT".equals(securityType) || "cert".equals(securityType)) { commonspec.getLogger().debug("opening secure database"); try { this.commonspec.connectToPostgreSQLDatabase(database, host, port, user, password, true, ca, crt, key); } catch (Exception e) { this.commonspec.getExceptions().add(e); } } else { commonspec.getLogger().debug("opening database"); try { this.commonspec.connectToPostgreSQLDatabase(database, host, port, user, password, false, ca, crt, key); } catch (Exception e) { this.commonspec.getExceptions().add(e); } } }
java
@Given("^I connect with JDBC and security type '(TLS|MD5|TRUST|CERT|LDAP|tls|md5|trust|cert|ldap)' to database '(.+?)' on host '(.+?)' and port '(.+?)' with user '(.+?)'( and password '(.+?)')?( and root ca '(.+?)')?(, crt '(.+?)')?( and key '(.+?)' certificates)?$") public void connectDatabasePostgres(String securityType, String database, String host, String port, String user, String foo1, String password, String foo2, String ca, String foo3, String crt, String foo4, String key) throws Exception { this.commonspec.getExceptions().clear(); if ("TLS".equals(securityType) || "tls".equals(securityType) || "CERT".equals(securityType) || "cert".equals(securityType)) { commonspec.getLogger().debug("opening secure database"); try { this.commonspec.connectToPostgreSQLDatabase(database, host, port, user, password, true, ca, crt, key); } catch (Exception e) { this.commonspec.getExceptions().add(e); } } else { commonspec.getLogger().debug("opening database"); try { this.commonspec.connectToPostgreSQLDatabase(database, host, port, user, password, false, ca, crt, key); } catch (Exception e) { this.commonspec.getExceptions().add(e); } } }
[ "@", "Given", "(", "\"^I connect with JDBC and security type '(TLS|MD5|TRUST|CERT|LDAP|tls|md5|trust|cert|ldap)' to database '(.+?)' on host '(.+?)' and port '(.+?)' with user '(.+?)'( and password '(.+?)')?( and root ca '(.+?)')?(, crt '(.+?)')?( and key '(.+?)' certificates)?$\"", ")", "public", "void", "connectDatabasePostgres", "(", "String", "securityType", ",", "String", "database", ",", "String", "host", ",", "String", "port", ",", "String", "user", ",", "String", "foo1", ",", "String", "password", ",", "String", "foo2", ",", "String", "ca", ",", "String", "foo3", ",", "String", "crt", ",", "String", "foo4", ",", "String", "key", ")", "throws", "Exception", "{", "this", ".", "commonspec", ".", "getExceptions", "(", ")", ".", "clear", "(", ")", ";", "if", "(", "\"TLS\"", ".", "equals", "(", "securityType", ")", "||", "\"tls\"", ".", "equals", "(", "securityType", ")", "||", "\"CERT\"", ".", "equals", "(", "securityType", ")", "||", "\"cert\"", ".", "equals", "(", "securityType", ")", ")", "{", "commonspec", ".", "getLogger", "(", ")", ".", "debug", "(", "\"opening secure database\"", ")", ";", "try", "{", "this", ".", "commonspec", ".", "connectToPostgreSQLDatabase", "(", "database", ",", "host", ",", "port", ",", "user", ",", "password", ",", "true", ",", "ca", ",", "crt", ",", "key", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "this", ".", "commonspec", ".", "getExceptions", "(", ")", ".", "add", "(", "e", ")", ";", "}", "}", "else", "{", "commonspec", ".", "getLogger", "(", ")", ".", "debug", "(", "\"opening database\"", ")", ";", "try", "{", "this", ".", "commonspec", ".", "connectToPostgreSQLDatabase", "(", "database", ",", "host", ",", "port", ",", "user", ",", "password", ",", "false", ",", "ca", ",", "crt", ",", "key", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "this", ".", "commonspec", ".", "getExceptions", "(", ")", ".", "add", "(", "e", ")", ";", "}", "}", "}" ]
Connect to JDBC secured/not secured database @param database database connection string @param host database host @param port database port @param user database user @param password database password @param ca database self signed certs @param crt: database certificate @param key: database private key @throws Exception exception *
[ "Connect", "to", "JDBC", "secured", "/", "not", "secured", "database" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DatabaseSpec.java#L358-L376
greatman/craftconomy3
src/main/java/com/greatmancode/craftconomy3/account/AccountACL.java
AccountACL.setShow
public void setShow(String name, boolean show) { """ Set if a player can show the bank balance. @param name The player name @param show can show the bank balance or not. """ String newName = name.toLowerCase(); if (aclList.containsKey(newName)) { AccountACLValue value = aclList.get(newName); set(newName, value.canDeposit(), value.canWithdraw(), value.canAcl(), show, value.isOwner()); } else { set(newName, false, false, false, show, false); } }
java
public void setShow(String name, boolean show) { String newName = name.toLowerCase(); if (aclList.containsKey(newName)) { AccountACLValue value = aclList.get(newName); set(newName, value.canDeposit(), value.canWithdraw(), value.canAcl(), show, value.isOwner()); } else { set(newName, false, false, false, show, false); } }
[ "public", "void", "setShow", "(", "String", "name", ",", "boolean", "show", ")", "{", "String", "newName", "=", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "aclList", ".", "containsKey", "(", "newName", ")", ")", "{", "AccountACLValue", "value", "=", "aclList", ".", "get", "(", "newName", ")", ";", "set", "(", "newName", ",", "value", ".", "canDeposit", "(", ")", ",", "value", ".", "canWithdraw", "(", ")", ",", "value", ".", "canAcl", "(", ")", ",", "show", ",", "value", ".", "isOwner", "(", ")", ")", ";", "}", "else", "{", "set", "(", "newName", ",", "false", ",", "false", ",", "false", ",", "show", ",", "false", ")", ";", "}", "}" ]
Set if a player can show the bank balance. @param name The player name @param show can show the bank balance or not.
[ "Set", "if", "a", "player", "can", "show", "the", "bank", "balance", "." ]
train
https://github.com/greatman/craftconomy3/blob/51b1b3de7d039e20c7418d1e70b8c4b02b8cf840/src/main/java/com/greatmancode/craftconomy3/account/AccountACL.java#L165-L173
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLClassImpl_CustomFieldSerializer.java
OWLClassImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLClass instance) throws SerializationException { """ Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful """ serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLClass instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLClass", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{" ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLClassImpl_CustomFieldSerializer.java#L65-L68
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/views/Projection.java
Projection.rotateAndScalePoint
public Point rotateAndScalePoint(int x, int y, Point reuse) { """ This will apply the current map's scaling and rotation for a point. This can be useful when converting MotionEvents to a screen point. """ return applyMatrixToPoint(x, y, reuse, mRotateAndScaleMatrix, mOrientation != 0); }
java
public Point rotateAndScalePoint(int x, int y, Point reuse) { return applyMatrixToPoint(x, y, reuse, mRotateAndScaleMatrix, mOrientation != 0); }
[ "public", "Point", "rotateAndScalePoint", "(", "int", "x", ",", "int", "y", ",", "Point", "reuse", ")", "{", "return", "applyMatrixToPoint", "(", "x", ",", "y", ",", "reuse", ",", "mRotateAndScaleMatrix", ",", "mOrientation", "!=", "0", ")", ";", "}" ]
This will apply the current map's scaling and rotation for a point. This can be useful when converting MotionEvents to a screen point.
[ "This", "will", "apply", "the", "current", "map", "s", "scaling", "and", "rotation", "for", "a", "point", ".", "This", "can", "be", "useful", "when", "converting", "MotionEvents", "to", "a", "screen", "point", "." ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/Projection.java#L374-L376
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShaderData.java
GVRShaderData.setFloat
public void setFloat(String key, float value) { """ Bind a {@code float} to the shader uniform {@code key}. Throws an exception of the key is not found. @param key Name of the shader uniform @param value New data """ checkKeyIsUniform(key); checkFloatNotNaNOrInfinity("value", value); NativeShaderData.setFloat(getNative(), key, value); }
java
public void setFloat(String key, float value) { checkKeyIsUniform(key); checkFloatNotNaNOrInfinity("value", value); NativeShaderData.setFloat(getNative(), key, value); }
[ "public", "void", "setFloat", "(", "String", "key", ",", "float", "value", ")", "{", "checkKeyIsUniform", "(", "key", ")", ";", "checkFloatNotNaNOrInfinity", "(", "\"value\"", ",", "value", ")", ";", "NativeShaderData", ".", "setFloat", "(", "getNative", "(", ")", ",", "key", ",", "value", ")", ";", "}" ]
Bind a {@code float} to the shader uniform {@code key}. Throws an exception of the key is not found. @param key Name of the shader uniform @param value New data
[ "Bind", "a", "{", "@code", "float", "}", "to", "the", "shader", "uniform", "{", "@code", "key", "}", ".", "Throws", "an", "exception", "of", "the", "key", "is", "not", "found", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRShaderData.java#L247-L252
sporniket/core
sporniket-core-io/src/main/java/com/sporniket/libre/io/parser/properties/LineByLinePropertyParser.java
LineByLinePropertyParser.fireMultipleLinePropertyParsedEvent
private void fireMultipleLinePropertyParsedEvent(String name, String[] value) { """ Notify listeners that a multiple line property has been parsed. @param name property name. @param value property value. """ MultipleLinePropertyParsedEvent _event = new MultipleLinePropertyParsedEvent(name, value); for (PropertiesParsingListener _listener : getListeners()) { _listener.onMultipleLinePropertyParsed(_event); } }
java
private void fireMultipleLinePropertyParsedEvent(String name, String[] value) { MultipleLinePropertyParsedEvent _event = new MultipleLinePropertyParsedEvent(name, value); for (PropertiesParsingListener _listener : getListeners()) { _listener.onMultipleLinePropertyParsed(_event); } }
[ "private", "void", "fireMultipleLinePropertyParsedEvent", "(", "String", "name", ",", "String", "[", "]", "value", ")", "{", "MultipleLinePropertyParsedEvent", "_event", "=", "new", "MultipleLinePropertyParsedEvent", "(", "name", ",", "value", ")", ";", "for", "(", "PropertiesParsingListener", "_listener", ":", "getListeners", "(", ")", ")", "{", "_listener", ".", "onMultipleLinePropertyParsed", "(", "_event", ")", ";", "}", "}" ]
Notify listeners that a multiple line property has been parsed. @param name property name. @param value property value.
[ "Notify", "listeners", "that", "a", "multiple", "line", "property", "has", "been", "parsed", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/parser/properties/LineByLinePropertyParser.java#L553-L560
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor
SurveyorCore/src/main/java/org/wwarn/surveyor/server/core/FileChangeMonitor.java
FileChangeMonitor.initNewThread
protected void initNewThread(Path monitoredFile, CountDownLatch start, CountDownLatch stop) throws IOException { """ Added countdown latches as a synchronization aid to allow better unit testing Allows one or more threads to wait until a set of operations being performed in other threads completes, @param monitoredFile @param start calling start.await() waits till file listner is active and ready @param stop calling stop.await() allows calling code to wait until a fileChangedEvent is processed @throws IOException """ final Runnable watcher = initializeWatcherWithDirectory(monitoredFile, start, stop); final Thread thread = new Thread(watcher); thread.setDaemon(false); thread.start(); }
java
protected void initNewThread(Path monitoredFile, CountDownLatch start, CountDownLatch stop) throws IOException { final Runnable watcher = initializeWatcherWithDirectory(monitoredFile, start, stop); final Thread thread = new Thread(watcher); thread.setDaemon(false); thread.start(); }
[ "protected", "void", "initNewThread", "(", "Path", "monitoredFile", ",", "CountDownLatch", "start", ",", "CountDownLatch", "stop", ")", "throws", "IOException", "{", "final", "Runnable", "watcher", "=", "initializeWatcherWithDirectory", "(", "monitoredFile", ",", "start", ",", "stop", ")", ";", "final", "Thread", "thread", "=", "new", "Thread", "(", "watcher", ")", ";", "thread", ".", "setDaemon", "(", "false", ")", ";", "thread", ".", "start", "(", ")", ";", "}" ]
Added countdown latches as a synchronization aid to allow better unit testing Allows one or more threads to wait until a set of operations being performed in other threads completes, @param monitoredFile @param start calling start.await() waits till file listner is active and ready @param stop calling stop.await() allows calling code to wait until a fileChangedEvent is processed @throws IOException
[ "Added", "countdown", "latches", "as", "a", "synchronization", "aid", "to", "allow", "better", "unit", "testing", "Allows", "one", "or", "more", "threads", "to", "wait", "until", "a", "set", "of", "operations", "being", "performed", "in", "other", "threads", "completes" ]
train
https://github.com/WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor/blob/224280bcd6e8045bda6b673584caf0aea5e4c841/SurveyorCore/src/main/java/org/wwarn/surveyor/server/core/FileChangeMonitor.java#L101-L106
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/KeyDecoder.java
KeyDecoder.decodeString
public static int decodeString(byte[] src, int srcOffset, String[] valueRef) throws CorruptEncodingException { """ Decodes an encoded string from the given byte array. @param src source of encoded data @param srcOffset offset into encoded data @param valueRef decoded string is stored in element 0, which may be null @return amount of bytes read from source @throws CorruptEncodingException if source data is corrupt """ try { return decodeString(src, srcOffset, valueRef, 0); } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
java
public static int decodeString(byte[] src, int srcOffset, String[] valueRef) throws CorruptEncodingException { try { return decodeString(src, srcOffset, valueRef, 0); } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
[ "public", "static", "int", "decodeString", "(", "byte", "[", "]", "src", ",", "int", "srcOffset", ",", "String", "[", "]", "valueRef", ")", "throws", "CorruptEncodingException", "{", "try", "{", "return", "decodeString", "(", "src", ",", "srcOffset", ",", "valueRef", ",", "0", ")", ";", "}", "catch", "(", "IndexOutOfBoundsException", "e", ")", "{", "throw", "new", "CorruptEncodingException", "(", "null", ",", "e", ")", ";", "}", "}" ]
Decodes an encoded string from the given byte array. @param src source of encoded data @param srcOffset offset into encoded data @param valueRef decoded string is stored in element 0, which may be null @return amount of bytes read from source @throws CorruptEncodingException if source data is corrupt
[ "Decodes", "an", "encoded", "string", "from", "the", "given", "byte", "array", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyDecoder.java#L719-L727
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java
PhotosInterface.setDates
public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity) throws FlickrException { """ Set the dates for the specified photo. This method requires authentication with 'write' permission. @param photoId The photo ID @param datePosted The date the photo was posted or null @param dateTaken The date the photo was taken or null @param dateTakenGranularity The granularity of the taken date or null @throws FlickrException """ Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_DATES); parameters.put("photo_id", photoId); if (datePosted != null) { parameters.put("date_posted", Long.toString(datePosted.getTime() / 1000)); } if (dateTaken != null) { parameters.put("date_taken", ((DateFormat) DATE_FORMATS.get()).format(dateTaken)); } if (dateTakenGranularity != null) { parameters.put("date_taken_granularity", dateTakenGranularity); } Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
java
public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_SET_DATES); parameters.put("photo_id", photoId); if (datePosted != null) { parameters.put("date_posted", Long.toString(datePosted.getTime() / 1000)); } if (dateTaken != null) { parameters.put("date_taken", ((DateFormat) DATE_FORMATS.get()).format(dateTaken)); } if (dateTakenGranularity != null) { parameters.put("date_taken_granularity", dateTakenGranularity); } Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } }
[ "public", "void", "setDates", "(", "String", "photoId", ",", "Date", "datePosted", ",", "Date", "dateTaken", ",", "String", "dateTakenGranularity", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "parameters", ".", "put", "(", "\"method\"", ",", "METHOD_SET_DATES", ")", ";", "parameters", ".", "put", "(", "\"photo_id\"", ",", "photoId", ")", ";", "if", "(", "datePosted", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"date_posted\"", ",", "Long", ".", "toString", "(", "datePosted", ".", "getTime", "(", ")", "/", "1000", ")", ")", ";", "}", "if", "(", "dateTaken", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"date_taken\"", ",", "(", "(", "DateFormat", ")", "DATE_FORMATS", ".", "get", "(", ")", ")", ".", "format", "(", "dateTaken", ")", ")", ";", "}", "if", "(", "dateTakenGranularity", "!=", "null", ")", "{", "parameters", ".", "put", "(", "\"date_taken_granularity\"", ",", "dateTakenGranularity", ")", ";", "}", "Response", "response", "=", "transport", ".", "post", "(", "transport", ".", "getPath", "(", ")", ",", "parameters", ",", "apiKey", ",", "sharedSecret", ")", ";", "if", "(", "response", ".", "isError", "(", ")", ")", "{", "throw", "new", "FlickrException", "(", "response", ".", "getErrorCode", "(", ")", ",", "response", ".", "getErrorMessage", "(", ")", ")", ";", "}", "}" ]
Set the dates for the specified photo. This method requires authentication with 'write' permission. @param photoId The photo ID @param datePosted The date the photo was posted or null @param dateTaken The date the photo was taken or null @param dateTakenGranularity The granularity of the taken date or null @throws FlickrException
[ "Set", "the", "dates", "for", "the", "specified", "photo", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java#L1164-L1186
nohana/Amalgam
amalgam/src/main/java/com/amalgam/view/ViewUtils.java
ViewUtils.findViewById
@SuppressWarnings("unchecked") // we know that return value type is a child of view, and V is bound to a child of view. public static <V extends View> V findViewById(View view, int id) { """ Find the specific view from the view as traversal root. Returning value type is bound to your variable type. @param view the root view to find the view. @param id the view id. @param <V> the view class type parameter. @return the view, null if not found. """ return (V) view.findViewById(id); }
java
@SuppressWarnings("unchecked") // we know that return value type is a child of view, and V is bound to a child of view. public static <V extends View> V findViewById(View view, int id) { return (V) view.findViewById(id); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// we know that return value type is a child of view, and V is bound to a child of view.", "public", "static", "<", "V", "extends", "View", ">", "V", "findViewById", "(", "View", "view", ",", "int", "id", ")", "{", "return", "(", "V", ")", "view", ".", "findViewById", "(", "id", ")", ";", "}" ]
Find the specific view from the view as traversal root. Returning value type is bound to your variable type. @param view the root view to find the view. @param id the view id. @param <V> the view class type parameter. @return the view, null if not found.
[ "Find", "the", "specific", "view", "from", "the", "view", "as", "traversal", "root", ".", "Returning", "value", "type", "is", "bound", "to", "your", "variable", "type", "." ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/view/ViewUtils.java#L137-L140
h2oai/h2o-3
h2o-genmodel/src/main/java/hex/genmodel/easy/EasyPredictModelWrapper.java
EasyPredictModelWrapper.predictWord2Vec
public Word2VecPrediction predictWord2Vec(RowData data) throws PredictException { """ Lookup word embeddings for a given word (or set of words). @param data RawData structure, every key with a String value will be translated to an embedding @return The prediction @throws PredictException if model is not a WordEmbedding model """ validateModelCategory(ModelCategory.WordEmbedding); if (! (m instanceof WordEmbeddingModel)) throw new PredictException("Model is not of the expected type, class = " + m.getClass().getSimpleName()); final WordEmbeddingModel weModel = (WordEmbeddingModel) m; final int vecSize = weModel.getVecSize(); HashMap<String, float[]> embeddings = new HashMap<>(data.size()); for (String wordKey : data.keySet()) { Object value = data.get(wordKey); if (value instanceof String) { String word = (String) value; embeddings.put(wordKey, weModel.transform0(word, new float[vecSize])); } } Word2VecPrediction p = new Word2VecPrediction(); p.wordEmbeddings = embeddings; return p; }
java
public Word2VecPrediction predictWord2Vec(RowData data) throws PredictException { validateModelCategory(ModelCategory.WordEmbedding); if (! (m instanceof WordEmbeddingModel)) throw new PredictException("Model is not of the expected type, class = " + m.getClass().getSimpleName()); final WordEmbeddingModel weModel = (WordEmbeddingModel) m; final int vecSize = weModel.getVecSize(); HashMap<String, float[]> embeddings = new HashMap<>(data.size()); for (String wordKey : data.keySet()) { Object value = data.get(wordKey); if (value instanceof String) { String word = (String) value; embeddings.put(wordKey, weModel.transform0(word, new float[vecSize])); } } Word2VecPrediction p = new Word2VecPrediction(); p.wordEmbeddings = embeddings; return p; }
[ "public", "Word2VecPrediction", "predictWord2Vec", "(", "RowData", "data", ")", "throws", "PredictException", "{", "validateModelCategory", "(", "ModelCategory", ".", "WordEmbedding", ")", ";", "if", "(", "!", "(", "m", "instanceof", "WordEmbeddingModel", ")", ")", "throw", "new", "PredictException", "(", "\"Model is not of the expected type, class = \"", "+", "m", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "final", "WordEmbeddingModel", "weModel", "=", "(", "WordEmbeddingModel", ")", "m", ";", "final", "int", "vecSize", "=", "weModel", ".", "getVecSize", "(", ")", ";", "HashMap", "<", "String", ",", "float", "[", "]", ">", "embeddings", "=", "new", "HashMap", "<>", "(", "data", ".", "size", "(", ")", ")", ";", "for", "(", "String", "wordKey", ":", "data", ".", "keySet", "(", ")", ")", "{", "Object", "value", "=", "data", ".", "get", "(", "wordKey", ")", ";", "if", "(", "value", "instanceof", "String", ")", "{", "String", "word", "=", "(", "String", ")", "value", ";", "embeddings", ".", "put", "(", "wordKey", ",", "weModel", ".", "transform0", "(", "word", ",", "new", "float", "[", "vecSize", "]", ")", ")", ";", "}", "}", "Word2VecPrediction", "p", "=", "new", "Word2VecPrediction", "(", ")", ";", "p", ".", "wordEmbeddings", "=", "embeddings", ";", "return", "p", ";", "}" ]
Lookup word embeddings for a given word (or set of words). @param data RawData structure, every key with a String value will be translated to an embedding @return The prediction @throws PredictException if model is not a WordEmbedding model
[ "Lookup", "word", "embeddings", "for", "a", "given", "word", "(", "or", "set", "of", "words", ")", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-genmodel/src/main/java/hex/genmodel/easy/EasyPredictModelWrapper.java#L468-L490
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/SpriteFontImpl.java
SpriteFontImpl.getCharWidth
private int getCharWidth(String text, Align align) { """ Get character width depending of alignment. @param text The text reference. @param align The align. @return The char width. """ final int width; if (align == Align.RIGHT) { width = getTextWidth(text); } else if (align == Align.CENTER) { width = getTextWidth(text) / 2; } else { width = 0; } return width; }
java
private int getCharWidth(String text, Align align) { final int width; if (align == Align.RIGHT) { width = getTextWidth(text); } else if (align == Align.CENTER) { width = getTextWidth(text) / 2; } else { width = 0; } return width; }
[ "private", "int", "getCharWidth", "(", "String", "text", ",", "Align", "align", ")", "{", "final", "int", "width", ";", "if", "(", "align", "==", "Align", ".", "RIGHT", ")", "{", "width", "=", "getTextWidth", "(", "text", ")", ";", "}", "else", "if", "(", "align", "==", "Align", ".", "CENTER", ")", "{", "width", "=", "getTextWidth", "(", "text", ")", "/", "2", ";", "}", "else", "{", "width", "=", "0", ";", "}", "return", "width", ";", "}" ]
Get character width depending of alignment. @param text The text reference. @param align The align. @return The char width.
[ "Get", "character", "width", "depending", "of", "alignment", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/SpriteFontImpl.java#L56-L72
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/dom3/LSSerializerImpl.java
LSSerializerImpl.createLSException
private static LSException createLSException(short code, Throwable cause) { """ Creates an LSException. On J2SE 1.4 and above the cause for the exception will be set. """ LSException lse = new LSException(code, cause != null ? cause.getMessage() : null); if (cause != null && ThrowableMethods.fgThrowableMethodsAvailable) { try { ThrowableMethods.fgThrowableInitCauseMethod.invoke(lse, new Object [] {cause}); } // Something went wrong. There's not much we can do about it. catch (Exception e) {} } return lse; }
java
private static LSException createLSException(short code, Throwable cause) { LSException lse = new LSException(code, cause != null ? cause.getMessage() : null); if (cause != null && ThrowableMethods.fgThrowableMethodsAvailable) { try { ThrowableMethods.fgThrowableInitCauseMethod.invoke(lse, new Object [] {cause}); } // Something went wrong. There's not much we can do about it. catch (Exception e) {} } return lse; }
[ "private", "static", "LSException", "createLSException", "(", "short", "code", ",", "Throwable", "cause", ")", "{", "LSException", "lse", "=", "new", "LSException", "(", "code", ",", "cause", "!=", "null", "?", "cause", ".", "getMessage", "(", ")", ":", "null", ")", ";", "if", "(", "cause", "!=", "null", "&&", "ThrowableMethods", ".", "fgThrowableMethodsAvailable", ")", "{", "try", "{", "ThrowableMethods", ".", "fgThrowableInitCauseMethod", ".", "invoke", "(", "lse", ",", "new", "Object", "[", "]", "{", "cause", "}", ")", ";", "}", "// Something went wrong. There's not much we can do about it.", "catch", "(", "Exception", "e", ")", "{", "}", "}", "return", "lse", ";", "}" ]
Creates an LSException. On J2SE 1.4 and above the cause for the exception will be set.
[ "Creates", "an", "LSException", ".", "On", "J2SE", "1", ".", "4", "and", "above", "the", "cause", "for", "the", "exception", "will", "be", "set", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/dom3/LSSerializerImpl.java#L1498-L1508
yannrichet/rsession
src/main/java/org/math/R/RserverConf.java
RserverConf.newLocalInstance
public static RserverConf newLocalInstance(Properties p) { """ if we want to re-use older sessions. May wrongly fil if older session is already stucked... """ RserverConf server = null; if (RserveDaemon.isWindows() || !UNIX_OPTIMIZE) { while (!isPortAvailable(RserverPort)) { RserverPort++; } server = new RserverConf(null, RserverPort, null, null, p); } else { // Unix supports multi-sessions natively, so no need to open a different Rserve on a new port server = new RserverConf(null, -1, null, null, p); } return server; }
java
public static RserverConf newLocalInstance(Properties p) { RserverConf server = null; if (RserveDaemon.isWindows() || !UNIX_OPTIMIZE) { while (!isPortAvailable(RserverPort)) { RserverPort++; } server = new RserverConf(null, RserverPort, null, null, p); } else { // Unix supports multi-sessions natively, so no need to open a different Rserve on a new port server = new RserverConf(null, -1, null, null, p); } return server; }
[ "public", "static", "RserverConf", "newLocalInstance", "(", "Properties", "p", ")", "{", "RserverConf", "server", "=", "null", ";", "if", "(", "RserveDaemon", ".", "isWindows", "(", ")", "||", "!", "UNIX_OPTIMIZE", ")", "{", "while", "(", "!", "isPortAvailable", "(", "RserverPort", ")", ")", "{", "RserverPort", "++", ";", "}", "server", "=", "new", "RserverConf", "(", "null", ",", "RserverPort", ",", "null", ",", "null", ",", "p", ")", ";", "}", "else", "{", "// Unix supports multi-sessions natively, so no need to open a different Rserve on a new port", "server", "=", "new", "RserverConf", "(", "null", ",", "-", "1", ",", "null", ",", "null", ",", "p", ")", ";", "}", "return", "server", ";", "}" ]
if we want to re-use older sessions. May wrongly fil if older session is already stucked...
[ "if", "we", "want", "to", "re", "-", "use", "older", "sessions", ".", "May", "wrongly", "fil", "if", "older", "session", "is", "already", "stucked", "..." ]
train
https://github.com/yannrichet/rsession/blob/acaa47f4da1644e0d067634130c0e88e38cb9035/src/main/java/org/math/R/RserverConf.java#L216-L227
ttddyy/datasource-proxy
src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultJsonQueryLogEntryCreator.java
DefaultJsonQueryLogEntryCreator.writeBatchSizeEntry
protected void writeBatchSizeEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { """ Write batch size as json. <p>default: "batchSize":1, @param sb StringBuilder to write @param execInfo execution info @param queryInfoList query info list """ sb.append("\"batchSize\":"); sb.append(execInfo.getBatchSize()); sb.append(", "); }
java
protected void writeBatchSizeEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { sb.append("\"batchSize\":"); sb.append(execInfo.getBatchSize()); sb.append(", "); }
[ "protected", "void", "writeBatchSizeEntry", "(", "StringBuilder", "sb", ",", "ExecutionInfo", "execInfo", ",", "List", "<", "QueryInfo", ">", "queryInfoList", ")", "{", "sb", ".", "append", "(", "\"\\\"batchSize\\\":\"", ")", ";", "sb", ".", "append", "(", "execInfo", ".", "getBatchSize", "(", ")", ")", ";", "sb", ".", "append", "(", "\", \"", ")", ";", "}" ]
Write batch size as json. <p>default: "batchSize":1, @param sb StringBuilder to write @param execInfo execution info @param queryInfoList query info list
[ "Write", "batch", "size", "as", "json", "." ]
train
https://github.com/ttddyy/datasource-proxy/blob/62163ccf9a569a99aa3ad9f9151a32567447a62e/src/main/java/net/ttddyy/dsproxy/listener/logging/DefaultJsonQueryLogEntryCreator.java#L182-L186
alipay/sofa-rpc
core/api/src/main/java/com/alipay/sofa/rpc/common/RpcConfigs.java
RpcConfigs.subscribe
public static synchronized void subscribe(String key, RpcConfigListener listener) { """ 订阅配置变化 @param key 关键字 @param listener 配置监听器 @see RpcOptions """ List<RpcConfigListener> listeners = CFG_LISTENER.get(key); if (listeners == null) { listeners = new ArrayList<RpcConfigListener>(); CFG_LISTENER.put(key, listeners); } listeners.add(listener); }
java
public static synchronized void subscribe(String key, RpcConfigListener listener) { List<RpcConfigListener> listeners = CFG_LISTENER.get(key); if (listeners == null) { listeners = new ArrayList<RpcConfigListener>(); CFG_LISTENER.put(key, listeners); } listeners.add(listener); }
[ "public", "static", "synchronized", "void", "subscribe", "(", "String", "key", ",", "RpcConfigListener", "listener", ")", "{", "List", "<", "RpcConfigListener", ">", "listeners", "=", "CFG_LISTENER", ".", "get", "(", "key", ")", ";", "if", "(", "listeners", "==", "null", ")", "{", "listeners", "=", "new", "ArrayList", "<", "RpcConfigListener", ">", "(", ")", ";", "CFG_LISTENER", ".", "put", "(", "key", ",", "listeners", ")", ";", "}", "listeners", ".", "add", "(", "listener", ")", ";", "}" ]
订阅配置变化 @param key 关键字 @param listener 配置监听器 @see RpcOptions
[ "订阅配置变化" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/common/RpcConfigs.java#L316-L323
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/xen/host_cpu_core.java
host_cpu_core.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> """ host_cpu_core_responses result = (host_cpu_core_responses) service.get_payload_formatter().string_to_resource(host_cpu_core_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.host_cpu_core_response_array); } host_cpu_core[] result_host_cpu_core = new host_cpu_core[result.host_cpu_core_response_array.length]; for(int i = 0; i < result.host_cpu_core_response_array.length; i++) { result_host_cpu_core[i] = result.host_cpu_core_response_array[i].host_cpu_core[0]; } return result_host_cpu_core; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { host_cpu_core_responses result = (host_cpu_core_responses) service.get_payload_formatter().string_to_resource(host_cpu_core_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.host_cpu_core_response_array); } host_cpu_core[] result_host_cpu_core = new host_cpu_core[result.host_cpu_core_response_array.length]; for(int i = 0; i < result.host_cpu_core_response_array.length; i++) { result_host_cpu_core[i] = result.host_cpu_core_response_array[i].host_cpu_core[0]; } return result_host_cpu_core; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "host_cpu_core_responses", "result", "=", "(", "host_cpu_core_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "host_cpu_core_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", ".", "host_cpu_core_response_array", ")", ";", "}", "host_cpu_core", "[", "]", "result_host_cpu_core", "=", "new", "host_cpu_core", "[", "result", ".", "host_cpu_core_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "host_cpu_core_response_array", ".", "length", ";", "i", "++", ")", "{", "result_host_cpu_core", "[", "i", "]", "=", "result", ".", "host_cpu_core_response_array", "[", "i", "]", ".", "host_cpu_core", "[", "0", "]", ";", "}", "return", "result_host_cpu_core", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/host_cpu_core.java#L232-L249
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_forecast_GET
public OvhProjectForecast project_serviceName_forecast_GET(String serviceName, Date toDate) throws IOException { """ Get your consumption forecast REST: GET /cloud/project/{serviceName}/forecast @param serviceName [required] Service name @param toDate [required] Forecast until date """ String qPath = "/cloud/project/{serviceName}/forecast"; StringBuilder sb = path(qPath, serviceName); query(sb, "toDate", toDate); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhProjectForecast.class); }
java
public OvhProjectForecast project_serviceName_forecast_GET(String serviceName, Date toDate) throws IOException { String qPath = "/cloud/project/{serviceName}/forecast"; StringBuilder sb = path(qPath, serviceName); query(sb, "toDate", toDate); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhProjectForecast.class); }
[ "public", "OvhProjectForecast", "project_serviceName_forecast_GET", "(", "String", "serviceName", ",", "Date", "toDate", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/forecast\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"toDate\"", ",", "toDate", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhProjectForecast", ".", "class", ")", ";", "}" ]
Get your consumption forecast REST: GET /cloud/project/{serviceName}/forecast @param serviceName [required] Service name @param toDate [required] Forecast until date
[ "Get", "your", "consumption", "forecast" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1426-L1432
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/util/TaskQueueThread.java
TaskQueueThread.execute
public void execute(Runnable task, long timeoutMillis) throws RejectedExecutionException { """ Enqueue a task to run. @param task task to enqueue @param timeoutMillis maximum time to wait for queue to have an available slot @throws RejectedExecutionException if wait interrupted, timeout expires, or shutdown has been called """ if (task == null) { throw new NullPointerException("Cannot accept null task"); } synchronized (this) { if (mState != STATE_RUNNING && mState != STATE_NOT_STARTED) { throw new RejectedExecutionException("Task queue is shutdown"); } } try { if (!mQueue.offer(task, timeoutMillis, TimeUnit.MILLISECONDS)) { throw new RejectedExecutionException("Unable to enqueue task after waiting " + timeoutMillis + " milliseconds"); } } catch (InterruptedException e) { throw new RejectedExecutionException(e); } }
java
public void execute(Runnable task, long timeoutMillis) throws RejectedExecutionException { if (task == null) { throw new NullPointerException("Cannot accept null task"); } synchronized (this) { if (mState != STATE_RUNNING && mState != STATE_NOT_STARTED) { throw new RejectedExecutionException("Task queue is shutdown"); } } try { if (!mQueue.offer(task, timeoutMillis, TimeUnit.MILLISECONDS)) { throw new RejectedExecutionException("Unable to enqueue task after waiting " + timeoutMillis + " milliseconds"); } } catch (InterruptedException e) { throw new RejectedExecutionException(e); } }
[ "public", "void", "execute", "(", "Runnable", "task", ",", "long", "timeoutMillis", ")", "throws", "RejectedExecutionException", "{", "if", "(", "task", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Cannot accept null task\"", ")", ";", "}", "synchronized", "(", "this", ")", "{", "if", "(", "mState", "!=", "STATE_RUNNING", "&&", "mState", "!=", "STATE_NOT_STARTED", ")", "{", "throw", "new", "RejectedExecutionException", "(", "\"Task queue is shutdown\"", ")", ";", "}", "}", "try", "{", "if", "(", "!", "mQueue", ".", "offer", "(", "task", ",", "timeoutMillis", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "throw", "new", "RejectedExecutionException", "(", "\"Unable to enqueue task after waiting \"", "+", "timeoutMillis", "+", "\" milliseconds\"", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "RejectedExecutionException", "(", "e", ")", ";", "}", "}" ]
Enqueue a task to run. @param task task to enqueue @param timeoutMillis maximum time to wait for queue to have an available slot @throws RejectedExecutionException if wait interrupted, timeout expires, or shutdown has been called
[ "Enqueue", "a", "task", "to", "run", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/util/TaskQueueThread.java#L85-L102
killbill/killbill
invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java
CBADao.computeCBAComplexity
public InvoiceItemModelDao computeCBAComplexity(final InvoiceModelDao invoice, @Nullable final BigDecimal accountCBAOrNull, @Nullable final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException { """ We expect a clean up to date invoice, with all the items except the cba, that we will compute in that method """ final BigDecimal balance = getInvoiceBalance(invoice); if (balance.compareTo(BigDecimal.ZERO) < 0) { // Current balance is negative, we need to generate a credit (positive CBA amount) return buildCBAItem(invoice, balance, context); } else if (balance.compareTo(BigDecimal.ZERO) > 0 && invoice.getStatus() == InvoiceStatus.COMMITTED && !invoice.isWrittenOff()) { // Current balance is positive and the invoice is COMMITTED, we need to use some of the existing if available (negative CBA amount) // PERF: in some codepaths, the CBA maybe have already been computed BigDecimal accountCBA = accountCBAOrNull; if (accountCBAOrNull == null) { accountCBA = getAccountCBAFromTransaction(entitySqlDaoWrapperFactory, context); } if (accountCBA.compareTo(BigDecimal.ZERO) <= 0) { return null; } final BigDecimal positiveCreditAmount = accountCBA.compareTo(balance) > 0 ? balance : accountCBA; return buildCBAItem(invoice, positiveCreditAmount, context); } else { // 0 balance, nothing to do. return null; } }
java
public InvoiceItemModelDao computeCBAComplexity(final InvoiceModelDao invoice, @Nullable final BigDecimal accountCBAOrNull, @Nullable final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory, final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException { final BigDecimal balance = getInvoiceBalance(invoice); if (balance.compareTo(BigDecimal.ZERO) < 0) { // Current balance is negative, we need to generate a credit (positive CBA amount) return buildCBAItem(invoice, balance, context); } else if (balance.compareTo(BigDecimal.ZERO) > 0 && invoice.getStatus() == InvoiceStatus.COMMITTED && !invoice.isWrittenOff()) { // Current balance is positive and the invoice is COMMITTED, we need to use some of the existing if available (negative CBA amount) // PERF: in some codepaths, the CBA maybe have already been computed BigDecimal accountCBA = accountCBAOrNull; if (accountCBAOrNull == null) { accountCBA = getAccountCBAFromTransaction(entitySqlDaoWrapperFactory, context); } if (accountCBA.compareTo(BigDecimal.ZERO) <= 0) { return null; } final BigDecimal positiveCreditAmount = accountCBA.compareTo(balance) > 0 ? balance : accountCBA; return buildCBAItem(invoice, positiveCreditAmount, context); } else { // 0 balance, nothing to do. return null; } }
[ "public", "InvoiceItemModelDao", "computeCBAComplexity", "(", "final", "InvoiceModelDao", "invoice", ",", "@", "Nullable", "final", "BigDecimal", "accountCBAOrNull", ",", "@", "Nullable", "final", "EntitySqlDaoWrapperFactory", "entitySqlDaoWrapperFactory", ",", "final", "InternalCallContext", "context", ")", "throws", "EntityPersistenceException", ",", "InvoiceApiException", "{", "final", "BigDecimal", "balance", "=", "getInvoiceBalance", "(", "invoice", ")", ";", "if", "(", "balance", ".", "compareTo", "(", "BigDecimal", ".", "ZERO", ")", "<", "0", ")", "{", "// Current balance is negative, we need to generate a credit (positive CBA amount)", "return", "buildCBAItem", "(", "invoice", ",", "balance", ",", "context", ")", ";", "}", "else", "if", "(", "balance", ".", "compareTo", "(", "BigDecimal", ".", "ZERO", ")", ">", "0", "&&", "invoice", ".", "getStatus", "(", ")", "==", "InvoiceStatus", ".", "COMMITTED", "&&", "!", "invoice", ".", "isWrittenOff", "(", ")", ")", "{", "// Current balance is positive and the invoice is COMMITTED, we need to use some of the existing if available (negative CBA amount)", "// PERF: in some codepaths, the CBA maybe have already been computed", "BigDecimal", "accountCBA", "=", "accountCBAOrNull", ";", "if", "(", "accountCBAOrNull", "==", "null", ")", "{", "accountCBA", "=", "getAccountCBAFromTransaction", "(", "entitySqlDaoWrapperFactory", ",", "context", ")", ";", "}", "if", "(", "accountCBA", ".", "compareTo", "(", "BigDecimal", ".", "ZERO", ")", "<=", "0", ")", "{", "return", "null", ";", "}", "final", "BigDecimal", "positiveCreditAmount", "=", "accountCBA", ".", "compareTo", "(", "balance", ")", ">", "0", "?", "balance", ":", "accountCBA", ";", "return", "buildCBAItem", "(", "invoice", ",", "positiveCreditAmount", ",", "context", ")", ";", "}", "else", "{", "// 0 balance, nothing to do.", "return", "null", ";", "}", "}" ]
We expect a clean up to date invoice, with all the items except the cba, that we will compute in that method
[ "We", "expect", "a", "clean", "up", "to", "date", "invoice", "with", "all", "the", "items", "except", "the", "cba", "that", "we", "will", "compute", "in", "that", "method" ]
train
https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/invoice/src/main/java/org/killbill/billing/invoice/dao/CBADao.java#L58-L84
prestodb/presto
presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/Indexer.java
Indexer.getIndexTableName
public static String getIndexTableName(String schema, String table) { """ Gets the fully-qualified index table name for the given table. @param schema Schema name @param table Table name @return Qualified index table name """ return schema.equals("default") ? table + "_idx" : schema + '.' + table + "_idx"; }
java
public static String getIndexTableName(String schema, String table) { return schema.equals("default") ? table + "_idx" : schema + '.' + table + "_idx"; }
[ "public", "static", "String", "getIndexTableName", "(", "String", "schema", ",", "String", "table", ")", "{", "return", "schema", ".", "equals", "(", "\"default\"", ")", "?", "table", "+", "\"_idx\"", ":", "schema", "+", "'", "'", "+", "table", "+", "\"_idx\"", ";", "}" ]
Gets the fully-qualified index table name for the given table. @param schema Schema name @param table Table name @return Qualified index table name
[ "Gets", "the", "fully", "-", "qualified", "index", "table", "name", "for", "the", "given", "table", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/Indexer.java#L431-L434
codeprimate-software/cp-elements
src/main/java/org/cp/elements/tools/net/EchoServer.java
EchoServer.sendResponse
protected void sendResponse(Socket socket, String message) { """ Sends the {@link String message} received from the Echo Client back to the Echo Client on the given {@link Socket}. @param socket {@link Socket} used to send the Echo Client's {@link String message} back to the Echo Client. @param message {@link String} containing the message to send the Echo Client. This is the same message sent by the Echo Client and received by the Echo Server. @see AbstractClientServerSupport#sendMessage(Socket, String) """ try { getLogger().info(() -> String.format("Sending response [%1$s] to EchoClient [%2$s]", message, socket.getRemoteSocketAddress())); sendMessage(socket, message); } catch (IOException cause) { getLogger().warning(() -> String.format("Failed to send response [%1$s] to EchoClient [%2$s]", message, socket.getRemoteSocketAddress())); getLogger().fine(() -> ThrowableUtils.getStackTrace(cause)); } }
java
protected void sendResponse(Socket socket, String message) { try { getLogger().info(() -> String.format("Sending response [%1$s] to EchoClient [%2$s]", message, socket.getRemoteSocketAddress())); sendMessage(socket, message); } catch (IOException cause) { getLogger().warning(() -> String.format("Failed to send response [%1$s] to EchoClient [%2$s]", message, socket.getRemoteSocketAddress())); getLogger().fine(() -> ThrowableUtils.getStackTrace(cause)); } }
[ "protected", "void", "sendResponse", "(", "Socket", "socket", ",", "String", "message", ")", "{", "try", "{", "getLogger", "(", ")", ".", "info", "(", "(", ")", "->", "String", ".", "format", "(", "\"Sending response [%1$s] to EchoClient [%2$s]\"", ",", "message", ",", "socket", ".", "getRemoteSocketAddress", "(", ")", ")", ")", ";", "sendMessage", "(", "socket", ",", "message", ")", ";", "}", "catch", "(", "IOException", "cause", ")", "{", "getLogger", "(", ")", ".", "warning", "(", "(", ")", "->", "String", ".", "format", "(", "\"Failed to send response [%1$s] to EchoClient [%2$s]\"", ",", "message", ",", "socket", ".", "getRemoteSocketAddress", "(", ")", ")", ")", ";", "getLogger", "(", ")", ".", "fine", "(", "(", ")", "->", "ThrowableUtils", ".", "getStackTrace", "(", "cause", ")", ")", ";", "}", "}" ]
Sends the {@link String message} received from the Echo Client back to the Echo Client on the given {@link Socket}. @param socket {@link Socket} used to send the Echo Client's {@link String message} back to the Echo Client. @param message {@link String} containing the message to send the Echo Client. This is the same message sent by the Echo Client and received by the Echo Server. @see AbstractClientServerSupport#sendMessage(Socket, String)
[ "Sends", "the", "{", "@link", "String", "message", "}", "received", "from", "the", "Echo", "Client", "back", "to", "the", "Echo", "Client", "on", "the", "given", "{", "@link", "Socket", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/tools/net/EchoServer.java#L289-L302
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/AuthenticateApi.java
AuthenticateApi.postProgrammaticAuthenticate
public void postProgrammaticAuthenticate(HttpServletRequest req, HttpServletResponse resp, AuthenticationResult authResult) { """ This method set the caller and invocation subject and call the addSsoCookiesToResponse @param req @param resp @param authResult """ postProgrammaticAuthenticate(req, resp, authResult, false, true); }
java
public void postProgrammaticAuthenticate(HttpServletRequest req, HttpServletResponse resp, AuthenticationResult authResult) { postProgrammaticAuthenticate(req, resp, authResult, false, true); }
[ "public", "void", "postProgrammaticAuthenticate", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "resp", ",", "AuthenticationResult", "authResult", ")", "{", "postProgrammaticAuthenticate", "(", "req", ",", "resp", ",", "authResult", ",", "false", ",", "true", ")", ";", "}" ]
This method set the caller and invocation subject and call the addSsoCookiesToResponse @param req @param resp @param authResult
[ "This", "method", "set", "the", "caller", "and", "invocation", "subject", "and", "call", "the", "addSsoCookiesToResponse" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/AuthenticateApi.java#L464-L466
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.deleteProjectBadge
public void deleteProjectBadge(Serializable projectId, Integer badgeId) throws IOException { """ Delete project badge @param projectId The id of the project for which the badge should be deleted @param badgeId The id of the badge that should be deleted @throws IOException on GitLab API call error """ String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + "/" + badgeId; retrieve().method(DELETE).to(tailUrl, Void.class); }
java
public void deleteProjectBadge(Serializable projectId, Integer badgeId) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabBadge.URL + "/" + badgeId; retrieve().method(DELETE).to(tailUrl, Void.class); }
[ "public", "void", "deleteProjectBadge", "(", "Serializable", "projectId", ",", "Integer", "badgeId", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "GitlabProject", ".", "URL", "+", "\"/\"", "+", "sanitizeProjectId", "(", "projectId", ")", "+", "GitlabBadge", ".", "URL", "+", "\"/\"", "+", "badgeId", ";", "retrieve", "(", ")", ".", "method", "(", "DELETE", ")", ".", "to", "(", "tailUrl", ",", "Void", ".", "class", ")", ";", "}" ]
Delete project badge @param projectId The id of the project for which the badge should be deleted @param badgeId The id of the badge that should be deleted @throws IOException on GitLab API call error
[ "Delete", "project", "badge" ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L2667-L2671
apereo/cas
support/cas-server-support-consent-ldap/src/main/java/org/apereo/cas/consent/LdapConsentRepository.java
LdapConsentRepository.executeModifyOperation
private boolean executeModifyOperation(final Set<String> newConsent, final LdapEntry entry) { """ Modifies the consent decisions attribute on the entry. @param newConsent new set of consent decisions @param entry entry of consent decisions @return true / false """ val attrMap = new HashMap<String, Set<String>>(); attrMap.put(this.ldap.getConsentAttributeName(), newConsent); LOGGER.debug("Storing consent decisions [{}] at LDAP attribute [{}] for [{}]", newConsent, attrMap.keySet(), entry.getDn()); return LdapUtils.executeModifyOperation(entry.getDn(), this.connectionFactory, CollectionUtils.wrap(attrMap)); }
java
private boolean executeModifyOperation(final Set<String> newConsent, final LdapEntry entry) { val attrMap = new HashMap<String, Set<String>>(); attrMap.put(this.ldap.getConsentAttributeName(), newConsent); LOGGER.debug("Storing consent decisions [{}] at LDAP attribute [{}] for [{}]", newConsent, attrMap.keySet(), entry.getDn()); return LdapUtils.executeModifyOperation(entry.getDn(), this.connectionFactory, CollectionUtils.wrap(attrMap)); }
[ "private", "boolean", "executeModifyOperation", "(", "final", "Set", "<", "String", ">", "newConsent", ",", "final", "LdapEntry", "entry", ")", "{", "val", "attrMap", "=", "new", "HashMap", "<", "String", ",", "Set", "<", "String", ">", ">", "(", ")", ";", "attrMap", ".", "put", "(", "this", ".", "ldap", ".", "getConsentAttributeName", "(", ")", ",", "newConsent", ")", ";", "LOGGER", ".", "debug", "(", "\"Storing consent decisions [{}] at LDAP attribute [{}] for [{}]\"", ",", "newConsent", ",", "attrMap", ".", "keySet", "(", ")", ",", "entry", ".", "getDn", "(", ")", ")", ";", "return", "LdapUtils", ".", "executeModifyOperation", "(", "entry", ".", "getDn", "(", ")", ",", "this", ".", "connectionFactory", ",", "CollectionUtils", ".", "wrap", "(", "attrMap", ")", ")", ";", "}" ]
Modifies the consent decisions attribute on the entry. @param newConsent new set of consent decisions @param entry entry of consent decisions @return true / false
[ "Modifies", "the", "consent", "decisions", "attribute", "on", "the", "entry", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-consent-ldap/src/main/java/org/apereo/cas/consent/LdapConsentRepository.java#L156-L162
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ConnectionMonitorsInner.java
ConnectionMonitorsInner.beginStart
public void beginStart(String resourceGroupName, String networkWatcherName, String connectionMonitorName) { """ Starts the specified connection monitor. @param resourceGroupName The name of the resource group containing Network Watcher. @param networkWatcherName The name of the Network Watcher resource. @param connectionMonitorName The name of the connection monitor. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent """ beginStartWithServiceResponseAsync(resourceGroupName, networkWatcherName, connectionMonitorName).toBlocking().single().body(); }
java
public void beginStart(String resourceGroupName, String networkWatcherName, String connectionMonitorName) { beginStartWithServiceResponseAsync(resourceGroupName, networkWatcherName, connectionMonitorName).toBlocking().single().body(); }
[ "public", "void", "beginStart", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "connectionMonitorName", ")", "{", "beginStartWithServiceResponseAsync", "(", "resourceGroupName", ",", "networkWatcherName", ",", "connectionMonitorName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Starts the specified connection monitor. @param resourceGroupName The name of the resource group containing Network Watcher. @param networkWatcherName The name of the Network Watcher resource. @param connectionMonitorName The name of the connection monitor. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Starts", "the", "specified", "connection", "monitor", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ConnectionMonitorsInner.java#L794-L796
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/HexUtil.java
HexUtil.bytesToHex
public static final String bytesToHex(byte[] bs, int off, int length) { """ Converts a byte array into a string of upper case hex chars. @param bs A byte array @param off The index of the first byte to read @param length The number of bytes to read. @return the string of hex chars. """ StringBuffer sb = new StringBuffer(length * 2); bytesToHexAppend(bs, off, length, sb); return sb.toString(); }
java
public static final String bytesToHex(byte[] bs, int off, int length) { StringBuffer sb = new StringBuffer(length * 2); bytesToHexAppend(bs, off, length, sb); return sb.toString(); }
[ "public", "static", "final", "String", "bytesToHex", "(", "byte", "[", "]", "bs", ",", "int", "off", ",", "int", "length", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "length", "*", "2", ")", ";", "bytesToHexAppend", "(", "bs", ",", "off", ",", "length", ",", "sb", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Converts a byte array into a string of upper case hex chars. @param bs A byte array @param off The index of the first byte to read @param length The number of bytes to read. @return the string of hex chars.
[ "Converts", "a", "byte", "array", "into", "a", "string", "of", "upper", "case", "hex", "chars", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/HexUtil.java#L47-L51
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java
CommonOps_DDF4.elementMult
public static void elementMult( DMatrix4 a , DMatrix4 b) { """ <p>Performs an element by element multiplication operation:<br> <br> a<sub>i</sub> = a<sub>i</sub> * b<sub>i</sub> <br> </p> @param a The left vector in the multiplication operation. Modified. @param b The right vector in the multiplication operation. Not modified. """ a.a1 *= b.a1; a.a2 *= b.a2; a.a3 *= b.a3; a.a4 *= b.a4; }
java
public static void elementMult( DMatrix4 a , DMatrix4 b) { a.a1 *= b.a1; a.a2 *= b.a2; a.a3 *= b.a3; a.a4 *= b.a4; }
[ "public", "static", "void", "elementMult", "(", "DMatrix4", "a", ",", "DMatrix4", "b", ")", "{", "a", ".", "a1", "*=", "b", ".", "a1", ";", "a", ".", "a2", "*=", "b", ".", "a2", ";", "a", ".", "a3", "*=", "b", ".", "a3", ";", "a", ".", "a4", "*=", "b", ".", "a4", ";", "}" ]
<p>Performs an element by element multiplication operation:<br> <br> a<sub>i</sub> = a<sub>i</sub> * b<sub>i</sub> <br> </p> @param a The left vector in the multiplication operation. Modified. @param b The right vector in the multiplication operation. Not modified.
[ "<p", ">", "Performs", "an", "element", "by", "element", "multiplication", "operation", ":", "<br", ">", "<br", ">", "a<sub", ">", "i<", "/", "sub", ">", "=", "a<sub", ">", "i<", "/", "sub", ">", "*", "b<sub", ">", "i<", "/", "sub", ">", "<br", ">", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF4.java#L1307-L1312
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java
TypeUtility.typeName
public static TypeName typeName(TypeElement element, String suffix) { """ Type name. @param element the element @param suffix the suffix @return the type name """ String fullName = element.getQualifiedName().toString() + suffix; int lastIndex = fullName.lastIndexOf("."); String packageName = fullName.substring(0, lastIndex); String className = fullName.substring(lastIndex + 1); return typeName(packageName, className); }
java
public static TypeName typeName(TypeElement element, String suffix) { String fullName = element.getQualifiedName().toString() + suffix; int lastIndex = fullName.lastIndexOf("."); String packageName = fullName.substring(0, lastIndex); String className = fullName.substring(lastIndex + 1); return typeName(packageName, className); }
[ "public", "static", "TypeName", "typeName", "(", "TypeElement", "element", ",", "String", "suffix", ")", "{", "String", "fullName", "=", "element", ".", "getQualifiedName", "(", ")", ".", "toString", "(", ")", "+", "suffix", ";", "int", "lastIndex", "=", "fullName", ".", "lastIndexOf", "(", "\".\"", ")", ";", "String", "packageName", "=", "fullName", ".", "substring", "(", "0", ",", "lastIndex", ")", ";", "String", "className", "=", "fullName", ".", "substring", "(", "lastIndex", "+", "1", ")", ";", "return", "typeName", "(", "packageName", ",", "className", ")", ";", "}" ]
Type name. @param element the element @param suffix the suffix @return the type name
[ "Type", "name", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/core/reflect/TypeUtility.java#L488-L497
openengsb/openengsb
components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/AbstractEDBService.java
AbstractEDBService.runErrorHooks
private Long runErrorHooks(EDBCommit commit, EDBException exception) throws EDBException { """ Runs all registered error hooks on the EDBCommit object. Logs exceptions which occurs in the hooks, except for ServiceUnavailableExceptions and EDBExceptions. If an EDBException occurs, the function overrides the cause of the error with the new Exception. If an error hook returns a new EDBCommit, the EDB tries to persist this commit instead. """ for (EDBErrorHook hook : errorHooks) { try { EDBCommit newCommit = hook.onError(commit, exception); if (newCommit != null) { return commit(newCommit); } } catch (ServiceUnavailableException e) { // Ignore } catch (EDBException e) { exception = e; break; } catch (Exception e) { logger.error("Error while performing EDBErrorHook", e); } } throw exception; }
java
private Long runErrorHooks(EDBCommit commit, EDBException exception) throws EDBException { for (EDBErrorHook hook : errorHooks) { try { EDBCommit newCommit = hook.onError(commit, exception); if (newCommit != null) { return commit(newCommit); } } catch (ServiceUnavailableException e) { // Ignore } catch (EDBException e) { exception = e; break; } catch (Exception e) { logger.error("Error while performing EDBErrorHook", e); } } throw exception; }
[ "private", "Long", "runErrorHooks", "(", "EDBCommit", "commit", ",", "EDBException", "exception", ")", "throws", "EDBException", "{", "for", "(", "EDBErrorHook", "hook", ":", "errorHooks", ")", "{", "try", "{", "EDBCommit", "newCommit", "=", "hook", ".", "onError", "(", "commit", ",", "exception", ")", ";", "if", "(", "newCommit", "!=", "null", ")", "{", "return", "commit", "(", "newCommit", ")", ";", "}", "}", "catch", "(", "ServiceUnavailableException", "e", ")", "{", "// Ignore", "}", "catch", "(", "EDBException", "e", ")", "{", "exception", "=", "e", ";", "break", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Error while performing EDBErrorHook\"", ",", "e", ")", ";", "}", "}", "throw", "exception", ";", "}" ]
Runs all registered error hooks on the EDBCommit object. Logs exceptions which occurs in the hooks, except for ServiceUnavailableExceptions and EDBExceptions. If an EDBException occurs, the function overrides the cause of the error with the new Exception. If an error hook returns a new EDBCommit, the EDB tries to persist this commit instead.
[ "Runs", "all", "registered", "error", "hooks", "on", "the", "EDBCommit", "object", ".", "Logs", "exceptions", "which", "occurs", "in", "the", "hooks", "except", "for", "ServiceUnavailableExceptions", "and", "EDBExceptions", ".", "If", "an", "EDBException", "occurs", "the", "function", "overrides", "the", "cause", "of", "the", "error", "with", "the", "new", "Exception", ".", "If", "an", "error", "hook", "returns", "a", "new", "EDBCommit", "the", "EDB", "tries", "to", "persist", "this", "commit", "instead", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/edb/src/main/java/org/openengsb/core/edb/jpa/internal/AbstractEDBService.java#L192-L209
audit4j/audit4j-core
src/main/java/org/audit4j/core/ObjectToJsonSerializer.java
ObjectToJsonSerializer.deidentifyObject
public final static Object deidentifyObject(Object object, DeIdentify deidentify) { """ Deidentify object @param object the object to deidentify @param deidentify deidentify definition @return Object """ if (object == null || deidentify == null) { return object; } return DeIdentifyUtil.deidentify(String.valueOf(object), deidentify.left(), deidentify.right(), deidentify.fromLeft(), deidentify.fromRight()); }
java
public final static Object deidentifyObject(Object object, DeIdentify deidentify) { if (object == null || deidentify == null) { return object; } return DeIdentifyUtil.deidentify(String.valueOf(object), deidentify.left(), deidentify.right(), deidentify.fromLeft(), deidentify.fromRight()); }
[ "public", "final", "static", "Object", "deidentifyObject", "(", "Object", "object", ",", "DeIdentify", "deidentify", ")", "{", "if", "(", "object", "==", "null", "||", "deidentify", "==", "null", ")", "{", "return", "object", ";", "}", "return", "DeIdentifyUtil", ".", "deidentify", "(", "String", ".", "valueOf", "(", "object", ")", ",", "deidentify", ".", "left", "(", ")", ",", "deidentify", ".", "right", "(", ")", ",", "deidentify", ".", "fromLeft", "(", ")", ",", "deidentify", ".", "fromRight", "(", ")", ")", ";", "}" ]
Deidentify object @param object the object to deidentify @param deidentify deidentify definition @return Object
[ "Deidentify", "object" ]
train
https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/ObjectToJsonSerializer.java#L96-L103
jeremylong/DependencyCheck
utils/src/main/java/org/owasp/dependencycheck/utils/Checksum.java
Checksum.getMD5Checksum
public static String getMD5Checksum(String text) { """ Calculates the MD5 checksum of the specified text. @param text the text to generate the MD5 checksum @return the hex representation of the MD5 """ final byte[] data = stringToBytes(text); return getChecksum(MD5, data); }
java
public static String getMD5Checksum(String text) { final byte[] data = stringToBytes(text); return getChecksum(MD5, data); }
[ "public", "static", "String", "getMD5Checksum", "(", "String", "text", ")", "{", "final", "byte", "[", "]", "data", "=", "stringToBytes", "(", "text", ")", ";", "return", "getChecksum", "(", "MD5", ",", "data", ")", ";", "}" ]
Calculates the MD5 checksum of the specified text. @param text the text to generate the MD5 checksum @return the hex representation of the MD5
[ "Calculates", "the", "MD5", "checksum", "of", "the", "specified", "text", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/Checksum.java#L158-L161
liyiorg/weixin-popular
src/main/java/weixin/popular/api/MediaAPI.java
MediaAPI.mediaGet
public static MediaGetResult mediaGet(String access_token,String media_id) { """ 获取临时素材 @since 2.8.0 @param access_token access_token @param media_id media_id @return MediaGetResult """ return mediaGet(access_token, media_id, false); }
java
public static MediaGetResult mediaGet(String access_token,String media_id){ return mediaGet(access_token, media_id, false); }
[ "public", "static", "MediaGetResult", "mediaGet", "(", "String", "access_token", ",", "String", "media_id", ")", "{", "return", "mediaGet", "(", "access_token", ",", "media_id", ",", "false", ")", ";", "}" ]
获取临时素材 @since 2.8.0 @param access_token access_token @param media_id media_id @return MediaGetResult
[ "获取临时素材" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/MediaAPI.java#L169-L171
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/spi/index/provider/IndexChangeAdapters.java
IndexChangeAdapters.forPrimaryType
public static IndexChangeAdapter forPrimaryType( ExecutionContext context, NodeTypePredicate matcher, String workspaceName, ProvidedIndex<?> index ) { """ Create an {@link IndexChangeAdapter} implementation that handles the "jcr:primaryType" property. @param context the execution context; may not be null @param matcher the node type matcher used to determine which nodes should be included in the index; may not be null @param workspaceName the name of the workspace; may not be null @param index the local index that should be used; may not be null @return the new {@link IndexChangeAdapter}; never null """ return new PrimaryTypeChangeAdapter(context, matcher, workspaceName, index); }
java
public static IndexChangeAdapter forPrimaryType( ExecutionContext context, NodeTypePredicate matcher, String workspaceName, ProvidedIndex<?> index ) { return new PrimaryTypeChangeAdapter(context, matcher, workspaceName, index); }
[ "public", "static", "IndexChangeAdapter", "forPrimaryType", "(", "ExecutionContext", "context", ",", "NodeTypePredicate", "matcher", ",", "String", "workspaceName", ",", "ProvidedIndex", "<", "?", ">", "index", ")", "{", "return", "new", "PrimaryTypeChangeAdapter", "(", "context", ",", "matcher", ",", "workspaceName", ",", "index", ")", ";", "}" ]
Create an {@link IndexChangeAdapter} implementation that handles the "jcr:primaryType" property. @param context the execution context; may not be null @param matcher the node type matcher used to determine which nodes should be included in the index; may not be null @param workspaceName the name of the workspace; may not be null @param index the local index that should be used; may not be null @return the new {@link IndexChangeAdapter}; never null
[ "Create", "an", "{", "@link", "IndexChangeAdapter", "}", "implementation", "that", "handles", "the", "jcr", ":", "primaryType", "property", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/spi/index/provider/IndexChangeAdapters.java#L144-L149
groupon/odo
client/src/main/java/com/groupon/odo/client/Client.java
Client.setCustomResponseForDefaultClient
public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) { """ set custom response for profile's default client @param profileName profileName to modify @param pathName friendly name of path @param customData custom request data @return true if success, false otherwise """ try { return setCustomForDefaultClient(profileName, pathName, true, customData); } catch (Exception e) { e.printStackTrace(); } return false; }
java
public static boolean setCustomResponseForDefaultClient(String profileName, String pathName, String customData) { try { return setCustomForDefaultClient(profileName, pathName, true, customData); } catch (Exception e) { e.printStackTrace(); } return false; }
[ "public", "static", "boolean", "setCustomResponseForDefaultClient", "(", "String", "profileName", ",", "String", "pathName", ",", "String", "customData", ")", "{", "try", "{", "return", "setCustomForDefaultClient", "(", "profileName", ",", "pathName", ",", "true", ",", "customData", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "false", ";", "}" ]
set custom response for profile's default client @param profileName profileName to modify @param pathName friendly name of path @param customData custom request data @return true if success, false otherwise
[ "set", "custom", "response", "for", "profile", "s", "default", "client" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L835-L842
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Calendar.java
Calendar.getLimit
protected int getLimit(int field, int limitType) { """ Returns a limit for a field. @param field the field, from 0..<code>getFieldCount()-1</code> @param limitType the type specifier for the limit @see #MINIMUM @see #GREATEST_MINIMUM @see #LEAST_MAXIMUM @see #MAXIMUM """ switch (field) { case DAY_OF_WEEK: case AM_PM: case HOUR: case HOUR_OF_DAY: case MINUTE: case SECOND: case MILLISECOND: case ZONE_OFFSET: case DST_OFFSET: case DOW_LOCAL: case JULIAN_DAY: case MILLISECONDS_IN_DAY: case IS_LEAP_MONTH: return LIMITS[field][limitType]; case WEEK_OF_MONTH: { int limit; if (limitType == MINIMUM) { limit = getMinimalDaysInFirstWeek() == 1 ? 1 : 0; } else if (limitType == GREATEST_MINIMUM){ limit = 1; } else { int minDaysInFirst = getMinimalDaysInFirstWeek(); int daysInMonth = handleGetLimit(DAY_OF_MONTH, limitType); if (limitType == LEAST_MAXIMUM) { limit = (daysInMonth + (7 - minDaysInFirst)) / 7; } else { // limitType == MAXIMUM limit = (daysInMonth + 6 + (7 - minDaysInFirst)) / 7; } } return limit; } } return handleGetLimit(field, limitType); }
java
protected int getLimit(int field, int limitType) { switch (field) { case DAY_OF_WEEK: case AM_PM: case HOUR: case HOUR_OF_DAY: case MINUTE: case SECOND: case MILLISECOND: case ZONE_OFFSET: case DST_OFFSET: case DOW_LOCAL: case JULIAN_DAY: case MILLISECONDS_IN_DAY: case IS_LEAP_MONTH: return LIMITS[field][limitType]; case WEEK_OF_MONTH: { int limit; if (limitType == MINIMUM) { limit = getMinimalDaysInFirstWeek() == 1 ? 1 : 0; } else if (limitType == GREATEST_MINIMUM){ limit = 1; } else { int minDaysInFirst = getMinimalDaysInFirstWeek(); int daysInMonth = handleGetLimit(DAY_OF_MONTH, limitType); if (limitType == LEAST_MAXIMUM) { limit = (daysInMonth + (7 - minDaysInFirst)) / 7; } else { // limitType == MAXIMUM limit = (daysInMonth + 6 + (7 - minDaysInFirst)) / 7; } } return limit; } } return handleGetLimit(field, limitType); }
[ "protected", "int", "getLimit", "(", "int", "field", ",", "int", "limitType", ")", "{", "switch", "(", "field", ")", "{", "case", "DAY_OF_WEEK", ":", "case", "AM_PM", ":", "case", "HOUR", ":", "case", "HOUR_OF_DAY", ":", "case", "MINUTE", ":", "case", "SECOND", ":", "case", "MILLISECOND", ":", "case", "ZONE_OFFSET", ":", "case", "DST_OFFSET", ":", "case", "DOW_LOCAL", ":", "case", "JULIAN_DAY", ":", "case", "MILLISECONDS_IN_DAY", ":", "case", "IS_LEAP_MONTH", ":", "return", "LIMITS", "[", "field", "]", "[", "limitType", "]", ";", "case", "WEEK_OF_MONTH", ":", "{", "int", "limit", ";", "if", "(", "limitType", "==", "MINIMUM", ")", "{", "limit", "=", "getMinimalDaysInFirstWeek", "(", ")", "==", "1", "?", "1", ":", "0", ";", "}", "else", "if", "(", "limitType", "==", "GREATEST_MINIMUM", ")", "{", "limit", "=", "1", ";", "}", "else", "{", "int", "minDaysInFirst", "=", "getMinimalDaysInFirstWeek", "(", ")", ";", "int", "daysInMonth", "=", "handleGetLimit", "(", "DAY_OF_MONTH", ",", "limitType", ")", ";", "if", "(", "limitType", "==", "LEAST_MAXIMUM", ")", "{", "limit", "=", "(", "daysInMonth", "+", "(", "7", "-", "minDaysInFirst", ")", ")", "/", "7", ";", "}", "else", "{", "// limitType == MAXIMUM", "limit", "=", "(", "daysInMonth", "+", "6", "+", "(", "7", "-", "minDaysInFirst", ")", ")", "/", "7", ";", "}", "}", "return", "limit", ";", "}", "}", "return", "handleGetLimit", "(", "field", ",", "limitType", ")", ";", "}" ]
Returns a limit for a field. @param field the field, from 0..<code>getFieldCount()-1</code> @param limitType the type specifier for the limit @see #MINIMUM @see #GREATEST_MINIMUM @see #LEAST_MAXIMUM @see #MAXIMUM
[ "Returns", "a", "limit", "for", "a", "field", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Calendar.java#L4296-L4334
yanzhenjie/Album
album/src/main/java/com/yanzhenjie/album/util/AlbumUtils.java
AlbumUtils.takeImage
public static void takeImage(@NonNull Activity activity, int requestCode, File outPath) { """ Take picture. @param activity activity. @param requestCode code, see {@link Activity#onActivityResult(int, int, Intent)}. @param outPath file path. """ Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri uri = getUri(activity, outPath); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); activity.startActivityForResult(intent, requestCode); }
java
public static void takeImage(@NonNull Activity activity, int requestCode, File outPath) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri uri = getUri(activity, outPath); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); activity.startActivityForResult(intent, requestCode); }
[ "public", "static", "void", "takeImage", "(", "@", "NonNull", "Activity", "activity", ",", "int", "requestCode", ",", "File", "outPath", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "MediaStore", ".", "ACTION_IMAGE_CAPTURE", ")", ";", "Uri", "uri", "=", "getUri", "(", "activity", ",", "outPath", ")", ";", "intent", ".", "putExtra", "(", "MediaStore", ".", "EXTRA_OUTPUT", ",", "uri", ")", ";", "intent", ".", "addFlags", "(", "Intent", ".", "FLAG_GRANT_READ_URI_PERMISSION", ")", ";", "intent", ".", "addFlags", "(", "Intent", ".", "FLAG_GRANT_WRITE_URI_PERMISSION", ")", ";", "activity", ".", "startActivityForResult", "(", "intent", ",", "requestCode", ")", ";", "}" ]
Take picture. @param activity activity. @param requestCode code, see {@link Activity#onActivityResult(int, int, Intent)}. @param outPath file path.
[ "Take", "picture", "." ]
train
https://github.com/yanzhenjie/Album/blob/b17506440d32909d42aba41f6a388041a25c8363/album/src/main/java/com/yanzhenjie/album/util/AlbumUtils.java#L114-L121
getsentry/sentry-java
sentry/src/main/java/io/sentry/jvmti/FrameCache.java
FrameCache.shouldCacheThrowable
public static boolean shouldCacheThrowable(Throwable throwable, int numFrames) { """ Check whether the provided {@link Throwable} should be cached or not. Called by the native agent code so that the Java side (this code) can check the existing cache and user configuration, such as which packages are "in app". @param throwable Throwable to be checked @param numFrames Number of frames in the Throwable's stacktrace @return true if the Throwable should be processed and cached """ // only cache frames when 'in app' packages are provided if (appPackages.isEmpty()) { return false; } // many libraries/frameworks seem to rethrow the same object with trimmed // stacktraces, which means later ("smaller") throws would overwrite the existing // object in cache. for this reason we prefer the throw with the greatest stack // length... Map<Throwable, Frame[]> weakMap = cache.get(); Frame[] existing = weakMap.get(throwable); if (existing != null && numFrames <= existing.length) { return false; } // check each frame against all "in app" package prefixes for (StackTraceElement stackTraceElement : throwable.getStackTrace()) { for (String appFrame : appPackages) { if (stackTraceElement.getClassName().startsWith(appFrame)) { return true; } } } return false; }
java
public static boolean shouldCacheThrowable(Throwable throwable, int numFrames) { // only cache frames when 'in app' packages are provided if (appPackages.isEmpty()) { return false; } // many libraries/frameworks seem to rethrow the same object with trimmed // stacktraces, which means later ("smaller") throws would overwrite the existing // object in cache. for this reason we prefer the throw with the greatest stack // length... Map<Throwable, Frame[]> weakMap = cache.get(); Frame[] existing = weakMap.get(throwable); if (existing != null && numFrames <= existing.length) { return false; } // check each frame against all "in app" package prefixes for (StackTraceElement stackTraceElement : throwable.getStackTrace()) { for (String appFrame : appPackages) { if (stackTraceElement.getClassName().startsWith(appFrame)) { return true; } } } return false; }
[ "public", "static", "boolean", "shouldCacheThrowable", "(", "Throwable", "throwable", ",", "int", "numFrames", ")", "{", "// only cache frames when 'in app' packages are provided", "if", "(", "appPackages", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "// many libraries/frameworks seem to rethrow the same object with trimmed", "// stacktraces, which means later (\"smaller\") throws would overwrite the existing", "// object in cache. for this reason we prefer the throw with the greatest stack", "// length...", "Map", "<", "Throwable", ",", "Frame", "[", "]", ">", "weakMap", "=", "cache", ".", "get", "(", ")", ";", "Frame", "[", "]", "existing", "=", "weakMap", ".", "get", "(", "throwable", ")", ";", "if", "(", "existing", "!=", "null", "&&", "numFrames", "<=", "existing", ".", "length", ")", "{", "return", "false", ";", "}", "// check each frame against all \"in app\" package prefixes", "for", "(", "StackTraceElement", "stackTraceElement", ":", "throwable", ".", "getStackTrace", "(", ")", ")", "{", "for", "(", "String", "appFrame", ":", "appPackages", ")", "{", "if", "(", "stackTraceElement", ".", "getClassName", "(", ")", ".", "startsWith", "(", "appFrame", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Check whether the provided {@link Throwable} should be cached or not. Called by the native agent code so that the Java side (this code) can check the existing cache and user configuration, such as which packages are "in app". @param throwable Throwable to be checked @param numFrames Number of frames in the Throwable's stacktrace @return true if the Throwable should be processed and cached
[ "Check", "whether", "the", "provided", "{", "@link", "Throwable", "}", "should", "be", "cached", "or", "not", ".", "Called", "by", "the", "native", "agent", "code", "so", "that", "the", "Java", "side", "(", "this", "code", ")", "can", "check", "the", "existing", "cache", "and", "user", "configuration", "such", "as", "which", "packages", "are", "in", "app", "." ]
train
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/jvmti/FrameCache.java#L58-L84
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/TransformXMLInterceptor.java
TransformXMLInterceptor.newTransformer
private static Transformer newTransformer() { """ Creates a new Transformer instance using cached XSLT Templates. There will be one cached template. Transformer instances are not thread-safe and cannot be reused (they can after the transformation is complete). @return A new Transformer instance. """ if (TEMPLATES == null) { throw new IllegalStateException("TransformXMLInterceptor not initialized."); } try { return TEMPLATES.newTransformer(); } catch (TransformerConfigurationException ex) { throw new SystemException("Could not create transformer for " + RESOURCE_NAME, ex); } }
java
private static Transformer newTransformer() { if (TEMPLATES == null) { throw new IllegalStateException("TransformXMLInterceptor not initialized."); } try { return TEMPLATES.newTransformer(); } catch (TransformerConfigurationException ex) { throw new SystemException("Could not create transformer for " + RESOURCE_NAME, ex); } }
[ "private", "static", "Transformer", "newTransformer", "(", ")", "{", "if", "(", "TEMPLATES", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"TransformXMLInterceptor not initialized.\"", ")", ";", "}", "try", "{", "return", "TEMPLATES", ".", "newTransformer", "(", ")", ";", "}", "catch", "(", "TransformerConfigurationException", "ex", ")", "{", "throw", "new", "SystemException", "(", "\"Could not create transformer for \"", "+", "RESOURCE_NAME", ",", "ex", ")", ";", "}", "}" ]
Creates a new Transformer instance using cached XSLT Templates. There will be one cached template. Transformer instances are not thread-safe and cannot be reused (they can after the transformation is complete). @return A new Transformer instance.
[ "Creates", "a", "new", "Transformer", "instance", "using", "cached", "XSLT", "Templates", ".", "There", "will", "be", "one", "cached", "template", ".", "Transformer", "instances", "are", "not", "thread", "-", "safe", "and", "cannot", "be", "reused", "(", "they", "can", "after", "the", "transformation", "is", "complete", ")", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/container/TransformXMLInterceptor.java#L203-L214
opendigitaleducation/web-utils
src/main/java/org/vertx/java/core/http/RouteMatcher.java
RouteMatcher.optionsWithRegEx
public RouteMatcher optionsWithRegEx(String regex, Handler<HttpServerRequest> handler) { """ Specify a handler that will be called for a matching HTTP OPTIONS @param regex A regular expression @param handler The handler to call """ addRegEx(regex, handler, optionsBindings); return this; }
java
public RouteMatcher optionsWithRegEx(String regex, Handler<HttpServerRequest> handler) { addRegEx(regex, handler, optionsBindings); return this; }
[ "public", "RouteMatcher", "optionsWithRegEx", "(", "String", "regex", ",", "Handler", "<", "HttpServerRequest", ">", "handler", ")", "{", "addRegEx", "(", "regex", ",", "handler", ",", "optionsBindings", ")", ";", "return", "this", ";", "}" ]
Specify a handler that will be called for a matching HTTP OPTIONS @param regex A regular expression @param handler The handler to call
[ "Specify", "a", "handler", "that", "will", "be", "called", "for", "a", "matching", "HTTP", "OPTIONS" ]
train
https://github.com/opendigitaleducation/web-utils/blob/5c12f7e8781a9a0fbbe7b8d9fb741627aa97a1e3/src/main/java/org/vertx/java/core/http/RouteMatcher.java#L249-L252
gallandarakhneorg/afc
advanced/shapefile/src/main/java/org/arakhne/afc/io/shape/AbstractShapeFileReader.java
AbstractShapeFileReader.readPoint
private E readPoint(int elementIndex, ShapeElementType type) throws IOException { """ Read a point. @param elementIndex is the index of the element inside the shape file @param type is the type of the element to read. @return an object representing the creating point, depending of your implementation. This value will be passed to {@link #postRecordReadingStage(E)}. """ final boolean hasZ = type.hasZ(); final boolean hasM = type.hasM(); // Read coordinates final double x = fromESRI_x(readLEDouble()); final double y = fromESRI_y(readLEDouble()); double z = 0; double measure = Double.NaN; if (hasZ) { z = fromESRI_z(readLEDouble()); } if (hasM) { measure = fromESRI_m(readLEDouble()); } // Create the point if (!Double.isNaN(x) && !Double.isNaN(y)) { return createPoint(createAttributeCollection(elementIndex), elementIndex, new ESRIPoint(x, y, z, measure)); } return null; }
java
private E readPoint(int elementIndex, ShapeElementType type) throws IOException { final boolean hasZ = type.hasZ(); final boolean hasM = type.hasM(); // Read coordinates final double x = fromESRI_x(readLEDouble()); final double y = fromESRI_y(readLEDouble()); double z = 0; double measure = Double.NaN; if (hasZ) { z = fromESRI_z(readLEDouble()); } if (hasM) { measure = fromESRI_m(readLEDouble()); } // Create the point if (!Double.isNaN(x) && !Double.isNaN(y)) { return createPoint(createAttributeCollection(elementIndex), elementIndex, new ESRIPoint(x, y, z, measure)); } return null; }
[ "private", "E", "readPoint", "(", "int", "elementIndex", ",", "ShapeElementType", "type", ")", "throws", "IOException", "{", "final", "boolean", "hasZ", "=", "type", ".", "hasZ", "(", ")", ";", "final", "boolean", "hasM", "=", "type", ".", "hasM", "(", ")", ";", "// Read coordinates", "final", "double", "x", "=", "fromESRI_x", "(", "readLEDouble", "(", ")", ")", ";", "final", "double", "y", "=", "fromESRI_y", "(", "readLEDouble", "(", ")", ")", ";", "double", "z", "=", "0", ";", "double", "measure", "=", "Double", ".", "NaN", ";", "if", "(", "hasZ", ")", "{", "z", "=", "fromESRI_z", "(", "readLEDouble", "(", ")", ")", ";", "}", "if", "(", "hasM", ")", "{", "measure", "=", "fromESRI_m", "(", "readLEDouble", "(", ")", ")", ";", "}", "// Create the point", "if", "(", "!", "Double", ".", "isNaN", "(", "x", ")", "&&", "!", "Double", ".", "isNaN", "(", "y", ")", ")", "{", "return", "createPoint", "(", "createAttributeCollection", "(", "elementIndex", ")", ",", "elementIndex", ",", "new", "ESRIPoint", "(", "x", ",", "y", ",", "z", ",", "measure", ")", ")", ";", "}", "return", "null", ";", "}" ]
Read a point. @param elementIndex is the index of the element inside the shape file @param type is the type of the element to read. @return an object representing the creating point, depending of your implementation. This value will be passed to {@link #postRecordReadingStage(E)}.
[ "Read", "a", "point", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/shapefile/src/main/java/org/arakhne/afc/io/shape/AbstractShapeFileReader.java#L278-L301
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/async/WatcherManager.java
WatcherManager.addWatcher
public void addWatcher(String name, Watcher watcher) { """ Add a Watcher for the Service. @param name the ServiceName. @param watcher the Watcher. """ if(LOGGER.isTraceEnabled()){ LOGGER.trace("Add a watcher, name={}", name); } synchronized(watchers){ if (watchers.containsKey(name)) { watchers.get(name).add(watcher); } else { Set<Watcher> set = new HashSet<Watcher>(); set.add(watcher); watchers.put(name, set); } } }
java
public void addWatcher(String name, Watcher watcher){ if(LOGGER.isTraceEnabled()){ LOGGER.trace("Add a watcher, name={}", name); } synchronized(watchers){ if (watchers.containsKey(name)) { watchers.get(name).add(watcher); } else { Set<Watcher> set = new HashSet<Watcher>(); set.add(watcher); watchers.put(name, set); } } }
[ "public", "void", "addWatcher", "(", "String", "name", ",", "Watcher", "watcher", ")", "{", "if", "(", "LOGGER", ".", "isTraceEnabled", "(", ")", ")", "{", "LOGGER", ".", "trace", "(", "\"Add a watcher, name={}\"", ",", "name", ")", ";", "}", "synchronized", "(", "watchers", ")", "{", "if", "(", "watchers", ".", "containsKey", "(", "name", ")", ")", "{", "watchers", ".", "get", "(", "name", ")", ".", "add", "(", "watcher", ")", ";", "}", "else", "{", "Set", "<", "Watcher", ">", "set", "=", "new", "HashSet", "<", "Watcher", ">", "(", ")", ";", "set", ".", "add", "(", "watcher", ")", ";", "watchers", ".", "put", "(", "name", ",", "set", ")", ";", "}", "}", "}" ]
Add a Watcher for the Service. @param name the ServiceName. @param watcher the Watcher.
[ "Add", "a", "Watcher", "for", "the", "Service", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/async/WatcherManager.java#L85-L100
googleapis/google-oauth-java-client
google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java
AuthorizationCodeFlow.createAndStoreCredential
@SuppressWarnings("deprecation") public Credential createAndStoreCredential(TokenResponse response, String userId) throws IOException { """ Creates a new credential for the given user ID based on the given token response and stores it in the credential store. @param response token response @param userId user ID or {@code null} if not using a persisted credential store @return newly created credential """ Credential credential = newCredential(userId).setFromTokenResponse(response); if (credentialStore != null) { credentialStore.store(userId, credential); } if (credentialDataStore != null) { credentialDataStore.set(userId, new StoredCredential(credential)); } if (credentialCreatedListener != null) { credentialCreatedListener.onCredentialCreated(credential, response); } return credential; }
java
@SuppressWarnings("deprecation") public Credential createAndStoreCredential(TokenResponse response, String userId) throws IOException { Credential credential = newCredential(userId).setFromTokenResponse(response); if (credentialStore != null) { credentialStore.store(userId, credential); } if (credentialDataStore != null) { credentialDataStore.set(userId, new StoredCredential(credential)); } if (credentialCreatedListener != null) { credentialCreatedListener.onCredentialCreated(credential, response); } return credential; }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "Credential", "createAndStoreCredential", "(", "TokenResponse", "response", ",", "String", "userId", ")", "throws", "IOException", "{", "Credential", "credential", "=", "newCredential", "(", "userId", ")", ".", "setFromTokenResponse", "(", "response", ")", ";", "if", "(", "credentialStore", "!=", "null", ")", "{", "credentialStore", ".", "store", "(", "userId", ",", "credential", ")", ";", "}", "if", "(", "credentialDataStore", "!=", "null", ")", "{", "credentialDataStore", ".", "set", "(", "userId", ",", "new", "StoredCredential", "(", "credential", ")", ")", ";", "}", "if", "(", "credentialCreatedListener", "!=", "null", ")", "{", "credentialCreatedListener", ".", "onCredentialCreated", "(", "credential", ",", "response", ")", ";", "}", "return", "credential", ";", "}" ]
Creates a new credential for the given user ID based on the given token response and stores it in the credential store. @param response token response @param userId user ID or {@code null} if not using a persisted credential store @return newly created credential
[ "Creates", "a", "new", "credential", "for", "the", "given", "user", "ID", "based", "on", "the", "given", "token", "response", "and", "stores", "it", "in", "the", "credential", "store", "." ]
train
https://github.com/googleapis/google-oauth-java-client/blob/7a829f8fd4d216c7d5882a82b9b58930fb375592/google-oauth-client/src/main/java/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java#L222-L236
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java
ReviewsImpl.createVideoReviews
public List<String> createVideoReviews(String teamName, String contentType, List<CreateVideoReviewsBodyItem> createVideoReviewsBody, CreateVideoReviewsOptionalParameter createVideoReviewsOptionalParameter) { """ The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint. &lt;h3&gt;CallBack Schemas &lt;/h3&gt; &lt;h4&gt;Review Completion CallBack Sample&lt;/h4&gt; &lt;p&gt; {&lt;br/&gt; "ReviewId": "&lt;Review Id&gt;",&lt;br/&gt; "ModifiedOn": "2016-10-11T22:36:32.9934851Z",&lt;br/&gt; "ModifiedBy": "&lt;Name of the Reviewer&gt;",&lt;br/&gt; "CallBackType": "Review",&lt;br/&gt; "ContentId": "&lt;The ContentId that was specified input&gt;",&lt;br/&gt; "Metadata": {&lt;br/&gt; "adultscore": "0.xxx",&lt;br/&gt; "a": "False",&lt;br/&gt; "racyscore": "0.xxx",&lt;br/&gt; "r": "True"&lt;br/&gt; },&lt;br/&gt; "ReviewerResultTags": {&lt;br/&gt; "a": "False",&lt;br/&gt; "r": "True"&lt;br/&gt; }&lt;br/&gt; }&lt;br/&gt; &lt;/p&gt;. @param teamName Your team name. @param contentType The content type. @param createVideoReviewsBody Body for create reviews API @param createVideoReviewsOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the List&lt;String&gt; object if successful. """ return createVideoReviewsWithServiceResponseAsync(teamName, contentType, createVideoReviewsBody, createVideoReviewsOptionalParameter).toBlocking().single().body(); }
java
public List<String> createVideoReviews(String teamName, String contentType, List<CreateVideoReviewsBodyItem> createVideoReviewsBody, CreateVideoReviewsOptionalParameter createVideoReviewsOptionalParameter) { return createVideoReviewsWithServiceResponseAsync(teamName, contentType, createVideoReviewsBody, createVideoReviewsOptionalParameter).toBlocking().single().body(); }
[ "public", "List", "<", "String", ">", "createVideoReviews", "(", "String", "teamName", ",", "String", "contentType", ",", "List", "<", "CreateVideoReviewsBodyItem", ">", "createVideoReviewsBody", ",", "CreateVideoReviewsOptionalParameter", "createVideoReviewsOptionalParameter", ")", "{", "return", "createVideoReviewsWithServiceResponseAsync", "(", "teamName", ",", "contentType", ",", "createVideoReviewsBody", ",", "createVideoReviewsOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
The reviews created would show up for Reviewers on your team. As Reviewers complete reviewing, results of the Review would be POSTED (i.e. HTTP POST) on the specified CallBackEndpoint. &lt;h3&gt;CallBack Schemas &lt;/h3&gt; &lt;h4&gt;Review Completion CallBack Sample&lt;/h4&gt; &lt;p&gt; {&lt;br/&gt; "ReviewId": "&lt;Review Id&gt;",&lt;br/&gt; "ModifiedOn": "2016-10-11T22:36:32.9934851Z",&lt;br/&gt; "ModifiedBy": "&lt;Name of the Reviewer&gt;",&lt;br/&gt; "CallBackType": "Review",&lt;br/&gt; "ContentId": "&lt;The ContentId that was specified input&gt;",&lt;br/&gt; "Metadata": {&lt;br/&gt; "adultscore": "0.xxx",&lt;br/&gt; "a": "False",&lt;br/&gt; "racyscore": "0.xxx",&lt;br/&gt; "r": "True"&lt;br/&gt; },&lt;br/&gt; "ReviewerResultTags": {&lt;br/&gt; "a": "False",&lt;br/&gt; "r": "True"&lt;br/&gt; }&lt;br/&gt; }&lt;br/&gt; &lt;/p&gt;. @param teamName Your team name. @param contentType The content type. @param createVideoReviewsBody Body for create reviews API @param createVideoReviewsOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the List&lt;String&gt; object if successful.
[ "The", "reviews", "created", "would", "show", "up", "for", "Reviewers", "on", "your", "team", ".", "As", "Reviewers", "complete", "reviewing", "results", "of", "the", "Review", "would", "be", "POSTED", "(", "i", ".", "e", ".", "HTTP", "POST", ")", "on", "the", "specified", "CallBackEndpoint", ".", "&lt", ";", "h3&gt", ";", "CallBack", "Schemas", "&lt", ";", "/", "h3&gt", ";", "&lt", ";", "h4&gt", ";", "Review", "Completion", "CallBack", "Sample&lt", ";", "/", "h4&gt", ";", "&lt", ";", "p&gt", ";", "{", "&lt", ";", "br", "/", "&gt", ";", "ReviewId", ":", "&lt", ";", "Review", "Id&gt", ";", "&lt", ";", "br", "/", "&gt", ";", "ModifiedOn", ":", "2016", "-", "10", "-", "11T22", ":", "36", ":", "32", ".", "9934851Z", "&lt", ";", "br", "/", "&gt", ";", "ModifiedBy", ":", "&lt", ";", "Name", "of", "the", "Reviewer&gt", ";", "&lt", ";", "br", "/", "&gt", ";", "CallBackType", ":", "Review", "&lt", ";", "br", "/", "&gt", ";", "ContentId", ":", "&lt", ";", "The", "ContentId", "that", "was", "specified", "input&gt", ";", "&lt", ";", "br", "/", "&gt", ";", "Metadata", ":", "{", "&lt", ";", "br", "/", "&gt", ";", "adultscore", ":", "0", ".", "xxx", "&lt", ";", "br", "/", "&gt", ";", "a", ":", "False", "&lt", ";", "br", "/", "&gt", ";", "racyscore", ":", "0", ".", "xxx", "&lt", ";", "br", "/", "&gt", ";", "r", ":", "True", "&lt", ";", "br", "/", "&gt", ";", "}", "&lt", ";", "br", "/", "&gt", ";", "ReviewerResultTags", ":", "{", "&lt", ";", "br", "/", "&gt", ";", "a", ":", "False", "&lt", ";", "br", "/", "&gt", ";", "r", ":", "True", "&lt", ";", "br", "/", "&gt", ";", "}", "&lt", ";", "br", "/", "&gt", ";", "}", "&lt", ";", "br", "/", "&gt", ";", "&lt", ";", "/", "p&gt", ";", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java#L1908-L1910
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormat.java
DecimalFormat.skipUWhiteSpace
private static int skipUWhiteSpace(String text, int pos) { """ Skips over a run of zero or more isUWhiteSpace() characters at pos in text. """ while (pos < text.length()) { int c = UTF16.charAt(text, pos); if (!UCharacter.isUWhiteSpace(c)) { break; } pos += UTF16.getCharCount(c); } return pos; }
java
private static int skipUWhiteSpace(String text, int pos) { while (pos < text.length()) { int c = UTF16.charAt(text, pos); if (!UCharacter.isUWhiteSpace(c)) { break; } pos += UTF16.getCharCount(c); } return pos; }
[ "private", "static", "int", "skipUWhiteSpace", "(", "String", "text", ",", "int", "pos", ")", "{", "while", "(", "pos", "<", "text", ".", "length", "(", ")", ")", "{", "int", "c", "=", "UTF16", ".", "charAt", "(", "text", ",", "pos", ")", ";", "if", "(", "!", "UCharacter", ".", "isUWhiteSpace", "(", "c", ")", ")", "{", "break", ";", "}", "pos", "+=", "UTF16", ".", "getCharCount", "(", "c", ")", ";", "}", "return", "pos", ";", "}" ]
Skips over a run of zero or more isUWhiteSpace() characters at pos in text.
[ "Skips", "over", "a", "run", "of", "zero", "or", "more", "isUWhiteSpace", "()", "characters", "at", "pos", "in", "text", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormat.java#L3025-L3034
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/msgs/AirbornePositionV0Msg.java
AirbornePositionV0Msg.getLocalPosition
public Position getLocalPosition(Position ref) { """ This method uses a locally unambiguous decoding for airborne position messages. It uses a reference position known to be within 180NM (= 333.36km) of the true target airborne position. the reference point may be a previously tracked position that has been confirmed by global decoding (see getGlobalPosition()). @param ref reference position @return decoded position. The positional accuracy maintained by the Airborne CPR encoding will be approximately 5.1 meters. Result will be null if message does not contain horizontal position information. This can also be checked with {@link #hasPosition()}. """ if (!horizontal_position_available) return null; // latitude zone size double Dlat = isOddFormat() ? 360.0 / 59.0 : 360.0 / 60.0; // latitude zone index double j = Math.floor(ref.getLatitude() / Dlat) + Math.floor( 0.5 + mod(ref.getLatitude(), Dlat) / Dlat - ((double) getCPREncodedLatitude()) / ((double) (1 << 17))); // decoded position latitude double Rlat = Dlat * (j + ((double) getCPREncodedLatitude()) / ((double) (1 << 17))); // longitude zone size double Dlon = 360.0 / Math.max(1.0, NL(Rlat) - (isOddFormat() ? 1.0 : 0.0)); // longitude zone coordinate double m = Math.floor(ref.getLongitude() / Dlon) + Math.floor(0.5 + mod(ref.getLongitude(), Dlon) / Dlon - ((double) getCPREncodedLongitude()) / ((double) (1 << 17))); // and finally the longitude double Rlon = Dlon * (m + ((double) getCPREncodedLongitude()) / ((double) (1 << 17))); Integer alt = this.getAltitude(); return new Position(Rlon, Rlat, alt != null ? alt.doubleValue() : null); }
java
public Position getLocalPosition(Position ref) { if (!horizontal_position_available) return null; // latitude zone size double Dlat = isOddFormat() ? 360.0 / 59.0 : 360.0 / 60.0; // latitude zone index double j = Math.floor(ref.getLatitude() / Dlat) + Math.floor( 0.5 + mod(ref.getLatitude(), Dlat) / Dlat - ((double) getCPREncodedLatitude()) / ((double) (1 << 17))); // decoded position latitude double Rlat = Dlat * (j + ((double) getCPREncodedLatitude()) / ((double) (1 << 17))); // longitude zone size double Dlon = 360.0 / Math.max(1.0, NL(Rlat) - (isOddFormat() ? 1.0 : 0.0)); // longitude zone coordinate double m = Math.floor(ref.getLongitude() / Dlon) + Math.floor(0.5 + mod(ref.getLongitude(), Dlon) / Dlon - ((double) getCPREncodedLongitude()) / ((double) (1 << 17))); // and finally the longitude double Rlon = Dlon * (m + ((double) getCPREncodedLongitude()) / ((double) (1 << 17))); Integer alt = this.getAltitude(); return new Position(Rlon, Rlat, alt != null ? alt.doubleValue() : null); }
[ "public", "Position", "getLocalPosition", "(", "Position", "ref", ")", "{", "if", "(", "!", "horizontal_position_available", ")", "return", "null", ";", "// latitude zone size", "double", "Dlat", "=", "isOddFormat", "(", ")", "?", "360.0", "/", "59.0", ":", "360.0", "/", "60.0", ";", "// latitude zone index", "double", "j", "=", "Math", ".", "floor", "(", "ref", ".", "getLatitude", "(", ")", "/", "Dlat", ")", "+", "Math", ".", "floor", "(", "0.5", "+", "mod", "(", "ref", ".", "getLatitude", "(", ")", ",", "Dlat", ")", "/", "Dlat", "-", "(", "(", "double", ")", "getCPREncodedLatitude", "(", ")", ")", "/", "(", "(", "double", ")", "(", "1", "<<", "17", ")", ")", ")", ";", "// decoded position latitude", "double", "Rlat", "=", "Dlat", "*", "(", "j", "+", "(", "(", "double", ")", "getCPREncodedLatitude", "(", ")", ")", "/", "(", "(", "double", ")", "(", "1", "<<", "17", ")", ")", ")", ";", "// longitude zone size", "double", "Dlon", "=", "360.0", "/", "Math", ".", "max", "(", "1.0", ",", "NL", "(", "Rlat", ")", "-", "(", "isOddFormat", "(", ")", "?", "1.0", ":", "0.0", ")", ")", ";", "// longitude zone coordinate", "double", "m", "=", "Math", ".", "floor", "(", "ref", ".", "getLongitude", "(", ")", "/", "Dlon", ")", "+", "Math", ".", "floor", "(", "0.5", "+", "mod", "(", "ref", ".", "getLongitude", "(", ")", ",", "Dlon", ")", "/", "Dlon", "-", "(", "(", "double", ")", "getCPREncodedLongitude", "(", ")", ")", "/", "(", "(", "double", ")", "(", "1", "<<", "17", ")", ")", ")", ";", "// and finally the longitude", "double", "Rlon", "=", "Dlon", "*", "(", "m", "+", "(", "(", "double", ")", "getCPREncodedLongitude", "(", ")", ")", "/", "(", "(", "double", ")", "(", "1", "<<", "17", ")", ")", ")", ";", "Integer", "alt", "=", "this", ".", "getAltitude", "(", ")", ";", "return", "new", "Position", "(", "Rlon", ",", "Rlat", ",", "alt", "!=", "null", "?", "alt", ".", "doubleValue", "(", ")", ":", "null", ")", ";", "}" ]
This method uses a locally unambiguous decoding for airborne position messages. It uses a reference position known to be within 180NM (= 333.36km) of the true target airborne position. the reference point may be a previously tracked position that has been confirmed by global decoding (see getGlobalPosition()). @param ref reference position @return decoded position. The positional accuracy maintained by the Airborne CPR encoding will be approximately 5.1 meters. Result will be null if message does not contain horizontal position information. This can also be checked with {@link #hasPosition()}.
[ "This", "method", "uses", "a", "locally", "unambiguous", "decoding", "for", "airborne", "position", "messages", ".", "It", "uses", "a", "reference", "position", "known", "to", "be", "within", "180NM", "(", "=", "333", ".", "36km", ")", "of", "the", "true", "target", "airborne", "position", ".", "the", "reference", "point", "may", "be", "a", "previously", "tracked", "position", "that", "has", "been", "confirmed", "by", "global", "decoding", "(", "see", "getGlobalPosition", "()", ")", "." ]
train
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/msgs/AirbornePositionV0Msg.java#L403-L429
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/bayesian/graphicalmodel/DirectedGraph.java
DirectedGraph.removeEdge
public void removeEdge(N a, N b) { """ Removes a directed edge from the network connecting <tt>a</tt> to <tt>b</tt>. If <tt>a</tt> and <tt>b</tt> are not nodes in the graph, nothing occurs. @param a the parent node @param b the child node """ if(!containsBoth(a, b)) return; nodes.get(a).getOutgoing().remove(b); nodes.get(b).getIncoming().remove(a); }
java
public void removeEdge(N a, N b) { if(!containsBoth(a, b)) return; nodes.get(a).getOutgoing().remove(b); nodes.get(b).getIncoming().remove(a); }
[ "public", "void", "removeEdge", "(", "N", "a", ",", "N", "b", ")", "{", "if", "(", "!", "containsBoth", "(", "a", ",", "b", ")", ")", "return", ";", "nodes", ".", "get", "(", "a", ")", ".", "getOutgoing", "(", ")", ".", "remove", "(", "b", ")", ";", "nodes", ".", "get", "(", "b", ")", ".", "getIncoming", "(", ")", ".", "remove", "(", "a", ")", ";", "}" ]
Removes a directed edge from the network connecting <tt>a</tt> to <tt>b</tt>. If <tt>a</tt> and <tt>b</tt> are not nodes in the graph, nothing occurs. @param a the parent node @param b the child node
[ "Removes", "a", "directed", "edge", "from", "the", "network", "connecting", "<tt", ">", "a<", "/", "tt", ">", "to", "<tt", ">", "b<", "/", "tt", ">", ".", "If", "<tt", ">", "a<", "/", "tt", ">", "and", "<tt", ">", "b<", "/", "tt", ">", "are", "not", "nodes", "in", "the", "graph", "nothing", "occurs", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/bayesian/graphicalmodel/DirectedGraph.java#L190-L196
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/URLConnection.java
URLConnection.getHeaderFieldDate
public long getHeaderFieldDate(String name, long Default) { """ Returns the value of the named field parsed as date. The result is the number of milliseconds since January 1, 1970 GMT represented by the named field. <p> This form of <code>getHeaderField</code> exists because some connection types (e.g., <code>http-ng</code>) have pre-parsed headers. Classes for that connection type can override this method and short-circuit the parsing. @param name the name of the header field. @param Default a default value. @return the value of the field, parsed as a date. The value of the <code>Default</code> argument is returned if the field is missing or malformed. """ String value = getHeaderField(name); try { return Date.parse(value); } catch (Exception e) { } return Default; }
java
public long getHeaderFieldDate(String name, long Default) { String value = getHeaderField(name); try { return Date.parse(value); } catch (Exception e) { } return Default; }
[ "public", "long", "getHeaderFieldDate", "(", "String", "name", ",", "long", "Default", ")", "{", "String", "value", "=", "getHeaderField", "(", "name", ")", ";", "try", "{", "return", "Date", ".", "parse", "(", "value", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "return", "Default", ";", "}" ]
Returns the value of the named field parsed as date. The result is the number of milliseconds since January 1, 1970 GMT represented by the named field. <p> This form of <code>getHeaderField</code> exists because some connection types (e.g., <code>http-ng</code>) have pre-parsed headers. Classes for that connection type can override this method and short-circuit the parsing. @param name the name of the header field. @param Default a default value. @return the value of the field, parsed as a date. The value of the <code>Default</code> argument is returned if the field is missing or malformed.
[ "Returns", "the", "value", "of", "the", "named", "field", "parsed", "as", "date", ".", "The", "result", "is", "the", "number", "of", "milliseconds", "since", "January", "1", "1970", "GMT", "represented", "by", "the", "named", "field", ".", "<p", ">", "This", "form", "of", "<code", ">", "getHeaderField<", "/", "code", ">", "exists", "because", "some", "connection", "types", "(", "e", ".", "g", ".", "<code", ">", "http", "-", "ng<", "/", "code", ">", ")", "have", "pre", "-", "parsed", "headers", ".", "Classes", "for", "that", "connection", "type", "can", "override", "this", "method", "and", "short", "-", "circuit", "the", "parsing", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/URLConnection.java#L649-L655
jasminb/jsonapi-converter
src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java
ResourceConverter.readObject
@Deprecated public <T> T readObject(byte [] data, Class<T> clazz) { """ Converts raw data input into requested target type. @param data raw data @param clazz target object @param <T> type @return converted object @throws RuntimeException in case conversion fails """ return readDocument(data, clazz).get(); }
java
@Deprecated public <T> T readObject(byte [] data, Class<T> clazz) { return readDocument(data, clazz).get(); }
[ "@", "Deprecated", "public", "<", "T", ">", "T", "readObject", "(", "byte", "[", "]", "data", ",", "Class", "<", "T", ">", "clazz", ")", "{", "return", "readDocument", "(", "data", ",", "clazz", ")", ".", "get", "(", ")", ";", "}" ]
Converts raw data input into requested target type. @param data raw data @param clazz target object @param <T> type @return converted object @throws RuntimeException in case conversion fails
[ "Converts", "raw", "data", "input", "into", "requested", "target", "type", "." ]
train
https://github.com/jasminb/jsonapi-converter/blob/73b41c3b9274e70e62b3425071ca8afdc7bddaf6/src/main/java/com/github/jasminb/jsonapi/ResourceConverter.java#L148-L151
apache/incubator-gobblin
gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/GoogleWebmasterDataFetcherImpl.java
GoogleWebmasterDataFetcherImpl.getAllPages
@Override public Collection<ProducerJob> getAllPages(String startDate, String endDate, String country, int rowLimit) throws IOException { """ Due to the limitation of the API, we can get a maximum of 5000 rows at a time. Another limitation is that, results are sorted by click count descending. If two rows have the same click count, they are sorted in an arbitrary way. (Read more at https://developers.google.com/webmaster-tools/v3/searchanalytics). So we try to get all pages by partitions, if a partition has 5000 rows returned. We try partition current partition into more granular levels. """ log.info("Requested row limit: " + rowLimit); if (!_jobs.isEmpty()) { log.info("Service got hot started."); return _jobs; } ApiDimensionFilter countryFilter = GoogleWebmasterFilter.countryEqFilter(country); List<GoogleWebmasterFilter.Dimension> requestedDimensions = new ArrayList<>(); requestedDimensions.add(GoogleWebmasterFilter.Dimension.PAGE); int expectedSize = -1; if (rowLimit >= GoogleWebmasterClient.API_ROW_LIMIT) { //expected size only makes sense when the data set size is larger than GoogleWebmasterClient.API_ROW_LIMIT expectedSize = getPagesSize(startDate, endDate, country, requestedDimensions, Arrays.asList(countryFilter)); log.info(String.format("Expected number of pages is %d for market-%s from %s to %s", expectedSize, GoogleWebmasterFilter.countryFilterToString(countryFilter), startDate, endDate)); } Queue<Pair<String, FilterOperator>> jobs = new ArrayDeque<>(); jobs.add(Pair.of(_siteProperty, FilterOperator.CONTAINS)); Collection<String> allPages = getPages(startDate, endDate, requestedDimensions, countryFilter, jobs, Math.min(rowLimit, GoogleWebmasterClient.API_ROW_LIMIT)); int actualSize = allPages.size(); log.info(String.format("A total of %d pages fetched for property %s at country-%s from %s to %s", actualSize, _siteProperty, country, startDate, endDate)); if (expectedSize != -1 && actualSize != expectedSize) { log.warn(String.format("Expected page size is %d, but only able to get %d", expectedSize, actualSize)); } ArrayDeque<ProducerJob> producerJobs = new ArrayDeque<>(actualSize); for (String page : allPages) { producerJobs.add(new SimpleProducerJob(page, startDate, endDate)); } return producerJobs; }
java
@Override public Collection<ProducerJob> getAllPages(String startDate, String endDate, String country, int rowLimit) throws IOException { log.info("Requested row limit: " + rowLimit); if (!_jobs.isEmpty()) { log.info("Service got hot started."); return _jobs; } ApiDimensionFilter countryFilter = GoogleWebmasterFilter.countryEqFilter(country); List<GoogleWebmasterFilter.Dimension> requestedDimensions = new ArrayList<>(); requestedDimensions.add(GoogleWebmasterFilter.Dimension.PAGE); int expectedSize = -1; if (rowLimit >= GoogleWebmasterClient.API_ROW_LIMIT) { //expected size only makes sense when the data set size is larger than GoogleWebmasterClient.API_ROW_LIMIT expectedSize = getPagesSize(startDate, endDate, country, requestedDimensions, Arrays.asList(countryFilter)); log.info(String.format("Expected number of pages is %d for market-%s from %s to %s", expectedSize, GoogleWebmasterFilter.countryFilterToString(countryFilter), startDate, endDate)); } Queue<Pair<String, FilterOperator>> jobs = new ArrayDeque<>(); jobs.add(Pair.of(_siteProperty, FilterOperator.CONTAINS)); Collection<String> allPages = getPages(startDate, endDate, requestedDimensions, countryFilter, jobs, Math.min(rowLimit, GoogleWebmasterClient.API_ROW_LIMIT)); int actualSize = allPages.size(); log.info(String.format("A total of %d pages fetched for property %s at country-%s from %s to %s", actualSize, _siteProperty, country, startDate, endDate)); if (expectedSize != -1 && actualSize != expectedSize) { log.warn(String.format("Expected page size is %d, but only able to get %d", expectedSize, actualSize)); } ArrayDeque<ProducerJob> producerJobs = new ArrayDeque<>(actualSize); for (String page : allPages) { producerJobs.add(new SimpleProducerJob(page, startDate, endDate)); } return producerJobs; }
[ "@", "Override", "public", "Collection", "<", "ProducerJob", ">", "getAllPages", "(", "String", "startDate", ",", "String", "endDate", ",", "String", "country", ",", "int", "rowLimit", ")", "throws", "IOException", "{", "log", ".", "info", "(", "\"Requested row limit: \"", "+", "rowLimit", ")", ";", "if", "(", "!", "_jobs", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "info", "(", "\"Service got hot started.\"", ")", ";", "return", "_jobs", ";", "}", "ApiDimensionFilter", "countryFilter", "=", "GoogleWebmasterFilter", ".", "countryEqFilter", "(", "country", ")", ";", "List", "<", "GoogleWebmasterFilter", ".", "Dimension", ">", "requestedDimensions", "=", "new", "ArrayList", "<>", "(", ")", ";", "requestedDimensions", ".", "add", "(", "GoogleWebmasterFilter", ".", "Dimension", ".", "PAGE", ")", ";", "int", "expectedSize", "=", "-", "1", ";", "if", "(", "rowLimit", ">=", "GoogleWebmasterClient", ".", "API_ROW_LIMIT", ")", "{", "//expected size only makes sense when the data set size is larger than GoogleWebmasterClient.API_ROW_LIMIT", "expectedSize", "=", "getPagesSize", "(", "startDate", ",", "endDate", ",", "country", ",", "requestedDimensions", ",", "Arrays", ".", "asList", "(", "countryFilter", ")", ")", ";", "log", ".", "info", "(", "String", ".", "format", "(", "\"Expected number of pages is %d for market-%s from %s to %s\"", ",", "expectedSize", ",", "GoogleWebmasterFilter", ".", "countryFilterToString", "(", "countryFilter", ")", ",", "startDate", ",", "endDate", ")", ")", ";", "}", "Queue", "<", "Pair", "<", "String", ",", "FilterOperator", ">", ">", "jobs", "=", "new", "ArrayDeque", "<>", "(", ")", ";", "jobs", ".", "add", "(", "Pair", ".", "of", "(", "_siteProperty", ",", "FilterOperator", ".", "CONTAINS", ")", ")", ";", "Collection", "<", "String", ">", "allPages", "=", "getPages", "(", "startDate", ",", "endDate", ",", "requestedDimensions", ",", "countryFilter", ",", "jobs", ",", "Math", ".", "min", "(", "rowLimit", ",", "GoogleWebmasterClient", ".", "API_ROW_LIMIT", ")", ")", ";", "int", "actualSize", "=", "allPages", ".", "size", "(", ")", ";", "log", ".", "info", "(", "String", ".", "format", "(", "\"A total of %d pages fetched for property %s at country-%s from %s to %s\"", ",", "actualSize", ",", "_siteProperty", ",", "country", ",", "startDate", ",", "endDate", ")", ")", ";", "if", "(", "expectedSize", "!=", "-", "1", "&&", "actualSize", "!=", "expectedSize", ")", "{", "log", ".", "warn", "(", "String", ".", "format", "(", "\"Expected page size is %d, but only able to get %d\"", ",", "expectedSize", ",", "actualSize", ")", ")", ";", "}", "ArrayDeque", "<", "ProducerJob", ">", "producerJobs", "=", "new", "ArrayDeque", "<>", "(", "actualSize", ")", ";", "for", "(", "String", "page", ":", "allPages", ")", "{", "producerJobs", ".", "add", "(", "new", "SimpleProducerJob", "(", "page", ",", "startDate", ",", "endDate", ")", ")", ";", "}", "return", "producerJobs", ";", "}" ]
Due to the limitation of the API, we can get a maximum of 5000 rows at a time. Another limitation is that, results are sorted by click count descending. If two rows have the same click count, they are sorted in an arbitrary way. (Read more at https://developers.google.com/webmaster-tools/v3/searchanalytics). So we try to get all pages by partitions, if a partition has 5000 rows returned. We try partition current partition into more granular levels.
[ "Due", "to", "the", "limitation", "of", "the", "API", "we", "can", "get", "a", "maximum", "of", "5000", "rows", "at", "a", "time", ".", "Another", "limitation", "is", "that", "results", "are", "sorted", "by", "click", "count", "descending", ".", "If", "two", "rows", "have", "the", "same", "click", "count", "they", "are", "sorted", "in", "an", "arbitrary", "way", ".", "(", "Read", "more", "at", "https", ":", "//", "developers", ".", "google", ".", "com", "/", "webmaster", "-", "tools", "/", "v3", "/", "searchanalytics", ")", ".", "So", "we", "try", "to", "get", "all", "pages", "by", "partitions", "if", "a", "partition", "has", "5000", "rows", "returned", ".", "We", "try", "partition", "current", "partition", "into", "more", "granular", "levels", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/GoogleWebmasterDataFetcherImpl.java#L86-L124
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonWriter.java
JsonWriter.writeRawJson
public String writeRawJson(final String json, final String contextUrl) throws ODataRenderException { """ Writes raw json to the JSON stream. @param json JSON to write @param contextUrl context URL @return JSON result @throws ODataRenderException OData render exception """ this.contextURL = checkNotNull(contextUrl); try { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8); jsonGenerator.writeRaw(json); jsonGenerator.close(); return stream.toString(StandardCharsets.UTF_8.name()); } catch (final IOException e) { throw new ODataRenderException("Not possible to write raw json to stream JSON: ", e); } }
java
public String writeRawJson(final String json, final String contextUrl) throws ODataRenderException { this.contextURL = checkNotNull(contextUrl); try { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8); jsonGenerator.writeRaw(json); jsonGenerator.close(); return stream.toString(StandardCharsets.UTF_8.name()); } catch (final IOException e) { throw new ODataRenderException("Not possible to write raw json to stream JSON: ", e); } }
[ "public", "String", "writeRawJson", "(", "final", "String", "json", ",", "final", "String", "contextUrl", ")", "throws", "ODataRenderException", "{", "this", ".", "contextURL", "=", "checkNotNull", "(", "contextUrl", ")", ";", "try", "{", "final", "ByteArrayOutputStream", "stream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "jsonGenerator", "=", "JSON_FACTORY", ".", "createGenerator", "(", "stream", ",", "JsonEncoding", ".", "UTF8", ")", ";", "jsonGenerator", ".", "writeRaw", "(", "json", ")", ";", "jsonGenerator", ".", "close", "(", ")", ";", "return", "stream", ".", "toString", "(", "StandardCharsets", ".", "UTF_8", ".", "name", "(", ")", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "throw", "new", "ODataRenderException", "(", "\"Not possible to write raw json to stream JSON: \"", ",", "e", ")", ";", "}", "}" ]
Writes raw json to the JSON stream. @param json JSON to write @param contextUrl context URL @return JSON result @throws ODataRenderException OData render exception
[ "Writes", "raw", "json", "to", "the", "JSON", "stream", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/json/writer/JsonWriter.java#L146-L157
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
EscapedFunctions2.sqldayofmonth
public static void sqldayofmonth(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { """ dayofmonth translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens """ singleArgumentFunctionCall(buf, "extract(day from ", "dayofmonth", parsedArgs); }
java
public static void sqldayofmonth(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "extract(day from ", "dayofmonth", parsedArgs); }
[ "public", "static", "void", "sqldayofmonth", "(", "StringBuilder", "buf", ",", "List", "<", "?", "extends", "CharSequence", ">", "parsedArgs", ")", "throws", "SQLException", "{", "singleArgumentFunctionCall", "(", "buf", ",", "\"extract(day from \"", ",", "\"dayofmonth\"", ",", "parsedArgs", ")", ";", "}" ]
dayofmonth translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens
[ "dayofmonth", "translation" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L368-L370
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java
StringIterate.tokensToMap
public static MutableMap<String, String> tokensToMap( String string, String pairSeparator, String keyValueSeparator) { """ Converts a string of tokens to a {@link MutableMap} using the specified separators. """ MutableMap<String, String> map = UnifiedMap.newMap(); for (StringTokenizer tokenizer = new StringTokenizer(string, pairSeparator); tokenizer.hasMoreTokens(); ) { String token = tokenizer.nextToken(); String key = token.substring(0, token.indexOf(keyValueSeparator)); String value = token.substring(token.indexOf(keyValueSeparator) + 1, token.length()); map.put(key, value); } return map; }
java
public static MutableMap<String, String> tokensToMap( String string, String pairSeparator, String keyValueSeparator) { MutableMap<String, String> map = UnifiedMap.newMap(); for (StringTokenizer tokenizer = new StringTokenizer(string, pairSeparator); tokenizer.hasMoreTokens(); ) { String token = tokenizer.nextToken(); String key = token.substring(0, token.indexOf(keyValueSeparator)); String value = token.substring(token.indexOf(keyValueSeparator) + 1, token.length()); map.put(key, value); } return map; }
[ "public", "static", "MutableMap", "<", "String", ",", "String", ">", "tokensToMap", "(", "String", "string", ",", "String", "pairSeparator", ",", "String", "keyValueSeparator", ")", "{", "MutableMap", "<", "String", ",", "String", ">", "map", "=", "UnifiedMap", ".", "newMap", "(", ")", ";", "for", "(", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "string", ",", "pairSeparator", ")", ";", "tokenizer", ".", "hasMoreTokens", "(", ")", ";", ")", "{", "String", "token", "=", "tokenizer", ".", "nextToken", "(", ")", ";", "String", "key", "=", "token", ".", "substring", "(", "0", ",", "token", ".", "indexOf", "(", "keyValueSeparator", ")", ")", ";", "String", "value", "=", "token", ".", "substring", "(", "token", ".", "indexOf", "(", "keyValueSeparator", ")", "+", "1", ",", "token", ".", "length", "(", ")", ")", ";", "map", ".", "put", "(", "key", ",", "value", ")", ";", "}", "return", "map", ";", "}" ]
Converts a string of tokens to a {@link MutableMap} using the specified separators.
[ "Converts", "a", "string", "of", "tokens", "to", "a", "{" ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java#L223-L237
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java
DateFunctions.dateDiffStr
public static Expression dateDiffStr(Expression expression1, Expression expression2, DatePart part) { """ Returned expression results in Performs Date arithmetic. Returns the elapsed time between two date strings in a supported format, as an integer whose unit is part. """ return x("DATE_DIFF_STR(" + expression1.toString() + ", " + expression2.toString() + ", \"" + part.toString() + "\")"); }
java
public static Expression dateDiffStr(Expression expression1, Expression expression2, DatePart part) { return x("DATE_DIFF_STR(" + expression1.toString() + ", " + expression2.toString() + ", \"" + part.toString() + "\")"); }
[ "public", "static", "Expression", "dateDiffStr", "(", "Expression", "expression1", ",", "Expression", "expression2", ",", "DatePart", "part", ")", "{", "return", "x", "(", "\"DATE_DIFF_STR(\"", "+", "expression1", ".", "toString", "(", ")", "+", "\", \"", "+", "expression2", ".", "toString", "(", ")", "+", "\", \\\"\"", "+", "part", ".", "toString", "(", ")", "+", "\"\\\")\"", ")", ";", "}" ]
Returned expression results in Performs Date arithmetic. Returns the elapsed time between two date strings in a supported format, as an integer whose unit is part.
[ "Returned", "expression", "results", "in", "Performs", "Date", "arithmetic", ".", "Returns", "the", "elapsed", "time", "between", "two", "date", "strings", "in", "a", "supported", "format", "as", "an", "integer", "whose", "unit", "is", "part", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L123-L126
OpenLiberty/open-liberty
dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/SystemConfiguration.java
SystemConfiguration.addDefaultConfiguration
BaseConfiguration addDefaultConfiguration(String pid, Dictionary<String, String> props) throws ConfigUpdateException { """ Add configuration to the default configuration add runtime @param pid @param props @return """ return defaultConfiguration.add(pid, props, serverXMLConfig, variableRegistry); }
java
BaseConfiguration addDefaultConfiguration(String pid, Dictionary<String, String> props) throws ConfigUpdateException { return defaultConfiguration.add(pid, props, serverXMLConfig, variableRegistry); }
[ "BaseConfiguration", "addDefaultConfiguration", "(", "String", "pid", ",", "Dictionary", "<", "String", ",", "String", ">", "props", ")", "throws", "ConfigUpdateException", "{", "return", "defaultConfiguration", ".", "add", "(", "pid", ",", "props", ",", "serverXMLConfig", ",", "variableRegistry", ")", ";", "}" ]
Add configuration to the default configuration add runtime @param pid @param props @return
[ "Add", "configuration", "to", "the", "default", "configuration", "add", "runtime" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.config/src/com/ibm/ws/config/xml/internal/SystemConfiguration.java#L190-L192
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/ZoneOperationId.java
ZoneOperationId.of
public static ZoneOperationId of(String zone, String operation) { """ Returns a zone operation identity given the zone and operation names. """ return new ZoneOperationId(null, zone, operation); }
java
public static ZoneOperationId of(String zone, String operation) { return new ZoneOperationId(null, zone, operation); }
[ "public", "static", "ZoneOperationId", "of", "(", "String", "zone", ",", "String", "operation", ")", "{", "return", "new", "ZoneOperationId", "(", "null", ",", "zone", ",", "operation", ")", ";", "}" ]
Returns a zone operation identity given the zone and operation names.
[ "Returns", "a", "zone", "operation", "identity", "given", "the", "zone", "and", "operation", "names", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/ZoneOperationId.java#L96-L98
Impetus/Kundera
src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java
MongoDBClient.createUniqueIndexGFS
private void createUniqueIndexGFS(DBCollection coll, String id) { """ Creates the unique index gfs. @param coll the coll @param id the id """ try { coll.createIndex(new BasicDBObject("metadata." + id, 1), new BasicDBObject("unique", true)); } catch (MongoException ex) { throw new KunderaException("Error in creating unique indexes in " + coll.getFullName() + " collection on " + id + " field"); } }
java
private void createUniqueIndexGFS(DBCollection coll, String id) { try { coll.createIndex(new BasicDBObject("metadata." + id, 1), new BasicDBObject("unique", true)); } catch (MongoException ex) { throw new KunderaException("Error in creating unique indexes in " + coll.getFullName() + " collection on " + id + " field"); } }
[ "private", "void", "createUniqueIndexGFS", "(", "DBCollection", "coll", ",", "String", "id", ")", "{", "try", "{", "coll", ".", "createIndex", "(", "new", "BasicDBObject", "(", "\"metadata.\"", "+", "id", ",", "1", ")", ",", "new", "BasicDBObject", "(", "\"unique\"", ",", "true", ")", ")", ";", "}", "catch", "(", "MongoException", "ex", ")", "{", "throw", "new", "KunderaException", "(", "\"Error in creating unique indexes in \"", "+", "coll", ".", "getFullName", "(", ")", "+", "\" collection on \"", "+", "id", "+", "\" field\"", ")", ";", "}", "}" ]
Creates the unique index gfs. @param coll the coll @param id the id
[ "Creates", "the", "unique", "index", "gfs", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java#L1958-L1969
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java
JDBC4CallableStatement.registerOutParameter
@Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { """ Registers the parameter named parameterName to be of JDBC type sqlType. """ checkClosed(); throw SQLError.noSupport(); }
java
@Override public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "void", "registerOutParameter", "(", "String", "parameterName", ",", "int", "sqlType", ",", "int", "scale", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Registers the parameter named parameterName to be of JDBC type sqlType.
[ "Registers", "the", "parameter", "named", "parameterName", "to", "be", "of", "JDBC", "type", "sqlType", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L551-L556
code4everything/util
src/main/java/com/zhazhapan/util/Checker.java
Checker.isIn
public static <T> boolean isIn(T t, List<T> ts) { """ 检查对象是否在集合中 @param <T> 类型 @param t 对象 @param ts 集合 @return 是否存在 @since 1.0.8 """ return isIn(t, ts.toArray()); }
java
public static <T> boolean isIn(T t, List<T> ts) { return isIn(t, ts.toArray()); }
[ "public", "static", "<", "T", ">", "boolean", "isIn", "(", "T", "t", ",", "List", "<", "T", ">", "ts", ")", "{", "return", "isIn", "(", "t", ",", "ts", ".", "toArray", "(", ")", ")", ";", "}" ]
检查对象是否在集合中 @param <T> 类型 @param t 对象 @param ts 集合 @return 是否存在 @since 1.0.8
[ "检查对象是否在集合中" ]
train
https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L641-L643
groupon/odo
examples/api-usage/src/main/java/com/groupon/odo/sample/SampleClient.java
SampleClient.getHistory
public static void getHistory() throws Exception { """ Demonstrates obtaining the request history data from a test run """ Client client = new Client("ProfileName", false); // Obtain the 100 history entries starting from offset 0 History[] history = client.refreshHistory(100, 0); client.clearHistory(); }
java
public static void getHistory() throws Exception{ Client client = new Client("ProfileName", false); // Obtain the 100 history entries starting from offset 0 History[] history = client.refreshHistory(100, 0); client.clearHistory(); }
[ "public", "static", "void", "getHistory", "(", ")", "throws", "Exception", "{", "Client", "client", "=", "new", "Client", "(", "\"ProfileName\"", ",", "false", ")", ";", "// Obtain the 100 history entries starting from offset 0", "History", "[", "]", "history", "=", "client", ".", "refreshHistory", "(", "100", ",", "0", ")", ";", "client", ".", "clearHistory", "(", ")", ";", "}" ]
Demonstrates obtaining the request history data from a test run
[ "Demonstrates", "obtaining", "the", "request", "history", "data", "from", "a", "test", "run" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/examples/api-usage/src/main/java/com/groupon/odo/sample/SampleClient.java#L99-L106
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedDatabasesInner.java
ManagedDatabasesInner.beginCreateOrUpdate
public ManagedDatabaseInner beginCreateOrUpdate(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseInner parameters) { """ Creates a new database or updates an existing database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param databaseName The name of the database. @param parameters The requested database resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ManagedDatabaseInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).toBlocking().single().body(); }
java
public ManagedDatabaseInner beginCreateOrUpdate(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).toBlocking().single().body(); }
[ "public", "ManagedDatabaseInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "String", "databaseName", ",", "ManagedDatabaseInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "managedInstanceName", ",", "databaseName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates a new database or updates an existing database. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param managedInstanceName The name of the managed instance. @param databaseName The name of the database. @param parameters The requested database resource state. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ManagedDatabaseInner object if successful.
[ "Creates", "a", "new", "database", "or", "updates", "an", "existing", "database", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedDatabasesInner.java#L599-L601
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java
DateTimeUtils.addMilliseconds
public static Calendar addMilliseconds(Calendar origin, int value) { """ Add/Subtract the specified amount of milliseconds to the given {@link Calendar}. <p> The returned {@link Calendar} has its fields synced. </p> @param origin @param value @return @since 0.9.2 """ Calendar cal = sync((Calendar) origin.clone()); cal.add(Calendar.MILLISECOND, value); return sync(cal); }
java
public static Calendar addMilliseconds(Calendar origin, int value) { Calendar cal = sync((Calendar) origin.clone()); cal.add(Calendar.MILLISECOND, value); return sync(cal); }
[ "public", "static", "Calendar", "addMilliseconds", "(", "Calendar", "origin", ",", "int", "value", ")", "{", "Calendar", "cal", "=", "sync", "(", "(", "Calendar", ")", "origin", ".", "clone", "(", ")", ")", ";", "cal", ".", "add", "(", "Calendar", ".", "MILLISECOND", ",", "value", ")", ";", "return", "sync", "(", "cal", ")", ";", "}" ]
Add/Subtract the specified amount of milliseconds to the given {@link Calendar}. <p> The returned {@link Calendar} has its fields synced. </p> @param origin @param value @return @since 0.9.2
[ "Add", "/", "Subtract", "the", "specified", "amount", "of", "milliseconds", "to", "the", "given", "{", "@link", "Calendar", "}", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java#L80-L84
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java
BatchTask.closeChainedTasks
public static void closeChainedTasks(List<ChainedDriver<?, ?>> tasks, AbstractInvokable parent) throws Exception { """ Closes all chained tasks, in the order as they are stored in the array. The closing process creates a standardized log info message. @param tasks The tasks to be closed. @param parent The parent task, used to obtain parameters to include in the log message. @throws Exception Thrown, if the closing encounters an exception. """ for (int i = 0; i < tasks.size(); i++) { final ChainedDriver<?, ?> task = tasks.get(i); task.closeTask(); if (LOG.isDebugEnabled()) { LOG.debug(constructLogString("Finished task code", task.getTaskName(), parent)); } } }
java
public static void closeChainedTasks(List<ChainedDriver<?, ?>> tasks, AbstractInvokable parent) throws Exception { for (int i = 0; i < tasks.size(); i++) { final ChainedDriver<?, ?> task = tasks.get(i); task.closeTask(); if (LOG.isDebugEnabled()) { LOG.debug(constructLogString("Finished task code", task.getTaskName(), parent)); } } }
[ "public", "static", "void", "closeChainedTasks", "(", "List", "<", "ChainedDriver", "<", "?", ",", "?", ">", ">", "tasks", ",", "AbstractInvokable", "parent", ")", "throws", "Exception", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tasks", ".", "size", "(", ")", ";", "i", "++", ")", "{", "final", "ChainedDriver", "<", "?", ",", "?", ">", "task", "=", "tasks", ".", "get", "(", "i", ")", ";", "task", ".", "closeTask", "(", ")", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "constructLogString", "(", "\"Finished task code\"", ",", "task", ".", "getTaskName", "(", ")", ",", "parent", ")", ")", ";", "}", "}", "}" ]
Closes all chained tasks, in the order as they are stored in the array. The closing process creates a standardized log info message. @param tasks The tasks to be closed. @param parent The parent task, used to obtain parameters to include in the log message. @throws Exception Thrown, if the closing encounters an exception.
[ "Closes", "all", "chained", "tasks", "in", "the", "order", "as", "they", "are", "stored", "in", "the", "array", ".", "The", "closing", "process", "creates", "a", "standardized", "log", "info", "message", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java#L1403-L1412
playn/playn
html/src/playn/html/HtmlGraphics.java
HtmlGraphics.setSize
public void setSize (int width, int height) { """ Sizes or resizes the root element that contains the game view. This is specified in pixels as understood by page elements. If the page is actually being dispalyed on a HiDPI (Retina) device, the actual framebuffer may be 2x (or larger) the specified size. """ rootElement.getStyle().setWidth(width, Unit.PX); rootElement.getStyle().setHeight(height, Unit.PX); // the frame buffer may be larger (or smaller) than the logical size, depending on whether // we're on a HiDPI display, or how the game has configured things (maybe they're scaling down // from native resolution to improve performance) Scale fbScale = new Scale(frameBufferPixelRatio); canvas.setWidth(fbScale.scaledCeil(width)); canvas.setHeight(fbScale.scaledCeil(height)); // set the canvas's CSS size to the logical size; the browser works in logical pixels canvas.getStyle().setWidth(width, Style.Unit.PX); canvas.getStyle().setHeight(height, Style.Unit.PX); viewportChanged(canvas.getWidth(), canvas.getHeight()); }
java
public void setSize (int width, int height) { rootElement.getStyle().setWidth(width, Unit.PX); rootElement.getStyle().setHeight(height, Unit.PX); // the frame buffer may be larger (or smaller) than the logical size, depending on whether // we're on a HiDPI display, or how the game has configured things (maybe they're scaling down // from native resolution to improve performance) Scale fbScale = new Scale(frameBufferPixelRatio); canvas.setWidth(fbScale.scaledCeil(width)); canvas.setHeight(fbScale.scaledCeil(height)); // set the canvas's CSS size to the logical size; the browser works in logical pixels canvas.getStyle().setWidth(width, Style.Unit.PX); canvas.getStyle().setHeight(height, Style.Unit.PX); viewportChanged(canvas.getWidth(), canvas.getHeight()); }
[ "public", "void", "setSize", "(", "int", "width", ",", "int", "height", ")", "{", "rootElement", ".", "getStyle", "(", ")", ".", "setWidth", "(", "width", ",", "Unit", ".", "PX", ")", ";", "rootElement", ".", "getStyle", "(", ")", ".", "setHeight", "(", "height", ",", "Unit", ".", "PX", ")", ";", "// the frame buffer may be larger (or smaller) than the logical size, depending on whether", "// we're on a HiDPI display, or how the game has configured things (maybe they're scaling down", "// from native resolution to improve performance)", "Scale", "fbScale", "=", "new", "Scale", "(", "frameBufferPixelRatio", ")", ";", "canvas", ".", "setWidth", "(", "fbScale", ".", "scaledCeil", "(", "width", ")", ")", ";", "canvas", ".", "setHeight", "(", "fbScale", ".", "scaledCeil", "(", "height", ")", ")", ";", "// set the canvas's CSS size to the logical size; the browser works in logical pixels", "canvas", ".", "getStyle", "(", ")", ".", "setWidth", "(", "width", ",", "Style", ".", "Unit", ".", "PX", ")", ";", "canvas", ".", "getStyle", "(", ")", ".", "setHeight", "(", "height", ",", "Style", ".", "Unit", ".", "PX", ")", ";", "viewportChanged", "(", "canvas", ".", "getWidth", "(", ")", ",", "canvas", ".", "getHeight", "(", ")", ")", ";", "}" ]
Sizes or resizes the root element that contains the game view. This is specified in pixels as understood by page elements. If the page is actually being dispalyed on a HiDPI (Retina) device, the actual framebuffer may be 2x (or larger) the specified size.
[ "Sizes", "or", "resizes", "the", "root", "element", "that", "contains", "the", "game", "view", ".", "This", "is", "specified", "in", "pixels", "as", "understood", "by", "page", "elements", ".", "If", "the", "page", "is", "actually", "being", "dispalyed", "on", "a", "HiDPI", "(", "Retina", ")", "device", "the", "actual", "framebuffer", "may", "be", "2x", "(", "or", "larger", ")", "the", "specified", "size", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/html/src/playn/html/HtmlGraphics.java#L145-L158
OpenLiberty/open-liberty
dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/config/KeyStoreManager.java
KeyStoreManager.loadKeyStores
public void loadKeyStores(Map<String, WSKeyStore> config) { """ Load the provided list of keystores from the configuration. @param config """ // now process each keystore in the provided config for (Entry<String, WSKeyStore> current : config.entrySet()) { try { String name = current.getKey(); WSKeyStore keystore = current.getValue(); addKeyStoreToMap(name, keystore); } catch (Exception e) { FFDCFilter.processException(e, getClass().getName(), "loadKeyStores", new Object[] { this, config }); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Error loading keystore; " + current.getKey() + " " + e); } } } }
java
public void loadKeyStores(Map<String, WSKeyStore> config) { // now process each keystore in the provided config for (Entry<String, WSKeyStore> current : config.entrySet()) { try { String name = current.getKey(); WSKeyStore keystore = current.getValue(); addKeyStoreToMap(name, keystore); } catch (Exception e) { FFDCFilter.processException(e, getClass().getName(), "loadKeyStores", new Object[] { this, config }); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Error loading keystore; " + current.getKey() + " " + e); } } } }
[ "public", "void", "loadKeyStores", "(", "Map", "<", "String", ",", "WSKeyStore", ">", "config", ")", "{", "// now process each keystore in the provided config", "for", "(", "Entry", "<", "String", ",", "WSKeyStore", ">", "current", ":", "config", ".", "entrySet", "(", ")", ")", "{", "try", "{", "String", "name", "=", "current", ".", "getKey", "(", ")", ";", "WSKeyStore", "keystore", "=", "current", ".", "getValue", "(", ")", ";", "addKeyStoreToMap", "(", "name", ",", "keystore", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "FFDCFilter", ".", "processException", "(", "e", ",", "getClass", "(", ")", ".", "getName", "(", ")", ",", "\"loadKeyStores\"", ",", "new", "Object", "[", "]", "{", "this", ",", "config", "}", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEventEnabled", "(", ")", ")", "{", "Tr", ".", "event", "(", "tc", ",", "\"Error loading keystore; \"", "+", "current", ".", "getKey", "(", ")", "+", "\" \"", "+", "e", ")", ";", "}", "}", "}", "}" ]
Load the provided list of keystores from the configuration. @param config
[ "Load", "the", "provided", "list", "of", "keystores", "from", "the", "configuration", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/config/KeyStoreManager.java#L91-L105
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.deleteHierarchicalEntityAsync
public Observable<OperationStatus> deleteHierarchicalEntityAsync(UUID appId, String versionId, UUID hEntityId) { """ Deletes a hierarchical entity extractor from the application version. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object """ return deleteHierarchicalEntityWithServiceResponseAsync(appId, versionId, hEntityId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
java
public Observable<OperationStatus> deleteHierarchicalEntityAsync(UUID appId, String versionId, UUID hEntityId) { return deleteHierarchicalEntityWithServiceResponseAsync(appId, versionId, hEntityId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatus", ">", "deleteHierarchicalEntityAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "hEntityId", ")", "{", "return", "deleteHierarchicalEntityWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "hEntityId", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "OperationStatus", ">", ",", "OperationStatus", ">", "(", ")", "{", "@", "Override", "public", "OperationStatus", "call", "(", "ServiceResponse", "<", "OperationStatus", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Deletes a hierarchical entity extractor from the application version. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Deletes", "a", "hierarchical", "entity", "extractor", "from", "the", "application", "version", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L3873-L3880
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/sptree/SpTree.java
SpTree.computeNonEdgeForces
public void computeNonEdgeForces(int pointIndex, double theta, INDArray negativeForce, AtomicDouble sumQ) { """ Compute non edge forces using barnes hut @param pointIndex @param theta @param negativeForce @param sumQ """ // Make sure that we spend no time on empty nodes or self-interactions if (cumSize == 0 || (isLeaf() && size == 1 && index[0] == pointIndex)) return; MemoryWorkspace workspace = workspaceMode == WorkspaceMode.NONE ? new DummyWorkspace() : Nd4j.getWorkspaceManager().getWorkspaceForCurrentThread( workspaceConfigurationExternal, workspaceExternal); try (MemoryWorkspace ws = workspace.notifyScopeEntered()) { // Compute distance between point and center-of-mass buf.assign(data.slice(pointIndex)).subi(centerOfMass); double D = Nd4j.getBlasWrapper().dot(buf, buf); // Check whether we can use this node as a "summary" double maxWidth = boundary.width().max(Integer.MAX_VALUE).getDouble(0); // Check whether we can use this node as a "summary" if (isLeaf() || maxWidth / Math.sqrt(D) < theta) { // Compute and add t-SNE force between point and current node double Q = 1.0 / (1.0 + D); double mult = cumSize * Q; sumQ.addAndGet(mult); mult *= Q; negativeForce.addi(buf.muli(mult)); } else { // Recursively apply Barnes-Hut to children for (int i = 0; i < numChildren; i++) { children[i].computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ); } } } }
java
public void computeNonEdgeForces(int pointIndex, double theta, INDArray negativeForce, AtomicDouble sumQ) { // Make sure that we spend no time on empty nodes or self-interactions if (cumSize == 0 || (isLeaf() && size == 1 && index[0] == pointIndex)) return; MemoryWorkspace workspace = workspaceMode == WorkspaceMode.NONE ? new DummyWorkspace() : Nd4j.getWorkspaceManager().getWorkspaceForCurrentThread( workspaceConfigurationExternal, workspaceExternal); try (MemoryWorkspace ws = workspace.notifyScopeEntered()) { // Compute distance between point and center-of-mass buf.assign(data.slice(pointIndex)).subi(centerOfMass); double D = Nd4j.getBlasWrapper().dot(buf, buf); // Check whether we can use this node as a "summary" double maxWidth = boundary.width().max(Integer.MAX_VALUE).getDouble(0); // Check whether we can use this node as a "summary" if (isLeaf() || maxWidth / Math.sqrt(D) < theta) { // Compute and add t-SNE force between point and current node double Q = 1.0 / (1.0 + D); double mult = cumSize * Q; sumQ.addAndGet(mult); mult *= Q; negativeForce.addi(buf.muli(mult)); } else { // Recursively apply Barnes-Hut to children for (int i = 0; i < numChildren; i++) { children[i].computeNonEdgeForces(pointIndex, theta, negativeForce, sumQ); } } } }
[ "public", "void", "computeNonEdgeForces", "(", "int", "pointIndex", ",", "double", "theta", ",", "INDArray", "negativeForce", ",", "AtomicDouble", "sumQ", ")", "{", "// Make sure that we spend no time on empty nodes or self-interactions", "if", "(", "cumSize", "==", "0", "||", "(", "isLeaf", "(", ")", "&&", "size", "==", "1", "&&", "index", "[", "0", "]", "==", "pointIndex", ")", ")", "return", ";", "MemoryWorkspace", "workspace", "=", "workspaceMode", "==", "WorkspaceMode", ".", "NONE", "?", "new", "DummyWorkspace", "(", ")", ":", "Nd4j", ".", "getWorkspaceManager", "(", ")", ".", "getWorkspaceForCurrentThread", "(", "workspaceConfigurationExternal", ",", "workspaceExternal", ")", ";", "try", "(", "MemoryWorkspace", "ws", "=", "workspace", ".", "notifyScopeEntered", "(", ")", ")", "{", "// Compute distance between point and center-of-mass", "buf", ".", "assign", "(", "data", ".", "slice", "(", "pointIndex", ")", ")", ".", "subi", "(", "centerOfMass", ")", ";", "double", "D", "=", "Nd4j", ".", "getBlasWrapper", "(", ")", ".", "dot", "(", "buf", ",", "buf", ")", ";", "// Check whether we can use this node as a \"summary\"", "double", "maxWidth", "=", "boundary", ".", "width", "(", ")", ".", "max", "(", "Integer", ".", "MAX_VALUE", ")", ".", "getDouble", "(", "0", ")", ";", "// Check whether we can use this node as a \"summary\"", "if", "(", "isLeaf", "(", ")", "||", "maxWidth", "/", "Math", ".", "sqrt", "(", "D", ")", "<", "theta", ")", "{", "// Compute and add t-SNE force between point and current node", "double", "Q", "=", "1.0", "/", "(", "1.0", "+", "D", ")", ";", "double", "mult", "=", "cumSize", "*", "Q", ";", "sumQ", ".", "addAndGet", "(", "mult", ")", ";", "mult", "*=", "Q", ";", "negativeForce", ".", "addi", "(", "buf", ".", "muli", "(", "mult", ")", ")", ";", "}", "else", "{", "// Recursively apply Barnes-Hut to children", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numChildren", ";", "i", "++", ")", "{", "children", "[", "i", "]", ".", "computeNonEdgeForces", "(", "pointIndex", ",", "theta", ",", "negativeForce", ",", "sumQ", ")", ";", "}", "}", "}", "}" ]
Compute non edge forces using barnes hut @param pointIndex @param theta @param negativeForce @param sumQ
[ "Compute", "non", "edge", "forces", "using", "barnes", "hut" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/sptree/SpTree.java#L265-L302
infinispan/infinispan
core/src/main/java/org/infinispan/configuration/global/TransportConfigurationBuilder.java
TransportConfigurationBuilder.initialClusterTimeout
public TransportConfigurationBuilder initialClusterTimeout(long initialClusterTimeout, TimeUnit unit) { """ Sets the timeout for the initial cluster to form. Defaults to 1 minute """ attributes.attribute(INITIAL_CLUSTER_TIMEOUT).set(unit.toMillis(initialClusterTimeout)); return this; }
java
public TransportConfigurationBuilder initialClusterTimeout(long initialClusterTimeout, TimeUnit unit) { attributes.attribute(INITIAL_CLUSTER_TIMEOUT).set(unit.toMillis(initialClusterTimeout)); return this; }
[ "public", "TransportConfigurationBuilder", "initialClusterTimeout", "(", "long", "initialClusterTimeout", ",", "TimeUnit", "unit", ")", "{", "attributes", ".", "attribute", "(", "INITIAL_CLUSTER_TIMEOUT", ")", ".", "set", "(", "unit", ".", "toMillis", "(", "initialClusterTimeout", ")", ")", ";", "return", "this", ";", "}" ]
Sets the timeout for the initial cluster to form. Defaults to 1 minute
[ "Sets", "the", "timeout", "for", "the", "initial", "cluster", "to", "form", ".", "Defaults", "to", "1", "minute" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/configuration/global/TransportConfigurationBuilder.java#L117-L120
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java
CmsSitemapView.initiateTreeItems
void initiateTreeItems(FlowPanel page, Label loadingLabel) { """ Builds the tree items initially.<p> @param page the page @param loadingLabel the loading label, will be removed when finished """ CmsSitemapTreeItem rootItem = getRootItem(); m_controller.addPropertyUpdateHandler(new CmsStatusIconUpdateHandler()); m_controller.recomputeProperties(); rootItem.updateSitePath(); // check if editable if (!m_controller.isEditable()) { // notify user CmsNotification.get().sendSticky( CmsNotification.Type.WARNING, Messages.get().key(Messages.GUI_NO_EDIT_NOTIFICATION_1, m_controller.getData().getNoEditReason())); } String openPath = m_controller.getData().getOpenPath(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(openPath)) { m_openHandler.setInitializing(true); openItemsOnPath(openPath); m_openHandler.setInitializing(false); } page.remove(loadingLabel); }
java
void initiateTreeItems(FlowPanel page, Label loadingLabel) { CmsSitemapTreeItem rootItem = getRootItem(); m_controller.addPropertyUpdateHandler(new CmsStatusIconUpdateHandler()); m_controller.recomputeProperties(); rootItem.updateSitePath(); // check if editable if (!m_controller.isEditable()) { // notify user CmsNotification.get().sendSticky( CmsNotification.Type.WARNING, Messages.get().key(Messages.GUI_NO_EDIT_NOTIFICATION_1, m_controller.getData().getNoEditReason())); } String openPath = m_controller.getData().getOpenPath(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(openPath)) { m_openHandler.setInitializing(true); openItemsOnPath(openPath); m_openHandler.setInitializing(false); } page.remove(loadingLabel); }
[ "void", "initiateTreeItems", "(", "FlowPanel", "page", ",", "Label", "loadingLabel", ")", "{", "CmsSitemapTreeItem", "rootItem", "=", "getRootItem", "(", ")", ";", "m_controller", ".", "addPropertyUpdateHandler", "(", "new", "CmsStatusIconUpdateHandler", "(", ")", ")", ";", "m_controller", ".", "recomputeProperties", "(", ")", ";", "rootItem", ".", "updateSitePath", "(", ")", ";", "// check if editable", "if", "(", "!", "m_controller", ".", "isEditable", "(", ")", ")", "{", "// notify user", "CmsNotification", ".", "get", "(", ")", ".", "sendSticky", "(", "CmsNotification", ".", "Type", ".", "WARNING", ",", "Messages", ".", "get", "(", ")", ".", "key", "(", "Messages", ".", "GUI_NO_EDIT_NOTIFICATION_1", ",", "m_controller", ".", "getData", "(", ")", ".", "getNoEditReason", "(", ")", ")", ")", ";", "}", "String", "openPath", "=", "m_controller", ".", "getData", "(", ")", ".", "getOpenPath", "(", ")", ";", "if", "(", "CmsStringUtil", ".", "isNotEmptyOrWhitespaceOnly", "(", "openPath", ")", ")", "{", "m_openHandler", ".", "setInitializing", "(", "true", ")", ";", "openItemsOnPath", "(", "openPath", ")", ";", "m_openHandler", ".", "setInitializing", "(", "false", ")", ";", "}", "page", ".", "remove", "(", "loadingLabel", ")", ";", "}" ]
Builds the tree items initially.<p> @param page the page @param loadingLabel the loading label, will be removed when finished
[ "Builds", "the", "tree", "items", "initially", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java#L1490-L1510
alipay/sofa-rpc
extension-impl/registry-sofa/src/main/java/com/alipay/sofa/rpc/registry/sofa/SofaRegistry.java
SofaRegistry.doRegister
protected void doRegister(String appName, String serviceName, String serviceData, String group) { """ 注册单条服务信息 @param appName 应用 @param serviceName 服务关键字 @param serviceData 服务提供者数据 @param group 服务分组 """ PublisherRegistration publisherRegistration; // 生成注册对象,并添加额外属性 publisherRegistration = new PublisherRegistration(serviceName); publisherRegistration.setGroup(group); addAttributes(publisherRegistration, group); // 去注册 SofaRegistryClient.getRegistryClient(appName, registryConfig).register(publisherRegistration, serviceData); }
java
protected void doRegister(String appName, String serviceName, String serviceData, String group) { PublisherRegistration publisherRegistration; // 生成注册对象,并添加额外属性 publisherRegistration = new PublisherRegistration(serviceName); publisherRegistration.setGroup(group); addAttributes(publisherRegistration, group); // 去注册 SofaRegistryClient.getRegistryClient(appName, registryConfig).register(publisherRegistration, serviceData); }
[ "protected", "void", "doRegister", "(", "String", "appName", ",", "String", "serviceName", ",", "String", "serviceData", ",", "String", "group", ")", "{", "PublisherRegistration", "publisherRegistration", ";", "// 生成注册对象,并添加额外属性", "publisherRegistration", "=", "new", "PublisherRegistration", "(", "serviceName", ")", ";", "publisherRegistration", ".", "setGroup", "(", "group", ")", ";", "addAttributes", "(", "publisherRegistration", ",", "group", ")", ";", "// 去注册", "SofaRegistryClient", ".", "getRegistryClient", "(", "appName", ",", "registryConfig", ")", ".", "register", "(", "publisherRegistration", ",", "serviceData", ")", ";", "}" ]
注册单条服务信息 @param appName 应用 @param serviceName 服务关键字 @param serviceData 服务提供者数据 @param group 服务分组
[ "注册单条服务信息" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/registry-sofa/src/main/java/com/alipay/sofa/rpc/registry/sofa/SofaRegistry.java#L131-L141
brettwooldridge/HikariCP
src/main/java/com/zaxxer/hikari/pool/ProxyFactory.java
ProxyFactory.getProxyConnection
static ProxyConnection getProxyConnection(final PoolEntry poolEntry, final Connection connection, final FastList<Statement> openStatements, final ProxyLeakTask leakTask, final long now, final boolean isReadOnly, final boolean isAutoCommit) { """ Create a proxy for the specified {@link Connection} instance. @param poolEntry the PoolEntry holding pool state @param connection the raw database Connection @param openStatements a reusable list to track open Statement instances @param leakTask the ProxyLeakTask for this connection @param now the current timestamp @param isReadOnly the default readOnly state of the connection @param isAutoCommit the default autoCommit state of the connection @return a proxy that wraps the specified {@link Connection} """ // Body is replaced (injected) by JavassistProxyFactory throw new IllegalStateException("You need to run the CLI build and you need target/classes in your classpath to run."); }
java
static ProxyConnection getProxyConnection(final PoolEntry poolEntry, final Connection connection, final FastList<Statement> openStatements, final ProxyLeakTask leakTask, final long now, final boolean isReadOnly, final boolean isAutoCommit) { // Body is replaced (injected) by JavassistProxyFactory throw new IllegalStateException("You need to run the CLI build and you need target/classes in your classpath to run."); }
[ "static", "ProxyConnection", "getProxyConnection", "(", "final", "PoolEntry", "poolEntry", ",", "final", "Connection", "connection", ",", "final", "FastList", "<", "Statement", ">", "openStatements", ",", "final", "ProxyLeakTask", "leakTask", ",", "final", "long", "now", ",", "final", "boolean", "isReadOnly", ",", "final", "boolean", "isAutoCommit", ")", "{", "// Body is replaced (injected) by JavassistProxyFactory", "throw", "new", "IllegalStateException", "(", "\"You need to run the CLI build and you need target/classes in your classpath to run.\"", ")", ";", "}" ]
Create a proxy for the specified {@link Connection} instance. @param poolEntry the PoolEntry holding pool state @param connection the raw database Connection @param openStatements a reusable list to track open Statement instances @param leakTask the ProxyLeakTask for this connection @param now the current timestamp @param isReadOnly the default readOnly state of the connection @param isAutoCommit the default autoCommit state of the connection @return a proxy that wraps the specified {@link Connection}
[ "Create", "a", "proxy", "for", "the", "specified", "{" ]
train
https://github.com/brettwooldridge/HikariCP/blob/c509ec1a3f1e19769ee69323972f339cf098ff4b/src/main/java/com/zaxxer/hikari/pool/ProxyFactory.java#L52-L56
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslservicegroup_binding.java
sslservicegroup_binding.get
public static sslservicegroup_binding get(nitro_service service, String servicegroupname) throws Exception { """ Use this API to fetch sslservicegroup_binding resource of given name . """ sslservicegroup_binding obj = new sslservicegroup_binding(); obj.set_servicegroupname(servicegroupname); sslservicegroup_binding response = (sslservicegroup_binding) obj.get_resource(service); return response; }
java
public static sslservicegroup_binding get(nitro_service service, String servicegroupname) throws Exception{ sslservicegroup_binding obj = new sslservicegroup_binding(); obj.set_servicegroupname(servicegroupname); sslservicegroup_binding response = (sslservicegroup_binding) obj.get_resource(service); return response; }
[ "public", "static", "sslservicegroup_binding", "get", "(", "nitro_service", "service", ",", "String", "servicegroupname", ")", "throws", "Exception", "{", "sslservicegroup_binding", "obj", "=", "new", "sslservicegroup_binding", "(", ")", ";", "obj", ".", "set_servicegroupname", "(", "servicegroupname", ")", ";", "sslservicegroup_binding", "response", "=", "(", "sslservicegroup_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch sslservicegroup_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "sslservicegroup_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslservicegroup_binding.java#L125-L130
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java
XMLProperties.storeProperties
public static void storeProperties(Map pProperties, OutputStream pOutput, String pHeader) throws IOException { """ Utility method that stores the property list in normal properties format. This method writes the list of Properties (key and element pairs) in the given {@code Properties} table to the output stream in a format suitable for loading into a Properties table using the load method. The stream is written using the ISO 8859-1 character encoding. @param pProperties the Properties table to store @param pOutput the output stream to write to. @param pHeader a description of the property list. @exception IOException if writing this property list to the specified output stream throws an IOException. @see java.util.Properties#store(OutputStream,String) """ // Create new properties Properties props = new Properties(); // Copy all elements from the pProperties (shallow) Iterator iterator = pProperties.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); props.setProperty((String) entry.getKey(), StringUtil.valueOf(entry.getValue())); } // Store normal properties props.store(pOutput, pHeader); }
java
public static void storeProperties(Map pProperties, OutputStream pOutput, String pHeader) throws IOException { // Create new properties Properties props = new Properties(); // Copy all elements from the pProperties (shallow) Iterator iterator = pProperties.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); props.setProperty((String) entry.getKey(), StringUtil.valueOf(entry.getValue())); } // Store normal properties props.store(pOutput, pHeader); }
[ "public", "static", "void", "storeProperties", "(", "Map", "pProperties", ",", "OutputStream", "pOutput", ",", "String", "pHeader", ")", "throws", "IOException", "{", "// Create new properties\r", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "// Copy all elements from the pProperties (shallow)\r", "Iterator", "iterator", "=", "pProperties", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "Map", ".", "Entry", "entry", "=", "(", "Map", ".", "Entry", ")", "iterator", ".", "next", "(", ")", ";", "props", ".", "setProperty", "(", "(", "String", ")", "entry", ".", "getKey", "(", ")", ",", "StringUtil", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ")", ";", "}", "// Store normal properties\r", "props", ".", "store", "(", "pOutput", ",", "pHeader", ")", ";", "}" ]
Utility method that stores the property list in normal properties format. This method writes the list of Properties (key and element pairs) in the given {@code Properties} table to the output stream in a format suitable for loading into a Properties table using the load method. The stream is written using the ISO 8859-1 character encoding. @param pProperties the Properties table to store @param pOutput the output stream to write to. @param pHeader a description of the property list. @exception IOException if writing this property list to the specified output stream throws an IOException. @see java.util.Properties#store(OutputStream,String)
[ "Utility", "method", "that", "stores", "the", "property", "list", "in", "normal", "properties", "format", ".", "This", "method", "writes", "the", "list", "of", "Properties", "(", "key", "and", "element", "pairs", ")", "in", "the", "given", "{", "@code", "Properties", "}", "table", "to", "the", "output", "stream", "in", "a", "format", "suitable", "for", "loading", "into", "a", "Properties", "table", "using", "the", "load", "method", ".", "The", "stream", "is", "written", "using", "the", "ISO", "8859", "-", "1", "character", "encoding", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java#L691-L706