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
symphonyoss/messageml-utils
src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java
MessageMLParser.validateEntities
private static void validateEntities(org.w3c.dom.Element document, JsonNode entityJson) throws InvalidInputException, ProcessingException { """ Check whether <i>data-entity-id</i> attributes in the message match EntityJSON entities. """ XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList nodes; try { XPathExpression expr = xpath.compile("//@data-entity-id"); nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new ProcessingException("Internal error processing document tree: " + e.getMessage()); } for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String entityId = ((org.w3c.dom.Attr) node).getValue(); JsonNode entityNode = entityJson.findPath(entityId); if (entityNode.isMissingNode()) { throw new InvalidInputException("Error processing EntityJSON: " + "no entity data provided for \"data-entity-id\"=\"" + entityId + "\""); } else if (!entityNode.isObject()) { throw new InvalidInputException("Error processing EntityJSON: " + "the node \"" + entityId + "\" has to be an object"); } } }
java
private static void validateEntities(org.w3c.dom.Element document, JsonNode entityJson) throws InvalidInputException, ProcessingException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList nodes; try { XPathExpression expr = xpath.compile("//@data-entity-id"); nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new ProcessingException("Internal error processing document tree: " + e.getMessage()); } for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String entityId = ((org.w3c.dom.Attr) node).getValue(); JsonNode entityNode = entityJson.findPath(entityId); if (entityNode.isMissingNode()) { throw new InvalidInputException("Error processing EntityJSON: " + "no entity data provided for \"data-entity-id\"=\"" + entityId + "\""); } else if (!entityNode.isObject()) { throw new InvalidInputException("Error processing EntityJSON: " + "the node \"" + entityId + "\" has to be an object"); } } }
[ "private", "static", "void", "validateEntities", "(", "org", ".", "w3c", ".", "dom", ".", "Element", "document", ",", "JsonNode", "entityJson", ")", "throws", "InvalidInputException", ",", "ProcessingException", "{", "XPathFactory", "xPathfactory", "=", "XPathFactory", ".", "newInstance", "(", ")", ";", "XPath", "xpath", "=", "xPathfactory", ".", "newXPath", "(", ")", ";", "NodeList", "nodes", ";", "try", "{", "XPathExpression", "expr", "=", "xpath", ".", "compile", "(", "\"//@data-entity-id\"", ")", ";", "nodes", "=", "(", "NodeList", ")", "expr", ".", "evaluate", "(", "document", ",", "XPathConstants", ".", "NODESET", ")", ";", "}", "catch", "(", "XPathExpressionException", "e", ")", "{", "throw", "new", "ProcessingException", "(", "\"Internal error processing document tree: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodes", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "node", "=", "nodes", ".", "item", "(", "i", ")", ";", "String", "entityId", "=", "(", "(", "org", ".", "w3c", ".", "dom", ".", "Attr", ")", "node", ")", ".", "getValue", "(", ")", ";", "JsonNode", "entityNode", "=", "entityJson", ".", "findPath", "(", "entityId", ")", ";", "if", "(", "entityNode", ".", "isMissingNode", "(", ")", ")", "{", "throw", "new", "InvalidInputException", "(", "\"Error processing EntityJSON: \"", "+", "\"no entity data provided for \\\"data-entity-id\\\"=\\\"\"", "+", "entityId", "+", "\"\\\"\"", ")", ";", "}", "else", "if", "(", "!", "entityNode", ".", "isObject", "(", ")", ")", "{", "throw", "new", "InvalidInputException", "(", "\"Error processing EntityJSON: \"", "+", "\"the node \\\"\"", "+", "entityId", "+", "\"\\\" has to be an object\"", ")", ";", "}", "}", "}" ]
Check whether <i>data-entity-id</i> attributes in the message match EntityJSON entities.
[ "Check", "whether", "<i", ">", "data", "-", "entity", "-", "id<", "/", "i", ">", "attributes", "in", "the", "message", "match", "EntityJSON", "entities", "." ]
train
https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/messageml/MessageMLParser.java#L142-L168
otto-de/edison-microservice
edison-jobs/src/main/java/de/otto/edison/jobs/repository/inmem/InMemJobMetaRepository.java
InMemJobMetaRepository.getJobMeta
@Override public JobMeta getJobMeta(String jobType) { """ Returns the current state of the specified job type. @param jobType the job type @return current state of the job type """ final Map<String, String> document = map.get(jobType); if (document != null) { final Map<String, String> meta = document.keySet() .stream() .filter(key -> !key.startsWith("_e_")) .collect(toMap( key -> key, document::get )); final boolean isRunning = document.containsKey(KEY_RUNNING); final boolean isDisabled = document.containsKey(KEY_DISABLED); final String comment = document.get(KEY_DISABLED); return new JobMeta(jobType, isRunning, isDisabled, comment, meta); } else { return new JobMeta(jobType, false, false, "", emptyMap()); } }
java
@Override public JobMeta getJobMeta(String jobType) { final Map<String, String> document = map.get(jobType); if (document != null) { final Map<String, String> meta = document.keySet() .stream() .filter(key -> !key.startsWith("_e_")) .collect(toMap( key -> key, document::get )); final boolean isRunning = document.containsKey(KEY_RUNNING); final boolean isDisabled = document.containsKey(KEY_DISABLED); final String comment = document.get(KEY_DISABLED); return new JobMeta(jobType, isRunning, isDisabled, comment, meta); } else { return new JobMeta(jobType, false, false, "", emptyMap()); } }
[ "@", "Override", "public", "JobMeta", "getJobMeta", "(", "String", "jobType", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "document", "=", "map", ".", "get", "(", "jobType", ")", ";", "if", "(", "document", "!=", "null", ")", "{", "final", "Map", "<", "String", ",", "String", ">", "meta", "=", "document", ".", "keySet", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "key", "->", "!", "key", ".", "startsWith", "(", "\"_e_\"", ")", ")", ".", "collect", "(", "toMap", "(", "key", "->", "key", ",", "document", "::", "get", ")", ")", ";", "final", "boolean", "isRunning", "=", "document", ".", "containsKey", "(", "KEY_RUNNING", ")", ";", "final", "boolean", "isDisabled", "=", "document", ".", "containsKey", "(", "KEY_DISABLED", ")", ";", "final", "String", "comment", "=", "document", ".", "get", "(", "KEY_DISABLED", ")", ";", "return", "new", "JobMeta", "(", "jobType", ",", "isRunning", ",", "isDisabled", ",", "comment", ",", "meta", ")", ";", "}", "else", "{", "return", "new", "JobMeta", "(", "jobType", ",", "false", ",", "false", ",", "\"\"", ",", "emptyMap", "(", ")", ")", ";", "}", "}" ]
Returns the current state of the specified job type. @param jobType the job type @return current state of the job type
[ "Returns", "the", "current", "state", "of", "the", "specified", "job", "type", "." ]
train
https://github.com/otto-de/edison-microservice/blob/89ecf0a0dee40977f004370b0b474a36c699e8a2/edison-jobs/src/main/java/de/otto/edison/jobs/repository/inmem/InMemJobMetaRepository.java#L100-L118
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java
AbstractIndexWriter.addClassInfo
protected void addClassInfo(ClassDoc cd, Content contentTree) { """ Add the classkind (class, interface, exception), error of the class passed. @param cd the class being documented @param contentTree the content tree to which the class info will be added """ contentTree.addContent(getResource("doclet.in", utils.getTypeName(configuration, cd, false), getPackageLink(cd.containingPackage(), utils.getPackageName(cd.containingPackage())) )); }
java
protected void addClassInfo(ClassDoc cd, Content contentTree) { contentTree.addContent(getResource("doclet.in", utils.getTypeName(configuration, cd, false), getPackageLink(cd.containingPackage(), utils.getPackageName(cd.containingPackage())) )); }
[ "protected", "void", "addClassInfo", "(", "ClassDoc", "cd", ",", "Content", "contentTree", ")", "{", "contentTree", ".", "addContent", "(", "getResource", "(", "\"doclet.in\"", ",", "utils", ".", "getTypeName", "(", "configuration", ",", "cd", ",", "false", ")", ",", "getPackageLink", "(", "cd", ".", "containingPackage", "(", ")", ",", "utils", ".", "getPackageName", "(", "cd", ".", "containingPackage", "(", ")", ")", ")", ")", ")", ";", "}" ]
Add the classkind (class, interface, exception), error of the class passed. @param cd the class being documented @param contentTree the content tree to which the class info will be added
[ "Add", "the", "classkind", "(", "class", "interface", "exception", ")", "error", "of", "the", "class", "passed", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/AbstractIndexWriter.java#L229-L235
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContentErrorHandler.java
CmsXmlContentErrorHandler.addError
public void addError(I_CmsXmlContentValue value, String message) { """ Adds an error message to the internal list of errors, also raised the "has errors" flag.<p> @param value the value that contains the error @param message the error message to add """ m_hasErrors = true; Locale locale = value.getLocale(); Map<String, String> localeErrors = getLocalIssueMap(m_errors, locale); localeErrors.put(value.getPath(), message); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_XMLCONTENT_VALIDATION_ERR_2, value.getPath(), message)); } }
java
public void addError(I_CmsXmlContentValue value, String message) { m_hasErrors = true; Locale locale = value.getLocale(); Map<String, String> localeErrors = getLocalIssueMap(m_errors, locale); localeErrors.put(value.getPath(), message); if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_XMLCONTENT_VALIDATION_ERR_2, value.getPath(), message)); } }
[ "public", "void", "addError", "(", "I_CmsXmlContentValue", "value", ",", "String", "message", ")", "{", "m_hasErrors", "=", "true", ";", "Locale", "locale", "=", "value", ".", "getLocale", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "localeErrors", "=", "getLocalIssueMap", "(", "m_errors", ",", "locale", ")", ";", "localeErrors", ".", "put", "(", "value", ".", "getPath", "(", ")", ",", "message", ")", ";", "if", "(", "LOG", ".", "isDebugEnabled", "(", ")", ")", "{", "LOG", ".", "debug", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "LOG_XMLCONTENT_VALIDATION_ERR_2", ",", "value", ".", "getPath", "(", ")", ",", "message", ")", ")", ";", "}", "}" ]
Adds an error message to the internal list of errors, also raised the "has errors" flag.<p> @param value the value that contains the error @param message the error message to add
[ "Adds", "an", "error", "message", "to", "the", "internal", "list", "of", "errors", "also", "raised", "the", "has", "errors", "flag", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContentErrorHandler.java#L78-L89
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/KeyEncoder.java
KeyEncoder.encodeDesc
public static int encodeDesc(Long value, byte[] dst, int dstOffset) { """ Encodes the given signed Long object into exactly 1 or 9 bytes for descending order. If the Long object is never expected to be null, consider encoding as a long primitive. @param value optional signed Long value to encode @param dst destination for encoded bytes @param dstOffset offset into destination array @return amount of bytes written """ if (value == null) { dst[dstOffset] = NULL_BYTE_LOW; return 1; } else { dst[dstOffset] = NOT_NULL_BYTE_LOW; DataEncoder.encode(~value.longValue(), dst, dstOffset + 1); return 9; } }
java
public static int encodeDesc(Long value, byte[] dst, int dstOffset) { if (value == null) { dst[dstOffset] = NULL_BYTE_LOW; return 1; } else { dst[dstOffset] = NOT_NULL_BYTE_LOW; DataEncoder.encode(~value.longValue(), dst, dstOffset + 1); return 9; } }
[ "public", "static", "int", "encodeDesc", "(", "Long", "value", ",", "byte", "[", "]", "dst", ",", "int", "dstOffset", ")", "{", "if", "(", "value", "==", "null", ")", "{", "dst", "[", "dstOffset", "]", "=", "NULL_BYTE_LOW", ";", "return", "1", ";", "}", "else", "{", "dst", "[", "dstOffset", "]", "=", "NOT_NULL_BYTE_LOW", ";", "DataEncoder", ".", "encode", "(", "~", "value", ".", "longValue", "(", ")", ",", "dst", ",", "dstOffset", "+", "1", ")", ";", "return", "9", ";", "}", "}" ]
Encodes the given signed Long object into exactly 1 or 9 bytes for descending order. If the Long object is never expected to be null, consider encoding as a long primitive. @param value optional signed Long value to encode @param dst destination for encoded bytes @param dstOffset offset into destination array @return amount of bytes written
[ "Encodes", "the", "given", "signed", "Long", "object", "into", "exactly", "1", "or", "9", "bytes", "for", "descending", "order", ".", "If", "the", "Long", "object", "is", "never", "expected", "to", "be", "null", "consider", "encoding", "as", "a", "long", "primitive", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/KeyEncoder.java#L94-L103
deeplearning4j/deeplearning4j
datavec/datavec-api/src/main/java/org/datavec/api/records/reader/impl/transform/TransformProcessRecordReader.java
TransformProcessRecordReader.initialize
@Override public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException { """ Called once at initialization. @param conf a configuration for initialization @param split the split that defines the range of records to read @throws IOException @throws InterruptedException """ recordReader.initialize(conf, split); }
java
@Override public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException { recordReader.initialize(conf, split); }
[ "@", "Override", "public", "void", "initialize", "(", "Configuration", "conf", ",", "InputSplit", "split", ")", "throws", "IOException", ",", "InterruptedException", "{", "recordReader", ".", "initialize", "(", "conf", ",", "split", ")", ";", "}" ]
Called once at initialization. @param conf a configuration for initialization @param split the split that defines the range of records to read @throws IOException @throws InterruptedException
[ "Called", "once", "at", "initialization", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/records/reader/impl/transform/TransformProcessRecordReader.java#L78-L81
auth0/auth0-java
src/main/java/com/auth0/client/mgmt/filter/QueryFilter.java
QueryFilter.withQuery
public QueryFilter withQuery(String query) { """ Filter by a query @param query the query expression to use @return this filter instance """ try { String encodedQuery = urlEncode(query); parameters.put(KEY_QUERY, encodedQuery); return this; } catch (UnsupportedEncodingException ex) { //"Every implementation of the Java platform is required to support the following standard charsets [...]: UTF-8" //cf. https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html throw new IllegalStateException("UTF-8 encoding not supported by current Java platform implementation.", ex); } }
java
public QueryFilter withQuery(String query) { try { String encodedQuery = urlEncode(query); parameters.put(KEY_QUERY, encodedQuery); return this; } catch (UnsupportedEncodingException ex) { //"Every implementation of the Java platform is required to support the following standard charsets [...]: UTF-8" //cf. https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html throw new IllegalStateException("UTF-8 encoding not supported by current Java platform implementation.", ex); } }
[ "public", "QueryFilter", "withQuery", "(", "String", "query", ")", "{", "try", "{", "String", "encodedQuery", "=", "urlEncode", "(", "query", ")", ";", "parameters", ".", "put", "(", "KEY_QUERY", ",", "encodedQuery", ")", ";", "return", "this", ";", "}", "catch", "(", "UnsupportedEncodingException", "ex", ")", "{", "//\"Every implementation of the Java platform is required to support the following standard charsets [...]: UTF-8\"", "//cf. https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html", "throw", "new", "IllegalStateException", "(", "\"UTF-8 encoding not supported by current Java platform implementation.\"", ",", "ex", ")", ";", "}", "}" ]
Filter by a query @param query the query expression to use @return this filter instance
[ "Filter", "by", "a", "query" ]
train
https://github.com/auth0/auth0-java/blob/b7bc099ee9c6cde5a87c4ecfebc6d811aeb1027c/src/main/java/com/auth0/client/mgmt/filter/QueryFilter.java#L16-L26
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.license_windows_serviceName_upgrade_duration_POST
public OvhOrder license_windows_serviceName_upgrade_duration_POST(String serviceName, String duration, OvhWindowsSqlVersionEnum sqlVersion, OvhWindowsOsVersionEnum version) throws IOException { """ Create order REST: POST /order/license/windows/{serviceName}/upgrade/{duration} @param version [required] The windows version you want to enable on your windows license @param sqlVersion [required] The SQL Server version to enable on this license Windows license @param serviceName [required] The name of your Windows license @param duration [required] Duration """ String qPath = "/order/license/windows/{serviceName}/upgrade/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "sqlVersion", sqlVersion); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder license_windows_serviceName_upgrade_duration_POST(String serviceName, String duration, OvhWindowsSqlVersionEnum sqlVersion, OvhWindowsOsVersionEnum version) throws IOException { String qPath = "/order/license/windows/{serviceName}/upgrade/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "sqlVersion", sqlVersion); addBody(o, "version", version); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "license_windows_serviceName_upgrade_duration_POST", "(", "String", "serviceName", ",", "String", "duration", ",", "OvhWindowsSqlVersionEnum", "sqlVersion", ",", "OvhWindowsOsVersionEnum", "version", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/license/windows/{serviceName}/upgrade/{duration}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "duration", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"sqlVersion\"", ",", "sqlVersion", ")", ";", "addBody", "(", "o", ",", "\"version\"", ",", "version", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOrder", ".", "class", ")", ";", "}" ]
Create order REST: POST /order/license/windows/{serviceName}/upgrade/{duration} @param version [required] The windows version you want to enable on your windows license @param sqlVersion [required] The SQL Server version to enable on this license Windows license @param serviceName [required] The name of your Windows license @param duration [required] Duration
[ "Create", "order" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L1210-L1218
xvik/guice-persist-orient
src/main/java/ru/vyarus/guice/persist/orient/repository/core/ext/SpiService.java
SpiService.process
public void process(final RepositoryMethodDescriptor descriptor, final ParamsContext paramsContext) { """ Parse method parameters. Resolves and applies all found parameter extensions. Resolves execution extensions and store ordered list of all found extensions in descriptor (extension will use them directly). Resolves result conversion extensions. <p> Called by method extension directly. @param descriptor repository method descriptor @param paramsContext extension specific parameters context """ paramsService.processParams(descriptor, paramsContext); // parameter extensions may also be amend extensions amendExtensionsService.registerExtensions(descriptor, paramsContext); resultService.registerExtensions(descriptor, paramsContext.getExtensionsContext()); }
java
public void process(final RepositoryMethodDescriptor descriptor, final ParamsContext paramsContext) { paramsService.processParams(descriptor, paramsContext); // parameter extensions may also be amend extensions amendExtensionsService.registerExtensions(descriptor, paramsContext); resultService.registerExtensions(descriptor, paramsContext.getExtensionsContext()); }
[ "public", "void", "process", "(", "final", "RepositoryMethodDescriptor", "descriptor", ",", "final", "ParamsContext", "paramsContext", ")", "{", "paramsService", ".", "processParams", "(", "descriptor", ",", "paramsContext", ")", ";", "// parameter extensions may also be amend extensions", "amendExtensionsService", ".", "registerExtensions", "(", "descriptor", ",", "paramsContext", ")", ";", "resultService", ".", "registerExtensions", "(", "descriptor", ",", "paramsContext", ".", "getExtensionsContext", "(", ")", ")", ";", "}" ]
Parse method parameters. Resolves and applies all found parameter extensions. Resolves execution extensions and store ordered list of all found extensions in descriptor (extension will use them directly). Resolves result conversion extensions. <p> Called by method extension directly. @param descriptor repository method descriptor @param paramsContext extension specific parameters context
[ "Parse", "method", "parameters", ".", "Resolves", "and", "applies", "all", "found", "parameter", "extensions", ".", "Resolves", "execution", "extensions", "and", "store", "ordered", "list", "of", "all", "found", "extensions", "in", "descriptor", "(", "extension", "will", "use", "them", "directly", ")", ".", "Resolves", "result", "conversion", "extensions", ".", "<p", ">", "Called", "by", "method", "extension", "directly", "." ]
train
https://github.com/xvik/guice-persist-orient/blob/5ef06fb4f734360512e9824a3b875c4906c56b5b/src/main/java/ru/vyarus/guice/persist/orient/repository/core/ext/SpiService.java#L76-L81
rterp/GMapsFX
GMapsFX/src/main/java/com/lynden/gmapsfx/service/elevation/ElevationService.java
ElevationService.processResponse
public void processResponse(Object results, Object status) { """ Processess the Javascript response and generates the required objects that are then passed back to the original callback. @param results @param status """ ElevationStatus pStatus = ElevationStatus.UNKNOWN_ERROR; if (status instanceof String && results instanceof JSObject) { pStatus = ElevationStatus.valueOf((String) status); if (ElevationStatus.OK.equals(pStatus)) { JSObject jsres = (JSObject) results; Object len = jsres.getMember("length"); if (len instanceof Number) { int n = ((Number)len).intValue(); ElevationResult[] ers = new ElevationResult[n]; for (int i = 0; i < n; i++) { Object obj = jsres.getSlot(i); if (obj instanceof JSObject) { ers[i] = new ElevationResult((JSObject) obj); } } callback.elevationsReceived(ers, pStatus); return; } } } callback.elevationsReceived(new ElevationResult[]{}, pStatus); }
java
public void processResponse(Object results, Object status) { ElevationStatus pStatus = ElevationStatus.UNKNOWN_ERROR; if (status instanceof String && results instanceof JSObject) { pStatus = ElevationStatus.valueOf((String) status); if (ElevationStatus.OK.equals(pStatus)) { JSObject jsres = (JSObject) results; Object len = jsres.getMember("length"); if (len instanceof Number) { int n = ((Number)len).intValue(); ElevationResult[] ers = new ElevationResult[n]; for (int i = 0; i < n; i++) { Object obj = jsres.getSlot(i); if (obj instanceof JSObject) { ers[i] = new ElevationResult((JSObject) obj); } } callback.elevationsReceived(ers, pStatus); return; } } } callback.elevationsReceived(new ElevationResult[]{}, pStatus); }
[ "public", "void", "processResponse", "(", "Object", "results", ",", "Object", "status", ")", "{", "ElevationStatus", "pStatus", "=", "ElevationStatus", ".", "UNKNOWN_ERROR", ";", "if", "(", "status", "instanceof", "String", "&&", "results", "instanceof", "JSObject", ")", "{", "pStatus", "=", "ElevationStatus", ".", "valueOf", "(", "(", "String", ")", "status", ")", ";", "if", "(", "ElevationStatus", ".", "OK", ".", "equals", "(", "pStatus", ")", ")", "{", "JSObject", "jsres", "=", "(", "JSObject", ")", "results", ";", "Object", "len", "=", "jsres", ".", "getMember", "(", "\"length\"", ")", ";", "if", "(", "len", "instanceof", "Number", ")", "{", "int", "n", "=", "(", "(", "Number", ")", "len", ")", ".", "intValue", "(", ")", ";", "ElevationResult", "[", "]", "ers", "=", "new", "ElevationResult", "[", "n", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "Object", "obj", "=", "jsres", ".", "getSlot", "(", "i", ")", ";", "if", "(", "obj", "instanceof", "JSObject", ")", "{", "ers", "[", "i", "]", "=", "new", "ElevationResult", "(", "(", "JSObject", ")", "obj", ")", ";", "}", "}", "callback", ".", "elevationsReceived", "(", "ers", ",", "pStatus", ")", ";", "return", ";", "}", "}", "}", "callback", ".", "elevationsReceived", "(", "new", "ElevationResult", "[", "]", "{", "}", ",", "pStatus", ")", ";", "}" ]
Processess the Javascript response and generates the required objects that are then passed back to the original callback. @param results @param status
[ "Processess", "the", "Javascript", "response", "and", "generates", "the", "required", "objects", "that", "are", "then", "passed", "back", "to", "the", "original", "callback", "." ]
train
https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/service/elevation/ElevationService.java#L89-L112
jingwei/krati
krati-main/src/main/java/krati/util/SourceWaterMarks.java
SourceWaterMarks.saveHWMark
public void saveHWMark(String source, long hwm) { """ Saves the high water mark of a source. This method has the same functionality as {@link #setHWMScn(String, long)}. @param source - the source @param hwm - the high water mark """ WaterMarkEntry wmEntry = sourceWaterMarkMap.get(source); if (wmEntry != null) { wmEntry.setHWMScn(Math.max(hwm, wmEntry.getHWMScn())); } else { wmEntry = new WaterMarkEntry(source); wmEntry.setHWMScn(hwm); sourceWaterMarkMap.put(source, wmEntry); } }
java
public void saveHWMark(String source, long hwm) { WaterMarkEntry wmEntry = sourceWaterMarkMap.get(source); if (wmEntry != null) { wmEntry.setHWMScn(Math.max(hwm, wmEntry.getHWMScn())); } else { wmEntry = new WaterMarkEntry(source); wmEntry.setHWMScn(hwm); sourceWaterMarkMap.put(source, wmEntry); } }
[ "public", "void", "saveHWMark", "(", "String", "source", ",", "long", "hwm", ")", "{", "WaterMarkEntry", "wmEntry", "=", "sourceWaterMarkMap", ".", "get", "(", "source", ")", ";", "if", "(", "wmEntry", "!=", "null", ")", "{", "wmEntry", ".", "setHWMScn", "(", "Math", ".", "max", "(", "hwm", ",", "wmEntry", ".", "getHWMScn", "(", ")", ")", ")", ";", "}", "else", "{", "wmEntry", "=", "new", "WaterMarkEntry", "(", "source", ")", ";", "wmEntry", ".", "setHWMScn", "(", "hwm", ")", ";", "sourceWaterMarkMap", ".", "put", "(", "source", ",", "wmEntry", ")", ";", "}", "}" ]
Saves the high water mark of a source. This method has the same functionality as {@link #setHWMScn(String, long)}. @param source - the source @param hwm - the high water mark
[ "Saves", "the", "high", "water", "mark", "of", "a", "source", ".", "This", "method", "has", "the", "same", "functionality", "as", "{", "@link", "#setHWMScn", "(", "String", "long", ")", "}", "." ]
train
https://github.com/jingwei/krati/blob/1ca0f994a7b0c8215b827eac9aaf95789ec08d21/krati-main/src/main/java/krati/util/SourceWaterMarks.java#L229-L239
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmVisitor.java
XsdAsmVisitor.generateVisitorInterface
private static void generateVisitorInterface(Set<String> elementNames, List<XsdAttribute> attributes, String apiName) { """ Generates the visitor class for this fluent interface with methods for all elements in the element list. Main methods: void visitElement(Element element); void visitAttribute(String attributeName, String attributeValue); void visitParent(Element elementName); <R> void visitText(Text<? extends Element, R> text); <R> void visitComment(Text<? extends Element, R> comment); @param elementNames The elements names list. @param attributes The list of attributes to be generated. @param apiName The name of the generated fluent interface. """ ClassWriter classWriter = generateClass(ELEMENT_VISITOR, JAVA_OBJECT, null, null, ACC_PUBLIC + ACC_ABSTRACT + ACC_SUPER, apiName); MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, CONSTRUCTOR, "()V", null, null); mVisitor.visitCode(); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKESPECIAL, JAVA_OBJECT, CONSTRUCTOR, "()V", false); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(1, 1); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, VISIT_ELEMENT_NAME, "(" + elementTypeDesc + ")V", null, null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, VISIT_ATTRIBUTE_NAME, "(" + JAVA_STRING_DESC + JAVA_STRING_DESC + ")V", null, null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, VISIT_PARENT_NAME, "(" + elementTypeDesc + ")V", null, null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "visitText", "(" + textTypeDesc + ")V", "<R:" + JAVA_OBJECT_DESC + ">(L" + textType + "<+" + elementTypeDesc + "TR;>;)V", null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "visitComment", "(" + textTypeDesc + ")V", "<R:" + JAVA_OBJECT_DESC + ">(L" + textType + "<+" + elementTypeDesc + "TR;>;)V", null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC, "visitOpenDynamic", "()V", null, null); mVisitor.visitCode(); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(0, 1); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC, "visitCloseDynamic", "()V", null, null); mVisitor.visitCode(); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(0, 1); mVisitor.visitEnd(); elementNames.forEach(elementName -> addVisitorParentMethod(classWriter, elementName, apiName)); elementNames.forEach(elementName -> addVisitorElementMethod(classWriter, elementName, apiName)); attributes.forEach(attribute -> addVisitorAttributeMethod(classWriter, attribute)); writeClassToFile(ELEMENT_VISITOR, classWriter, apiName); }
java
private static void generateVisitorInterface(Set<String> elementNames, List<XsdAttribute> attributes, String apiName) { ClassWriter classWriter = generateClass(ELEMENT_VISITOR, JAVA_OBJECT, null, null, ACC_PUBLIC + ACC_ABSTRACT + ACC_SUPER, apiName); MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, CONSTRUCTOR, "()V", null, null); mVisitor.visitCode(); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKESPECIAL, JAVA_OBJECT, CONSTRUCTOR, "()V", false); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(1, 1); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, VISIT_ELEMENT_NAME, "(" + elementTypeDesc + ")V", null, null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, VISIT_ATTRIBUTE_NAME, "(" + JAVA_STRING_DESC + JAVA_STRING_DESC + ")V", null, null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, VISIT_PARENT_NAME, "(" + elementTypeDesc + ")V", null, null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "visitText", "(" + textTypeDesc + ")V", "<R:" + JAVA_OBJECT_DESC + ">(L" + textType + "<+" + elementTypeDesc + "TR;>;)V", null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "visitComment", "(" + textTypeDesc + ")V", "<R:" + JAVA_OBJECT_DESC + ">(L" + textType + "<+" + elementTypeDesc + "TR;>;)V", null); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC, "visitOpenDynamic", "()V", null, null); mVisitor.visitCode(); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(0, 1); mVisitor.visitEnd(); mVisitor = classWriter.visitMethod(ACC_PUBLIC, "visitCloseDynamic", "()V", null, null); mVisitor.visitCode(); mVisitor.visitInsn(RETURN); mVisitor.visitMaxs(0, 1); mVisitor.visitEnd(); elementNames.forEach(elementName -> addVisitorParentMethod(classWriter, elementName, apiName)); elementNames.forEach(elementName -> addVisitorElementMethod(classWriter, elementName, apiName)); attributes.forEach(attribute -> addVisitorAttributeMethod(classWriter, attribute)); writeClassToFile(ELEMENT_VISITOR, classWriter, apiName); }
[ "private", "static", "void", "generateVisitorInterface", "(", "Set", "<", "String", ">", "elementNames", ",", "List", "<", "XsdAttribute", ">", "attributes", ",", "String", "apiName", ")", "{", "ClassWriter", "classWriter", "=", "generateClass", "(", "ELEMENT_VISITOR", ",", "JAVA_OBJECT", ",", "null", ",", "null", ",", "ACC_PUBLIC", "+", "ACC_ABSTRACT", "+", "ACC_SUPER", ",", "apiName", ")", ";", "MethodVisitor", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", ",", "CONSTRUCTOR", ",", "\"()V\"", ",", "null", ",", "null", ")", ";", "mVisitor", ".", "visitCode", "(", ")", ";", "mVisitor", ".", "visitVarInsn", "(", "ALOAD", ",", "0", ")", ";", "mVisitor", ".", "visitMethodInsn", "(", "INVOKESPECIAL", ",", "JAVA_OBJECT", ",", "CONSTRUCTOR", ",", "\"()V\"", ",", "false", ")", ";", "mVisitor", ".", "visitInsn", "(", "RETURN", ")", ";", "mVisitor", ".", "visitMaxs", "(", "1", ",", "1", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", "+", "ACC_ABSTRACT", ",", "VISIT_ELEMENT_NAME", ",", "\"(\"", "+", "elementTypeDesc", "+", "\")V\"", ",", "null", ",", "null", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", "+", "ACC_ABSTRACT", ",", "VISIT_ATTRIBUTE_NAME", ",", "\"(\"", "+", "JAVA_STRING_DESC", "+", "JAVA_STRING_DESC", "+", "\")V\"", ",", "null", ",", "null", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", "+", "ACC_ABSTRACT", ",", "VISIT_PARENT_NAME", ",", "\"(\"", "+", "elementTypeDesc", "+", "\")V\"", ",", "null", ",", "null", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", "+", "ACC_ABSTRACT", ",", "\"visitText\"", ",", "\"(\"", "+", "textTypeDesc", "+", "\")V\"", ",", "\"<R:\"", "+", "JAVA_OBJECT_DESC", "+", "\">(L\"", "+", "textType", "+", "\"<+\"", "+", "elementTypeDesc", "+", "\"TR;>;)V\"", ",", "null", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", "+", "ACC_ABSTRACT", ",", "\"visitComment\"", ",", "\"(\"", "+", "textTypeDesc", "+", "\")V\"", ",", "\"<R:\"", "+", "JAVA_OBJECT_DESC", "+", "\">(L\"", "+", "textType", "+", "\"<+\"", "+", "elementTypeDesc", "+", "\"TR;>;)V\"", ",", "null", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", ",", "\"visitOpenDynamic\"", ",", "\"()V\"", ",", "null", ",", "null", ")", ";", "mVisitor", ".", "visitCode", "(", ")", ";", "mVisitor", ".", "visitInsn", "(", "RETURN", ")", ";", "mVisitor", ".", "visitMaxs", "(", "0", ",", "1", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", ",", "\"visitCloseDynamic\"", ",", "\"()V\"", ",", "null", ",", "null", ")", ";", "mVisitor", ".", "visitCode", "(", ")", ";", "mVisitor", ".", "visitInsn", "(", "RETURN", ")", ";", "mVisitor", ".", "visitMaxs", "(", "0", ",", "1", ")", ";", "mVisitor", ".", "visitEnd", "(", ")", ";", "elementNames", ".", "forEach", "(", "elementName", "->", "addVisitorParentMethod", "(", "classWriter", ",", "elementName", ",", "apiName", ")", ")", ";", "elementNames", ".", "forEach", "(", "elementName", "->", "addVisitorElementMethod", "(", "classWriter", ",", "elementName", ",", "apiName", ")", ")", ";", "attributes", ".", "forEach", "(", "attribute", "->", "addVisitorAttributeMethod", "(", "classWriter", ",", "attribute", ")", ")", ";", "writeClassToFile", "(", "ELEMENT_VISITOR", ",", "classWriter", ",", "apiName", ")", ";", "}" ]
Generates the visitor class for this fluent interface with methods for all elements in the element list. Main methods: void visitElement(Element element); void visitAttribute(String attributeName, String attributeValue); void visitParent(Element elementName); <R> void visitText(Text<? extends Element, R> text); <R> void visitComment(Text<? extends Element, R> comment); @param elementNames The elements names list. @param attributes The list of attributes to be generated. @param apiName The name of the generated fluent interface.
[ "Generates", "the", "visitor", "class", "for", "this", "fluent", "interface", "with", "methods", "for", "all", "elements", "in", "the", "element", "list", "." ]
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmVisitor.java#L51-L96
strator-dev/greenpepper
greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/I18nUtil.java
I18nUtil.getText
public static String getText(String key, ResourceBundle bundle) { """ Custom I18n. Based on WebWork i18n. @param key a {@link java.lang.String} object. @return the i18nze message. If none found key is returned. @param bundle a {@link java.util.ResourceBundle} object. """ try { return bundle.getString(key); } catch (MissingResourceException ex) { return key; } }
java
public static String getText(String key, ResourceBundle bundle) { try { return bundle.getString(key); } catch (MissingResourceException ex) { return key; } }
[ "public", "static", "String", "getText", "(", "String", "key", ",", "ResourceBundle", "bundle", ")", "{", "try", "{", "return", "bundle", ".", "getString", "(", "key", ")", ";", "}", "catch", "(", "MissingResourceException", "ex", ")", "{", "return", "key", ";", "}", "}" ]
Custom I18n. Based on WebWork i18n. @param key a {@link java.lang.String} object. @return the i18nze message. If none found key is returned. @param bundle a {@link java.util.ResourceBundle} object.
[ "Custom", "I18n", ".", "Based", "on", "WebWork", "i18n", "." ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/I18nUtil.java#L28-L38
googleapis/google-http-java-client
google-http-client/src/main/java/com/google/api/client/util/SecurityUtils.java
SecurityUtils.loadPrivateKeyFromKeyStore
public static PrivateKey loadPrivateKeyFromKeyStore( KeyStore keyStore, InputStream keyStream, String storePass, String alias, String keyPass) throws IOException, GeneralSecurityException { """ Retrieves a private key from the specified key store stream and specified key store. @param keyStore key store @param keyStream input stream to the key store (closed at the end of this method in a finally block) @param storePass password protecting the key store file @param alias alias under which the key is stored @param keyPass password protecting the key @return key from the key store """ loadKeyStore(keyStore, keyStream, storePass); return getPrivateKey(keyStore, alias, keyPass); }
java
public static PrivateKey loadPrivateKeyFromKeyStore( KeyStore keyStore, InputStream keyStream, String storePass, String alias, String keyPass) throws IOException, GeneralSecurityException { loadKeyStore(keyStore, keyStream, storePass); return getPrivateKey(keyStore, alias, keyPass); }
[ "public", "static", "PrivateKey", "loadPrivateKeyFromKeyStore", "(", "KeyStore", "keyStore", ",", "InputStream", "keyStream", ",", "String", "storePass", ",", "String", "alias", ",", "String", "keyPass", ")", "throws", "IOException", ",", "GeneralSecurityException", "{", "loadKeyStore", "(", "keyStore", ",", "keyStream", ",", "storePass", ")", ";", "return", "getPrivateKey", "(", "keyStore", ",", "alias", ",", "keyPass", ")", ";", "}" ]
Retrieves a private key from the specified key store stream and specified key store. @param keyStore key store @param keyStream input stream to the key store (closed at the end of this method in a finally block) @param storePass password protecting the key store file @param alias alias under which the key is stored @param keyPass password protecting the key @return key from the key store
[ "Retrieves", "a", "private", "key", "from", "the", "specified", "key", "store", "stream", "and", "specified", "key", "store", "." ]
train
https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/util/SecurityUtils.java#L108-L113
lucee/Lucee
core/src/main/java/lucee/runtime/reflection/Invoker.java
Invoker.getProperty
public static Object getProperty(Object o, String prop) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { """ to get a visible Property of a object @param o Object to invoke @param prop property to call @return property value @throws NoSuchFieldException @throws IllegalArgumentException @throws IllegalAccessException """ Field f = getFieldIgnoreCase(o.getClass(), prop); return f.get(o); }
java
public static Object getProperty(Object o, String prop) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = getFieldIgnoreCase(o.getClass(), prop); return f.get(o); }
[ "public", "static", "Object", "getProperty", "(", "Object", "o", ",", "String", "prop", ")", "throws", "NoSuchFieldException", ",", "IllegalArgumentException", ",", "IllegalAccessException", "{", "Field", "f", "=", "getFieldIgnoreCase", "(", "o", ".", "getClass", "(", ")", ",", "prop", ")", ";", "return", "f", ".", "get", "(", "o", ")", ";", "}" ]
to get a visible Property of a object @param o Object to invoke @param prop property to call @return property value @throws NoSuchFieldException @throws IllegalArgumentException @throws IllegalAccessException
[ "to", "get", "a", "visible", "Property", "of", "a", "object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/reflection/Invoker.java#L361-L364
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/Step.java
Step.updateDateValidated
protected void updateDateValidated(PageElement pageElement, String dateType, String date) throws TechnicalException, FailureException { """ Update a html input text value with a date. @param pageElement Is target element @param dateType "any", "future", "today", "future_strict" @param date Is the new data (date) @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_WRONG_DATE_FORMAT} message (no screenshot, no exception) or with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNEXPECTED_DATE} message (with screenshot, no exception) @throws FailureException if the scenario encounters a functional error """ logger.debug("updateDateValidated with elementName={}, dateType={} and date={}", pageElement, dateType, date); final DateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT); final Date today = Calendar.getInstance().getTime(); try { final Date valideDate = formatter.parse(date); if ("any".equals(dateType)) { logger.debug("update Date with any date: {}", date); updateText(pageElement, date); } else if (formatter.format(today).equals(date) && ("future".equals(dateType) || "today".equals(dateType))) { logger.debug("update Date with today"); updateText(pageElement, date); } else if (valideDate.after(Calendar.getInstance().getTime()) && ("future".equals(dateType) || "future_strict".equals(dateType))) { logger.debug("update Date with a date after today: {}", date); updateText(pageElement, date); } else { new Result.Failure<>(date, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNEXPECTED_DATE), Messages.getMessage(Messages.DATE_GREATER_THAN_TODAY)), true, pageElement.getPage().getCallBack()); } } catch (final ParseException e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_WRONG_DATE_FORMAT), pageElement, date), false, pageElement.getPage().getCallBack()); } }
java
protected void updateDateValidated(PageElement pageElement, String dateType, String date) throws TechnicalException, FailureException { logger.debug("updateDateValidated with elementName={}, dateType={} and date={}", pageElement, dateType, date); final DateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT); final Date today = Calendar.getInstance().getTime(); try { final Date valideDate = formatter.parse(date); if ("any".equals(dateType)) { logger.debug("update Date with any date: {}", date); updateText(pageElement, date); } else if (formatter.format(today).equals(date) && ("future".equals(dateType) || "today".equals(dateType))) { logger.debug("update Date with today"); updateText(pageElement, date); } else if (valideDate.after(Calendar.getInstance().getTime()) && ("future".equals(dateType) || "future_strict".equals(dateType))) { logger.debug("update Date with a date after today: {}", date); updateText(pageElement, date); } else { new Result.Failure<>(date, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNEXPECTED_DATE), Messages.getMessage(Messages.DATE_GREATER_THAN_TODAY)), true, pageElement.getPage().getCallBack()); } } catch (final ParseException e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_WRONG_DATE_FORMAT), pageElement, date), false, pageElement.getPage().getCallBack()); } }
[ "protected", "void", "updateDateValidated", "(", "PageElement", "pageElement", ",", "String", "dateType", ",", "String", "date", ")", "throws", "TechnicalException", ",", "FailureException", "{", "logger", ".", "debug", "(", "\"updateDateValidated with elementName={}, dateType={} and date={}\"", ",", "pageElement", ",", "dateType", ",", "date", ")", ";", "final", "DateFormat", "formatter", "=", "new", "SimpleDateFormat", "(", "Constants", ".", "DATE_FORMAT", ")", ";", "final", "Date", "today", "=", "Calendar", ".", "getInstance", "(", ")", ".", "getTime", "(", ")", ";", "try", "{", "final", "Date", "valideDate", "=", "formatter", ".", "parse", "(", "date", ")", ";", "if", "(", "\"any\"", ".", "equals", "(", "dateType", ")", ")", "{", "logger", ".", "debug", "(", "\"update Date with any date: {}\"", ",", "date", ")", ";", "updateText", "(", "pageElement", ",", "date", ")", ";", "}", "else", "if", "(", "formatter", ".", "format", "(", "today", ")", ".", "equals", "(", "date", ")", "&&", "(", "\"future\"", ".", "equals", "(", "dateType", ")", "||", "\"today\"", ".", "equals", "(", "dateType", ")", ")", ")", "{", "logger", ".", "debug", "(", "\"update Date with today\"", ")", ";", "updateText", "(", "pageElement", ",", "date", ")", ";", "}", "else", "if", "(", "valideDate", ".", "after", "(", "Calendar", ".", "getInstance", "(", ")", ".", "getTime", "(", ")", ")", "&&", "(", "\"future\"", ".", "equals", "(", "dateType", ")", "||", "\"future_strict\"", ".", "equals", "(", "dateType", ")", ")", ")", "{", "logger", ".", "debug", "(", "\"update Date with a date after today: {}\"", ",", "date", ")", ";", "updateText", "(", "pageElement", ",", "date", ")", ";", "}", "else", "{", "new", "Result", ".", "Failure", "<>", "(", "date", ",", "Messages", ".", "format", "(", "Messages", ".", "getMessage", "(", "Messages", ".", "FAIL_MESSAGE_UNEXPECTED_DATE", ")", ",", "Messages", ".", "getMessage", "(", "Messages", ".", "DATE_GREATER_THAN_TODAY", ")", ")", ",", "true", ",", "pageElement", ".", "getPage", "(", ")", ".", "getCallBack", "(", ")", ")", ";", "}", "}", "catch", "(", "final", "ParseException", "e", ")", "{", "new", "Result", ".", "Failure", "<>", "(", "e", ".", "getMessage", "(", ")", ",", "Messages", ".", "format", "(", "Messages", ".", "getMessage", "(", "Messages", ".", "FAIL_MESSAGE_WRONG_DATE_FORMAT", ")", ",", "pageElement", ",", "date", ")", ",", "false", ",", "pageElement", ".", "getPage", "(", ")", ".", "getCallBack", "(", ")", ")", ";", "}", "}" ]
Update a html input text value with a date. @param pageElement Is target element @param dateType "any", "future", "today", "future_strict" @param date Is the new data (date) @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_WRONG_DATE_FORMAT} message (no screenshot, no exception) or with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNEXPECTED_DATE} message (with screenshot, no exception) @throws FailureException if the scenario encounters a functional error
[ "Update", "a", "html", "input", "text", "value", "with", "a", "date", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L506-L529
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpClient.java
UdpClient.doOnConnected
public final UdpClient doOnConnected(Consumer<? super Connection> doOnConnected) { """ Setup a callback called when {@link io.netty.channel.Channel} is connected. @param doOnConnected a consumer observing client started event @return a new {@link UdpClient} """ Objects.requireNonNull(doOnConnected, "doOnConnected"); return new UdpClientDoOn(this, null, doOnConnected, null); }
java
public final UdpClient doOnConnected(Consumer<? super Connection> doOnConnected) { Objects.requireNonNull(doOnConnected, "doOnConnected"); return new UdpClientDoOn(this, null, doOnConnected, null); }
[ "public", "final", "UdpClient", "doOnConnected", "(", "Consumer", "<", "?", "super", "Connection", ">", "doOnConnected", ")", "{", "Objects", ".", "requireNonNull", "(", "doOnConnected", ",", "\"doOnConnected\"", ")", ";", "return", "new", "UdpClientDoOn", "(", "this", ",", "null", ",", "doOnConnected", ",", "null", ")", ";", "}" ]
Setup a callback called when {@link io.netty.channel.Channel} is connected. @param doOnConnected a consumer observing client started event @return a new {@link UdpClient}
[ "Setup", "a", "callback", "called", "when", "{", "@link", "io", ".", "netty", ".", "channel", ".", "Channel", "}", "is", "connected", "." ]
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpClient.java#L193-L196
craterdog/java-general-utilities
src/main/java/craterdog/utils/ByteUtils.java
ByteUtils.bytesToBigDecimal
static public BigDecimal bytesToBigDecimal(byte[] buffer, int index) { """ This function converts the bytes in a byte array at the specified index to its corresponding big decimal value. @param buffer The byte array containing the big decimal. @param index The index for the first byte in the byte array. @return The corresponding big decimal value. """ int scale = bytesToInt(buffer, index); index += 4; int precision = bytesToInt(buffer, index); index += 4; BigInteger intVal = bytesToBigInteger(buffer, index); return new BigDecimal(intVal, scale, new MathContext(precision)); }
java
static public BigDecimal bytesToBigDecimal(byte[] buffer, int index) { int scale = bytesToInt(buffer, index); index += 4; int precision = bytesToInt(buffer, index); index += 4; BigInteger intVal = bytesToBigInteger(buffer, index); return new BigDecimal(intVal, scale, new MathContext(precision)); }
[ "static", "public", "BigDecimal", "bytesToBigDecimal", "(", "byte", "[", "]", "buffer", ",", "int", "index", ")", "{", "int", "scale", "=", "bytesToInt", "(", "buffer", ",", "index", ")", ";", "index", "+=", "4", ";", "int", "precision", "=", "bytesToInt", "(", "buffer", ",", "index", ")", ";", "index", "+=", "4", ";", "BigInteger", "intVal", "=", "bytesToBigInteger", "(", "buffer", ",", "index", ")", ";", "return", "new", "BigDecimal", "(", "intVal", ",", "scale", ",", "new", "MathContext", "(", "precision", ")", ")", ";", "}" ]
This function converts the bytes in a byte array at the specified index to its corresponding big decimal value. @param buffer The byte array containing the big decimal. @param index The index for the first byte in the byte array. @return The corresponding big decimal value.
[ "This", "function", "converts", "the", "bytes", "in", "a", "byte", "array", "at", "the", "specified", "index", "to", "its", "corresponding", "big", "decimal", "value", "." ]
train
https://github.com/craterdog/java-general-utilities/blob/a3ff45eaa00c2b8ed5c53efe9fe5166065fc1f57/src/main/java/craterdog/utils/ByteUtils.java#L536-L543
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/QuickSelect.java
QuickSelect.insertionSort
private static <T> void insertionSort(List<T> data, Comparator<? super T> comparator, int start, int end) { """ Sort a small array using repetitive insertion sort. @param <T> object type @param data Data to sort @param start Interval start @param end Interval end """ for(int i = start + 1; i < end; i++) { for(int j = i; j > start && comparator.compare(data.get(j - 1), data.get(j)) > 0; j--) { swap(data, j, j - 1); } } }
java
private static <T> void insertionSort(List<T> data, Comparator<? super T> comparator, int start, int end) { for(int i = start + 1; i < end; i++) { for(int j = i; j > start && comparator.compare(data.get(j - 1), data.get(j)) > 0; j--) { swap(data, j, j - 1); } } }
[ "private", "static", "<", "T", ">", "void", "insertionSort", "(", "List", "<", "T", ">", "data", ",", "Comparator", "<", "?", "super", "T", ">", "comparator", ",", "int", "start", ",", "int", "end", ")", "{", "for", "(", "int", "i", "=", "start", "+", "1", ";", "i", "<", "end", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "i", ";", "j", ">", "start", "&&", "comparator", ".", "compare", "(", "data", ".", "get", "(", "j", "-", "1", ")", ",", "data", ".", "get", "(", "j", ")", ")", ">", "0", ";", "j", "--", ")", "{", "swap", "(", "data", ",", "j", ",", "j", "-", "1", ")", ";", "}", "}", "}" ]
Sort a small array using repetitive insertion sort. @param <T> object type @param data Data to sort @param start Interval start @param end Interval end
[ "Sort", "a", "small", "array", "using", "repetitive", "insertion", "sort", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/QuickSelect.java#L806-L812
playn/playn
core/src/playn/core/json/JsonObject.java
JsonObject.getArray
public Json.Array getArray(String key, Json.Array default_) { """ Returns the {@link JsonArray} at the given key, or the default if it does not exist or is the wrong type. """ Object o = get(key); return (o instanceof Json.Array) ? (Json.Array) o : default_; }
java
public Json.Array getArray(String key, Json.Array default_) { Object o = get(key); return (o instanceof Json.Array) ? (Json.Array) o : default_; }
[ "public", "Json", ".", "Array", "getArray", "(", "String", "key", ",", "Json", ".", "Array", "default_", ")", "{", "Object", "o", "=", "get", "(", "key", ")", ";", "return", "(", "o", "instanceof", "Json", ".", "Array", ")", "?", "(", "Json", ".", "Array", ")", "o", ":", "default_", ";", "}" ]
Returns the {@link JsonArray} at the given key, or the default if it does not exist or is the wrong type.
[ "Returns", "the", "{" ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/json/JsonObject.java#L58-L61
intellimate/Izou
src/main/java/org/intellimate/izou/system/sound/SoundManager.java
SoundManager.addNonPermanent
private void addNonPermanent(AddOnModel addOnModel, IzouSoundLineBaseClass izouSoundLine) { """ adds the IzouSoundLine as NonPermanent @param addOnModel the AddonModel to @param izouSoundLine the IzouSoundLine to add """ debug("adding " + izouSoundLine + " from " + addOnModel + " to non-permanent"); if (izouSoundLine.isPermanent()) izouSoundLine.setToNonPermanent(); List<WeakReference<IzouSoundLineBaseClass>> weakReferences = nonPermanent.get(addOnModel); if (weakReferences == null) weakReferences = Collections.synchronizedList(new ArrayList<>()); nonPermanent.put(addOnModel, weakReferences); weakReferences.add(new WeakReference<>(izouSoundLine)); }
java
private void addNonPermanent(AddOnModel addOnModel, IzouSoundLineBaseClass izouSoundLine) { debug("adding " + izouSoundLine + " from " + addOnModel + " to non-permanent"); if (izouSoundLine.isPermanent()) izouSoundLine.setToNonPermanent(); List<WeakReference<IzouSoundLineBaseClass>> weakReferences = nonPermanent.get(addOnModel); if (weakReferences == null) weakReferences = Collections.synchronizedList(new ArrayList<>()); nonPermanent.put(addOnModel, weakReferences); weakReferences.add(new WeakReference<>(izouSoundLine)); }
[ "private", "void", "addNonPermanent", "(", "AddOnModel", "addOnModel", ",", "IzouSoundLineBaseClass", "izouSoundLine", ")", "{", "debug", "(", "\"adding \"", "+", "izouSoundLine", "+", "\" from \"", "+", "addOnModel", "+", "\" to non-permanent\"", ")", ";", "if", "(", "izouSoundLine", ".", "isPermanent", "(", ")", ")", "izouSoundLine", ".", "setToNonPermanent", "(", ")", ";", "List", "<", "WeakReference", "<", "IzouSoundLineBaseClass", ">", ">", "weakReferences", "=", "nonPermanent", ".", "get", "(", "addOnModel", ")", ";", "if", "(", "weakReferences", "==", "null", ")", "weakReferences", "=", "Collections", ".", "synchronizedList", "(", "new", "ArrayList", "<>", "(", ")", ")", ";", "nonPermanent", ".", "put", "(", "addOnModel", ",", "weakReferences", ")", ";", "weakReferences", ".", "add", "(", "new", "WeakReference", "<>", "(", "izouSoundLine", ")", ")", ";", "}" ]
adds the IzouSoundLine as NonPermanent @param addOnModel the AddonModel to @param izouSoundLine the IzouSoundLine to add
[ "adds", "the", "IzouSoundLine", "as", "NonPermanent" ]
train
https://github.com/intellimate/Izou/blob/40a808b97998e17655c4a78e30ce7326148aed27/src/main/java/org/intellimate/izou/system/sound/SoundManager.java#L227-L236
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/EllipticalArc.java
EllipticalArc.prepare
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { """ Draws this arc. @param context the {@link Context2D} used to draw this arc. """ final double rx = attr.getRadiusX(); final double ry = attr.getRadiusY(); if ((rx > 0) && (ry > 0)) { context.beginPath(); context.ellipse(0, 0, rx, ry, 0, attr.getStartAngle(), attr.getEndAngle(), attr.isCounterClockwise()); return true; } return false; }
java
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { final double rx = attr.getRadiusX(); final double ry = attr.getRadiusY(); if ((rx > 0) && (ry > 0)) { context.beginPath(); context.ellipse(0, 0, rx, ry, 0, attr.getStartAngle(), attr.getEndAngle(), attr.isCounterClockwise()); return true; } return false; }
[ "@", "Override", "protected", "boolean", "prepare", "(", "final", "Context2D", "context", ",", "final", "Attributes", "attr", ",", "final", "double", "alpha", ")", "{", "final", "double", "rx", "=", "attr", ".", "getRadiusX", "(", ")", ";", "final", "double", "ry", "=", "attr", ".", "getRadiusY", "(", ")", ";", "if", "(", "(", "rx", ">", "0", ")", "&&", "(", "ry", ">", "0", ")", ")", "{", "context", ".", "beginPath", "(", ")", ";", "context", ".", "ellipse", "(", "0", ",", "0", ",", "rx", ",", "ry", ",", "0", ",", "attr", ".", "getStartAngle", "(", ")", ",", "attr", ".", "getEndAngle", "(", ")", ",", "attr", ".", "isCounterClockwise", "(", ")", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Draws this arc. @param context the {@link Context2D} used to draw this arc.
[ "Draws", "this", "arc", "." ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/EllipticalArc.java#L86-L102
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/BinaryLogRecordSerializerVersion2Impl.java
BinaryLogRecordSerializerVersion2Impl.readParam
private static Object readParam(DataInput reader) throws IOException { """ /* Deserialize parameter Object. Restores {@link Number} and {@link Date} instances into their original type. """ int type = reader.readUnsignedByte(); switch (type) { case BYTE_ID: return Byte.valueOf(reader.readByte()); case SHORT_ID: return Short.valueOf(reader.readShort()); case INTEGER_ID: return Integer.valueOf(reader.readInt()); case CHAR_ID: return Character.valueOf(reader.readChar()); case LONG_ID: return Long.valueOf(reader.readLong()); case FLOAT_ID: return Float.valueOf(reader.readFloat()); case DOUBLE_ID: return Double.valueOf(reader.readDouble()); case DATE_ID: return new Date(reader.readLong()); case STRING_ID: return readString(reader); case NULL_ID: return null; } throw new DeserializerException("Wrong type of a parameter", "one of the B,S,I,C,L,F,D,T,O,N", Character.toString((char)type)); }
java
private static Object readParam(DataInput reader) throws IOException { int type = reader.readUnsignedByte(); switch (type) { case BYTE_ID: return Byte.valueOf(reader.readByte()); case SHORT_ID: return Short.valueOf(reader.readShort()); case INTEGER_ID: return Integer.valueOf(reader.readInt()); case CHAR_ID: return Character.valueOf(reader.readChar()); case LONG_ID: return Long.valueOf(reader.readLong()); case FLOAT_ID: return Float.valueOf(reader.readFloat()); case DOUBLE_ID: return Double.valueOf(reader.readDouble()); case DATE_ID: return new Date(reader.readLong()); case STRING_ID: return readString(reader); case NULL_ID: return null; } throw new DeserializerException("Wrong type of a parameter", "one of the B,S,I,C,L,F,D,T,O,N", Character.toString((char)type)); }
[ "private", "static", "Object", "readParam", "(", "DataInput", "reader", ")", "throws", "IOException", "{", "int", "type", "=", "reader", ".", "readUnsignedByte", "(", ")", ";", "switch", "(", "type", ")", "{", "case", "BYTE_ID", ":", "return", "Byte", ".", "valueOf", "(", "reader", ".", "readByte", "(", ")", ")", ";", "case", "SHORT_ID", ":", "return", "Short", ".", "valueOf", "(", "reader", ".", "readShort", "(", ")", ")", ";", "case", "INTEGER_ID", ":", "return", "Integer", ".", "valueOf", "(", "reader", ".", "readInt", "(", ")", ")", ";", "case", "CHAR_ID", ":", "return", "Character", ".", "valueOf", "(", "reader", ".", "readChar", "(", ")", ")", ";", "case", "LONG_ID", ":", "return", "Long", ".", "valueOf", "(", "reader", ".", "readLong", "(", ")", ")", ";", "case", "FLOAT_ID", ":", "return", "Float", ".", "valueOf", "(", "reader", ".", "readFloat", "(", ")", ")", ";", "case", "DOUBLE_ID", ":", "return", "Double", ".", "valueOf", "(", "reader", ".", "readDouble", "(", ")", ")", ";", "case", "DATE_ID", ":", "return", "new", "Date", "(", "reader", ".", "readLong", "(", ")", ")", ";", "case", "STRING_ID", ":", "return", "readString", "(", "reader", ")", ";", "case", "NULL_ID", ":", "return", "null", ";", "}", "throw", "new", "DeserializerException", "(", "\"Wrong type of a parameter\"", ",", "\"one of the B,S,I,C,L,F,D,T,O,N\"", ",", "Character", ".", "toString", "(", "(", "char", ")", "type", ")", ")", ";", "}" ]
/* Deserialize parameter Object. Restores {@link Number} and {@link Date} instances into their original type.
[ "/", "*", "Deserialize", "parameter", "Object", ".", "Restores", "{" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/BinaryLogRecordSerializerVersion2Impl.java#L792-L817
google/error-prone-javac
src/jdk.jdeps/share/classes/com/sun/tools/jdeps/InverseDepsAnalyzer.java
InverseDepsAnalyzer.inverseDependences
public Set<Deque<Archive>> inverseDependences() throws IOException { """ Finds all inverse transitive dependencies using the given requires set as the targets, if non-empty. If the given requires set is empty, use the archives depending the packages specified in -regex or -p options. """ // create a new dependency finder to do the analysis DependencyFinder dependencyFinder = new DependencyFinder(configuration, DEFAULT_FILTER); try { // parse all archives in unnamed module to get compile-time dependences Stream<Archive> archives = Stream.concat(configuration.initialArchives().stream(), configuration.classPathArchives().stream()); if (apiOnly) { dependencyFinder.parseExportedAPIs(archives); } else { dependencyFinder.parse(archives); } Graph.Builder<Archive> builder = new Graph.Builder<>(); // include all target nodes targets().forEach(builder::addNode); // transpose the module graph configuration.getModules().values().stream() .forEach(m -> { builder.addNode(m); m.descriptor().requires().stream() .map(Requires::name) .map(configuration::findModule) // must be present .forEach(v -> builder.addEdge(v.get(), m)); }); // add the dependences from the analysis Map<Archive, Set<Archive>> dependences = dependencyFinder.dependences(); dependences.entrySet().stream() .forEach(e -> { Archive u = e.getKey(); builder.addNode(u); e.getValue().forEach(v -> builder.addEdge(v, u)); }); // transposed dependence graph. Graph<Archive> graph = builder.build(); trace("targets: %s%n", targets()); // Traverse from the targets and find all paths // rebuild a graph with all nodes that depends on targets // targets directly and indirectly return targets().stream() .map(t -> findPaths(graph, t)) .flatMap(Set::stream) .collect(Collectors.toSet()); } finally { dependencyFinder.shutdown(); } }
java
public Set<Deque<Archive>> inverseDependences() throws IOException { // create a new dependency finder to do the analysis DependencyFinder dependencyFinder = new DependencyFinder(configuration, DEFAULT_FILTER); try { // parse all archives in unnamed module to get compile-time dependences Stream<Archive> archives = Stream.concat(configuration.initialArchives().stream(), configuration.classPathArchives().stream()); if (apiOnly) { dependencyFinder.parseExportedAPIs(archives); } else { dependencyFinder.parse(archives); } Graph.Builder<Archive> builder = new Graph.Builder<>(); // include all target nodes targets().forEach(builder::addNode); // transpose the module graph configuration.getModules().values().stream() .forEach(m -> { builder.addNode(m); m.descriptor().requires().stream() .map(Requires::name) .map(configuration::findModule) // must be present .forEach(v -> builder.addEdge(v.get(), m)); }); // add the dependences from the analysis Map<Archive, Set<Archive>> dependences = dependencyFinder.dependences(); dependences.entrySet().stream() .forEach(e -> { Archive u = e.getKey(); builder.addNode(u); e.getValue().forEach(v -> builder.addEdge(v, u)); }); // transposed dependence graph. Graph<Archive> graph = builder.build(); trace("targets: %s%n", targets()); // Traverse from the targets and find all paths // rebuild a graph with all nodes that depends on targets // targets directly and indirectly return targets().stream() .map(t -> findPaths(graph, t)) .flatMap(Set::stream) .collect(Collectors.toSet()); } finally { dependencyFinder.shutdown(); } }
[ "public", "Set", "<", "Deque", "<", "Archive", ">", ">", "inverseDependences", "(", ")", "throws", "IOException", "{", "// create a new dependency finder to do the analysis", "DependencyFinder", "dependencyFinder", "=", "new", "DependencyFinder", "(", "configuration", ",", "DEFAULT_FILTER", ")", ";", "try", "{", "// parse all archives in unnamed module to get compile-time dependences", "Stream", "<", "Archive", ">", "archives", "=", "Stream", ".", "concat", "(", "configuration", ".", "initialArchives", "(", ")", ".", "stream", "(", ")", ",", "configuration", ".", "classPathArchives", "(", ")", ".", "stream", "(", ")", ")", ";", "if", "(", "apiOnly", ")", "{", "dependencyFinder", ".", "parseExportedAPIs", "(", "archives", ")", ";", "}", "else", "{", "dependencyFinder", ".", "parse", "(", "archives", ")", ";", "}", "Graph", ".", "Builder", "<", "Archive", ">", "builder", "=", "new", "Graph", ".", "Builder", "<>", "(", ")", ";", "// include all target nodes", "targets", "(", ")", ".", "forEach", "(", "builder", "::", "addNode", ")", ";", "// transpose the module graph", "configuration", ".", "getModules", "(", ")", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "forEach", "(", "m", "->", "{", "builder", ".", "addNode", "(", "m", ")", ";", "m", ".", "descriptor", "(", ")", ".", "requires", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "Requires", "::", "name", ")", ".", "map", "(", "configuration", "::", "findModule", ")", "// must be present", ".", "forEach", "(", "v", "->", "builder", ".", "addEdge", "(", "v", ".", "get", "(", ")", ",", "m", ")", ")", ";", "}", ")", ";", "// add the dependences from the analysis", "Map", "<", "Archive", ",", "Set", "<", "Archive", ">", ">", "dependences", "=", "dependencyFinder", ".", "dependences", "(", ")", ";", "dependences", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "forEach", "(", "e", "->", "{", "Archive", "u", "=", "e", ".", "getKey", "(", ")", ";", "builder", ".", "addNode", "(", "u", ")", ";", "e", ".", "getValue", "(", ")", ".", "forEach", "(", "v", "->", "builder", ".", "addEdge", "(", "v", ",", "u", ")", ")", ";", "}", ")", ";", "// transposed dependence graph.", "Graph", "<", "Archive", ">", "graph", "=", "builder", ".", "build", "(", ")", ";", "trace", "(", "\"targets: %s%n\"", ",", "targets", "(", ")", ")", ";", "// Traverse from the targets and find all paths", "// rebuild a graph with all nodes that depends on targets", "// targets directly and indirectly", "return", "targets", "(", ")", ".", "stream", "(", ")", ".", "map", "(", "t", "->", "findPaths", "(", "graph", ",", "t", ")", ")", ".", "flatMap", "(", "Set", "::", "stream", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "}", "finally", "{", "dependencyFinder", ".", "shutdown", "(", ")", ";", "}", "}" ]
Finds all inverse transitive dependencies using the given requires set as the targets, if non-empty. If the given requires set is empty, use the archives depending the packages specified in -regex or -p options.
[ "Finds", "all", "inverse", "transitive", "dependencies", "using", "the", "given", "requires", "set", "as", "the", "targets", "if", "non", "-", "empty", ".", "If", "the", "given", "requires", "set", "is", "empty", "use", "the", "archives", "depending", "the", "packages", "specified", "in", "-", "regex", "or", "-", "p", "options", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/InverseDepsAnalyzer.java#L125-L176
j256/ormlite-android
src/main/java/com/j256/ormlite/android/DatabaseTableConfigUtil.java
DatabaseTableConfigUtil.buildConfig
private static DatabaseFieldConfig buildConfig(DatabaseField databaseField, String tableName, Field field) throws Exception { """ Instead of calling the annotation methods directly, we peer inside the proxy and investigate the array of AnnotationMember objects stored by the AnnotationFactory. """ InvocationHandler proxy = Proxy.getInvocationHandler(databaseField); if (proxy.getClass() != annotationFactoryClazz) { return null; } // this should be an array of AnnotationMember objects Object elementsObject = elementsField.get(proxy); if (elementsObject == null) { return null; } DatabaseFieldConfig config = new DatabaseFieldConfig(field.getName()); Object[] objs = (Object[]) elementsObject; for (int i = 0; i < configFieldNums.length; i++) { Object value = valueField.get(objs[i]); if (value != null) { assignConfigField(configFieldNums[i], config, field, value); } } return config; }
java
private static DatabaseFieldConfig buildConfig(DatabaseField databaseField, String tableName, Field field) throws Exception { InvocationHandler proxy = Proxy.getInvocationHandler(databaseField); if (proxy.getClass() != annotationFactoryClazz) { return null; } // this should be an array of AnnotationMember objects Object elementsObject = elementsField.get(proxy); if (elementsObject == null) { return null; } DatabaseFieldConfig config = new DatabaseFieldConfig(field.getName()); Object[] objs = (Object[]) elementsObject; for (int i = 0; i < configFieldNums.length; i++) { Object value = valueField.get(objs[i]); if (value != null) { assignConfigField(configFieldNums[i], config, field, value); } } return config; }
[ "private", "static", "DatabaseFieldConfig", "buildConfig", "(", "DatabaseField", "databaseField", ",", "String", "tableName", ",", "Field", "field", ")", "throws", "Exception", "{", "InvocationHandler", "proxy", "=", "Proxy", ".", "getInvocationHandler", "(", "databaseField", ")", ";", "if", "(", "proxy", ".", "getClass", "(", ")", "!=", "annotationFactoryClazz", ")", "{", "return", "null", ";", "}", "// this should be an array of AnnotationMember objects", "Object", "elementsObject", "=", "elementsField", ".", "get", "(", "proxy", ")", ";", "if", "(", "elementsObject", "==", "null", ")", "{", "return", "null", ";", "}", "DatabaseFieldConfig", "config", "=", "new", "DatabaseFieldConfig", "(", "field", ".", "getName", "(", ")", ")", ";", "Object", "[", "]", "objs", "=", "(", "Object", "[", "]", ")", "elementsObject", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "configFieldNums", ".", "length", ";", "i", "++", ")", "{", "Object", "value", "=", "valueField", ".", "get", "(", "objs", "[", "i", "]", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "assignConfigField", "(", "configFieldNums", "[", "i", "]", ",", "config", ",", "field", ",", "value", ")", ";", "}", "}", "return", "config", ";", "}" ]
Instead of calling the annotation methods directly, we peer inside the proxy and investigate the array of AnnotationMember objects stored by the AnnotationFactory.
[ "Instead", "of", "calling", "the", "annotation", "methods", "directly", "we", "peer", "inside", "the", "proxy", "and", "investigate", "the", "array", "of", "AnnotationMember", "objects", "stored", "by", "the", "AnnotationFactory", "." ]
train
https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/DatabaseTableConfigUtil.java#L292-L312
thorstenwagner/TraJ
src/main/java/de/biomedical_imaging/traj/math/TrajectorySplineFit.java
TrajectorySplineFit.minDistancePointSpline
public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment) { """ Finds to a given point p the point on the spline with minimum distance. @param p Point where the nearest distance is searched for @param nPointsPerSegment Number of interpolation points between two support points @return Point spline which has the minimum distance to p """ double minDistance = Double.MAX_VALUE; Point2D.Double minDistancePoint = null; int numberOfSplines = spline.getN(); double[] knots = spline.getKnots(); for(int i = 0; i < numberOfSplines; i++){ double x = knots[i]; double stopx = knots[i+1]; double dx = (stopx-x)/nPointsPerSegment; for(int j = 0; j < nPointsPerSegment; j++){ Point2D.Double candidate = new Point2D.Double(x, spline.value(x)); double d = p.distance(candidate); if(d<minDistance){ minDistance = d; minDistancePoint = candidate; } x += dx; } } return minDistancePoint; }
java
public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){ double minDistance = Double.MAX_VALUE; Point2D.Double minDistancePoint = null; int numberOfSplines = spline.getN(); double[] knots = spline.getKnots(); for(int i = 0; i < numberOfSplines; i++){ double x = knots[i]; double stopx = knots[i+1]; double dx = (stopx-x)/nPointsPerSegment; for(int j = 0; j < nPointsPerSegment; j++){ Point2D.Double candidate = new Point2D.Double(x, spline.value(x)); double d = p.distance(candidate); if(d<minDistance){ minDistance = d; minDistancePoint = candidate; } x += dx; } } return minDistancePoint; }
[ "public", "Point2D", ".", "Double", "minDistancePointSpline", "(", "Point2D", ".", "Double", "p", ",", "int", "nPointsPerSegment", ")", "{", "double", "minDistance", "=", "Double", ".", "MAX_VALUE", ";", "Point2D", ".", "Double", "minDistancePoint", "=", "null", ";", "int", "numberOfSplines", "=", "spline", ".", "getN", "(", ")", ";", "double", "[", "]", "knots", "=", "spline", ".", "getKnots", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numberOfSplines", ";", "i", "++", ")", "{", "double", "x", "=", "knots", "[", "i", "]", ";", "double", "stopx", "=", "knots", "[", "i", "+", "1", "]", ";", "double", "dx", "=", "(", "stopx", "-", "x", ")", "/", "nPointsPerSegment", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "nPointsPerSegment", ";", "j", "++", ")", "{", "Point2D", ".", "Double", "candidate", "=", "new", "Point2D", ".", "Double", "(", "x", ",", "spline", ".", "value", "(", "x", ")", ")", ";", "double", "d", "=", "p", ".", "distance", "(", "candidate", ")", ";", "if", "(", "d", "<", "minDistance", ")", "{", "minDistance", "=", "d", ";", "minDistancePoint", "=", "candidate", ";", "}", "x", "+=", "dx", ";", "}", "}", "return", "minDistancePoint", ";", "}" ]
Finds to a given point p the point on the spline with minimum distance. @param p Point where the nearest distance is searched for @param nPointsPerSegment Number of interpolation points between two support points @return Point spline which has the minimum distance to p
[ "Finds", "to", "a", "given", "point", "p", "the", "point", "on", "the", "spline", "with", "minimum", "distance", "." ]
train
https://github.com/thorstenwagner/TraJ/blob/505fafb1f2f77a2d67bb2a089a2fdebe2c9bc7cb/src/main/java/de/biomedical_imaging/traj/math/TrajectorySplineFit.java#L538-L560
samskivert/samskivert
src/main/java/com/samskivert/util/RandomUtil.java
RandomUtil.pickRandom
public static <T> T pickRandom (List<T> values, T skip) { """ Picks a random object from the supplied List. The specified skip object will be skipped when selecting a random value. The skipped object must exist exactly once in the List. @return a randomly selected item. """ return pickRandom(values, skip, rand); }
java
public static <T> T pickRandom (List<T> values, T skip) { return pickRandom(values, skip, rand); }
[ "public", "static", "<", "T", ">", "T", "pickRandom", "(", "List", "<", "T", ">", "values", ",", "T", "skip", ")", "{", "return", "pickRandom", "(", "values", ",", "skip", ",", "rand", ")", ";", "}" ]
Picks a random object from the supplied List. The specified skip object will be skipped when selecting a random value. The skipped object must exist exactly once in the List. @return a randomly selected item.
[ "Picks", "a", "random", "object", "from", "the", "supplied", "List", ".", "The", "specified", "skip", "object", "will", "be", "skipped", "when", "selecting", "a", "random", "value", ".", "The", "skipped", "object", "must", "exist", "exactly", "once", "in", "the", "List", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/RandomUtil.java#L350-L353
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java
ImageModerationsImpl.matchFileInput
public MatchResponse matchFileInput(byte[] imageStream, MatchFileInputOptionalParameter matchFileInputOptionalParameter) { """ Fuzzily match an image against one of your custom Image Lists. You can create and manage your custom image lists using &lt;a href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe"&gt;this&lt;/a&gt; API. Returns ID and tags of matching image.&lt;br/&gt; &lt;br/&gt; Note: Refresh Index must be run on the corresponding Image List before additions and removals are reflected in the response. @param imageStream The image file. @param matchFileInputOptionalParameter 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 MatchResponse object if successful. """ return matchFileInputWithServiceResponseAsync(imageStream, matchFileInputOptionalParameter).toBlocking().single().body(); }
java
public MatchResponse matchFileInput(byte[] imageStream, MatchFileInputOptionalParameter matchFileInputOptionalParameter) { return matchFileInputWithServiceResponseAsync(imageStream, matchFileInputOptionalParameter).toBlocking().single().body(); }
[ "public", "MatchResponse", "matchFileInput", "(", "byte", "[", "]", "imageStream", ",", "MatchFileInputOptionalParameter", "matchFileInputOptionalParameter", ")", "{", "return", "matchFileInputWithServiceResponseAsync", "(", "imageStream", ",", "matchFileInputOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Fuzzily match an image against one of your custom Image Lists. You can create and manage your custom image lists using &lt;a href="/docs/services/578ff44d2703741568569ab9/operations/578ff7b12703741568569abe"&gt;this&lt;/a&gt; API. Returns ID and tags of matching image.&lt;br/&gt; &lt;br/&gt; Note: Refresh Index must be run on the corresponding Image List before additions and removals are reflected in the response. @param imageStream The image file. @param matchFileInputOptionalParameter 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 MatchResponse object if successful.
[ "Fuzzily", "match", "an", "image", "against", "one", "of", "your", "custom", "Image", "Lists", ".", "You", "can", "create", "and", "manage", "your", "custom", "image", "lists", "using", "&lt", ";", "a", "href", "=", "/", "docs", "/", "services", "/", "578ff44d2703741568569ab9", "/", "operations", "/", "578ff7b12703741568569abe", "&gt", ";", "this&lt", ";", "/", "a&gt", ";", "API", ".", "Returns", "ID", "and", "tags", "of", "matching", "image", ".", "&lt", ";", "br", "/", "&gt", ";", "&lt", ";", "br", "/", "&gt", ";", "Note", ":", "Refresh", "Index", "must", "be", "run", "on", "the", "corresponding", "Image", "List", "before", "additions", "and", "removals", "are", "reflected", "in", "the", "response", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java#L1947-L1949
dita-ot/dita-ot
src/main/java/org/dita/dost/util/URLUtils.java
URLUtils.directoryContains
public static boolean directoryContains(final URI directory, final URI child) { """ Determines whether the parent directory contains the child element (a file or directory) @param directory the file to consider as the parent @param child the file to consider as the child @return true is the candidate leaf is under by the specified composite, otherwise false """ final String d = directory.normalize().toString(); final String c = child.normalize().toString(); if (d.equals(c)) { return false; } else { return c.startsWith(d); } }
java
public static boolean directoryContains(final URI directory, final URI child) { final String d = directory.normalize().toString(); final String c = child.normalize().toString(); if (d.equals(c)) { return false; } else { return c.startsWith(d); } }
[ "public", "static", "boolean", "directoryContains", "(", "final", "URI", "directory", ",", "final", "URI", "child", ")", "{", "final", "String", "d", "=", "directory", ".", "normalize", "(", ")", ".", "toString", "(", ")", ";", "final", "String", "c", "=", "child", ".", "normalize", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "d", ".", "equals", "(", "c", ")", ")", "{", "return", "false", ";", "}", "else", "{", "return", "c", ".", "startsWith", "(", "d", ")", ";", "}", "}" ]
Determines whether the parent directory contains the child element (a file or directory) @param directory the file to consider as the parent @param child the file to consider as the child @return true is the candidate leaf is under by the specified composite, otherwise false
[ "Determines", "whether", "the", "parent", "directory", "contains", "the", "child", "element", "(", "a", "file", "or", "directory", ")" ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/URLUtils.java#L524-L532
apereo/cas
support/cas-server-support-jdbc-authentication/src/main/java/org/apereo/cas/adaptors/jdbc/QueryAndEncodeDatabaseAuthenticationHandler.java
QueryAndEncodeDatabaseAuthenticationHandler.digestEncodedPassword
protected String digestEncodedPassword(final String encodedPassword, final Map<String, Object> values) { """ Digest encoded password. @param encodedPassword the encoded password @param values the values retrieved from database @return the digested password """ val hashService = new DefaultHashService(); if (StringUtils.isNotBlank(this.staticSalt)) { hashService.setPrivateSalt(ByteSource.Util.bytes(this.staticSalt)); } hashService.setHashAlgorithmName(this.algorithmName); if (values.containsKey(this.numberOfIterationsFieldName)) { val longAsStr = values.get(this.numberOfIterationsFieldName).toString(); hashService.setHashIterations(Integer.parseInt(longAsStr)); } else { hashService.setHashIterations(this.numberOfIterations); } if (!values.containsKey(this.saltFieldName)) { throw new IllegalArgumentException("Specified field name for salt does not exist in the results"); } val dynaSalt = values.get(this.saltFieldName).toString(); val request = new HashRequest.Builder() .setSalt(dynaSalt) .setSource(encodedPassword) .build(); return hashService.computeHash(request).toHex(); }
java
protected String digestEncodedPassword(final String encodedPassword, final Map<String, Object> values) { val hashService = new DefaultHashService(); if (StringUtils.isNotBlank(this.staticSalt)) { hashService.setPrivateSalt(ByteSource.Util.bytes(this.staticSalt)); } hashService.setHashAlgorithmName(this.algorithmName); if (values.containsKey(this.numberOfIterationsFieldName)) { val longAsStr = values.get(this.numberOfIterationsFieldName).toString(); hashService.setHashIterations(Integer.parseInt(longAsStr)); } else { hashService.setHashIterations(this.numberOfIterations); } if (!values.containsKey(this.saltFieldName)) { throw new IllegalArgumentException("Specified field name for salt does not exist in the results"); } val dynaSalt = values.get(this.saltFieldName).toString(); val request = new HashRequest.Builder() .setSalt(dynaSalt) .setSource(encodedPassword) .build(); return hashService.computeHash(request).toHex(); }
[ "protected", "String", "digestEncodedPassword", "(", "final", "String", "encodedPassword", ",", "final", "Map", "<", "String", ",", "Object", ">", "values", ")", "{", "val", "hashService", "=", "new", "DefaultHashService", "(", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "this", ".", "staticSalt", ")", ")", "{", "hashService", ".", "setPrivateSalt", "(", "ByteSource", ".", "Util", ".", "bytes", "(", "this", ".", "staticSalt", ")", ")", ";", "}", "hashService", ".", "setHashAlgorithmName", "(", "this", ".", "algorithmName", ")", ";", "if", "(", "values", ".", "containsKey", "(", "this", ".", "numberOfIterationsFieldName", ")", ")", "{", "val", "longAsStr", "=", "values", ".", "get", "(", "this", ".", "numberOfIterationsFieldName", ")", ".", "toString", "(", ")", ";", "hashService", ".", "setHashIterations", "(", "Integer", ".", "parseInt", "(", "longAsStr", ")", ")", ";", "}", "else", "{", "hashService", ".", "setHashIterations", "(", "this", ".", "numberOfIterations", ")", ";", "}", "if", "(", "!", "values", ".", "containsKey", "(", "this", ".", "saltFieldName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Specified field name for salt does not exist in the results\"", ")", ";", "}", "val", "dynaSalt", "=", "values", ".", "get", "(", "this", ".", "saltFieldName", ")", ".", "toString", "(", ")", ";", "val", "request", "=", "new", "HashRequest", ".", "Builder", "(", ")", ".", "setSalt", "(", "dynaSalt", ")", ".", "setSource", "(", "encodedPassword", ")", ".", "build", "(", ")", ";", "return", "hashService", ".", "computeHash", "(", "request", ")", ".", "toHex", "(", ")", ";", "}" ]
Digest encoded password. @param encodedPassword the encoded password @param values the values retrieved from database @return the digested password
[ "Digest", "encoded", "password", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-jdbc-authentication/src/main/java/org/apereo/cas/adaptors/jdbc/QueryAndEncodeDatabaseAuthenticationHandler.java#L177-L201
kiegroup/droolsjbpm-integration
kie-spring-boot/kie-spring-boot-autoconfiguration/kie-server-spring-boot-autoconfiguration-jbpm/src/main/java/org/kie/server/springboot/jbpm/ContainerAliasResolver.java
ContainerAliasResolver.forTaskInstance
public String forTaskInstance(String alias, long taskId) { """ Looks up container id for given alias that is associated with task instance @param alias container alias @param taskId unique task instance id @return @throws IllegalArgumentException in case there are no containers for given alias """ return registry.getContainerId(alias, new ByTaskIdContainerLocator(taskId)); }
java
public String forTaskInstance(String alias, long taskId) { return registry.getContainerId(alias, new ByTaskIdContainerLocator(taskId)); }
[ "public", "String", "forTaskInstance", "(", "String", "alias", ",", "long", "taskId", ")", "{", "return", "registry", ".", "getContainerId", "(", "alias", ",", "new", "ByTaskIdContainerLocator", "(", "taskId", ")", ")", ";", "}" ]
Looks up container id for given alias that is associated with task instance @param alias container alias @param taskId unique task instance id @return @throws IllegalArgumentException in case there are no containers for given alias
[ "Looks", "up", "container", "id", "for", "given", "alias", "that", "is", "associated", "with", "task", "instance" ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-spring-boot/kie-spring-boot-autoconfiguration/kie-server-spring-boot-autoconfiguration-jbpm/src/main/java/org/kie/server/springboot/jbpm/ContainerAliasResolver.java#L76-L78
jbundle/jbundle
thin/opt/location/src/main/java/org/jbundle/thin/opt/location/NodeData.java
NodeData.init
public void init(BaseApplet baseApplet, RemoteSession remoteSession, String strDescription, String objID, String strRecordName) { """ Constructs a new instance of SampleData with the passed in arguments. """ m_baseApplet = baseApplet; m_remoteSession = remoteSession; m_strDescription = strDescription; m_objID = objID; m_strRecordName = strRecordName; }
java
public void init(BaseApplet baseApplet, RemoteSession remoteSession, String strDescription, String objID, String strRecordName) { m_baseApplet = baseApplet; m_remoteSession = remoteSession; m_strDescription = strDescription; m_objID = objID; m_strRecordName = strRecordName; }
[ "public", "void", "init", "(", "BaseApplet", "baseApplet", ",", "RemoteSession", "remoteSession", ",", "String", "strDescription", ",", "String", "objID", ",", "String", "strRecordName", ")", "{", "m_baseApplet", "=", "baseApplet", ";", "m_remoteSession", "=", "remoteSession", ";", "m_strDescription", "=", "strDescription", ";", "m_objID", "=", "objID", ";", "m_strRecordName", "=", "strRecordName", ";", "}" ]
Constructs a new instance of SampleData with the passed in arguments.
[ "Constructs", "a", "new", "instance", "of", "SampleData", "with", "the", "passed", "in", "arguments", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/opt/location/src/main/java/org/jbundle/thin/opt/location/NodeData.java#L52-L59
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/BICO.java
BICO.bicoUpdate
protected void bicoUpdate(double[] x) { """ Inserts a new point into the ClusteringFeature tree. @param x the point """ assert (!this.bufferPhase && this.numDimensions == x.length); // Starts with the global root node as the current root node ClusteringTreeNode r = this.root; int i = 1; while (true) { ClusteringTreeNode y = r.nearestChild(x); // Checks if the point can not be added to the current level if (r.hasNoChildren() || y == null || Metric.distanceSquared(x, y.getCenter()) > calcRSquared(i)) { // Creates a new node for the point and adds it to the current // root node r.addChild(new ClusteringTreeNode(x, new ClusteringFeature(x, calcR(i)))); this.rootCount++; break; } else { // Checks if the point can be added to the nearest node without // exceeding the global threshold if (y.getClusteringFeature().calcKMeansCosts(y.getCenter(), x) <= this.T) { // Adds the point to the ClusteringFeature y.getClusteringFeature().add(1, x, Metric.distanceSquared(x)); break; } else { // Navigates one level down in the tree r = y; i++; } } } // Checks if the number of nodes in the tree exceeds the maximum number if (this.rootCount > this.maxNumClusterFeatures) { rebuild(); } }
java
protected void bicoUpdate(double[] x) { assert (!this.bufferPhase && this.numDimensions == x.length); // Starts with the global root node as the current root node ClusteringTreeNode r = this.root; int i = 1; while (true) { ClusteringTreeNode y = r.nearestChild(x); // Checks if the point can not be added to the current level if (r.hasNoChildren() || y == null || Metric.distanceSquared(x, y.getCenter()) > calcRSquared(i)) { // Creates a new node for the point and adds it to the current // root node r.addChild(new ClusteringTreeNode(x, new ClusteringFeature(x, calcR(i)))); this.rootCount++; break; } else { // Checks if the point can be added to the nearest node without // exceeding the global threshold if (y.getClusteringFeature().calcKMeansCosts(y.getCenter(), x) <= this.T) { // Adds the point to the ClusteringFeature y.getClusteringFeature().add(1, x, Metric.distanceSquared(x)); break; } else { // Navigates one level down in the tree r = y; i++; } } } // Checks if the number of nodes in the tree exceeds the maximum number if (this.rootCount > this.maxNumClusterFeatures) { rebuild(); } }
[ "protected", "void", "bicoUpdate", "(", "double", "[", "]", "x", ")", "{", "assert", "(", "!", "this", ".", "bufferPhase", "&&", "this", ".", "numDimensions", "==", "x", ".", "length", ")", ";", "// Starts with the global root node as the current root node", "ClusteringTreeNode", "r", "=", "this", ".", "root", ";", "int", "i", "=", "1", ";", "while", "(", "true", ")", "{", "ClusteringTreeNode", "y", "=", "r", ".", "nearestChild", "(", "x", ")", ";", "// Checks if the point can not be added to the current level", "if", "(", "r", ".", "hasNoChildren", "(", ")", "||", "y", "==", "null", "||", "Metric", ".", "distanceSquared", "(", "x", ",", "y", ".", "getCenter", "(", ")", ")", ">", "calcRSquared", "(", "i", ")", ")", "{", "// Creates a new node for the point and adds it to the current", "// root node", "r", ".", "addChild", "(", "new", "ClusteringTreeNode", "(", "x", ",", "new", "ClusteringFeature", "(", "x", ",", "calcR", "(", "i", ")", ")", ")", ")", ";", "this", ".", "rootCount", "++", ";", "break", ";", "}", "else", "{", "// Checks if the point can be added to the nearest node without", "// exceeding the global threshold", "if", "(", "y", ".", "getClusteringFeature", "(", ")", ".", "calcKMeansCosts", "(", "y", ".", "getCenter", "(", ")", ",", "x", ")", "<=", "this", ".", "T", ")", "{", "// Adds the point to the ClusteringFeature", "y", ".", "getClusteringFeature", "(", ")", ".", "add", "(", "1", ",", "x", ",", "Metric", ".", "distanceSquared", "(", "x", ")", ")", ";", "break", ";", "}", "else", "{", "// Navigates one level down in the tree", "r", "=", "y", ";", "i", "++", ";", "}", "}", "}", "// Checks if the number of nodes in the tree exceeds the maximum number", "if", "(", "this", ".", "rootCount", ">", "this", ".", "maxNumClusterFeatures", ")", "{", "rebuild", "(", ")", ";", "}", "}" ]
Inserts a new point into the ClusteringFeature tree. @param x the point
[ "Inserts", "a", "new", "point", "into", "the", "ClusteringFeature", "tree", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/BICO.java#L294-L328
h2oai/h2o-3
h2o-algos/src/main/java/hex/deeplearning/Storage.java
Storage.toFrame
static Frame toFrame(Matrix m, Key key) { """ Helper to convert a Matrix into a Frame @param m Matrix @param key Key for output Frame @return Reference to Frame (which is also in DKV) """ final int log_rows_per_chunk = Math.max(1, FileVec.DFLT_LOG2_CHUNK_SIZE - (int) Math.floor(Math.log(m.cols()) / Math.log(2.))); Vec v[] = new Vec[m.cols()]; for (int i = 0; i < m.cols(); ++i) { v[i] = makeCon(0, m.rows(), log_rows_per_chunk); } Frame f = new FrameFiller(m).doAll(new Frame(key, v, true))._fr; DKV.put(key, f); return f; }
java
static Frame toFrame(Matrix m, Key key) { final int log_rows_per_chunk = Math.max(1, FileVec.DFLT_LOG2_CHUNK_SIZE - (int) Math.floor(Math.log(m.cols()) / Math.log(2.))); Vec v[] = new Vec[m.cols()]; for (int i = 0; i < m.cols(); ++i) { v[i] = makeCon(0, m.rows(), log_rows_per_chunk); } Frame f = new FrameFiller(m).doAll(new Frame(key, v, true))._fr; DKV.put(key, f); return f; }
[ "static", "Frame", "toFrame", "(", "Matrix", "m", ",", "Key", "key", ")", "{", "final", "int", "log_rows_per_chunk", "=", "Math", ".", "max", "(", "1", ",", "FileVec", ".", "DFLT_LOG2_CHUNK_SIZE", "-", "(", "int", ")", "Math", ".", "floor", "(", "Math", ".", "log", "(", "m", ".", "cols", "(", ")", ")", "/", "Math", ".", "log", "(", "2.", ")", ")", ")", ";", "Vec", "v", "[", "]", "=", "new", "Vec", "[", "m", ".", "cols", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "m", ".", "cols", "(", ")", ";", "++", "i", ")", "{", "v", "[", "i", "]", "=", "makeCon", "(", "0", ",", "m", ".", "rows", "(", ")", ",", "log_rows_per_chunk", ")", ";", "}", "Frame", "f", "=", "new", "FrameFiller", "(", "m", ")", ".", "doAll", "(", "new", "Frame", "(", "key", ",", "v", ",", "true", ")", ")", ".", "_fr", ";", "DKV", ".", "put", "(", "key", ",", "f", ")", ";", "return", "f", ";", "}" ]
Helper to convert a Matrix into a Frame @param m Matrix @param key Key for output Frame @return Reference to Frame (which is also in DKV)
[ "Helper", "to", "convert", "a", "Matrix", "into", "a", "Frame" ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-algos/src/main/java/hex/deeplearning/Storage.java#L251-L260
michael-rapp/AndroidUtil
library/src/main/java/de/mrapp/android/util/view/ExpandableGridView.java
ExpandableGridView.notifyOnItemClicked
private void notifyOnItemClicked(@NonNull final View view, final int position, final long id) { """ Notifies, the listener, which has been registered to be notified, when any item has been clicked, about an item being clicked. @param view The view within the expandable grid view, which has been clicked, as an instance of the class {@link View}. The view may not be null @param position The position of the item, which has been clicked, as an {@link Integer} value @param id The id of the item, which has been clicked, as a {@link Long} value """ if (itemClickListener != null) { itemClickListener.onItemClick(this, view, position, id); } }
java
private void notifyOnItemClicked(@NonNull final View view, final int position, final long id) { if (itemClickListener != null) { itemClickListener.onItemClick(this, view, position, id); } }
[ "private", "void", "notifyOnItemClicked", "(", "@", "NonNull", "final", "View", "view", ",", "final", "int", "position", ",", "final", "long", "id", ")", "{", "if", "(", "itemClickListener", "!=", "null", ")", "{", "itemClickListener", ".", "onItemClick", "(", "this", ",", "view", ",", "position", ",", "id", ")", ";", "}", "}" ]
Notifies, the listener, which has been registered to be notified, when any item has been clicked, about an item being clicked. @param view The view within the expandable grid view, which has been clicked, as an instance of the class {@link View}. The view may not be null @param position The position of the item, which has been clicked, as an {@link Integer} value @param id The id of the item, which has been clicked, as a {@link Long} value
[ "Notifies", "the", "listener", "which", "has", "been", "registered", "to", "be", "notified", "when", "any", "item", "has", "been", "clicked", "about", "an", "item", "being", "clicked", "." ]
train
https://github.com/michael-rapp/AndroidUtil/blob/67ec0e5732344eeb4d946dd1f96d782939e449f4/library/src/main/java/de/mrapp/android/util/view/ExpandableGridView.java#L557-L561
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/trees/DecisionStump.java
DecisionStump.distributMissing
static protected <T> void distributMissing(List<ClassificationDataSet> splits, double[] fracs, ClassificationDataSet source, IntList hadMissing) { """ Distributes a list of datapoints that had missing values to each split, re-weighted by the indicated fractions @param <T> @param splits a list of lists, where each inner list is a split @param fracs the fraction of weight to each split, should sum to one @param source @param hadMissing the list of datapoints that had missing values """ for (int i : hadMissing) { DataPoint dp = source.getDataPoint(i); for (int j = 0; j < fracs.length; j++) { double nw = fracs[j] * source.getWeight(i); if (Double.isNaN(nw))//happens when no weight is available continue; if (nw <= 1e-13) continue; splits.get(j).addDataPoint(dp, source.getDataPointCategory(i), nw); } } }
java
static protected <T> void distributMissing(List<ClassificationDataSet> splits, double[] fracs, ClassificationDataSet source, IntList hadMissing) { for (int i : hadMissing) { DataPoint dp = source.getDataPoint(i); for (int j = 0; j < fracs.length; j++) { double nw = fracs[j] * source.getWeight(i); if (Double.isNaN(nw))//happens when no weight is available continue; if (nw <= 1e-13) continue; splits.get(j).addDataPoint(dp, source.getDataPointCategory(i), nw); } } }
[ "static", "protected", "<", "T", ">", "void", "distributMissing", "(", "List", "<", "ClassificationDataSet", ">", "splits", ",", "double", "[", "]", "fracs", ",", "ClassificationDataSet", "source", ",", "IntList", "hadMissing", ")", "{", "for", "(", "int", "i", ":", "hadMissing", ")", "{", "DataPoint", "dp", "=", "source", ".", "getDataPoint", "(", "i", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "fracs", ".", "length", ";", "j", "++", ")", "{", "double", "nw", "=", "fracs", "[", "j", "]", "*", "source", ".", "getWeight", "(", "i", ")", ";", "if", "(", "Double", ".", "isNaN", "(", "nw", ")", ")", "//happens when no weight is available", "continue", ";", "if", "(", "nw", "<=", "1e-13", ")", "continue", ";", "splits", ".", "get", "(", "j", ")", ".", "addDataPoint", "(", "dp", ",", "source", ".", "getDataPointCategory", "(", "i", ")", ",", "nw", ")", ";", "}", "}", "}" ]
Distributes a list of datapoints that had missing values to each split, re-weighted by the indicated fractions @param <T> @param splits a list of lists, where each inner list is a split @param fracs the fraction of weight to each split, should sum to one @param source @param hadMissing the list of datapoints that had missing values
[ "Distributes", "a", "list", "of", "datapoints", "that", "had", "missing", "values", "to", "each", "split", "re", "-", "weighted", "by", "the", "indicated", "fractions" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/trees/DecisionStump.java#L723-L740
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java
TransformerIdentityImpl.startPrefixMapping
public void startPrefixMapping(String prefix, String uri) throws SAXException { """ Receive notification of the start of a Namespace mapping. <p>By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each Namespace prefix scope (such as storing the prefix mapping).</p> @param prefix The Namespace prefix being declared. @param uri The Namespace URI mapped to the prefix. @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception. @see org.xml.sax.ContentHandler#startPrefixMapping @throws SAXException """ flushStartDoc(); m_resultContentHandler.startPrefixMapping(prefix, uri); }
java
public void startPrefixMapping(String prefix, String uri) throws SAXException { flushStartDoc(); m_resultContentHandler.startPrefixMapping(prefix, uri); }
[ "public", "void", "startPrefixMapping", "(", "String", "prefix", ",", "String", "uri", ")", "throws", "SAXException", "{", "flushStartDoc", "(", ")", ";", "m_resultContentHandler", ".", "startPrefixMapping", "(", "prefix", ",", "uri", ")", ";", "}" ]
Receive notification of the start of a Namespace mapping. <p>By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each Namespace prefix scope (such as storing the prefix mapping).</p> @param prefix The Namespace prefix being declared. @param uri The Namespace URI mapped to the prefix. @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception. @see org.xml.sax.ContentHandler#startPrefixMapping @throws SAXException
[ "Receive", "notification", "of", "the", "start", "of", "a", "Namespace", "mapping", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java#L981-L986
apache/incubator-heron
heron/api/src/java/org/apache/heron/api/topology/TopologyBuilder.java
TopologyBuilder.setBolt
@SuppressWarnings("rawtypes") public <K extends Serializable, V extends Serializable> BoltDeclarer setBolt( String id, IStatefulWindowedBolt<K, V> bolt, Number parallelismHint) throws IllegalArgumentException { """ Define a new bolt in this topology. This defines a stateful windowed bolt, intended for stateful windowing operations. The {@link IStatefulWindowedBolt#execute(TupleWindow)} method is triggered for each window interval with the list of current events in the window. During initialization of this bolt (potentially after failure) {@link IStatefulWindowedBolt#initState(State)} is invoked with its previously saved state. @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. @param bolt the stateful windowed bolt @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somwehere around the cluster. @param <K> Type of key for {@link org.apache.heron.api.state.HashMapState} @param <V> Type of value for {@link org.apache.heron.api.state.HashMapState} @return use the returned object to declare the inputs to this component @throws IllegalArgumentException {@code parallelism_hint} is not positive """ return setBolt(id, new StatefulWindowedBoltExecutor<K, V>(bolt), parallelismHint); }
java
@SuppressWarnings("rawtypes") public <K extends Serializable, V extends Serializable> BoltDeclarer setBolt( String id, IStatefulWindowedBolt<K, V> bolt, Number parallelismHint) throws IllegalArgumentException { return setBolt(id, new StatefulWindowedBoltExecutor<K, V>(bolt), parallelismHint); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "<", "K", "extends", "Serializable", ",", "V", "extends", "Serializable", ">", "BoltDeclarer", "setBolt", "(", "String", "id", ",", "IStatefulWindowedBolt", "<", "K", ",", "V", ">", "bolt", ",", "Number", "parallelismHint", ")", "throws", "IllegalArgumentException", "{", "return", "setBolt", "(", "id", ",", "new", "StatefulWindowedBoltExecutor", "<", "K", ",", "V", ">", "(", "bolt", ")", ",", "parallelismHint", ")", ";", "}" ]
Define a new bolt in this topology. This defines a stateful windowed bolt, intended for stateful windowing operations. The {@link IStatefulWindowedBolt#execute(TupleWindow)} method is triggered for each window interval with the list of current events in the window. During initialization of this bolt (potentially after failure) {@link IStatefulWindowedBolt#initState(State)} is invoked with its previously saved state. @param id the id of this component. This id is referenced by other components that want to consume this bolt's outputs. @param bolt the stateful windowed bolt @param parallelismHint the number of tasks that should be assigned to execute this bolt. Each task will run on a thread in a process somwehere around the cluster. @param <K> Type of key for {@link org.apache.heron.api.state.HashMapState} @param <V> Type of value for {@link org.apache.heron.api.state.HashMapState} @return use the returned object to declare the inputs to this component @throws IllegalArgumentException {@code parallelism_hint} is not positive
[ "Define", "a", "new", "bolt", "in", "this", "topology", ".", "This", "defines", "a", "stateful", "windowed", "bolt", "intended", "for", "stateful", "windowing", "operations", ".", "The", "{" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/topology/TopologyBuilder.java#L233-L238
Azure/azure-sdk-for-java
resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/DeploymentsInner.java
DeploymentsInner.createOrUpdateAsync
public Observable<DeploymentExtendedInner> createOrUpdateAsync(String resourceGroupName, String deploymentName, DeploymentProperties properties) { """ Deploys resources to a resource group. You can provide the template and parameters directly in the request or link to JSON files. @param resourceGroupName The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. @param deploymentName The name of the deployment. @param properties The deployment properties. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, deploymentName, properties).map(new Func1<ServiceResponse<DeploymentExtendedInner>, DeploymentExtendedInner>() { @Override public DeploymentExtendedInner call(ServiceResponse<DeploymentExtendedInner> response) { return response.body(); } }); }
java
public Observable<DeploymentExtendedInner> createOrUpdateAsync(String resourceGroupName, String deploymentName, DeploymentProperties properties) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, deploymentName, properties).map(new Func1<ServiceResponse<DeploymentExtendedInner>, DeploymentExtendedInner>() { @Override public DeploymentExtendedInner call(ServiceResponse<DeploymentExtendedInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DeploymentExtendedInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "deploymentName", ",", "DeploymentProperties", "properties", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "deploymentName", ",", "properties", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DeploymentExtendedInner", ">", ",", "DeploymentExtendedInner", ">", "(", ")", "{", "@", "Override", "public", "DeploymentExtendedInner", "call", "(", "ServiceResponse", "<", "DeploymentExtendedInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Deploys resources to a resource group. You can provide the template and parameters directly in the request or link to JSON files. @param resourceGroupName The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. @param deploymentName The name of the deployment. @param properties The deployment properties. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Deploys", "resources", "to", "a", "resource", "group", ".", "You", "can", "provide", "the", "template", "and", "parameters", "directly", "in", "the", "request", "or", "link", "to", "JSON", "files", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/DeploymentsInner.java#L405-L412
pwittchen/prefser
library/src/main/java/com/github/pwittchen/prefser/library/rx2/Prefser.java
Prefser.getAndObserve
public <T> Observable<T> getAndObserve(final String key, final TypeToken<T> typeTokenOfT, final T defaultValue) { """ Gets value from SharedPreferences with a given key and type token as a RxJava Observable, which can be subscribed If value is not found, we can return defaultValue. Emit preference as first element of the stream even if preferences wasn't changed. @param key key of the preference @param typeTokenOfT type token of T (e.g. {@code new TypeToken<List<String>> {}) @param defaultValue default value of the preference (e.g. "" or "undefined") @param <T> return type of the preference (e.g. String) @return Observable value from SharedPreferences associated with given key or default value """ return observe(key, typeTokenOfT, defaultValue) // start observing .mergeWith( Observable.defer(new Callable<ObservableSource<? extends T>>() { // then start getting @Override public ObservableSource<? extends T> call() throws Exception { return Observable.just(get(key, typeTokenOfT, defaultValue)); } })); }
java
public <T> Observable<T> getAndObserve(final String key, final TypeToken<T> typeTokenOfT, final T defaultValue) { return observe(key, typeTokenOfT, defaultValue) // start observing .mergeWith( Observable.defer(new Callable<ObservableSource<? extends T>>() { // then start getting @Override public ObservableSource<? extends T> call() throws Exception { return Observable.just(get(key, typeTokenOfT, defaultValue)); } })); }
[ "public", "<", "T", ">", "Observable", "<", "T", ">", "getAndObserve", "(", "final", "String", "key", ",", "final", "TypeToken", "<", "T", ">", "typeTokenOfT", ",", "final", "T", "defaultValue", ")", "{", "return", "observe", "(", "key", ",", "typeTokenOfT", ",", "defaultValue", ")", "// start observing", ".", "mergeWith", "(", "Observable", ".", "defer", "(", "new", "Callable", "<", "ObservableSource", "<", "?", "extends", "T", ">", ">", "(", ")", "{", "// then start getting", "@", "Override", "public", "ObservableSource", "<", "?", "extends", "T", ">", "call", "(", ")", "throws", "Exception", "{", "return", "Observable", ".", "just", "(", "get", "(", "key", ",", "typeTokenOfT", ",", "defaultValue", ")", ")", ";", "}", "}", ")", ")", ";", "}" ]
Gets value from SharedPreferences with a given key and type token as a RxJava Observable, which can be subscribed If value is not found, we can return defaultValue. Emit preference as first element of the stream even if preferences wasn't changed. @param key key of the preference @param typeTokenOfT type token of T (e.g. {@code new TypeToken<List<String>> {}) @param defaultValue default value of the preference (e.g. "" or "undefined") @param <T> return type of the preference (e.g. String) @return Observable value from SharedPreferences associated with given key or default value
[ "Gets", "value", "from", "SharedPreferences", "with", "a", "given", "key", "and", "type", "token", "as", "a", "RxJava", "Observable", "which", "can", "be", "subscribed", "If", "value", "is", "not", "found", "we", "can", "return", "defaultValue", ".", "Emit", "preference", "as", "first", "element", "of", "the", "stream", "even", "if", "preferences", "wasn", "t", "changed", "." ]
train
https://github.com/pwittchen/prefser/blob/7dc7f980eeb71fd5617f8c749050c2400e4fbb2f/library/src/main/java/com/github/pwittchen/prefser/library/rx2/Prefser.java#L163-L172
sarl/sarl
main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java
SARLQuickfixProvider.fixIncompatibleReturnType
@Fix(org.eclipse.xtext.xbase.validation.IssueCodes.INCOMPATIBLE_RETURN_TYPE) public void fixIncompatibleReturnType(final Issue issue, IssueResolutionAcceptor acceptor) { """ Quick fix for "Incompatible return type". @param issue the issue. @param acceptor the quick fix acceptor. """ ReturnTypeReplaceModification.accept(this, issue, acceptor); }
java
@Fix(org.eclipse.xtext.xbase.validation.IssueCodes.INCOMPATIBLE_RETURN_TYPE) public void fixIncompatibleReturnType(final Issue issue, IssueResolutionAcceptor acceptor) { ReturnTypeReplaceModification.accept(this, issue, acceptor); }
[ "@", "Fix", "(", "org", ".", "eclipse", ".", "xtext", ".", "xbase", ".", "validation", ".", "IssueCodes", ".", "INCOMPATIBLE_RETURN_TYPE", ")", "public", "void", "fixIncompatibleReturnType", "(", "final", "Issue", "issue", ",", "IssueResolutionAcceptor", "acceptor", ")", "{", "ReturnTypeReplaceModification", ".", "accept", "(", "this", ",", "issue", ",", "acceptor", ")", ";", "}" ]
Quick fix for "Incompatible return type". @param issue the issue. @param acceptor the quick fix acceptor.
[ "Quick", "fix", "for", "Incompatible", "return", "type", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L866-L869
gliga/ekstazi
org.ekstazi.core/src/main/java/org/ekstazi/Ekstazi.java
Ekstazi.endClassCoverage
public void endClassCoverage(String className, boolean isFailOrError) { """ Saves info about the results of running the given test class. """ File testResultsDir = new File(Config.ROOT_DIR_V, Names.TEST_RESULTS_DIR_NAME); File outcomeFile = new File(testResultsDir, className); if (isFailOrError) { // TODO: long names. testResultsDir.mkdirs(); try { outcomeFile.createNewFile(); } catch (IOException e) { Log.e("Unable to create file for a failing test: " + className, e); } } else { outcomeFile.delete(); } endClassCoverage(className); }
java
public void endClassCoverage(String className, boolean isFailOrError) { File testResultsDir = new File(Config.ROOT_DIR_V, Names.TEST_RESULTS_DIR_NAME); File outcomeFile = new File(testResultsDir, className); if (isFailOrError) { // TODO: long names. testResultsDir.mkdirs(); try { outcomeFile.createNewFile(); } catch (IOException e) { Log.e("Unable to create file for a failing test: " + className, e); } } else { outcomeFile.delete(); } endClassCoverage(className); }
[ "public", "void", "endClassCoverage", "(", "String", "className", ",", "boolean", "isFailOrError", ")", "{", "File", "testResultsDir", "=", "new", "File", "(", "Config", ".", "ROOT_DIR_V", ",", "Names", ".", "TEST_RESULTS_DIR_NAME", ")", ";", "File", "outcomeFile", "=", "new", "File", "(", "testResultsDir", ",", "className", ")", ";", "if", "(", "isFailOrError", ")", "{", "// TODO: long names.", "testResultsDir", ".", "mkdirs", "(", ")", ";", "try", "{", "outcomeFile", ".", "createNewFile", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Log", ".", "e", "(", "\"Unable to create file for a failing test: \"", "+", "className", ",", "e", ")", ";", "}", "}", "else", "{", "outcomeFile", ".", "delete", "(", ")", ";", "}", "endClassCoverage", "(", "className", ")", ";", "}" ]
Saves info about the results of running the given test class.
[ "Saves", "info", "about", "the", "results", "of", "running", "the", "given", "test", "class", "." ]
train
https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/Ekstazi.java#L144-L159
Sciss/abc4j
abc/src/main/java/abc/xml/Abc2xml.java
Abc2xml.writeAsMusicXML
public void writeAsMusicXML(Document doc, BufferedWriter writer) throws IOException { """ Writes the specified Node to the given writer. @param node A DOM node. @param writer A stream writer. @throws IOException Thrown if the file cannot be created. """ /* * writer.write("<"+node.getNodeName()); NamedNodeMap attr = * node.getAttributes(); if (attr!=null) for (int i=0; * i<attr.getLength(); i++) writer.write(" " + * attr.item(i).getNodeName() + "=" + attr.item(i).getNodeValue()); * writer.write(">"); writer.newLine(); NodeList nlist = * node.getChildNodes(); for (int i=0; i<nlist.getLength(); i++) * writeAsMusicXML(writer, nlist.item(i)); * writer.write("</"+node.getNodeName()+">"); writer.newLine(); */ try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); // trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Recordare//DTD MusicXML 2.0 Partwise//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.musicxml.org/dtds/partwise.dtd"); // create string from xml tree // StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(doc); trans.transform(source, result); } catch (Exception e) { e.printStackTrace(); } // String xmlString = sw.toString(); // } }
java
public void writeAsMusicXML(Document doc, BufferedWriter writer) throws IOException { /* * writer.write("<"+node.getNodeName()); NamedNodeMap attr = * node.getAttributes(); if (attr!=null) for (int i=0; * i<attr.getLength(); i++) writer.write(" " + * attr.item(i).getNodeName() + "=" + attr.item(i).getNodeValue()); * writer.write(">"); writer.newLine(); NodeList nlist = * node.getChildNodes(); for (int i=0; i<nlist.getLength(); i++) * writeAsMusicXML(writer, nlist.item(i)); * writer.write("</"+node.getNodeName()+">"); writer.newLine(); */ try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); // trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//Recordare//DTD MusicXML 2.0 Partwise//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.musicxml.org/dtds/partwise.dtd"); // create string from xml tree // StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(doc); trans.transform(source, result); } catch (Exception e) { e.printStackTrace(); } // String xmlString = sw.toString(); // } }
[ "public", "void", "writeAsMusicXML", "(", "Document", "doc", ",", "BufferedWriter", "writer", ")", "throws", "IOException", "{", "/*\r\n\t\t * writer.write(\"<\"+node.getNodeName()); NamedNodeMap attr =\r\n\t\t * node.getAttributes(); if (attr!=null) for (int i=0;\r\n\t\t * i<attr.getLength(); i++) writer.write(\" \" +\r\n\t\t * attr.item(i).getNodeName() + \"=\" + attr.item(i).getNodeValue());\r\n\t\t * writer.write(\">\"); writer.newLine(); NodeList nlist =\r\n\t\t * node.getChildNodes(); for (int i=0; i<nlist.getLength(); i++)\r\n\t\t * writeAsMusicXML(writer, nlist.item(i));\r\n\t\t * writer.write(\"</\"+node.getNodeName()+\">\"); writer.newLine();\r\n\t\t */", "try", "{", "TransformerFactory", "transfac", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "trans", "=", "transfac", ".", "newTransformer", "(", ")", ";", "// trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"yes\");\r", "trans", ".", "setOutputProperty", "(", "OutputKeys", ".", "INDENT", ",", "\"yes\"", ")", ";", "trans", ".", "setOutputProperty", "(", "OutputKeys", ".", "DOCTYPE_PUBLIC", ",", "\"-//Recordare//DTD MusicXML 2.0 Partwise//EN\"", ")", ";", "trans", ".", "setOutputProperty", "(", "OutputKeys", ".", "DOCTYPE_SYSTEM", ",", "\"http://www.musicxml.org/dtds/partwise.dtd\"", ")", ";", "// create string from xml tree\r", "// StringWriter sw = new StringWriter();\r", "StreamResult", "result", "=", "new", "StreamResult", "(", "writer", ")", ";", "DOMSource", "source", "=", "new", "DOMSource", "(", "doc", ")", ";", "trans", ".", "transform", "(", "source", ",", "result", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "// String xmlString = sw.toString();\r", "// }\r", "}" ]
Writes the specified Node to the given writer. @param node A DOM node. @param writer A stream writer. @throws IOException Thrown if the file cannot be created.
[ "Writes", "the", "specified", "Node", "to", "the", "given", "writer", "." ]
train
https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/xml/Abc2xml.java#L194-L224
openxc/openxc-android
library/src/main/java/com/openxc/sources/trace/TraceVehicleDataSource.java
TraceVehicleDataSource.waitForNextRecord
private void waitForNextRecord(long startingTime, long timestamp) { """ Using the startingTime as the relative starting point, sleep this thread until the next timestamp would occur. @param startingTime the relative starting time in milliseconds @param timestamp the timestamp to wait for in milliseconds since the epoch """ if(mFirstTimestamp == 0) { mFirstTimestamp = timestamp; Log.d(TAG, "Storing " + timestamp + " as the first " + "timestamp of the trace file"); } long targetTime = startingTime + (timestamp - mFirstTimestamp); long sleepDuration = Math.max(targetTime - System.currentTimeMillis(), 0); try { Thread.sleep(sleepDuration); } catch(InterruptedException e) {} }
java
private void waitForNextRecord(long startingTime, long timestamp) { if(mFirstTimestamp == 0) { mFirstTimestamp = timestamp; Log.d(TAG, "Storing " + timestamp + " as the first " + "timestamp of the trace file"); } long targetTime = startingTime + (timestamp - mFirstTimestamp); long sleepDuration = Math.max(targetTime - System.currentTimeMillis(), 0); try { Thread.sleep(sleepDuration); } catch(InterruptedException e) {} }
[ "private", "void", "waitForNextRecord", "(", "long", "startingTime", ",", "long", "timestamp", ")", "{", "if", "(", "mFirstTimestamp", "==", "0", ")", "{", "mFirstTimestamp", "=", "timestamp", ";", "Log", ".", "d", "(", "TAG", ",", "\"Storing \"", "+", "timestamp", "+", "\" as the first \"", "+", "\"timestamp of the trace file\"", ")", ";", "}", "long", "targetTime", "=", "startingTime", "+", "(", "timestamp", "-", "mFirstTimestamp", ")", ";", "long", "sleepDuration", "=", "Math", ".", "max", "(", "targetTime", "-", "System", ".", "currentTimeMillis", "(", ")", ",", "0", ")", ";", "try", "{", "Thread", ".", "sleep", "(", "sleepDuration", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "}", "}" ]
Using the startingTime as the relative starting point, sleep this thread until the next timestamp would occur. @param startingTime the relative starting time in milliseconds @param timestamp the timestamp to wait for in milliseconds since the epoch
[ "Using", "the", "startingTime", "as", "the", "relative", "starting", "point", "sleep", "this", "thread", "until", "the", "next", "timestamp", "would", "occur", "." ]
train
https://github.com/openxc/openxc-android/blob/799adbdcd107a72fe89737bbf19c039dc2881665/library/src/main/java/com/openxc/sources/trace/TraceVehicleDataSource.java#L297-L308
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsProgressWidget.java
CmsProgressWidget.createError
private String createError(String errorMsg, Throwable t) { """ Creates the html code for the given error message and the provided Exception.<p> @param errorMsg the error message to place in the html code @param t the exception to add to the error message @return the html code for the error message """ StringBuffer msg = new StringBuffer(); msg.append(errorMsg); msg.append("\n"); msg.append(t.getMessage()); msg.append("\n"); msg.append(CmsException.getStackTraceAsString(t)); return createError(msg.toString()); }
java
private String createError(String errorMsg, Throwable t) { StringBuffer msg = new StringBuffer(); msg.append(errorMsg); msg.append("\n"); msg.append(t.getMessage()); msg.append("\n"); msg.append(CmsException.getStackTraceAsString(t)); return createError(msg.toString()); }
[ "private", "String", "createError", "(", "String", "errorMsg", ",", "Throwable", "t", ")", "{", "StringBuffer", "msg", "=", "new", "StringBuffer", "(", ")", ";", "msg", ".", "append", "(", "errorMsg", ")", ";", "msg", ".", "append", "(", "\"\\n\"", ")", ";", "msg", ".", "append", "(", "t", ".", "getMessage", "(", ")", ")", ";", "msg", ".", "append", "(", "\"\\n\"", ")", ";", "msg", ".", "append", "(", "CmsException", ".", "getStackTraceAsString", "(", "t", ")", ")", ";", "return", "createError", "(", "msg", ".", "toString", "(", ")", ")", ";", "}" ]
Creates the html code for the given error message and the provided Exception.<p> @param errorMsg the error message to place in the html code @param t the exception to add to the error message @return the html code for the error message
[ "Creates", "the", "html", "code", "for", "the", "given", "error", "message", "and", "the", "provided", "Exception", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsProgressWidget.java#L745-L755
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/abst/distort/FDistort.java
FDistort.init
public FDistort init(ImageBase input, ImageBase output) { """ Specifies the input and output image and sets interpolation to BILINEAR, black image border, cache is off. """ this.input = input; this.output = output; inputType = input.getImageType(); interp(InterpolationType.BILINEAR); border(0); cached = false; distorter = null; outputToInput = null; return this; }
java
public FDistort init(ImageBase input, ImageBase output) { this.input = input; this.output = output; inputType = input.getImageType(); interp(InterpolationType.BILINEAR); border(0); cached = false; distorter = null; outputToInput = null; return this; }
[ "public", "FDistort", "init", "(", "ImageBase", "input", ",", "ImageBase", "output", ")", "{", "this", ".", "input", "=", "input", ";", "this", ".", "output", "=", "output", ";", "inputType", "=", "input", ".", "getImageType", "(", ")", ";", "interp", "(", "InterpolationType", ".", "BILINEAR", ")", ";", "border", "(", "0", ")", ";", "cached", "=", "false", ";", "distorter", "=", "null", ";", "outputToInput", "=", "null", ";", "return", "this", ";", "}" ]
Specifies the input and output image and sets interpolation to BILINEAR, black image border, cache is off.
[ "Specifies", "the", "input", "and", "output", "image", "and", "sets", "interpolation", "to", "BILINEAR", "black", "image", "border", "cache", "is", "off", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/abst/distort/FDistort.java#L97-L110
alkacon/opencms-core
src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java
CmsDefaultXmlContentHandler.initHeadIncludes
protected void initHeadIncludes(Element root, CmsXmlContentDefinition contentDefinition) { """ Initializes the head includes for this content handler.<p> @param root the "headincludes" element from the appinfo node of the XML content definition @param contentDefinition the content definition the head-includes belong to """ Iterator<Element> itInclude = CmsXmlGenericWrapper.elementIterator(root, APPINFO_HEAD_INCLUDE); while (itInclude.hasNext()) { Element element = itInclude.next(); String type = element.attributeValue(APPINFO_ATTR_TYPE); String uri = element.attributeValue(APPINFO_ATTR_URI); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(uri)) { if (ATTRIBUTE_INCLUDE_TYPE_CSS.equals(type)) { m_cssHeadIncludes.add(uri); } else if (ATTRIBUTE_INCLUDE_TYPE_JAVASCRIPT.equals(type)) { m_jsHeadIncludes.add(uri); } } } }
java
protected void initHeadIncludes(Element root, CmsXmlContentDefinition contentDefinition) { Iterator<Element> itInclude = CmsXmlGenericWrapper.elementIterator(root, APPINFO_HEAD_INCLUDE); while (itInclude.hasNext()) { Element element = itInclude.next(); String type = element.attributeValue(APPINFO_ATTR_TYPE); String uri = element.attributeValue(APPINFO_ATTR_URI); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(uri)) { if (ATTRIBUTE_INCLUDE_TYPE_CSS.equals(type)) { m_cssHeadIncludes.add(uri); } else if (ATTRIBUTE_INCLUDE_TYPE_JAVASCRIPT.equals(type)) { m_jsHeadIncludes.add(uri); } } } }
[ "protected", "void", "initHeadIncludes", "(", "Element", "root", ",", "CmsXmlContentDefinition", "contentDefinition", ")", "{", "Iterator", "<", "Element", ">", "itInclude", "=", "CmsXmlGenericWrapper", ".", "elementIterator", "(", "root", ",", "APPINFO_HEAD_INCLUDE", ")", ";", "while", "(", "itInclude", ".", "hasNext", "(", ")", ")", "{", "Element", "element", "=", "itInclude", ".", "next", "(", ")", ";", "String", "type", "=", "element", ".", "attributeValue", "(", "APPINFO_ATTR_TYPE", ")", ";", "String", "uri", "=", "element", ".", "attributeValue", "(", "APPINFO_ATTR_URI", ")", ";", "if", "(", "CmsStringUtil", ".", "isNotEmptyOrWhitespaceOnly", "(", "uri", ")", ")", "{", "if", "(", "ATTRIBUTE_INCLUDE_TYPE_CSS", ".", "equals", "(", "type", ")", ")", "{", "m_cssHeadIncludes", ".", "add", "(", "uri", ")", ";", "}", "else", "if", "(", "ATTRIBUTE_INCLUDE_TYPE_JAVASCRIPT", ".", "equals", "(", "type", ")", ")", "{", "m_jsHeadIncludes", ".", "add", "(", "uri", ")", ";", "}", "}", "}", "}" ]
Initializes the head includes for this content handler.<p> @param root the "headincludes" element from the appinfo node of the XML content definition @param contentDefinition the content definition the head-includes belong to
[ "Initializes", "the", "head", "includes", "for", "this", "content", "handler", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2660-L2675
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseSnnz
public static int cusparseSnnz( cusparseHandle handle, int dirA, int m, int n, cusparseMatDescr descrA, Pointer A, int lda, Pointer nnzPerRowCol, Pointer nnzTotalDevHostPtr) { """ Description: This routine finds the total number of non-zero elements and the number of non-zero elements per row or column in the dense matrix A. """ return checkResult(cusparseSnnzNative(handle, dirA, m, n, descrA, A, lda, nnzPerRowCol, nnzTotalDevHostPtr)); }
java
public static int cusparseSnnz( cusparseHandle handle, int dirA, int m, int n, cusparseMatDescr descrA, Pointer A, int lda, Pointer nnzPerRowCol, Pointer nnzTotalDevHostPtr) { return checkResult(cusparseSnnzNative(handle, dirA, m, n, descrA, A, lda, nnzPerRowCol, nnzTotalDevHostPtr)); }
[ "public", "static", "int", "cusparseSnnz", "(", "cusparseHandle", "handle", ",", "int", "dirA", ",", "int", "m", ",", "int", "n", ",", "cusparseMatDescr", "descrA", ",", "Pointer", "A", ",", "int", "lda", ",", "Pointer", "nnzPerRowCol", ",", "Pointer", "nnzTotalDevHostPtr", ")", "{", "return", "checkResult", "(", "cusparseSnnzNative", "(", "handle", ",", "dirA", ",", "m", ",", "n", ",", "descrA", ",", "A", ",", "lda", ",", "nnzPerRowCol", ",", "nnzTotalDevHostPtr", ")", ")", ";", "}" ]
Description: This routine finds the total number of non-zero elements and the number of non-zero elements per row or column in the dense matrix A.
[ "Description", ":", "This", "routine", "finds", "the", "total", "number", "of", "non", "-", "zero", "elements", "and", "the", "number", "of", "non", "-", "zero", "elements", "per", "row", "or", "column", "in", "the", "dense", "matrix", "A", "." ]
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L10843-L10855
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/MethodUtils.java
MethodUtils.invokeSetter
public static void invokeSetter(Object object, String setterName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { """ Sets the value of a bean property to an Object. @param object the bean to change @param setterName the property name or setter method name @param arg use this argument @throws NoSuchMethodException the no such method exception @throws IllegalAccessException the illegal access exception @throws InvocationTargetException the invocation target exception """ Object[] args = { arg }; invokeSetter(object, setterName, args); }
java
public static void invokeSetter(Object object, String setterName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Object[] args = { arg }; invokeSetter(object, setterName, args); }
[ "public", "static", "void", "invokeSetter", "(", "Object", "object", ",", "String", "setterName", ",", "Object", "arg", ")", "throws", "NoSuchMethodException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "Object", "[", "]", "args", "=", "{", "arg", "}", ";", "invokeSetter", "(", "object", ",", "setterName", ",", "args", ")", ";", "}" ]
Sets the value of a bean property to an Object. @param object the bean to change @param setterName the property name or setter method name @param arg use this argument @throws NoSuchMethodException the no such method exception @throws IllegalAccessException the illegal access exception @throws InvocationTargetException the invocation target exception
[ "Sets", "the", "value", "of", "a", "bean", "property", "to", "an", "Object", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/MethodUtils.java#L53-L57
duracloud/duracloud
snapshotstorageprovider/src/main/java/org/duracloud/snapshottask/snapshot/AbstractSnapshotTaskRunner.java
AbstractSnapshotTaskRunner.getValueFromJson
protected <T> T getValueFromJson(String json, String propName) throws IOException { """ A helper method that takes a json string and extracts the value of the specified property. @param json the json string @param propName the name of the property to extract @param <T> The type for the value expected to be returned. @return the value of the specified property @throws IOException """ return (T) jsonStringToMap(json).get(propName); }
java
protected <T> T getValueFromJson(String json, String propName) throws IOException { return (T) jsonStringToMap(json).get(propName); }
[ "protected", "<", "T", ">", "T", "getValueFromJson", "(", "String", "json", ",", "String", "propName", ")", "throws", "IOException", "{", "return", "(", "T", ")", "jsonStringToMap", "(", "json", ")", ".", "get", "(", "propName", ")", ";", "}" ]
A helper method that takes a json string and extracts the value of the specified property. @param json the json string @param propName the name of the property to extract @param <T> The type for the value expected to be returned. @return the value of the specified property @throws IOException
[ "A", "helper", "method", "that", "takes", "a", "json", "string", "and", "extracts", "the", "value", "of", "the", "specified", "property", "." ]
train
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/snapshotstorageprovider/src/main/java/org/duracloud/snapshottask/snapshot/AbstractSnapshotTaskRunner.java#L79-L81
powermock/powermock
powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java
PowerMock.createNiceMock
public static <T> T createNiceMock(Class<T> type, Object... constructorArguments) { """ Creates a nice mock object that supports mocking of final and native methods and invokes a specific constructor based on the supplied argument values. @param <T> the type of the mock object @param type the type of the mock object @param constructorArguments The constructor arguments that will be used to invoke a certain constructor. @return the mock object. """ Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new NiceMockStrategy(), constructorArgs, (Method[]) null); }
java
public static <T> T createNiceMock(Class<T> type, Object... constructorArguments) { Constructor<?> constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new NiceMockStrategy(), constructorArgs, (Method[]) null); }
[ "public", "static", "<", "T", ">", "T", "createNiceMock", "(", "Class", "<", "T", ">", "type", ",", "Object", "...", "constructorArguments", ")", "{", "Constructor", "<", "?", ">", "constructor", "=", "WhiteboxImpl", ".", "findUniqueConstructorOrThrowException", "(", "type", ",", "constructorArguments", ")", ";", "ConstructorArgs", "constructorArgs", "=", "new", "ConstructorArgs", "(", "constructor", ",", "constructorArguments", ")", ";", "return", "doMock", "(", "type", ",", "false", ",", "new", "NiceMockStrategy", "(", ")", ",", "constructorArgs", ",", "(", "Method", "[", "]", ")", "null", ")", ";", "}" ]
Creates a nice mock object that supports mocking of final and native methods and invokes a specific constructor based on the supplied argument values. @param <T> the type of the mock object @param type the type of the mock object @param constructorArguments The constructor arguments that will be used to invoke a certain constructor. @return the mock object.
[ "Creates", "a", "nice", "mock", "object", "that", "supports", "mocking", "of", "final", "and", "native", "methods", "and", "invokes", "a", "specific", "constructor", "based", "on", "the", "supplied", "argument", "values", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java#L237-L241
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java
Bean.programWithFirmware
public OADProfile.OADApproval programWithFirmware(FirmwareBundle bundle, OADProfile.OADListener listener) { """ Programs the Bean with new firmware images. @param bundle The firmware package holding A and B images to be sent to the Bean @param listener OADListener to alert the client of OAD state """ return gattClient.getOADProfile().programWithFirmware(bundle, listener); }
java
public OADProfile.OADApproval programWithFirmware(FirmwareBundle bundle, OADProfile.OADListener listener) { return gattClient.getOADProfile().programWithFirmware(bundle, listener); }
[ "public", "OADProfile", ".", "OADApproval", "programWithFirmware", "(", "FirmwareBundle", "bundle", ",", "OADProfile", ".", "OADListener", "listener", ")", "{", "return", "gattClient", ".", "getOADProfile", "(", ")", ".", "programWithFirmware", "(", "bundle", ",", "listener", ")", ";", "}" ]
Programs the Bean with new firmware images. @param bundle The firmware package holding A and B images to be sent to the Bean @param listener OADListener to alert the client of OAD state
[ "Programs", "the", "Bean", "with", "new", "firmware", "images", "." ]
train
https://github.com/PunchThrough/bean-sdk-android/blob/dc33e8cc9258d6e028e0788d74735c75b54d1133/sdk/src/main/java/com/punchthrough/bean/sdk/Bean.java#L1141-L1143
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java
ServiceDiscoveryManager.accountSupportsFeatures
public boolean accountSupportsFeatures(Collection<? extends CharSequence> features) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { """ Check if the given collection of features are supported by the connection account. This means that the discovery information lookup will be performed on the bare JID of the connection managed by this ServiceDiscoveryManager. @param features a collection of features @return <code>true</code> if all features are supported by the connection account, <code>false</code> otherwise @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException @since 4.2.2 """ EntityBareJid accountJid = connection().getUser().asEntityBareJid(); return supportsFeatures(accountJid, features); }
java
public boolean accountSupportsFeatures(Collection<? extends CharSequence> features) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { EntityBareJid accountJid = connection().getUser().asEntityBareJid(); return supportsFeatures(accountJid, features); }
[ "public", "boolean", "accountSupportsFeatures", "(", "Collection", "<", "?", "extends", "CharSequence", ">", "features", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "EntityBareJid", "accountJid", "=", "connection", "(", ")", ".", "getUser", "(", ")", ".", "asEntityBareJid", "(", ")", ";", "return", "supportsFeatures", "(", "accountJid", ",", "features", ")", ";", "}" ]
Check if the given collection of features are supported by the connection account. This means that the discovery information lookup will be performed on the bare JID of the connection managed by this ServiceDiscoveryManager. @param features a collection of features @return <code>true</code> if all features are supported by the connection account, <code>false</code> otherwise @throws NoResponseException @throws XMPPErrorException @throws NotConnectedException @throws InterruptedException @since 4.2.2
[ "Check", "if", "the", "given", "collection", "of", "features", "are", "supported", "by", "the", "connection", "account", ".", "This", "means", "that", "the", "discovery", "information", "lookup", "will", "be", "performed", "on", "the", "bare", "JID", "of", "the", "connection", "managed", "by", "this", "ServiceDiscoveryManager", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java#L630-L634
arakelian/more-commons
src/main/java/com/arakelian/core/utils/XmlStreamReaderUtils.java
XmlStreamReaderUtils.requiredLongAttribute
public static long requiredLongAttribute(final XMLStreamReader reader, final String localName) throws XMLStreamException { """ Returns the value of an attribute as a long. If the attribute is empty, this method throws an exception. @param reader <code>XMLStreamReader</code> that contains attribute values. @param localName local name of attribute (the namespace is ignored). @return value of attribute as long @throws XMLStreamException if attribute is empty. """ return requiredLongAttribute(reader, null, localName); }
java
public static long requiredLongAttribute(final XMLStreamReader reader, final String localName) throws XMLStreamException { return requiredLongAttribute(reader, null, localName); }
[ "public", "static", "long", "requiredLongAttribute", "(", "final", "XMLStreamReader", "reader", ",", "final", "String", "localName", ")", "throws", "XMLStreamException", "{", "return", "requiredLongAttribute", "(", "reader", ",", "null", ",", "localName", ")", ";", "}" ]
Returns the value of an attribute as a long. If the attribute is empty, this method throws an exception. @param reader <code>XMLStreamReader</code> that contains attribute values. @param localName local name of attribute (the namespace is ignored). @return value of attribute as long @throws XMLStreamException if attribute is empty.
[ "Returns", "the", "value", "of", "an", "attribute", "as", "a", "long", ".", "If", "the", "attribute", "is", "empty", "this", "method", "throws", "an", "exception", "." ]
train
https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/XmlStreamReaderUtils.java#L1260-L1263
aws/aws-cloudtrail-processing-library
src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/utils/SourceIdentifier.java
SourceIdentifier.identifyWithEventName
public SourceType identifyWithEventName(String source, String eventName) { """ Identify the source type with event action. @param source the S3 object name @param eventName the event name defined by Amazon S3. @return {@link SourceType} """ if (eventName.startsWith(CREATE_EVENT_PREFIX)) { return getCloudTrailSourceType(source); } return SourceType.Other; }
java
public SourceType identifyWithEventName(String source, String eventName) { if (eventName.startsWith(CREATE_EVENT_PREFIX)) { return getCloudTrailSourceType(source); } return SourceType.Other; }
[ "public", "SourceType", "identifyWithEventName", "(", "String", "source", ",", "String", "eventName", ")", "{", "if", "(", "eventName", ".", "startsWith", "(", "CREATE_EVENT_PREFIX", ")", ")", "{", "return", "getCloudTrailSourceType", "(", "source", ")", ";", "}", "return", "SourceType", ".", "Other", ";", "}" ]
Identify the source type with event action. @param source the S3 object name @param eventName the event name defined by Amazon S3. @return {@link SourceType}
[ "Identify", "the", "source", "type", "with", "event", "action", "." ]
train
https://github.com/aws/aws-cloudtrail-processing-library/blob/411315808d8d3dc6b45e4182212e3e04d82e3782/src/main/java/com/amazonaws/services/cloudtrail/processinglibrary/utils/SourceIdentifier.java#L38-L43
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/AnimatedDialog.java
AnimatedDialog.slideClose
private void slideClose() { """ </p> Closes the dialog with a translation animation to the content view </p> """ if (!isClosing_) { isClosing_ = true; TranslateAnimation slideDown = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1f); slideDown.setDuration(500); slideDown.setInterpolator(new DecelerateInterpolator()); ((ViewGroup) getWindow().getDecorView()).getChildAt(0).startAnimation(slideDown); slideDown.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { dismiss(); } @Override public void onAnimationRepeat(Animation animation) { } }); } }
java
private void slideClose() { if (!isClosing_) { isClosing_ = true; TranslateAnimation slideDown = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1f); slideDown.setDuration(500); slideDown.setInterpolator(new DecelerateInterpolator()); ((ViewGroup) getWindow().getDecorView()).getChildAt(0).startAnimation(slideDown); slideDown.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { dismiss(); } @Override public void onAnimationRepeat(Animation animation) { } }); } }
[ "private", "void", "slideClose", "(", ")", "{", "if", "(", "!", "isClosing_", ")", "{", "isClosing_", "=", "true", ";", "TranslateAnimation", "slideDown", "=", "new", "TranslateAnimation", "(", "Animation", ".", "RELATIVE_TO_SELF", ",", "0", ",", "Animation", ".", "RELATIVE_TO_SELF", ",", "0", ",", "Animation", ".", "RELATIVE_TO_SELF", ",", "0.0f", ",", "Animation", ".", "RELATIVE_TO_SELF", ",", "1f", ")", ";", "slideDown", ".", "setDuration", "(", "500", ")", ";", "slideDown", ".", "setInterpolator", "(", "new", "DecelerateInterpolator", "(", ")", ")", ";", "(", "(", "ViewGroup", ")", "getWindow", "(", ")", ".", "getDecorView", "(", ")", ")", ".", "getChildAt", "(", "0", ")", ".", "startAnimation", "(", "slideDown", ")", ";", "slideDown", ".", "setAnimationListener", "(", "new", "Animation", ".", "AnimationListener", "(", ")", "{", "@", "Override", "public", "void", "onAnimationStart", "(", "Animation", "animation", ")", "{", "}", "@", "Override", "public", "void", "onAnimationEnd", "(", "Animation", "animation", ")", "{", "dismiss", "(", ")", ";", "}", "@", "Override", "public", "void", "onAnimationRepeat", "(", "Animation", "animation", ")", "{", "}", "}", ")", ";", "}", "}" ]
</p> Closes the dialog with a translation animation to the content view </p>
[ "<", "/", "p", ">", "Closes", "the", "dialog", "with", "a", "translation", "animation", "to", "the", "content", "view", "<", "/", "p", ">" ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/AnimatedDialog.java#L122-L145
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/provisioning/ImportApi.java
ImportApi.validateFile
public void validateFile(String fileName, String fileContents) throws ProvisioningApiException { """ Validate the import file. Performs pre-validation on the specified CSV/XLS file. @param fileName The name of the CSV/XLS file to validate. @param fileContents The contents of the CSV/XLS file to validate. @throws ProvisioningApiException if the call is unsuccessful. """ RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addPart( Headers.of("Content-Disposition", "form-data; name=\"csvfile\"; filename=\""+fileName+"\""), RequestBody.create(MediaType.parse("text/csv"), fileContents)) .build(); Request request = new Request.Builder() .url(this.client.getBasePath()+"/import-users/validate-csv") .post(requestBody) .build(); try { Response response = this.client.getHttpClient().newCall(request).execute(); } catch(IOException e) { throw new ProvisioningApiException("Error validating file", e); } }
java
public void validateFile(String fileName, String fileContents) throws ProvisioningApiException { RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addPart( Headers.of("Content-Disposition", "form-data; name=\"csvfile\"; filename=\""+fileName+"\""), RequestBody.create(MediaType.parse("text/csv"), fileContents)) .build(); Request request = new Request.Builder() .url(this.client.getBasePath()+"/import-users/validate-csv") .post(requestBody) .build(); try { Response response = this.client.getHttpClient().newCall(request).execute(); } catch(IOException e) { throw new ProvisioningApiException("Error validating file", e); } }
[ "public", "void", "validateFile", "(", "String", "fileName", ",", "String", "fileContents", ")", "throws", "ProvisioningApiException", "{", "RequestBody", "requestBody", "=", "new", "MultipartBuilder", "(", ")", ".", "type", "(", "MultipartBuilder", ".", "FORM", ")", ".", "addPart", "(", "Headers", ".", "of", "(", "\"Content-Disposition\"", ",", "\"form-data; name=\\\"csvfile\\\"; filename=\\\"\"", "+", "fileName", "+", "\"\\\"\"", ")", ",", "RequestBody", ".", "create", "(", "MediaType", ".", "parse", "(", "\"text/csv\"", ")", ",", "fileContents", ")", ")", ".", "build", "(", ")", ";", "Request", "request", "=", "new", "Request", ".", "Builder", "(", ")", ".", "url", "(", "this", ".", "client", ".", "getBasePath", "(", ")", "+", "\"/import-users/validate-csv\"", ")", ".", "post", "(", "requestBody", ")", ".", "build", "(", ")", ";", "try", "{", "Response", "response", "=", "this", ".", "client", ".", "getHttpClient", "(", ")", ".", "newCall", "(", "request", ")", ".", "execute", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "ProvisioningApiException", "(", "\"Error validating file\"", ",", "e", ")", ";", "}", "}" ]
Validate the import file. Performs pre-validation on the specified CSV/XLS file. @param fileName The name of the CSV/XLS file to validate. @param fileContents The contents of the CSV/XLS file to validate. @throws ProvisioningApiException if the call is unsuccessful.
[ "Validate", "the", "import", "file", ".", "Performs", "pre", "-", "validation", "on", "the", "specified", "CSV", "/", "XLS", "file", "." ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/provisioning/ImportApi.java#L87-L106
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/VertexLabel.java
VertexLabel.addEdgeLabel
EdgeLabel addEdgeLabel( String edgeLabelName, VertexLabel inVertexLabel, Map<String, PropertyType> properties) { """ Called via {@link Schema#ensureEdgeLabelExist(String, VertexLabel, VertexLabel, Map)} This is called when the {@link EdgeLabel} does not exist and needs to be created. @param edgeLabelName The edge's label. @param inVertexLabel The edge's in vertex. @param properties The edge's properties. @return The new EdgeLabel. """ return addEdgeLabel(edgeLabelName, inVertexLabel, properties, new ListOrderedSet<>()); }
java
EdgeLabel addEdgeLabel( String edgeLabelName, VertexLabel inVertexLabel, Map<String, PropertyType> properties) { return addEdgeLabel(edgeLabelName, inVertexLabel, properties, new ListOrderedSet<>()); }
[ "EdgeLabel", "addEdgeLabel", "(", "String", "edgeLabelName", ",", "VertexLabel", "inVertexLabel", ",", "Map", "<", "String", ",", "PropertyType", ">", "properties", ")", "{", "return", "addEdgeLabel", "(", "edgeLabelName", ",", "inVertexLabel", ",", "properties", ",", "new", "ListOrderedSet", "<>", "(", ")", ")", ";", "}" ]
Called via {@link Schema#ensureEdgeLabelExist(String, VertexLabel, VertexLabel, Map)} This is called when the {@link EdgeLabel} does not exist and needs to be created. @param edgeLabelName The edge's label. @param inVertexLabel The edge's in vertex. @param properties The edge's properties. @return The new EdgeLabel.
[ "Called", "via", "{", "@link", "Schema#ensureEdgeLabelExist", "(", "String", "VertexLabel", "VertexLabel", "Map", ")", "}", "This", "is", "called", "when", "the", "{", "@link", "EdgeLabel", "}", "does", "not", "exist", "and", "needs", "to", "be", "created", "." ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/VertexLabel.java#L371-L376
facebookarchive/hadoop-20
src/core/org/apache/hadoop/record/compiler/CppGenerator.java
CppGenerator.genCode
void genCode(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist, String destDir, ArrayList<String> options) throws IOException { """ Generate C++ code. This method only creates the requested file(s) and spits-out file-level elements (such as include statements etc.) record-level code is generated by JRecord. """ name = new File(destDir, (new File(name)).getName()).getAbsolutePath(); FileWriter cc = new FileWriter(name+".cc"); try { FileWriter hh = new FileWriter(name+".hh"); try { String fileName = (new File(name)).getName(); hh.write("#ifndef __"+fileName.toUpperCase().replace('.','_')+"__\n"); hh.write("#define __"+fileName.toUpperCase().replace('.','_')+"__\n"); hh.write("#include \"recordio.hh\"\n"); hh.write("#include \"recordTypeInfo.hh\"\n"); for (Iterator<JFile> iter = ilist.iterator(); iter.hasNext();) { hh.write("#include \""+iter.next().getName()+".hh\"\n"); } cc.write("#include \""+fileName+".hh\"\n"); cc.write("#include \"utils.hh\"\n"); for (Iterator<JRecord> iter = rlist.iterator(); iter.hasNext();) { iter.next().genCppCode(hh, cc, options); } hh.write("#endif //"+fileName.toUpperCase().replace('.','_')+"__\n"); } finally { hh.close(); } } finally { cc.close(); } }
java
void genCode(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist, String destDir, ArrayList<String> options) throws IOException { name = new File(destDir, (new File(name)).getName()).getAbsolutePath(); FileWriter cc = new FileWriter(name+".cc"); try { FileWriter hh = new FileWriter(name+".hh"); try { String fileName = (new File(name)).getName(); hh.write("#ifndef __"+fileName.toUpperCase().replace('.','_')+"__\n"); hh.write("#define __"+fileName.toUpperCase().replace('.','_')+"__\n"); hh.write("#include \"recordio.hh\"\n"); hh.write("#include \"recordTypeInfo.hh\"\n"); for (Iterator<JFile> iter = ilist.iterator(); iter.hasNext();) { hh.write("#include \""+iter.next().getName()+".hh\"\n"); } cc.write("#include \""+fileName+".hh\"\n"); cc.write("#include \"utils.hh\"\n"); for (Iterator<JRecord> iter = rlist.iterator(); iter.hasNext();) { iter.next().genCppCode(hh, cc, options); } hh.write("#endif //"+fileName.toUpperCase().replace('.','_')+"__\n"); } finally { hh.close(); } } finally { cc.close(); } }
[ "void", "genCode", "(", "String", "name", ",", "ArrayList", "<", "JFile", ">", "ilist", ",", "ArrayList", "<", "JRecord", ">", "rlist", ",", "String", "destDir", ",", "ArrayList", "<", "String", ">", "options", ")", "throws", "IOException", "{", "name", "=", "new", "File", "(", "destDir", ",", "(", "new", "File", "(", "name", ")", ")", ".", "getName", "(", ")", ")", ".", "getAbsolutePath", "(", ")", ";", "FileWriter", "cc", "=", "new", "FileWriter", "(", "name", "+", "\".cc\"", ")", ";", "try", "{", "FileWriter", "hh", "=", "new", "FileWriter", "(", "name", "+", "\".hh\"", ")", ";", "try", "{", "String", "fileName", "=", "(", "new", "File", "(", "name", ")", ")", ".", "getName", "(", ")", ";", "hh", ".", "write", "(", "\"#ifndef __\"", "+", "fileName", ".", "toUpperCase", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\"__\\n\"", ")", ";", "hh", ".", "write", "(", "\"#define __\"", "+", "fileName", ".", "toUpperCase", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\"__\\n\"", ")", ";", "hh", ".", "write", "(", "\"#include \\\"recordio.hh\\\"\\n\"", ")", ";", "hh", ".", "write", "(", "\"#include \\\"recordTypeInfo.hh\\\"\\n\"", ")", ";", "for", "(", "Iterator", "<", "JFile", ">", "iter", "=", "ilist", ".", "iterator", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "hh", ".", "write", "(", "\"#include \\\"\"", "+", "iter", ".", "next", "(", ")", ".", "getName", "(", ")", "+", "\".hh\\\"\\n\"", ")", ";", "}", "cc", ".", "write", "(", "\"#include \\\"\"", "+", "fileName", "+", "\".hh\\\"\\n\"", ")", ";", "cc", ".", "write", "(", "\"#include \\\"utils.hh\\\"\\n\"", ")", ";", "for", "(", "Iterator", "<", "JRecord", ">", "iter", "=", "rlist", ".", "iterator", "(", ")", ";", "iter", ".", "hasNext", "(", ")", ";", ")", "{", "iter", ".", "next", "(", ")", ".", "genCppCode", "(", "hh", ",", "cc", ",", "options", ")", ";", "}", "hh", ".", "write", "(", "\"#endif //\"", "+", "fileName", ".", "toUpperCase", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\"__\\n\"", ")", ";", "}", "finally", "{", "hh", ".", "close", "(", ")", ";", "}", "}", "finally", "{", "cc", ".", "close", "(", ")", ";", "}", "}" ]
Generate C++ code. This method only creates the requested file(s) and spits-out file-level elements (such as include statements etc.) record-level code is generated by JRecord.
[ "Generate", "C", "++", "code", ".", "This", "method", "only", "creates", "the", "requested", "file", "(", "s", ")", "and", "spits", "-", "out", "file", "-", "level", "elements", "(", "such", "as", "include", "statements", "etc", ".", ")", "record", "-", "level", "code", "is", "generated", "by", "JRecord", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/record/compiler/CppGenerator.java#L40-L73
JodaOrg/joda-time
src/main/java/org/joda/time/TimeOfDay.java
TimeOfDay.withSecondOfMinute
public TimeOfDay withSecondOfMinute(int second) { """ Returns a copy of this time with the second of minute field updated. <p> TimeOfDay is immutable, so there are no set methods. Instead, this method returns a new instance with the value of second of minute changed. @param second the second of minute to set @return a copy of this object with the field set @throws IllegalArgumentException if the value is invalid @since 1.3 """ int[] newValues = getValues(); newValues = getChronology().secondOfMinute().set(this, SECOND_OF_MINUTE, newValues, second); return new TimeOfDay(this, newValues); }
java
public TimeOfDay withSecondOfMinute(int second) { int[] newValues = getValues(); newValues = getChronology().secondOfMinute().set(this, SECOND_OF_MINUTE, newValues, second); return new TimeOfDay(this, newValues); }
[ "public", "TimeOfDay", "withSecondOfMinute", "(", "int", "second", ")", "{", "int", "[", "]", "newValues", "=", "getValues", "(", ")", ";", "newValues", "=", "getChronology", "(", ")", ".", "secondOfMinute", "(", ")", ".", "set", "(", "this", ",", "SECOND_OF_MINUTE", ",", "newValues", ",", "second", ")", ";", "return", "new", "TimeOfDay", "(", "this", ",", "newValues", ")", ";", "}" ]
Returns a copy of this time with the second of minute field updated. <p> TimeOfDay is immutable, so there are no set methods. Instead, this method returns a new instance with the value of second of minute changed. @param second the second of minute to set @return a copy of this object with the field set @throws IllegalArgumentException if the value is invalid @since 1.3
[ "Returns", "a", "copy", "of", "this", "time", "with", "the", "second", "of", "minute", "field", "updated", ".", "<p", ">", "TimeOfDay", "is", "immutable", "so", "there", "are", "no", "set", "methods", ".", "Instead", "this", "method", "returns", "a", "new", "instance", "with", "the", "value", "of", "second", "of", "minute", "changed", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/TimeOfDay.java#L936-L940
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/Name.java
Name.simple
@VisibleForTesting static Name simple(String name) { """ Creates a new name with no normalization done on the given string. """ switch (name) { case ".": return SELF; case "..": return PARENT; default: return new Name(name, name); } }
java
@VisibleForTesting static Name simple(String name) { switch (name) { case ".": return SELF; case "..": return PARENT; default: return new Name(name, name); } }
[ "@", "VisibleForTesting", "static", "Name", "simple", "(", "String", "name", ")", "{", "switch", "(", "name", ")", "{", "case", "\".\"", ":", "return", "SELF", ";", "case", "\"..\"", ":", "return", "PARENT", ";", "default", ":", "return", "new", "Name", "(", "name", ",", "name", ")", ";", "}", "}" ]
Creates a new name with no normalization done on the given string.
[ "Creates", "a", "new", "name", "with", "no", "normalization", "done", "on", "the", "given", "string", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/Name.java#L52-L62
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/http/HttpMessage.java
HttpMessage.addDateField
public void addDateField(String name, Date date) { """ Adds the value of a date field. Header or Trailer fields are set depending on message state. @param name the field name @param date the field date value """ if (_state!=__MSG_EDITABLE) return; _header.addDateField(name,date); }
java
public void addDateField(String name, Date date) { if (_state!=__MSG_EDITABLE) return; _header.addDateField(name,date); }
[ "public", "void", "addDateField", "(", "String", "name", ",", "Date", "date", ")", "{", "if", "(", "_state", "!=", "__MSG_EDITABLE", ")", "return", ";", "_header", ".", "addDateField", "(", "name", ",", "date", ")", ";", "}" ]
Adds the value of a date field. Header or Trailer fields are set depending on message state. @param name the field name @param date the field date value
[ "Adds", "the", "value", "of", "a", "date", "field", ".", "Header", "or", "Trailer", "fields", "are", "set", "depending", "on", "message", "state", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/http/HttpMessage.java#L385-L390
bullhorn/sdk-rest
src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java
StandardBullhornData.parseResume
protected ParsedResume parseResume(String url, Object requestPayLoad, Map<String, String> uriVariables) { """ Makes the call to the resume parser. If parse fails this method will retry RESUME_PARSE_RETRY number of times. @param url @param requestPayLoad @param uriVariables @return """ ParsedResume response = null; for (int tryNumber = 1; tryNumber <= RESUME_PARSE_RETRY; tryNumber++) { try { response = this.performPostResumeRequest(url, requestPayLoad, uriVariables); break; } catch (HttpStatusCodeException error) { response = handleResumeParseError(tryNumber, error); } catch (Exception e) { log.error("error", e); } } return response; }
java
protected ParsedResume parseResume(String url, Object requestPayLoad, Map<String, String> uriVariables) { ParsedResume response = null; for (int tryNumber = 1; tryNumber <= RESUME_PARSE_RETRY; tryNumber++) { try { response = this.performPostResumeRequest(url, requestPayLoad, uriVariables); break; } catch (HttpStatusCodeException error) { response = handleResumeParseError(tryNumber, error); } catch (Exception e) { log.error("error", e); } } return response; }
[ "protected", "ParsedResume", "parseResume", "(", "String", "url", ",", "Object", "requestPayLoad", ",", "Map", "<", "String", ",", "String", ">", "uriVariables", ")", "{", "ParsedResume", "response", "=", "null", ";", "for", "(", "int", "tryNumber", "=", "1", ";", "tryNumber", "<=", "RESUME_PARSE_RETRY", ";", "tryNumber", "++", ")", "{", "try", "{", "response", "=", "this", ".", "performPostResumeRequest", "(", "url", ",", "requestPayLoad", ",", "uriVariables", ")", ";", "break", ";", "}", "catch", "(", "HttpStatusCodeException", "error", ")", "{", "response", "=", "handleResumeParseError", "(", "tryNumber", ",", "error", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"error\"", ",", "e", ")", ";", "}", "}", "return", "response", ";", "}" ]
Makes the call to the resume parser. If parse fails this method will retry RESUME_PARSE_RETRY number of times. @param url @param requestPayLoad @param uriVariables @return
[ "Makes", "the", "call", "to", "the", "resume", "parser", ".", "If", "parse", "fails", "this", "method", "will", "retry", "RESUME_PARSE_RETRY", "number", "of", "times", "." ]
train
https://github.com/bullhorn/sdk-rest/blob/0c75a141c768bb31510afc3a412c11bd101eca06/src/main/java/com/bullhornsdk/data/api/StandardBullhornData.java#L1360-L1374
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java
TilesOverlay.protectDisplayedTilesForCache
public void protectDisplayedTilesForCache(final Canvas pCanvas, final Projection pProjection) { """ Populates the tile provider's memory cache with the list of displayed tiles @since 6.0.0 """ if (!setViewPort(pCanvas, pProjection)) { return; } TileSystem.getTileFromMercator(mViewPort, TileSystem.getTileSize(mProjection.getZoomLevel()), mProtectedTiles); final int tileZoomLevel = TileSystem.getInputTileZoomLevel(mProjection.getZoomLevel()); mTileProvider.getTileCache().getMapTileArea().set(tileZoomLevel, mProtectedTiles); mTileProvider.getTileCache().maintenance(); }
java
public void protectDisplayedTilesForCache(final Canvas pCanvas, final Projection pProjection) { if (!setViewPort(pCanvas, pProjection)) { return; } TileSystem.getTileFromMercator(mViewPort, TileSystem.getTileSize(mProjection.getZoomLevel()), mProtectedTiles); final int tileZoomLevel = TileSystem.getInputTileZoomLevel(mProjection.getZoomLevel()); mTileProvider.getTileCache().getMapTileArea().set(tileZoomLevel, mProtectedTiles); mTileProvider.getTileCache().maintenance(); }
[ "public", "void", "protectDisplayedTilesForCache", "(", "final", "Canvas", "pCanvas", ",", "final", "Projection", "pProjection", ")", "{", "if", "(", "!", "setViewPort", "(", "pCanvas", ",", "pProjection", ")", ")", "{", "return", ";", "}", "TileSystem", ".", "getTileFromMercator", "(", "mViewPort", ",", "TileSystem", ".", "getTileSize", "(", "mProjection", ".", "getZoomLevel", "(", ")", ")", ",", "mProtectedTiles", ")", ";", "final", "int", "tileZoomLevel", "=", "TileSystem", ".", "getInputTileZoomLevel", "(", "mProjection", ".", "getZoomLevel", "(", ")", ")", ";", "mTileProvider", ".", "getTileCache", "(", ")", ".", "getMapTileArea", "(", ")", ".", "set", "(", "tileZoomLevel", ",", "mProtectedTiles", ")", ";", "mTileProvider", ".", "getTileCache", "(", ")", ".", "maintenance", "(", ")", ";", "}" ]
Populates the tile provider's memory cache with the list of displayed tiles @since 6.0.0
[ "Populates", "the", "tile", "provider", "s", "memory", "cache", "with", "the", "list", "of", "displayed", "tiles" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java#L171-L179
protostuff/protostuff
protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java
JsonIOUtil.writeListTo
public static <T> void writeListTo(JsonGenerator generator, List<T> messages, Schema<T> schema, boolean numeric) throws IOException { """ Serializes the {@code messages} into the generator using the given schema. """ generator.writeStartArray(); if (messages.isEmpty()) { generator.writeEndArray(); return; } final JsonOutput output = new JsonOutput(generator, numeric, schema); for (T m : messages) { generator.writeStartObject(); schema.writeTo(output, m); if (output.isLastRepeated()) generator.writeEndArray(); generator.writeEndObject(); output.reset(); } generator.writeEndArray(); }
java
public static <T> void writeListTo(JsonGenerator generator, List<T> messages, Schema<T> schema, boolean numeric) throws IOException { generator.writeStartArray(); if (messages.isEmpty()) { generator.writeEndArray(); return; } final JsonOutput output = new JsonOutput(generator, numeric, schema); for (T m : messages) { generator.writeStartObject(); schema.writeTo(output, m); if (output.isLastRepeated()) generator.writeEndArray(); generator.writeEndObject(); output.reset(); } generator.writeEndArray(); }
[ "public", "static", "<", "T", ">", "void", "writeListTo", "(", "JsonGenerator", "generator", ",", "List", "<", "T", ">", "messages", ",", "Schema", "<", "T", ">", "schema", ",", "boolean", "numeric", ")", "throws", "IOException", "{", "generator", ".", "writeStartArray", "(", ")", ";", "if", "(", "messages", ".", "isEmpty", "(", ")", ")", "{", "generator", ".", "writeEndArray", "(", ")", ";", "return", ";", "}", "final", "JsonOutput", "output", "=", "new", "JsonOutput", "(", "generator", ",", "numeric", ",", "schema", ")", ";", "for", "(", "T", "m", ":", "messages", ")", "{", "generator", ".", "writeStartObject", "(", ")", ";", "schema", ".", "writeTo", "(", "output", ",", "m", ")", ";", "if", "(", "output", ".", "isLastRepeated", "(", ")", ")", "generator", ".", "writeEndArray", "(", ")", ";", "generator", ".", "writeEndObject", "(", ")", ";", "output", ".", "reset", "(", ")", ";", "}", "generator", ".", "writeEndArray", "(", ")", ";", "}" ]
Serializes the {@code messages} into the generator using the given schema.
[ "Serializes", "the", "{" ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-json/src/main/java/io/protostuff/JsonIOUtil.java#L534-L559
j256/simplecsv
src/main/java/com/j256/simplecsv/processor/CsvProcessor.java
CsvProcessor.processRow
public T processRow(String line, ParseError parseError) throws ParseException { """ Read and process a line and return the associated entity. @param line to process to build our entity. @param parseError If not null, this will be set with the first parse error and it will return null. If this is null then a ParseException will be thrown instead. @return Returns a processed entity or null if an error and parseError has been set. @throws ParseException Thrown on any parsing problems. If parseError is not null then the error will be added there and an exception should not be thrown. """ checkEntityConfig(); try { return processRow(line, null, parseError, 1); } catch (IOException e) { // this won't happen because processRow won't do any IO return null; } }
java
public T processRow(String line, ParseError parseError) throws ParseException { checkEntityConfig(); try { return processRow(line, null, parseError, 1); } catch (IOException e) { // this won't happen because processRow won't do any IO return null; } }
[ "public", "T", "processRow", "(", "String", "line", ",", "ParseError", "parseError", ")", "throws", "ParseException", "{", "checkEntityConfig", "(", ")", ";", "try", "{", "return", "processRow", "(", "line", ",", "null", ",", "parseError", ",", "1", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// this won't happen because processRow won't do any IO", "return", "null", ";", "}", "}" ]
Read and process a line and return the associated entity. @param line to process to build our entity. @param parseError If not null, this will be set with the first parse error and it will return null. If this is null then a ParseException will be thrown instead. @return Returns a processed entity or null if an error and parseError has been set. @throws ParseException Thrown on any parsing problems. If parseError is not null then the error will be added there and an exception should not be thrown.
[ "Read", "and", "process", "a", "line", "and", "return", "the", "associated", "entity", "." ]
train
https://github.com/j256/simplecsv/blob/964fe53073c43e2a311341e3f8fd2c94372f60cb/src/main/java/com/j256/simplecsv/processor/CsvProcessor.java#L388-L396
czyzby/gdx-lml
kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/reflection/Reflection.java
Reflection.getAnnotation
public static <Type extends Annotation> Type getAnnotation(final Field field, final Class<Type> annotationType) { """ Utility method that allows to extract actual annotation from field, bypassing LibGDX annotation wrapper. Returns null if annotation is not present. @param field might be annotated. @param annotationType class of the annotation. @return an instance of the annotation if the field is annotated or null if not. @param <Type> type of annotation. """ if (isAnnotationPresent(field, annotationType)) { return field.getDeclaredAnnotation(annotationType).getAnnotation(annotationType); } return null; }
java
public static <Type extends Annotation> Type getAnnotation(final Field field, final Class<Type> annotationType) { if (isAnnotationPresent(field, annotationType)) { return field.getDeclaredAnnotation(annotationType).getAnnotation(annotationType); } return null; }
[ "public", "static", "<", "Type", "extends", "Annotation", ">", "Type", "getAnnotation", "(", "final", "Field", "field", ",", "final", "Class", "<", "Type", ">", "annotationType", ")", "{", "if", "(", "isAnnotationPresent", "(", "field", ",", "annotationType", ")", ")", "{", "return", "field", ".", "getDeclaredAnnotation", "(", "annotationType", ")", ".", "getAnnotation", "(", "annotationType", ")", ";", "}", "return", "null", ";", "}" ]
Utility method that allows to extract actual annotation from field, bypassing LibGDX annotation wrapper. Returns null if annotation is not present. @param field might be annotated. @param annotationType class of the annotation. @return an instance of the annotation if the field is annotated or null if not. @param <Type> type of annotation.
[ "Utility", "method", "that", "allows", "to", "extract", "actual", "annotation", "from", "field", "bypassing", "LibGDX", "annotation", "wrapper", ".", "Returns", "null", "if", "annotation", "is", "not", "present", "." ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/reflection/Reflection.java#L68-L73
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/INodeFileUnderConstruction.java
INodeFileUnderConstruction.setTargets
void setTargets(DatanodeDescriptor[] locs, long generationStamp) { """ Set targets for list of replicas all sharing the same generationStamp @param locs location of replicas @param generationStamp shared generation stamp """ setTargets(locs); if (locs == null) { targetGSs = null; return; } long[] targetGSs = new long[locs.length]; for (int i=0; i<targetGSs.length; i++) { targetGSs[i] = generationStamp; } this.targetGSs = targetGSs; }
java
void setTargets(DatanodeDescriptor[] locs, long generationStamp) { setTargets(locs); if (locs == null) { targetGSs = null; return; } long[] targetGSs = new long[locs.length]; for (int i=0; i<targetGSs.length; i++) { targetGSs[i] = generationStamp; } this.targetGSs = targetGSs; }
[ "void", "setTargets", "(", "DatanodeDescriptor", "[", "]", "locs", ",", "long", "generationStamp", ")", "{", "setTargets", "(", "locs", ")", ";", "if", "(", "locs", "==", "null", ")", "{", "targetGSs", "=", "null", ";", "return", ";", "}", "long", "[", "]", "targetGSs", "=", "new", "long", "[", "locs", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "targetGSs", ".", "length", ";", "i", "++", ")", "{", "targetGSs", "[", "i", "]", "=", "generationStamp", ";", "}", "this", ".", "targetGSs", "=", "targetGSs", ";", "}" ]
Set targets for list of replicas all sharing the same generationStamp @param locs location of replicas @param generationStamp shared generation stamp
[ "Set", "targets", "for", "list", "of", "replicas", "all", "sharing", "the", "same", "generationStamp" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/INodeFileUnderConstruction.java#L178-L189
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/CriteriaReader.java
CriteriaReader.addBlock
private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator) { """ Adds a logical operator block. @param list parent criteria list @param block current block @param operator logical operator represented by this block """ GenericCriteria result = new GenericCriteria(m_properties); result.setOperator(operator); list.add(result); processBlock(result.getCriteriaList(), getChildBlock(block)); processBlock(list, getListNextBlock(block)); }
java
private void addBlock(List<GenericCriteria> list, byte[] block, TestOperator operator) { GenericCriteria result = new GenericCriteria(m_properties); result.setOperator(operator); list.add(result); processBlock(result.getCriteriaList(), getChildBlock(block)); processBlock(list, getListNextBlock(block)); }
[ "private", "void", "addBlock", "(", "List", "<", "GenericCriteria", ">", "list", ",", "byte", "[", "]", "block", ",", "TestOperator", "operator", ")", "{", "GenericCriteria", "result", "=", "new", "GenericCriteria", "(", "m_properties", ")", ";", "result", ".", "setOperator", "(", "operator", ")", ";", "list", ".", "add", "(", "result", ")", ";", "processBlock", "(", "result", ".", "getCriteriaList", "(", ")", ",", "getChildBlock", "(", "block", ")", ")", ";", "processBlock", "(", "list", ",", "getListNextBlock", "(", "block", ")", ")", ";", "}" ]
Adds a logical operator block. @param list parent criteria list @param block current block @param operator logical operator represented by this block
[ "Adds", "a", "logical", "operator", "block", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/CriteriaReader.java#L289-L296
duracloud/duracloud
chunk/src/main/java/org/duracloud/chunk/FileChunker.java
FileChunker.getContentId
private String getContentId(File baseDir, File file) { """ This method defines the returned contentId as the path of the arg file minus the path of the arg baseDir, in which the file was found. @param baseDir dir that contained the arg file or one of its parents @param file for which contentId is to be found @return contentId of arg file """ String filePath = file.getPath(); String basePath = baseDir.getPath(); int index = filePath.indexOf(basePath); if (index == -1) { StringBuilder sb = new StringBuilder("Invalid basePath for file: "); sb.append("b: '" + basePath + "', "); sb.append("f: '" + filePath + "'"); throw new DuraCloudRuntimeException(sb.toString()); } String contentId = filePath.substring(index + basePath.length()); if (contentId.startsWith(File.separator)) { contentId = contentId.substring(1, contentId.length()); } // Replace backslash (\) with forward slash (/) for all content IDs contentId = contentId.replaceAll("\\\\", "/"); return contentId; }
java
private String getContentId(File baseDir, File file) { String filePath = file.getPath(); String basePath = baseDir.getPath(); int index = filePath.indexOf(basePath); if (index == -1) { StringBuilder sb = new StringBuilder("Invalid basePath for file: "); sb.append("b: '" + basePath + "', "); sb.append("f: '" + filePath + "'"); throw new DuraCloudRuntimeException(sb.toString()); } String contentId = filePath.substring(index + basePath.length()); if (contentId.startsWith(File.separator)) { contentId = contentId.substring(1, contentId.length()); } // Replace backslash (\) with forward slash (/) for all content IDs contentId = contentId.replaceAll("\\\\", "/"); return contentId; }
[ "private", "String", "getContentId", "(", "File", "baseDir", ",", "File", "file", ")", "{", "String", "filePath", "=", "file", ".", "getPath", "(", ")", ";", "String", "basePath", "=", "baseDir", ".", "getPath", "(", ")", ";", "int", "index", "=", "filePath", ".", "indexOf", "(", "basePath", ")", ";", "if", "(", "index", "==", "-", "1", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "\"Invalid basePath for file: \"", ")", ";", "sb", ".", "append", "(", "\"b: '\"", "+", "basePath", "+", "\"', \"", ")", ";", "sb", ".", "append", "(", "\"f: '\"", "+", "filePath", "+", "\"'\"", ")", ";", "throw", "new", "DuraCloudRuntimeException", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "String", "contentId", "=", "filePath", ".", "substring", "(", "index", "+", "basePath", ".", "length", "(", ")", ")", ";", "if", "(", "contentId", ".", "startsWith", "(", "File", ".", "separator", ")", ")", "{", "contentId", "=", "contentId", ".", "substring", "(", "1", ",", "contentId", ".", "length", "(", ")", ")", ";", "}", "// Replace backslash (\\) with forward slash (/) for all content IDs", "contentId", "=", "contentId", ".", "replaceAll", "(", "\"\\\\\\\\\"", ",", "\"/\"", ")", ";", "return", "contentId", ";", "}" ]
This method defines the returned contentId as the path of the arg file minus the path of the arg baseDir, in which the file was found. @param baseDir dir that contained the arg file or one of its parents @param file for which contentId is to be found @return contentId of arg file
[ "This", "method", "defines", "the", "returned", "contentId", "as", "the", "path", "of", "the", "arg", "file", "minus", "the", "path", "of", "the", "arg", "baseDir", "in", "which", "the", "file", "was", "found", "." ]
train
https://github.com/duracloud/duracloud/blob/dc4f3a1716d43543cc3b2e1880605f9389849b66/chunk/src/main/java/org/duracloud/chunk/FileChunker.java#L275-L294
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseOpticalFlowKlt.java
DenseOpticalFlowKlt.checkNeighbors
protected void checkNeighbors( int cx , int cy , float score , float flowX , float flowY , ImageFlow output ) { """ Examines every pixel inside the region centered at (cx,cy) to see if their optical flow has a worse score the one specified in 'flow' """ int x0 = Math.max(0,cx-regionRadius); int x1 = Math.min(output.width, cx + regionRadius + 1); int y0 = Math.max(0,cy-regionRadius); int y1 = Math.min(output.height, cy + regionRadius + 1); for( int i = y0; i < y1; i++ ) { int index = width*i + x0; for( int j = x0; j < x1; j++ , index++ ) { float s = scores[ index ]; ImageFlow.D f = output.data[index]; if( s > score ) { f.set(flowX,flowY); scores[index] = score; } else if( s == score ) { // Pick solution with the least motion when ambiguous float m0 = f.x*f.x + f.y*f.y; float m1 = flowX*flowX + flowY*flowY; if( m1 < m0 ) { f.set(flowX,flowY); scores[index] = score; } } } } }
java
protected void checkNeighbors( int cx , int cy , float score , float flowX , float flowY , ImageFlow output ) { int x0 = Math.max(0,cx-regionRadius); int x1 = Math.min(output.width, cx + regionRadius + 1); int y0 = Math.max(0,cy-regionRadius); int y1 = Math.min(output.height, cy + regionRadius + 1); for( int i = y0; i < y1; i++ ) { int index = width*i + x0; for( int j = x0; j < x1; j++ , index++ ) { float s = scores[ index ]; ImageFlow.D f = output.data[index]; if( s > score ) { f.set(flowX,flowY); scores[index] = score; } else if( s == score ) { // Pick solution with the least motion when ambiguous float m0 = f.x*f.x + f.y*f.y; float m1 = flowX*flowX + flowY*flowY; if( m1 < m0 ) { f.set(flowX,flowY); scores[index] = score; } } } } }
[ "protected", "void", "checkNeighbors", "(", "int", "cx", ",", "int", "cy", ",", "float", "score", ",", "float", "flowX", ",", "float", "flowY", ",", "ImageFlow", "output", ")", "{", "int", "x0", "=", "Math", ".", "max", "(", "0", ",", "cx", "-", "regionRadius", ")", ";", "int", "x1", "=", "Math", ".", "min", "(", "output", ".", "width", ",", "cx", "+", "regionRadius", "+", "1", ")", ";", "int", "y0", "=", "Math", ".", "max", "(", "0", ",", "cy", "-", "regionRadius", ")", ";", "int", "y1", "=", "Math", ".", "min", "(", "output", ".", "height", ",", "cy", "+", "regionRadius", "+", "1", ")", ";", "for", "(", "int", "i", "=", "y0", ";", "i", "<", "y1", ";", "i", "++", ")", "{", "int", "index", "=", "width", "*", "i", "+", "x0", ";", "for", "(", "int", "j", "=", "x0", ";", "j", "<", "x1", ";", "j", "++", ",", "index", "++", ")", "{", "float", "s", "=", "scores", "[", "index", "]", ";", "ImageFlow", ".", "D", "f", "=", "output", ".", "data", "[", "index", "]", ";", "if", "(", "s", ">", "score", ")", "{", "f", ".", "set", "(", "flowX", ",", "flowY", ")", ";", "scores", "[", "index", "]", "=", "score", ";", "}", "else", "if", "(", "s", "==", "score", ")", "{", "// Pick solution with the least motion when ambiguous", "float", "m0", "=", "f", ".", "x", "*", "f", ".", "x", "+", "f", ".", "y", "*", "f", ".", "y", ";", "float", "m1", "=", "flowX", "*", "flowX", "+", "flowY", "*", "flowY", ";", "if", "(", "m1", "<", "m0", ")", "{", "f", ".", "set", "(", "flowX", ",", "flowY", ")", ";", "scores", "[", "index", "]", "=", "score", ";", "}", "}", "}", "}", "}" ]
Examines every pixel inside the region centered at (cx,cy) to see if their optical flow has a worse score the one specified in 'flow'
[ "Examines", "every", "pixel", "inside", "the", "region", "centered", "at", "(", "cx", "cy", ")", "to", "see", "if", "their", "optical", "flow", "has", "a", "worse", "score", "the", "one", "specified", "in", "flow" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/flow/DenseOpticalFlowKlt.java#L105-L131
headius/invokebinder
src/main/java/com/headius/invokebinder/transform/Transform.java
Transform.buildClassArgument
protected static void buildClassArgument(StringBuilder builder, Class cls) { """ Build Java code to represent a single .class reference. This will be an argument of the form "pkg.Cls1.class" or "pkg.Cls2[].class" or "primtype.class" @param builder the builder in which to build the argument @param cls the type for the argument """ buildClass(builder, cls); builder.append(".class"); }
java
protected static void buildClassArgument(StringBuilder builder, Class cls) { buildClass(builder, cls); builder.append(".class"); }
[ "protected", "static", "void", "buildClassArgument", "(", "StringBuilder", "builder", ",", "Class", "cls", ")", "{", "buildClass", "(", "builder", ",", "cls", ")", ";", "builder", ".", "append", "(", "\".class\"", ")", ";", "}" ]
Build Java code to represent a single .class reference. This will be an argument of the form "pkg.Cls1.class" or "pkg.Cls2[].class" or "primtype.class" @param builder the builder in which to build the argument @param cls the type for the argument
[ "Build", "Java", "code", "to", "represent", "a", "single", ".", "class", "reference", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/transform/Transform.java#L82-L85
alkacon/opencms-core
src/org/opencms/flex/CmsFlexRequest.java
CmsFlexRequest.setAttributeMap
public void setAttributeMap(Map<String, Object> map) { """ Sets the specified Map as attribute map of the request.<p> The map should be immutable. This will completely replace the attribute map. Use this in combination with {@link #getAttributeMap()} and {@link #addAttributeMap(Map)} in case you want to set the old status of the attribute map after you have modified it for a specific operation.<p> @param map the map to set """ m_attributes = new HashMap<String, Object>(map); }
java
public void setAttributeMap(Map<String, Object> map) { m_attributes = new HashMap<String, Object>(map); }
[ "public", "void", "setAttributeMap", "(", "Map", "<", "String", ",", "Object", ">", "map", ")", "{", "m_attributes", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", "map", ")", ";", "}" ]
Sets the specified Map as attribute map of the request.<p> The map should be immutable. This will completely replace the attribute map. Use this in combination with {@link #getAttributeMap()} and {@link #addAttributeMap(Map)} in case you want to set the old status of the attribute map after you have modified it for a specific operation.<p> @param map the map to set
[ "Sets", "the", "specified", "Map", "as", "attribute", "map", "of", "the", "request", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/flex/CmsFlexRequest.java#L728-L731
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/utils/Window.java
Window.snapToNextHigherInActiveRegionResolution
public static Point2D.Double snapToNextHigherInActiveRegionResolution( double x, double y, Window activeWindow ) { """ Moves the point given by X and Y to be on the grid of the active region. @param x the easting of the arbitrary point @param y the northing of the arbitrary point @param activeWindow the active window from which to take the grid @return the snapped point """ double minx = activeWindow.getRectangle().getBounds2D().getMinX(); double ewres = activeWindow.getWEResolution(); double xsnap = minx + (Math.ceil((x - minx) / ewres) * ewres); double miny = activeWindow.getRectangle().getBounds2D().getMinY(); double nsres = activeWindow.getNSResolution(); double ysnap = miny + (Math.ceil((y - miny) / nsres) * nsres); return new Point2D.Double(xsnap, ysnap); }
java
public static Point2D.Double snapToNextHigherInActiveRegionResolution( double x, double y, Window activeWindow ) { double minx = activeWindow.getRectangle().getBounds2D().getMinX(); double ewres = activeWindow.getWEResolution(); double xsnap = minx + (Math.ceil((x - minx) / ewres) * ewres); double miny = activeWindow.getRectangle().getBounds2D().getMinY(); double nsres = activeWindow.getNSResolution(); double ysnap = miny + (Math.ceil((y - miny) / nsres) * nsres); return new Point2D.Double(xsnap, ysnap); }
[ "public", "static", "Point2D", ".", "Double", "snapToNextHigherInActiveRegionResolution", "(", "double", "x", ",", "double", "y", ",", "Window", "activeWindow", ")", "{", "double", "minx", "=", "activeWindow", ".", "getRectangle", "(", ")", ".", "getBounds2D", "(", ")", ".", "getMinX", "(", ")", ";", "double", "ewres", "=", "activeWindow", ".", "getWEResolution", "(", ")", ";", "double", "xsnap", "=", "minx", "+", "(", "Math", ".", "ceil", "(", "(", "x", "-", "minx", ")", "/", "ewres", ")", "*", "ewres", ")", ";", "double", "miny", "=", "activeWindow", ".", "getRectangle", "(", ")", ".", "getBounds2D", "(", ")", ".", "getMinY", "(", ")", ";", "double", "nsres", "=", "activeWindow", ".", "getNSResolution", "(", ")", ";", "double", "ysnap", "=", "miny", "+", "(", "Math", ".", "ceil", "(", "(", "y", "-", "miny", ")", "/", "nsres", ")", "*", "nsres", ")", ";", "return", "new", "Point2D", ".", "Double", "(", "xsnap", ",", "ysnap", ")", ";", "}" ]
Moves the point given by X and Y to be on the grid of the active region. @param x the easting of the arbitrary point @param y the northing of the arbitrary point @param activeWindow the active window from which to take the grid @return the snapped point
[ "Moves", "the", "point", "given", "by", "X", "and", "Y", "to", "be", "on", "the", "grid", "of", "the", "active", "region", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/grasslegacy/utils/Window.java#L444-L456
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java
QueueEntryRow.isQueueEntry
public static boolean isQueueEntry(byte[] queueRowPrefix, byte[] rowBuffer, int rowOffset, int rowLength) { """ Returns true if the given KeyValue row is a queue entry of the given queue based on queue row prefix """ return isPrefix(rowBuffer, rowOffset + 1 + HBaseQueueAdmin.SALT_BYTES, rowLength - 1 - HBaseQueueAdmin.SALT_BYTES, queueRowPrefix); }
java
public static boolean isQueueEntry(byte[] queueRowPrefix, byte[] rowBuffer, int rowOffset, int rowLength) { return isPrefix(rowBuffer, rowOffset + 1 + HBaseQueueAdmin.SALT_BYTES, rowLength - 1 - HBaseQueueAdmin.SALT_BYTES, queueRowPrefix); }
[ "public", "static", "boolean", "isQueueEntry", "(", "byte", "[", "]", "queueRowPrefix", ",", "byte", "[", "]", "rowBuffer", ",", "int", "rowOffset", ",", "int", "rowLength", ")", "{", "return", "isPrefix", "(", "rowBuffer", ",", "rowOffset", "+", "1", "+", "HBaseQueueAdmin", ".", "SALT_BYTES", ",", "rowLength", "-", "1", "-", "HBaseQueueAdmin", ".", "SALT_BYTES", ",", "queueRowPrefix", ")", ";", "}" ]
Returns true if the given KeyValue row is a queue entry of the given queue based on queue row prefix
[ "Returns", "true", "if", "the", "given", "KeyValue", "row", "is", "a", "queue", "entry", "of", "the", "given", "queue", "based", "on", "queue", "row", "prefix" ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/transaction/queue/QueueEntryRow.java#L141-L146
radkovo/jStyleParser
src/main/java/cz/vutbr/web/css/MediaSpec.java
MediaSpec.valueMatches
protected boolean valueMatches(Integer required, int current, boolean min, boolean max) { """ Checks whether a value coresponds to the given criteria. @param required the required value @param current the tested value or {@code null} for invalid value @param min {@code true} when the required value is the minimal one @param max {@code true} when the required value is the maximal one @return {@code true} when the value matches the criteria. """ if (required != null) { if (min) return (current >= required); else if (max) return (current <= required); else return current == required; } else return false; //invalid values don't match }
java
protected boolean valueMatches(Integer required, int current, boolean min, boolean max) { if (required != null) { if (min) return (current >= required); else if (max) return (current <= required); else return current == required; } else return false; //invalid values don't match }
[ "protected", "boolean", "valueMatches", "(", "Integer", "required", ",", "int", "current", ",", "boolean", "min", ",", "boolean", "max", ")", "{", "if", "(", "required", "!=", "null", ")", "{", "if", "(", "min", ")", "return", "(", "current", ">=", "required", ")", ";", "else", "if", "(", "max", ")", "return", "(", "current", "<=", "required", ")", ";", "else", "return", "current", "==", "required", ";", "}", "else", "return", "false", ";", "//invalid values don't match", "}" ]
Checks whether a value coresponds to the given criteria. @param required the required value @param current the tested value or {@code null} for invalid value @param min {@code true} when the required value is the minimal one @param max {@code true} when the required value is the maximal one @return {@code true} when the value matches the criteria.
[ "Checks", "whether", "a", "value", "coresponds", "to", "the", "given", "criteria", "." ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/css/MediaSpec.java#L537-L550
ACRA/acra
acra-mail/src/main/java/org/acra/sender/EmailIntentSender.java
EmailIntentSender.createAttachmentFromString
@Nullable protected Uri createAttachmentFromString(@NonNull Context context, @NonNull String name, @NonNull String content) { """ Creates a temporary file with the given content and name, to be used as an email attachment @param context a context @param name the name @param content the content @return a content uri for the file """ final File cache = new File(context.getCacheDir(), name); try { IOUtils.writeStringToFile(cache, content); return AcraContentProvider.getUriForFile(context, cache); } catch (IOException ignored) { } return null; }
java
@Nullable protected Uri createAttachmentFromString(@NonNull Context context, @NonNull String name, @NonNull String content) { final File cache = new File(context.getCacheDir(), name); try { IOUtils.writeStringToFile(cache, content); return AcraContentProvider.getUriForFile(context, cache); } catch (IOException ignored) { } return null; }
[ "@", "Nullable", "protected", "Uri", "createAttachmentFromString", "(", "@", "NonNull", "Context", "context", ",", "@", "NonNull", "String", "name", ",", "@", "NonNull", "String", "content", ")", "{", "final", "File", "cache", "=", "new", "File", "(", "context", ".", "getCacheDir", "(", ")", ",", "name", ")", ";", "try", "{", "IOUtils", ".", "writeStringToFile", "(", "cache", ",", "content", ")", ";", "return", "AcraContentProvider", ".", "getUriForFile", "(", "context", ",", "cache", ")", ";", "}", "catch", "(", "IOException", "ignored", ")", "{", "}", "return", "null", ";", "}" ]
Creates a temporary file with the given content and name, to be used as an email attachment @param context a context @param name the name @param content the content @return a content uri for the file
[ "Creates", "a", "temporary", "file", "with", "the", "given", "content", "and", "name", "to", "be", "used", "as", "an", "email", "attachment" ]
train
https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-mail/src/main/java/org/acra/sender/EmailIntentSender.java#L248-L257
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/templateresolver/AbstractConfigurableTemplateResolver.java
AbstractConfigurableTemplateResolver.addTemplateAlias
public final void addTemplateAlias(final String alias, final String templateName) { """ <p> Adds a new template alias to the currently configured ones. </p> @param alias the new alias name @param templateName the name of the template the alias will be applied to """ Validate.notNull(alias, "Alias cannot be null"); Validate.notNull(templateName, "Template name cannot be null"); this.templateAliases.put(alias, templateName); }
java
public final void addTemplateAlias(final String alias, final String templateName) { Validate.notNull(alias, "Alias cannot be null"); Validate.notNull(templateName, "Template name cannot be null"); this.templateAliases.put(alias, templateName); }
[ "public", "final", "void", "addTemplateAlias", "(", "final", "String", "alias", ",", "final", "String", "templateName", ")", "{", "Validate", ".", "notNull", "(", "alias", ",", "\"Alias cannot be null\"", ")", ";", "Validate", ".", "notNull", "(", "templateName", ",", "\"Template name cannot be null\"", ")", ";", "this", ".", "templateAliases", ".", "put", "(", "alias", ",", "templateName", ")", ";", "}" ]
<p> Adds a new template alias to the currently configured ones. </p> @param alias the new alias name @param templateName the name of the template the alias will be applied to
[ "<p", ">", "Adds", "a", "new", "template", "alias", "to", "the", "currently", "configured", "ones", ".", "<", "/", "p", ">" ]
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/templateresolver/AbstractConfigurableTemplateResolver.java#L497-L501
mikepenz/Android-Iconics
library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java
IconicsDrawable.iconOffsetXDp
@NonNull public IconicsDrawable iconOffsetXDp(@Dimension(unit = DP) int sizeDp) { """ set the icon offset for X as dp @return The current IconicsDrawable for chaining. """ return iconOffsetXPx(Utils.convertDpToPx(mContext, sizeDp)); }
java
@NonNull public IconicsDrawable iconOffsetXDp(@Dimension(unit = DP) int sizeDp) { return iconOffsetXPx(Utils.convertDpToPx(mContext, sizeDp)); }
[ "@", "NonNull", "public", "IconicsDrawable", "iconOffsetXDp", "(", "@", "Dimension", "(", "unit", "=", "DP", ")", "int", "sizeDp", ")", "{", "return", "iconOffsetXPx", "(", "Utils", ".", "convertDpToPx", "(", "mContext", ",", "sizeDp", ")", ")", ";", "}" ]
set the icon offset for X as dp @return The current IconicsDrawable for chaining.
[ "set", "the", "icon", "offset", "for", "X", "as", "dp" ]
train
https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java#L525-L528
virgo47/javasimon
core/src/main/java/org/javasimon/callback/quantiles/AutoQuantilesCallback.java
AutoQuantilesCallback.onStopwatchSplit
@Override protected void onStopwatchSplit(Stopwatch stopwatch, Split split) { """ Called when there is a new split on a Stopwatch, either {@link #onStopwatchStop} or {@link #onStopwatchAdd}. If buckets have been initialized, the value is added to appropriate bucket. Else if stopwatch is warming up value is added to value list. """ Buckets buckets = getOrCreateBuckets(stopwatch); long value = split.runningFor(); if (buckets == null) { // Warming up getOrCreateBucketsValues(stopwatch).add(value); } else { // Warm buckets.addValue(value); buckets.log(split); } }
java
@Override protected void onStopwatchSplit(Stopwatch stopwatch, Split split) { Buckets buckets = getOrCreateBuckets(stopwatch); long value = split.runningFor(); if (buckets == null) { // Warming up getOrCreateBucketsValues(stopwatch).add(value); } else { // Warm buckets.addValue(value); buckets.log(split); } }
[ "@", "Override", "protected", "void", "onStopwatchSplit", "(", "Stopwatch", "stopwatch", ",", "Split", "split", ")", "{", "Buckets", "buckets", "=", "getOrCreateBuckets", "(", "stopwatch", ")", ";", "long", "value", "=", "split", ".", "runningFor", "(", ")", ";", "if", "(", "buckets", "==", "null", ")", "{", "// Warming up\r", "getOrCreateBucketsValues", "(", "stopwatch", ")", ".", "add", "(", "value", ")", ";", "}", "else", "{", "// Warm\r", "buckets", ".", "addValue", "(", "value", ")", ";", "buckets", ".", "log", "(", "split", ")", ";", "}", "}" ]
Called when there is a new split on a Stopwatch, either {@link #onStopwatchStop} or {@link #onStopwatchAdd}. If buckets have been initialized, the value is added to appropriate bucket. Else if stopwatch is warming up value is added to value list.
[ "Called", "when", "there", "is", "a", "new", "split", "on", "a", "Stopwatch", "either", "{" ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/callback/quantiles/AutoQuantilesCallback.java#L151-L163
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java
StringUtilities.checkSameName
public static String checkSameName( List<String> strings, String string ) { """ Checks if the list of strings supplied contains the supplied string. <p>If the string is contained it changes the name by adding a number. <p>The spaces are trimmed away before performing name equality. @param strings the list of existing strings. @param string the proposed new string, to be changed if colliding. @return the new non-colliding name for the string. """ int index = 1; for( int i = 0; i < strings.size(); i++ ) { if (index == 10000) { // something odd is going on throw new RuntimeException(); } String existingString = strings.get(i); existingString = existingString.trim(); if (existingString.trim().equals(string.trim())) { // name exists, change the name of the entering if (string.endsWith(")")) { string = string.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { string = string + " (" + (index++) + ")"; } // start again i = 0; } } return string; }
java
public static String checkSameName( List<String> strings, String string ) { int index = 1; for( int i = 0; i < strings.size(); i++ ) { if (index == 10000) { // something odd is going on throw new RuntimeException(); } String existingString = strings.get(i); existingString = existingString.trim(); if (existingString.trim().equals(string.trim())) { // name exists, change the name of the entering if (string.endsWith(")")) { string = string.trim().replaceFirst("\\([0-9]+\\)$", "(" + (index++) + ")"); } else { string = string + " (" + (index++) + ")"; } // start again i = 0; } } return string; }
[ "public", "static", "String", "checkSameName", "(", "List", "<", "String", ">", "strings", ",", "String", "string", ")", "{", "int", "index", "=", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "strings", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "index", "==", "10000", ")", "{", "// something odd is going on", "throw", "new", "RuntimeException", "(", ")", ";", "}", "String", "existingString", "=", "strings", ".", "get", "(", "i", ")", ";", "existingString", "=", "existingString", ".", "trim", "(", ")", ";", "if", "(", "existingString", ".", "trim", "(", ")", ".", "equals", "(", "string", ".", "trim", "(", ")", ")", ")", "{", "// name exists, change the name of the entering", "if", "(", "string", ".", "endsWith", "(", "\")\"", ")", ")", "{", "string", "=", "string", ".", "trim", "(", ")", ".", "replaceFirst", "(", "\"\\\\([0-9]+\\\\)$\"", ",", "\"(\"", "+", "(", "index", "++", ")", "+", "\")\"", ")", ";", "}", "else", "{", "string", "=", "string", "+", "\" (\"", "+", "(", "index", "++", ")", "+", "\")\"", ";", "}", "// start again", "i", "=", "0", ";", "}", "}", "return", "string", ";", "}" ]
Checks if the list of strings supplied contains the supplied string. <p>If the string is contained it changes the name by adding a number. <p>The spaces are trimmed away before performing name equality. @param strings the list of existing strings. @param string the proposed new string, to be changed if colliding. @return the new non-colliding name for the string.
[ "Checks", "if", "the", "list", "of", "strings", "supplied", "contains", "the", "supplied", "string", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/StringUtilities.java#L47-L68
audit4j/audit4j-core
src/main/java/org/audit4j/core/util/EncryptionUtil.java
EncryptionUtil.getInstance
public static EncryptionUtil getInstance(String key, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { """ Gets the Encryptor. @param key the key @param salt the salt @return the Encryptor @throws NoSuchAlgorithmException the no such algorithm exception @throws UnsupportedEncodingException the unsupported encoding exception @throws InvalidKeySpecException the invalid key spec exception """ if (instance == null) { synchronized (EncryptionUtil.class) { if (instance == null) { instance = new EncryptionUtil(); generateKeyIfNotAvailable(key, salt); } } } return instance; }
java
public static EncryptionUtil getInstance(String key, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { if (instance == null) { synchronized (EncryptionUtil.class) { if (instance == null) { instance = new EncryptionUtil(); generateKeyIfNotAvailable(key, salt); } } } return instance; }
[ "public", "static", "EncryptionUtil", "getInstance", "(", "String", "key", ",", "String", "salt", ")", "throws", "NoSuchAlgorithmException", ",", "UnsupportedEncodingException", ",", "InvalidKeySpecException", "{", "if", "(", "instance", "==", "null", ")", "{", "synchronized", "(", "EncryptionUtil", ".", "class", ")", "{", "if", "(", "instance", "==", "null", ")", "{", "instance", "=", "new", "EncryptionUtil", "(", ")", ";", "generateKeyIfNotAvailable", "(", "key", ",", "salt", ")", ";", "}", "}", "}", "return", "instance", ";", "}" ]
Gets the Encryptor. @param key the key @param salt the salt @return the Encryptor @throws NoSuchAlgorithmException the no such algorithm exception @throws UnsupportedEncodingException the unsupported encoding exception @throws InvalidKeySpecException the invalid key spec exception
[ "Gets", "the", "Encryptor", "." ]
train
https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/util/EncryptionUtil.java#L173-L184
jsurfer/JsonSurfer
jsurfer-core/src/main/java/org/jsfr/json/JsonSurfer.java
JsonSurfer.createResumableParser
@Deprecated public ResumableParser createResumableParser(Reader json, SurfingConfiguration configuration) { """ Create resumable parser @param json Json source @param configuration SurfingConfiguration @return Resumable parser @deprecated use {@link #createResumableParser(InputStream, SurfingConfiguration)} instead """ ensureSetting(configuration); return jsonParserAdapter.createResumableParser(json, new SurfingContext(configuration)); }
java
@Deprecated public ResumableParser createResumableParser(Reader json, SurfingConfiguration configuration) { ensureSetting(configuration); return jsonParserAdapter.createResumableParser(json, new SurfingContext(configuration)); }
[ "@", "Deprecated", "public", "ResumableParser", "createResumableParser", "(", "Reader", "json", ",", "SurfingConfiguration", "configuration", ")", "{", "ensureSetting", "(", "configuration", ")", ";", "return", "jsonParserAdapter", ".", "createResumableParser", "(", "json", ",", "new", "SurfingContext", "(", "configuration", ")", ")", ";", "}" ]
Create resumable parser @param json Json source @param configuration SurfingConfiguration @return Resumable parser @deprecated use {@link #createResumableParser(InputStream, SurfingConfiguration)} instead
[ "Create", "resumable", "parser" ]
train
https://github.com/jsurfer/JsonSurfer/blob/52bd75a453338b86e115092803da140bf99cee62/jsurfer-core/src/main/java/org/jsfr/json/JsonSurfer.java#L225-L229
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java
CPMeasurementUnitPersistenceImpl.fetchByUUID_G
@Override public CPMeasurementUnit fetchByUUID_G(String uuid, long groupId) { """ Returns the cp measurement unit where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param uuid the uuid @param groupId the group ID @return the matching cp measurement unit, or <code>null</code> if a matching cp measurement unit could not be found """ return fetchByUUID_G(uuid, groupId, true); }
java
@Override public CPMeasurementUnit fetchByUUID_G(String uuid, long groupId) { return fetchByUUID_G(uuid, groupId, true); }
[ "@", "Override", "public", "CPMeasurementUnit", "fetchByUUID_G", "(", "String", "uuid", ",", "long", "groupId", ")", "{", "return", "fetchByUUID_G", "(", "uuid", ",", "groupId", ",", "true", ")", ";", "}" ]
Returns the cp measurement unit where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. @param uuid the uuid @param groupId the group ID @return the matching cp measurement unit, or <code>null</code> if a matching cp measurement unit could not be found
[ "Returns", "the", "cp", "measurement", "unit", "where", "uuid", "=", "&#63", ";", "and", "groupId", "=", "&#63", ";", "or", "returns", "<code", ">", "null<", "/", "code", ">", "if", "it", "could", "not", "be", "found", ".", "Uses", "the", "finder", "cache", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L703-L706
shekhargulati/strman-java
src/main/java/strman/Strman.java
Strman.prependArray
public static String prependArray(final String value, final String[] prepends) { """ Return a new String starting with prepends @param value The input String @param prepends Strings to prepend @return The prepended String """ validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); if (prepends == null || prepends.length == 0) { return value; } StringJoiner joiner = new StringJoiner(""); for (String prepend : prepends) { joiner.add(prepend); } return joiner.toString() + value; }
java
public static String prependArray(final String value, final String[] prepends) { validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); if (prepends == null || prepends.length == 0) { return value; } StringJoiner joiner = new StringJoiner(""); for (String prepend : prepends) { joiner.add(prepend); } return joiner.toString() + value; }
[ "public", "static", "String", "prependArray", "(", "final", "String", "value", ",", "final", "String", "[", "]", "prepends", ")", "{", "validate", "(", "value", ",", "NULL_STRING_PREDICATE", ",", "NULL_STRING_MSG_SUPPLIER", ")", ";", "if", "(", "prepends", "==", "null", "||", "prepends", ".", "length", "==", "0", ")", "{", "return", "value", ";", "}", "StringJoiner", "joiner", "=", "new", "StringJoiner", "(", "\"\"", ")", ";", "for", "(", "String", "prepend", ":", "prepends", ")", "{", "joiner", ".", "add", "(", "prepend", ")", ";", "}", "return", "joiner", ".", "toString", "(", ")", "+", "value", ";", "}" ]
Return a new String starting with prepends @param value The input String @param prepends Strings to prepend @return The prepended String
[ "Return", "a", "new", "String", "starting", "with", "prepends" ]
train
https://github.com/shekhargulati/strman-java/blob/d0c2a10a6273fd6082f084e95156653ca55ce1be/src/main/java/strman/Strman.java#L693-L703
chhh/MSFTBX
MSFileToolbox/src/main/java/umich/ms/fileio/filetypes/mzxml/MZXMLPeaksDecoder.java
MZXMLPeaksDecoder.decode
public static DecodedData decode(byte[] bytesIn, int precision, PeaksCompression compression) throws FileParsingException, IOException, DataFormatException { """ Convenience shortcut, which assumes the whole {@code bytesIn} array is useful data. """ return decode(bytesIn, bytesIn.length, precision, compression); }
java
public static DecodedData decode(byte[] bytesIn, int precision, PeaksCompression compression) throws FileParsingException, IOException, DataFormatException { return decode(bytesIn, bytesIn.length, precision, compression); }
[ "public", "static", "DecodedData", "decode", "(", "byte", "[", "]", "bytesIn", ",", "int", "precision", ",", "PeaksCompression", "compression", ")", "throws", "FileParsingException", ",", "IOException", ",", "DataFormatException", "{", "return", "decode", "(", "bytesIn", ",", "bytesIn", ".", "length", ",", "precision", ",", "compression", ")", ";", "}" ]
Convenience shortcut, which assumes the whole {@code bytesIn} array is useful data.
[ "Convenience", "shortcut", "which", "assumes", "the", "whole", "{" ]
train
https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/fileio/filetypes/mzxml/MZXMLPeaksDecoder.java#L42-L45
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java
CmsListItemWidget.ensureOpenCloseAdditionalInfo
protected void ensureOpenCloseAdditionalInfo() { """ Ensures the open close button for the additional info list is present.<p> """ if (m_openClose == null) { m_openClose = new CmsPushButton(I_CmsButton.TRIANGLE_RIGHT, I_CmsButton.TRIANGLE_DOWN); m_openClose.setButtonStyle(ButtonStyle.FONT_ICON, null); m_openClose.setSize(Size.small); m_titleBox.insert(m_openClose, 0); m_openClose.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { setAdditionalInfoVisible(!getElement().getClassName().contains(CmsListItemWidget.OPENCLASS)); CmsDomUtil.resizeAncestor(CmsListItemWidget.this); } }); } }
java
protected void ensureOpenCloseAdditionalInfo() { if (m_openClose == null) { m_openClose = new CmsPushButton(I_CmsButton.TRIANGLE_RIGHT, I_CmsButton.TRIANGLE_DOWN); m_openClose.setButtonStyle(ButtonStyle.FONT_ICON, null); m_openClose.setSize(Size.small); m_titleBox.insert(m_openClose, 0); m_openClose.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { setAdditionalInfoVisible(!getElement().getClassName().contains(CmsListItemWidget.OPENCLASS)); CmsDomUtil.resizeAncestor(CmsListItemWidget.this); } }); } }
[ "protected", "void", "ensureOpenCloseAdditionalInfo", "(", ")", "{", "if", "(", "m_openClose", "==", "null", ")", "{", "m_openClose", "=", "new", "CmsPushButton", "(", "I_CmsButton", ".", "TRIANGLE_RIGHT", ",", "I_CmsButton", ".", "TRIANGLE_DOWN", ")", ";", "m_openClose", ".", "setButtonStyle", "(", "ButtonStyle", ".", "FONT_ICON", ",", "null", ")", ";", "m_openClose", ".", "setSize", "(", "Size", ".", "small", ")", ";", "m_titleBox", ".", "insert", "(", "m_openClose", ",", "0", ")", ";", "m_openClose", ".", "addClickHandler", "(", "new", "ClickHandler", "(", ")", "{", "/**\n * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent)\n */", "public", "void", "onClick", "(", "ClickEvent", "event", ")", "{", "setAdditionalInfoVisible", "(", "!", "getElement", "(", ")", ".", "getClassName", "(", ")", ".", "contains", "(", "CmsListItemWidget", ".", "OPENCLASS", ")", ")", ";", "CmsDomUtil", ".", "resizeAncestor", "(", "CmsListItemWidget", ".", "this", ")", ";", "}", "}", ")", ";", "}", "}" ]
Ensures the open close button for the additional info list is present.<p>
[ "Ensures", "the", "open", "close", "button", "for", "the", "additional", "info", "list", "is", "present", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java#L1071-L1090
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java
AtomWriter.writeEntry
public void writeEntry(Object entity, String requestContextURL) throws ODataRenderException { """ <p> Write a single entity to the XML stream. </p> <p> <b>Note:</b> Make sure {@link AtomWriter#startDocument()} has been previously invoked to start the XML stream document, and {@link AtomWriter#endDocument()} is invoked after to end it. </p> @param entity The entity to fill in the XML stream. It can not be {@code null}. @param requestContextURL The 'Context URL' to write for the feed. It can not {@code null}. @throws ODataRenderException In case it is not possible to write to the XML stream. """ checkNotNull(entity); this.contextURL = checkNotNull(requestContextURL); try { writeEntry(entity, false); } catch (XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e) { LOG.error("Not possible to render single entity stream XML"); throw new ODataRenderException("Not possible to render single entity stream XML: ", e); } }
java
public void writeEntry(Object entity, String requestContextURL) throws ODataRenderException { checkNotNull(entity); this.contextURL = checkNotNull(requestContextURL); try { writeEntry(entity, false); } catch (XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e) { LOG.error("Not possible to render single entity stream XML"); throw new ODataRenderException("Not possible to render single entity stream XML: ", e); } }
[ "public", "void", "writeEntry", "(", "Object", "entity", ",", "String", "requestContextURL", ")", "throws", "ODataRenderException", "{", "checkNotNull", "(", "entity", ")", ";", "this", ".", "contextURL", "=", "checkNotNull", "(", "requestContextURL", ")", ";", "try", "{", "writeEntry", "(", "entity", ",", "false", ")", ";", "}", "catch", "(", "XMLStreamException", "|", "IllegalAccessException", "|", "NoSuchFieldException", "|", "ODataEdmException", "e", ")", "{", "LOG", ".", "error", "(", "\"Not possible to render single entity stream XML\"", ")", ";", "throw", "new", "ODataRenderException", "(", "\"Not possible to render single entity stream XML: \"", ",", "e", ")", ";", "}", "}" ]
<p> Write a single entity to the XML stream. </p> <p> <b>Note:</b> Make sure {@link AtomWriter#startDocument()} has been previously invoked to start the XML stream document, and {@link AtomWriter#endDocument()} is invoked after to end it. </p> @param entity The entity to fill in the XML stream. It can not be {@code null}. @param requestContextURL The 'Context URL' to write for the feed. It can not {@code null}. @throws ODataRenderException In case it is not possible to write to the XML stream.
[ "<p", ">", "Write", "a", "single", "entity", "to", "the", "XML", "stream", ".", "<", "/", "p", ">", "<p", ">", "<b", ">", "Note", ":", "<", "/", "b", ">", "Make", "sure", "{", "@link", "AtomWriter#startDocument", "()", "}", "has", "been", "previously", "invoked", "to", "start", "the", "XML", "stream", "document", "and", "{", "@link", "AtomWriter#endDocument", "()", "}", "is", "invoked", "after", "to", "end", "it", ".", "<", "/", "p", ">" ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java#L284-L296
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/ir/transform/AbstractElementTransformer.java
AbstractElementTransformer.maybeGetFromEnclosingFunction
private IRExpression maybeGetFromEnclosingFunction( ICompilableType gsClass, TypeVariableType type, String strTypeVarField ) { """ An anonymous class enclosed in a generic function has as a synthetic field the type parameter[s] from the function. """ if( gsClass.isAnonymous() ) { IDynamicFunctionSymbol dfs = getEnclosingDFS( gsClass ); if( dfs != null && dfs != getEnclosingDFS( gsClass.getEnclosingType() ) ) { for( IGenericTypeVariable gv : getTypeVarsForDFS( dfs ) ) { if( gv.getName().equals( type.getName() ) ) { return getInstanceField( gsClass, strTypeVarField, getDescriptor( LazyTypeResolver.class ), AccessibilityUtil.forTypeParameter(), pushThisOrOuter( gsClass ) ); } } } } return null; }
java
private IRExpression maybeGetFromEnclosingFunction( ICompilableType gsClass, TypeVariableType type, String strTypeVarField ) { if( gsClass.isAnonymous() ) { IDynamicFunctionSymbol dfs = getEnclosingDFS( gsClass ); if( dfs != null && dfs != getEnclosingDFS( gsClass.getEnclosingType() ) ) { for( IGenericTypeVariable gv : getTypeVarsForDFS( dfs ) ) { if( gv.getName().equals( type.getName() ) ) { return getInstanceField( gsClass, strTypeVarField, getDescriptor( LazyTypeResolver.class ), AccessibilityUtil.forTypeParameter(), pushThisOrOuter( gsClass ) ); } } } } return null; }
[ "private", "IRExpression", "maybeGetFromEnclosingFunction", "(", "ICompilableType", "gsClass", ",", "TypeVariableType", "type", ",", "String", "strTypeVarField", ")", "{", "if", "(", "gsClass", ".", "isAnonymous", "(", ")", ")", "{", "IDynamicFunctionSymbol", "dfs", "=", "getEnclosingDFS", "(", "gsClass", ")", ";", "if", "(", "dfs", "!=", "null", "&&", "dfs", "!=", "getEnclosingDFS", "(", "gsClass", ".", "getEnclosingType", "(", ")", ")", ")", "{", "for", "(", "IGenericTypeVariable", "gv", ":", "getTypeVarsForDFS", "(", "dfs", ")", ")", "{", "if", "(", "gv", ".", "getName", "(", ")", ".", "equals", "(", "type", ".", "getName", "(", ")", ")", ")", "{", "return", "getInstanceField", "(", "gsClass", ",", "strTypeVarField", ",", "getDescriptor", "(", "LazyTypeResolver", ".", "class", ")", ",", "AccessibilityUtil", ".", "forTypeParameter", "(", ")", ",", "pushThisOrOuter", "(", "gsClass", ")", ")", ";", "}", "}", "}", "}", "return", "null", ";", "}" ]
An anonymous class enclosed in a generic function has as a synthetic field the type parameter[s] from the function.
[ "An", "anonymous", "class", "enclosed", "in", "a", "generic", "function", "has", "as", "a", "synthetic", "field", "the", "type", "parameter", "[", "s", "]", "from", "the", "function", "." ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/ir/transform/AbstractElementTransformer.java#L2785-L2802
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java
Item.withFloat
public Item withFloat(String attrName, float val) { """ Sets the value of the specified attribute in the current item to the given value. """ checkInvalidAttrName(attrName); return withNumber(attrName, Float.valueOf(val)); }
java
public Item withFloat(String attrName, float val) { checkInvalidAttrName(attrName); return withNumber(attrName, Float.valueOf(val)); }
[ "public", "Item", "withFloat", "(", "String", "attrName", ",", "float", "val", ")", "{", "checkInvalidAttrName", "(", "attrName", ")", ";", "return", "withNumber", "(", "attrName", ",", "Float", ".", "valueOf", "(", "val", ")", ")", ";", "}" ]
Sets the value of the specified attribute in the current item to the given value.
[ "Sets", "the", "value", "of", "the", "specified", "attribute", "in", "the", "current", "item", "to", "the", "given", "value", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java#L314-L317
zaproxy/zaproxy
src/org/zaproxy/zap/control/AddOn.java
AddOn.versionMatches
private static boolean versionMatches(AddOn addOn, AddOnDep dependency) { """ Tells whether or not the given add-on version matches the one required by the dependency. <p> This methods is required to also check the {@code semVer} of the add-on, once removed it can match the version directly. @param addOn the add-on to check @param dependency the dependency @return {@code true} if the version matches, {@code false} otherwise. """ if (addOn.version.matches(dependency.getVersion())) { return true; } if (addOn.semVer != null && addOn.semVer.matches(dependency.getVersion())) { return true; } return false; }
java
private static boolean versionMatches(AddOn addOn, AddOnDep dependency) { if (addOn.version.matches(dependency.getVersion())) { return true; } if (addOn.semVer != null && addOn.semVer.matches(dependency.getVersion())) { return true; } return false; }
[ "private", "static", "boolean", "versionMatches", "(", "AddOn", "addOn", ",", "AddOnDep", "dependency", ")", "{", "if", "(", "addOn", ".", "version", ".", "matches", "(", "dependency", ".", "getVersion", "(", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "addOn", ".", "semVer", "!=", "null", "&&", "addOn", ".", "semVer", ".", "matches", "(", "dependency", ".", "getVersion", "(", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Tells whether or not the given add-on version matches the one required by the dependency. <p> This methods is required to also check the {@code semVer} of the add-on, once removed it can match the version directly. @param addOn the add-on to check @param dependency the dependency @return {@code true} if the version matches, {@code false} otherwise.
[ "Tells", "whether", "or", "not", "the", "given", "add", "-", "on", "version", "matches", "the", "one", "required", "by", "the", "dependency", ".", "<p", ">", "This", "methods", "is", "required", "to", "also", "check", "the", "{", "@code", "semVer", "}", "of", "the", "add", "-", "on", "once", "removed", "it", "can", "match", "the", "version", "directly", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/control/AddOn.java#L1424-L1434
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/colors/ConsistentColor.java
ConsistentColor.applyColorDeficiencyCorrection
private static double applyColorDeficiencyCorrection(double angle, Deficiency deficiency) { """ Apply correction for color vision deficiencies to an angle in the CbCr plane. @see <a href="https://xmpp.org/extensions/xep-0392.html#algorithm-cvd">§5.2: Corrections for Color Vision Deficiencies</a> @param angle angle in CbCr plane @param deficiency type of vision deficiency @return corrected angle in CbCr plane """ switch (deficiency) { case none: break; case redGreenBlindness: angle %= Math.PI; break; case blueBlindness: angle -= Math.PI / 2; angle %= Math.PI; angle += Math.PI / 2; break; } return angle; }
java
private static double applyColorDeficiencyCorrection(double angle, Deficiency deficiency) { switch (deficiency) { case none: break; case redGreenBlindness: angle %= Math.PI; break; case blueBlindness: angle -= Math.PI / 2; angle %= Math.PI; angle += Math.PI / 2; break; } return angle; }
[ "private", "static", "double", "applyColorDeficiencyCorrection", "(", "double", "angle", ",", "Deficiency", "deficiency", ")", "{", "switch", "(", "deficiency", ")", "{", "case", "none", ":", "break", ";", "case", "redGreenBlindness", ":", "angle", "%=", "Math", ".", "PI", ";", "break", ";", "case", "blueBlindness", ":", "angle", "-=", "Math", ".", "PI", "/", "2", ";", "angle", "%=", "Math", ".", "PI", ";", "angle", "+=", "Math", ".", "PI", "/", "2", ";", "break", ";", "}", "return", "angle", ";", "}" ]
Apply correction for color vision deficiencies to an angle in the CbCr plane. @see <a href="https://xmpp.org/extensions/xep-0392.html#algorithm-cvd">§5.2: Corrections for Color Vision Deficiencies</a> @param angle angle in CbCr plane @param deficiency type of vision deficiency @return corrected angle in CbCr plane
[ "Apply", "correction", "for", "color", "vision", "deficiencies", "to", "an", "angle", "in", "the", "CbCr", "plane", ".", "@see", "<a", "href", "=", "https", ":", "//", "xmpp", ".", "org", "/", "extensions", "/", "xep", "-", "0392", ".", "html#algorithm", "-", "cvd", ">", "§5", ".", "2", ":", "Corrections", "for", "Color", "Vision", "Deficiencies<", "/", "a", ">" ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/colors/ConsistentColor.java#L73-L87
alkacon/opencms-core
src/org/opencms/importexport/CmsImport.java
CmsImport.importData
public void importData(CmsImportParameters parameters) throws CmsImportExportException, CmsXmlException { """ Imports the resources and writes them to the cms VFS, even if there already exist files with the same name.<p> @param parameters the import parameters @throws CmsImportExportException if something goes wrong @throws CmsXmlException if the manifest of the import file could not be unmarshalled """ boolean run = false; try { // now find the correct import implementation Iterator<I_CmsImport> i = m_importImplementations.iterator(); while (i.hasNext()) { I_CmsImport importVersion = i.next(); if (importVersion.matches(parameters)) { m_report.println( Messages.get().container( Messages.RPT_IMPORT_VERSION_1, String.valueOf(importVersion.getVersion())), I_CmsReport.FORMAT_NOTE); // this is the correct import version, so call it for the import process importVersion.importData(m_cms, m_report, parameters); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_FLEX_PURGE_JSP_REPOSITORY, null)); run = true; break; } } if (!run) { m_report.println( Messages.get().container(Messages.RPT_IMPORT_DB_NO_CLASS_1, parameters.getPath()), I_CmsReport.FORMAT_WARNING); } } finally { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_OFFLINE_CACHES, Collections.<String, Object> emptyMap())); } }
java
public void importData(CmsImportParameters parameters) throws CmsImportExportException, CmsXmlException { boolean run = false; try { // now find the correct import implementation Iterator<I_CmsImport> i = m_importImplementations.iterator(); while (i.hasNext()) { I_CmsImport importVersion = i.next(); if (importVersion.matches(parameters)) { m_report.println( Messages.get().container( Messages.RPT_IMPORT_VERSION_1, String.valueOf(importVersion.getVersion())), I_CmsReport.FORMAT_NOTE); // this is the correct import version, so call it for the import process importVersion.importData(m_cms, m_report, parameters); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_FLEX_PURGE_JSP_REPOSITORY, null)); run = true; break; } } if (!run) { m_report.println( Messages.get().container(Messages.RPT_IMPORT_DB_NO_CLASS_1, parameters.getPath()), I_CmsReport.FORMAT_WARNING); } } finally { OpenCms.fireCmsEvent( new CmsEvent(I_CmsEventListener.EVENT_CLEAR_OFFLINE_CACHES, Collections.<String, Object> emptyMap())); } }
[ "public", "void", "importData", "(", "CmsImportParameters", "parameters", ")", "throws", "CmsImportExportException", ",", "CmsXmlException", "{", "boolean", "run", "=", "false", ";", "try", "{", "// now find the correct import implementation", "Iterator", "<", "I_CmsImport", ">", "i", "=", "m_importImplementations", ".", "iterator", "(", ")", ";", "while", "(", "i", ".", "hasNext", "(", ")", ")", "{", "I_CmsImport", "importVersion", "=", "i", ".", "next", "(", ")", ";", "if", "(", "importVersion", ".", "matches", "(", "parameters", ")", ")", "{", "m_report", ".", "println", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "RPT_IMPORT_VERSION_1", ",", "String", ".", "valueOf", "(", "importVersion", ".", "getVersion", "(", ")", ")", ")", ",", "I_CmsReport", ".", "FORMAT_NOTE", ")", ";", "// this is the correct import version, so call it for the import process", "importVersion", ".", "importData", "(", "m_cms", ",", "m_report", ",", "parameters", ")", ";", "OpenCms", ".", "fireCmsEvent", "(", "new", "CmsEvent", "(", "I_CmsEventListener", ".", "EVENT_FLEX_PURGE_JSP_REPOSITORY", ",", "null", ")", ")", ";", "run", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "run", ")", "{", "m_report", ".", "println", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "RPT_IMPORT_DB_NO_CLASS_1", ",", "parameters", ".", "getPath", "(", ")", ")", ",", "I_CmsReport", ".", "FORMAT_WARNING", ")", ";", "}", "}", "finally", "{", "OpenCms", ".", "fireCmsEvent", "(", "new", "CmsEvent", "(", "I_CmsEventListener", ".", "EVENT_CLEAR_OFFLINE_CACHES", ",", "Collections", ".", "<", "String", ",", "Object", ">", "emptyMap", "(", ")", ")", ")", ";", "}", "}" ]
Imports the resources and writes them to the cms VFS, even if there already exist files with the same name.<p> @param parameters the import parameters @throws CmsImportExportException if something goes wrong @throws CmsXmlException if the manifest of the import file could not be unmarshalled
[ "Imports", "the", "resources", "and", "writes", "them", "to", "the", "cms", "VFS", "even", "if", "there", "already", "exist", "files", "with", "the", "same", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsImport.java#L99-L130
uoa-group-applications/morc
src/main/java/nz/ac/auckland/morc/MorcBuilder.java
MorcBuilder.predicateMultiplier
public Builder predicateMultiplier(int count, Predicate... predicates) { """ Expect a repeat of the same predicates multiple times @param count The number of times to repeat these predicates (separate responses) @param predicates The set of response validators/predicates that will be used to validate consecutive responses """ for (int i = 0; i < count; i++) { addPredicates(predicates); } return self(); }
java
public Builder predicateMultiplier(int count, Predicate... predicates) { for (int i = 0; i < count; i++) { addPredicates(predicates); } return self(); }
[ "public", "Builder", "predicateMultiplier", "(", "int", "count", ",", "Predicate", "...", "predicates", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "addPredicates", "(", "predicates", ")", ";", "}", "return", "self", "(", ")", ";", "}" ]
Expect a repeat of the same predicates multiple times @param count The number of times to repeat these predicates (separate responses) @param predicates The set of response validators/predicates that will be used to validate consecutive responses
[ "Expect", "a", "repeat", "of", "the", "same", "predicates", "multiple", "times" ]
train
https://github.com/uoa-group-applications/morc/blob/3add6308b1fbfc98187364ac73007c83012ea8ba/src/main/java/nz/ac/auckland/morc/MorcBuilder.java#L141-L147
thorntail/thorntail
arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyDeclarationFactory.java
GradleDependencyDeclarationFactory.resolveDependencies
private static void resolveDependencies(Collection<ArtifactSpec> collection, ShrinkwrapArtifactResolvingHelper helper) { """ Resolve the given collection of ArtifactSpec references. This method attempts the resolution and ensures that the references are updated to be as complete as possible. @param collection the collection artifact specifications. """ // Identify the artifact specs that need resolution. // Ideally, there should be none at this point. collection.forEach(spec -> { if (spec.file == null) { // Resolve it. ArtifactSpec resolved = helper.resolve(spec); if (resolved != null) { spec.file = resolved.file; } else { throw new IllegalStateException("Unable to resolve artifact: " + spec.toString()); } } }); }
java
private static void resolveDependencies(Collection<ArtifactSpec> collection, ShrinkwrapArtifactResolvingHelper helper) { // Identify the artifact specs that need resolution. // Ideally, there should be none at this point. collection.forEach(spec -> { if (spec.file == null) { // Resolve it. ArtifactSpec resolved = helper.resolve(spec); if (resolved != null) { spec.file = resolved.file; } else { throw new IllegalStateException("Unable to resolve artifact: " + spec.toString()); } } }); }
[ "private", "static", "void", "resolveDependencies", "(", "Collection", "<", "ArtifactSpec", ">", "collection", ",", "ShrinkwrapArtifactResolvingHelper", "helper", ")", "{", "// Identify the artifact specs that need resolution.", "// Ideally, there should be none at this point.", "collection", ".", "forEach", "(", "spec", "->", "{", "if", "(", "spec", ".", "file", "==", "null", ")", "{", "// Resolve it.", "ArtifactSpec", "resolved", "=", "helper", ".", "resolve", "(", "spec", ")", ";", "if", "(", "resolved", "!=", "null", ")", "{", "spec", ".", "file", "=", "resolved", ".", "file", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Unable to resolve artifact: \"", "+", "spec", ".", "toString", "(", ")", ")", ";", "}", "}", "}", ")", ";", "}" ]
Resolve the given collection of ArtifactSpec references. This method attempts the resolution and ensures that the references are updated to be as complete as possible. @param collection the collection artifact specifications.
[ "Resolve", "the", "given", "collection", "of", "ArtifactSpec", "references", ".", "This", "method", "attempts", "the", "resolution", "and", "ensures", "that", "the", "references", "are", "updated", "to", "be", "as", "complete", "as", "possible", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyDeclarationFactory.java#L56-L70
msgpack/msgpack-java
msgpack-core/src/main/java/org/msgpack/core/buffer/MessageBuffer.java
MessageBuffer.newInstance
private static MessageBuffer newInstance(Constructor<?> constructor, Object... args) { """ Creates a new MessageBuffer instance @param constructor A MessageBuffer constructor @return new MessageBuffer instance """ try { // We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method. TypeProfile will be // generated to resolve one of the method references when two or more classes overrides the method. return (MessageBuffer) constructor.newInstance(args); } catch (InstantiationException e) { // should never happen throw new IllegalStateException(e); } catch (IllegalAccessException e) { // should never happen unless security manager restricts this reflection throw new IllegalStateException(e); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { // underlying constructor may throw RuntimeException throw (RuntimeException) e.getCause(); } else if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } // should never happen throw new IllegalStateException(e.getCause()); } }
java
private static MessageBuffer newInstance(Constructor<?> constructor, Object... args) { try { // We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method. TypeProfile will be // generated to resolve one of the method references when two or more classes overrides the method. return (MessageBuffer) constructor.newInstance(args); } catch (InstantiationException e) { // should never happen throw new IllegalStateException(e); } catch (IllegalAccessException e) { // should never happen unless security manager restricts this reflection throw new IllegalStateException(e); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { // underlying constructor may throw RuntimeException throw (RuntimeException) e.getCause(); } else if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } // should never happen throw new IllegalStateException(e.getCause()); } }
[ "private", "static", "MessageBuffer", "newInstance", "(", "Constructor", "<", "?", ">", "constructor", ",", "Object", "...", "args", ")", "{", "try", "{", "// We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method. TypeProfile will be", "// generated to resolve one of the method references when two or more classes overrides the method.", "return", "(", "MessageBuffer", ")", "constructor", ".", "newInstance", "(", "args", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "// should never happen", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "// should never happen unless security manager restricts this reflection", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "RuntimeException", ")", "{", "// underlying constructor may throw RuntimeException", "throw", "(", "RuntimeException", ")", "e", ".", "getCause", "(", ")", ";", "}", "else", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "Error", ")", "{", "throw", "(", "Error", ")", "e", ".", "getCause", "(", ")", ";", "}", "// should never happen", "throw", "new", "IllegalStateException", "(", "e", ".", "getCause", "(", ")", ")", ";", "}", "}" ]
Creates a new MessageBuffer instance @param constructor A MessageBuffer constructor @return new MessageBuffer instance
[ "Creates", "a", "new", "MessageBuffer", "instance" ]
train
https://github.com/msgpack/msgpack-java/blob/16e370e348215a72a14c210b42d448d513aee015/msgpack-core/src/main/java/org/msgpack/core/buffer/MessageBuffer.java#L303-L329
Azure/azure-sdk-for-java
sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/ManagedInstancesInner.java
ManagedInstancesInner.createOrUpdateAsync
public Observable<ManagedInstanceInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, ManagedInstanceInner parameters) { """ Creates or updates a managed instance. @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 parameters The requested managed instance resource state. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, parameters).map(new Func1<ServiceResponse<ManagedInstanceInner>, ManagedInstanceInner>() { @Override public ManagedInstanceInner call(ServiceResponse<ManagedInstanceInner> response) { return response.body(); } }); }
java
public Observable<ManagedInstanceInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, ManagedInstanceInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, parameters).map(new Func1<ServiceResponse<ManagedInstanceInner>, ManagedInstanceInner>() { @Override public ManagedInstanceInner call(ServiceResponse<ManagedInstanceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ManagedInstanceInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "managedInstanceName", ",", "ManagedInstanceInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "managedInstanceName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ManagedInstanceInner", ">", ",", "ManagedInstanceInner", ">", "(", ")", "{", "@", "Override", "public", "ManagedInstanceInner", "call", "(", "ServiceResponse", "<", "ManagedInstanceInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a managed instance. @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 parameters The requested managed instance resource state. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "managed", "instance", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/ManagedInstancesInner.java#L461-L468
stickfigure/batchfb
src/main/java/com/googlecode/batchfb/impl/ErrorDetectingWrapper.java
ErrorDetectingWrapper.throwCodeAndMessage
protected void throwCodeAndMessage(int code, String msg) { """ Throw the appropriate exception for the given legacy code and message. Always throws, never returns. """ switch (code) { case 0: case 101: case 102: case 190: throw new OAuthException(msg, "OAuthException", code, null, null, null); default: throw new ErrorFacebookException(msg + " (code " + code +")", null, code, null, null, null); } }
java
protected void throwCodeAndMessage(int code, String msg) { switch (code) { case 0: case 101: case 102: case 190: throw new OAuthException(msg, "OAuthException", code, null, null, null); default: throw new ErrorFacebookException(msg + " (code " + code +")", null, code, null, null, null); } }
[ "protected", "void", "throwCodeAndMessage", "(", "int", "code", ",", "String", "msg", ")", "{", "switch", "(", "code", ")", "{", "case", "0", ":", "case", "101", ":", "case", "102", ":", "case", "190", ":", "throw", "new", "OAuthException", "(", "msg", ",", "\"OAuthException\"", ",", "code", ",", "null", ",", "null", ",", "null", ")", ";", "default", ":", "throw", "new", "ErrorFacebookException", "(", "msg", "+", "\" (code \"", "+", "code", "+", "\")\"", ",", "null", ",", "code", ",", "null", ",", "null", ",", "null", ")", ";", "}", "}" ]
Throw the appropriate exception for the given legacy code and message. Always throws, never returns.
[ "Throw", "the", "appropriate", "exception", "for", "the", "given", "legacy", "code", "and", "message", ".", "Always", "throws", "never", "returns", "." ]
train
https://github.com/stickfigure/batchfb/blob/ceeda78aa6d8397eec032ab1d8997adb7378e9e2/src/main/java/com/googlecode/batchfb/impl/ErrorDetectingWrapper.java#L227-L236
jcuda/jcufft
JCufftJava/src/main/java/jcuda/jcufft/JCufft.java
JCufft.cufftPlan3d
public static int cufftPlan3d(cufftHandle plan, int nx, int ny, int nz, int type) { """ <pre> Creates a 3D FFT plan configuration according to specified signal sizes and data type. cufftResult cufftPlan3d( cufftHandle *plan, int nx, int ny, int nz, cufftType type ); This function is the same as cufftPlan2d() except that it takes a third size parameter nz. Input ---- plan Pointer to a cufftHandle object nx The transform size in the X dimension ny The transform size in the Y dimension nz The transform size in the Z dimension type The transform data type (e.g., CUFFT_R2C for real to complex) Output ---- plan Contains a CUFFT 3D plan handle value Return Values ---- CUFFT_SETUP_FAILED CUFFT library failed to initialize. CUFFT_INVALID_SIZE Parameter nx, ny, or nz is not a supported size. CUFFT_INVALID_TYPE The type parameter is not supported. CUFFT_ALLOC_FAILED Allocation of GPU resources for the plan failed. CUFFT_SUCCESS CUFFT successfully created the FFT plan. JCUFFT_INTERNAL_ERROR If an internal JCufft error occurred <pre> """ plan.setDimension(3); plan.setType(type); plan.setSize(nx, ny, nz); return checkResult(cufftPlan3dNative(plan, nx, ny, nz, type)); }
java
public static int cufftPlan3d(cufftHandle plan, int nx, int ny, int nz, int type) { plan.setDimension(3); plan.setType(type); plan.setSize(nx, ny, nz); return checkResult(cufftPlan3dNative(plan, nx, ny, nz, type)); }
[ "public", "static", "int", "cufftPlan3d", "(", "cufftHandle", "plan", ",", "int", "nx", ",", "int", "ny", ",", "int", "nz", ",", "int", "type", ")", "{", "plan", ".", "setDimension", "(", "3", ")", ";", "plan", ".", "setType", "(", "type", ")", ";", "plan", ".", "setSize", "(", "nx", ",", "ny", ",", "nz", ")", ";", "return", "checkResult", "(", "cufftPlan3dNative", "(", "plan", ",", "nx", ",", "ny", ",", "nz", ",", "type", ")", ")", ";", "}" ]
<pre> Creates a 3D FFT plan configuration according to specified signal sizes and data type. cufftResult cufftPlan3d( cufftHandle *plan, int nx, int ny, int nz, cufftType type ); This function is the same as cufftPlan2d() except that it takes a third size parameter nz. Input ---- plan Pointer to a cufftHandle object nx The transform size in the X dimension ny The transform size in the Y dimension nz The transform size in the Z dimension type The transform data type (e.g., CUFFT_R2C for real to complex) Output ---- plan Contains a CUFFT 3D plan handle value Return Values ---- CUFFT_SETUP_FAILED CUFFT library failed to initialize. CUFFT_INVALID_SIZE Parameter nx, ny, or nz is not a supported size. CUFFT_INVALID_TYPE The type parameter is not supported. CUFFT_ALLOC_FAILED Allocation of GPU resources for the plan failed. CUFFT_SUCCESS CUFFT successfully created the FFT plan. JCUFFT_INTERNAL_ERROR If an internal JCufft error occurred <pre>
[ "<pre", ">", "Creates", "a", "3D", "FFT", "plan", "configuration", "according", "to", "specified", "signal", "sizes", "and", "data", "type", "." ]
train
https://github.com/jcuda/jcufft/blob/833c87ffb0864f7ee7270fddef8af57f48939b3a/JCufftJava/src/main/java/jcuda/jcufft/JCufft.java#L295-L301
drewnoakes/metadata-extractor
Source/com/drew/imaging/ImageMetadataReader.java
ImageMetadataReader.readMetadata
@NotNull public static Metadata readMetadata(@NotNull final InputStream inputStream) throws ImageProcessingException, IOException { """ Reads metadata from an {@link InputStream}. @param inputStream a stream from which the file data may be read. The stream must be positioned at the beginning of the file's data. @return a populated {@link Metadata} object containing directories of tags with values and any processing errors. @throws ImageProcessingException if the file type is unknown, or for general processing errors. """ return readMetadata(inputStream, -1); }
java
@NotNull public static Metadata readMetadata(@NotNull final InputStream inputStream) throws ImageProcessingException, IOException { return readMetadata(inputStream, -1); }
[ "@", "NotNull", "public", "static", "Metadata", "readMetadata", "(", "@", "NotNull", "final", "InputStream", "inputStream", ")", "throws", "ImageProcessingException", ",", "IOException", "{", "return", "readMetadata", "(", "inputStream", ",", "-", "1", ")", ";", "}" ]
Reads metadata from an {@link InputStream}. @param inputStream a stream from which the file data may be read. The stream must be positioned at the beginning of the file's data. @return a populated {@link Metadata} object containing directories of tags with values and any processing errors. @throws ImageProcessingException if the file type is unknown, or for general processing errors.
[ "Reads", "metadata", "from", "an", "{", "@link", "InputStream", "}", "." ]
train
https://github.com/drewnoakes/metadata-extractor/blob/a958e0b61b50e590731b3be1dca8df8e21ebd43c/Source/com/drew/imaging/ImageMetadataReader.java#L101-L105