repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLIrreflexiveObjectPropertyAxiomImpl_CustomFieldSerializer.java
OWLIrreflexiveObjectPropertyAxiomImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLIrreflexiveObjectPropertyAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLIrreflexiveObjectPropertyAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLIrreflexiveObjectPropertyAxiomImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";",...
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLIrreflexiveObjectPropertyAxiomImpl_CustomFieldSerializer.java#L95-L98
larsga/Duke
duke-core/src/main/java/no/priv/garshol/duke/utils/StringUtils.java
StringUtils.normalizeWS
public static String normalizeWS(String value) { char[] tmp = new char[value.length()]; int pos = 0; boolean prevws = false; for (int ix = 0; ix < tmp.length; ix++) { char ch = value.charAt(ix); if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') { if (prevws && pos != 0) tmp[pos++] = ' '; tmp[pos++] = ch; prevws = false; } else prevws = true; } return new String(tmp, 0, pos); }
java
public static String normalizeWS(String value) { char[] tmp = new char[value.length()]; int pos = 0; boolean prevws = false; for (int ix = 0; ix < tmp.length; ix++) { char ch = value.charAt(ix); if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') { if (prevws && pos != 0) tmp[pos++] = ' '; tmp[pos++] = ch; prevws = false; } else prevws = true; } return new String(tmp, 0, pos); }
[ "public", "static", "String", "normalizeWS", "(", "String", "value", ")", "{", "char", "[", "]", "tmp", "=", "new", "char", "[", "value", ".", "length", "(", ")", "]", ";", "int", "pos", "=", "0", ";", "boolean", "prevws", "=", "false", ";", "for",...
Removes trailing and leading whitespace, and also reduces each sequence of internal whitespace to a single space.
[ "Removes", "trailing", "and", "leading", "whitespace", "and", "also", "reduces", "each", "sequence", "of", "internal", "whitespace", "to", "a", "single", "space", "." ]
train
https://github.com/larsga/Duke/blob/6263f9c6e984c26362a76241c7c7ea3bb4469bac/duke-core/src/main/java/no/priv/garshol/duke/utils/StringUtils.java#L31-L47
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/util/cache/BucketImpl.java
BucketImpl.removeByKey
public Element removeByKey(Object key, boolean dropRef) { int i = findIndexByKey(key); Element element = null; // Check if the object is in the cache if (i != -1) { element = (Element) get(i); // Objects must either be unpinned, or pinned only once // (presumably by the caller) if ((!dropRef && element.pinned > 0) || (dropRef && element.pinned > 1)) { throw new IllegalOperationException(key, element.pinned); } remove(i); } return element; }
java
public Element removeByKey(Object key, boolean dropRef) { int i = findIndexByKey(key); Element element = null; // Check if the object is in the cache if (i != -1) { element = (Element) get(i); // Objects must either be unpinned, or pinned only once // (presumably by the caller) if ((!dropRef && element.pinned > 0) || (dropRef && element.pinned > 1)) { throw new IllegalOperationException(key, element.pinned); } remove(i); } return element; }
[ "public", "Element", "removeByKey", "(", "Object", "key", ",", "boolean", "dropRef", ")", "{", "int", "i", "=", "findIndexByKey", "(", "key", ")", ";", "Element", "element", "=", "null", ";", "// Check if the object is in the cache", "if", "(", "i", "!=", "-...
Remove the object associated with the specified key from the bucket. Returns the Element holding the removed object. Optionally drops a reference on the object before removing it @param key key of the object element to be removed. @param dropRef true indicates a reference should be dropped @return the Element holding the removed object.
[ "Remove", "the", "object", "associated", "with", "the", "specified", "key", "from", "the", "bucket", ".", "Returns", "the", "Element", "holding", "the", "removed", "object", ".", "Optionally", "drops", "a", "reference", "on", "the", "object", "before", "removi...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/util/cache/BucketImpl.java#L157-L178
classgraph/classgraph
src/main/java/io/github/classgraph/ClasspathElement.java
ClasspathElement.maskClassfiles
void maskClassfiles(final int classpathIdx, final Set<String> classpathRelativePathsFound, final LogNode log) { if (!scanSpec.performScan) { // Should not happen throw new IllegalArgumentException("performScan is false"); } // Find relative paths that occur more than once in the classpath / module path. // Usually duplicate relative paths occur only between classpath / module path elements, not within, // but actually there is no restriction for paths within a zipfile to be unique, and in fact // zipfiles in the wild do contain the same classfiles multiple times with the same exact path, // e.g.: xmlbeans-2.6.0.jar!org/apache/xmlbeans/xml/stream/Location.class final List<Resource> whitelistedClassfileResourcesFiltered = new ArrayList<>( whitelistedClassfileResources.size()); boolean foundMasked = false; for (final Resource res : whitelistedClassfileResources) { final String pathRelativeToPackageRoot = res.getPath(); // Don't mask module-info.class or package-info.class, these are read for every module/package if (!pathRelativeToPackageRoot.equals("module-info.class") && !pathRelativeToPackageRoot.endsWith("/module-info.class") && !pathRelativeToPackageRoot.equals("package-info.class") && !pathRelativeToPackageRoot.endsWith("/package-info.class") // Check if pathRelativeToPackageRoot has been seen before && !classpathRelativePathsFound.add(pathRelativeToPackageRoot)) { // This relative path has been encountered more than once; // mask the second and subsequent occurrences of the path foundMasked = true; if (log != null) { log.log(String.format("%06d-1", classpathIdx), "Ignoring duplicate (masked) class " + JarUtils.classfilePathToClassName(pathRelativeToPackageRoot) + " found at " + res); } } else { whitelistedClassfileResourcesFiltered.add(res); } } if (foundMasked) { // Remove masked (duplicated) paths. N.B. this replaces the concurrent collection with a non-concurrent // collection, but this is the last time the collection is changed during a scan, and this method is // run from a single thread. whitelistedClassfileResources = whitelistedClassfileResourcesFiltered; } }
java
void maskClassfiles(final int classpathIdx, final Set<String> classpathRelativePathsFound, final LogNode log) { if (!scanSpec.performScan) { // Should not happen throw new IllegalArgumentException("performScan is false"); } // Find relative paths that occur more than once in the classpath / module path. // Usually duplicate relative paths occur only between classpath / module path elements, not within, // but actually there is no restriction for paths within a zipfile to be unique, and in fact // zipfiles in the wild do contain the same classfiles multiple times with the same exact path, // e.g.: xmlbeans-2.6.0.jar!org/apache/xmlbeans/xml/stream/Location.class final List<Resource> whitelistedClassfileResourcesFiltered = new ArrayList<>( whitelistedClassfileResources.size()); boolean foundMasked = false; for (final Resource res : whitelistedClassfileResources) { final String pathRelativeToPackageRoot = res.getPath(); // Don't mask module-info.class or package-info.class, these are read for every module/package if (!pathRelativeToPackageRoot.equals("module-info.class") && !pathRelativeToPackageRoot.endsWith("/module-info.class") && !pathRelativeToPackageRoot.equals("package-info.class") && !pathRelativeToPackageRoot.endsWith("/package-info.class") // Check if pathRelativeToPackageRoot has been seen before && !classpathRelativePathsFound.add(pathRelativeToPackageRoot)) { // This relative path has been encountered more than once; // mask the second and subsequent occurrences of the path foundMasked = true; if (log != null) { log.log(String.format("%06d-1", classpathIdx), "Ignoring duplicate (masked) class " + JarUtils.classfilePathToClassName(pathRelativeToPackageRoot) + " found at " + res); } } else { whitelistedClassfileResourcesFiltered.add(res); } } if (foundMasked) { // Remove masked (duplicated) paths. N.B. this replaces the concurrent collection with a non-concurrent // collection, but this is the last time the collection is changed during a scan, and this method is // run from a single thread. whitelistedClassfileResources = whitelistedClassfileResourcesFiltered; } }
[ "void", "maskClassfiles", "(", "final", "int", "classpathIdx", ",", "final", "Set", "<", "String", ">", "classpathRelativePathsFound", ",", "final", "LogNode", "log", ")", "{", "if", "(", "!", "scanSpec", ".", "performScan", ")", "{", "// Should not happen", "...
Apply relative path masking within this classpath resource -- remove relative paths that were found in an earlier classpath element. @param classpathIdx the classpath index @param classpathRelativePathsFound the classpath relative paths found @param log the log
[ "Apply", "relative", "path", "masking", "within", "this", "classpath", "resource", "--", "remove", "relative", "paths", "that", "were", "found", "in", "an", "earlier", "classpath", "element", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/ClasspathElement.java#L186-L225
burberius/eve-esi
src/main/java/net/troja/eve/esi/api/CorporationApi.java
CorporationApi.getCorporationsCorporationIdStructuresWithHttpInfo
public ApiResponse<List<CorporationStructuresResponse>> getCorporationsCorporationIdStructuresWithHttpInfo( Integer corporationId, String acceptLanguage, String datasource, String ifNoneMatch, String language, Integer page, String token) throws ApiException { com.squareup.okhttp.Call call = getCorporationsCorporationIdStructuresValidateBeforeCall(corporationId, acceptLanguage, datasource, ifNoneMatch, language, page, token, null); Type localVarReturnType = new TypeToken<List<CorporationStructuresResponse>>() { }.getType(); return apiClient.execute(call, localVarReturnType); }
java
public ApiResponse<List<CorporationStructuresResponse>> getCorporationsCorporationIdStructuresWithHttpInfo( Integer corporationId, String acceptLanguage, String datasource, String ifNoneMatch, String language, Integer page, String token) throws ApiException { com.squareup.okhttp.Call call = getCorporationsCorporationIdStructuresValidateBeforeCall(corporationId, acceptLanguage, datasource, ifNoneMatch, language, page, token, null); Type localVarReturnType = new TypeToken<List<CorporationStructuresResponse>>() { }.getType(); return apiClient.execute(call, localVarReturnType); }
[ "public", "ApiResponse", "<", "List", "<", "CorporationStructuresResponse", ">", ">", "getCorporationsCorporationIdStructuresWithHttpInfo", "(", "Integer", "corporationId", ",", "String", "acceptLanguage", ",", "String", "datasource", ",", "String", "ifNoneMatch", ",", "S...
Get corporation structures Get a list of corporation structures. This route&#39;s version includes the changes to structures detailed in this blog: https://www.eveonline.com/article/upwell-2.0-structures-changes-coming -on-february-13th --- This route is cached for up to 3600 seconds --- Requires one of the following EVE corporation role(s): Station_Manager SSO Scope: esi-corporations.read_structures.v1 @param corporationId An EVE corporation ID (required) @param acceptLanguage Language to use in the response (optional, default to en-us) @param datasource The server name you would like data from (optional, default to tranquility) @param ifNoneMatch ETag from a previous request. A 304 will be returned if this matches the current ETag (optional) @param language Language to use in the response, takes precedence over Accept-Language (optional, default to en-us) @param page Which page of results to return (optional, default to 1) @param token Access token to use if unable to set a header (optional) @return ApiResponse&lt;List&lt;CorporationStructuresResponse&gt;&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "corporation", "structures", "Get", "a", "list", "of", "corporation", "structures", ".", "This", "route&#39", ";", "s", "version", "includes", "the", "changes", "to", "structures", "detailed", "in", "this", "blog", ":", "https", ":", "//", "www", ".",...
train
https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/api/CorporationApi.java#L3556-L3564
OpenLiberty/open-liberty
dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/config/SSLConfigManager.java
SSLConfigManager.checkURLHostNameVerificationProperty
public synchronized void checkURLHostNameVerificationProperty(boolean reinitialize) { // enable/disable hostname verification String urlHostNameVerification = getGlobalProperty(Constants.SSLPROP_URL_HOSTNAME_VERIFICATION); if (urlHostNameVerification == null || urlHostNameVerification.equalsIgnoreCase("false") || urlHostNameVerification.equalsIgnoreCase("no")) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "com.ibm.ssl.performURLHostNameVerification disabled"); HostnameVerifier verifier = new HostnameVerifier() { @Override public boolean verify(String urlHostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(verifier); if (!reinitialize) { Tr.info(tc, "ssl.disable.url.hostname.verification.CWPKI0027I"); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "com.ibm.ssl.performURLHostNameVerification enabled"); } }
java
public synchronized void checkURLHostNameVerificationProperty(boolean reinitialize) { // enable/disable hostname verification String urlHostNameVerification = getGlobalProperty(Constants.SSLPROP_URL_HOSTNAME_VERIFICATION); if (urlHostNameVerification == null || urlHostNameVerification.equalsIgnoreCase("false") || urlHostNameVerification.equalsIgnoreCase("no")) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "com.ibm.ssl.performURLHostNameVerification disabled"); HostnameVerifier verifier = new HostnameVerifier() { @Override public boolean verify(String urlHostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(verifier); if (!reinitialize) { Tr.info(tc, "ssl.disable.url.hostname.verification.CWPKI0027I"); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "com.ibm.ssl.performURLHostNameVerification enabled"); } }
[ "public", "synchronized", "void", "checkURLHostNameVerificationProperty", "(", "boolean", "reinitialize", ")", "{", "// enable/disable hostname verification", "String", "urlHostNameVerification", "=", "getGlobalProperty", "(", "Constants", ".", "SSLPROP_URL_HOSTNAME_VERIFICATION", ...
* This method installs a hostname verification checker that defaults to not check the hostname. If it does not install this hostname verification checker, then any URL connections must have a certificate that matches the host that sent it. @param reinitialize *
[ "*", "This", "method", "installs", "a", "hostname", "verification", "checker", "that", "defaults", "to", "not", "check", "the", "hostname", ".", "If", "it", "does", "not", "install", "this", "hostname", "verification", "checker", "then", "any", "URL", "connect...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/config/SSLConfigManager.java#L1412-L1434
liaochong/spring-boot-starter-converter
src/main/java/com/github/liaochong/converter/core/BeanConverter.java
BeanConverter.convert
public static <T, U> U convert(T source, Class<U> targetClass) { return BeanConvertStrategy.convertBean(source, targetClass); }
java
public static <T, U> U convert(T source, Class<U> targetClass) { return BeanConvertStrategy.convertBean(source, targetClass); }
[ "public", "static", "<", "T", ",", "U", ">", "U", "convert", "(", "T", "source", ",", "Class", "<", "U", ">", "targetClass", ")", "{", "return", "BeanConvertStrategy", ".", "convertBean", "(", "source", ",", "targetClass", ")", ";", "}" ]
单个Bean转换 @param source 被转换对象 @param targetClass 需要转换到的类型 @param <T> 转换前的类型 @param <U> 转换后的类型 @return 结果
[ "单个Bean转换" ]
train
https://github.com/liaochong/spring-boot-starter-converter/blob/a36bea44bd23330a6f43b0372906a804a09285c5/src/main/java/com/github/liaochong/converter/core/BeanConverter.java#L125-L127
beihaifeiwu/dolphin
dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java
StringHelper.collapseQualifierBase
public static String collapseQualifierBase(String name, String qualifierBase) { if (name == null || !name.startsWith(qualifierBase)) { return collapse(name); } return collapseQualifier(qualifierBase, true) + name.substring(qualifierBase.length()); }
java
public static String collapseQualifierBase(String name, String qualifierBase) { if (name == null || !name.startsWith(qualifierBase)) { return collapse(name); } return collapseQualifier(qualifierBase, true) + name.substring(qualifierBase.length()); }
[ "public", "static", "String", "collapseQualifierBase", "(", "String", "name", ",", "String", "qualifierBase", ")", "{", "if", "(", "name", "==", "null", "||", "!", "name", ".", "startsWith", "(", "qualifierBase", ")", ")", "{", "return", "collapse", "(", "...
Cross between {@link #collapse} and {@link #partiallyUnqualify}. Functions much like {@link #collapse} except that only the qualifierBase is collapsed. For example, with a base of 'org.hibernate' the name 'org.hibernate.internal.util.StringHelper' would become 'o.h.util.StringHelper'. @param name The (potentially) qualified name. @param qualifierBase The qualifier base. @return The name itself if it does not begin with the qualifierBase, or the properly collapsed form otherwise.
[ "Cross", "between", "{", "@link", "#collapse", "}", "and", "{", "@link", "#partiallyUnqualify", "}", ".", "Functions", "much", "like", "{", "@link", "#collapse", "}", "except", "that", "only", "the", "qualifierBase", "is", "collapsed", ".", "For", "example", ...
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-mybatis-generator/src/main/java/com/freetmp/mbg/formatter/StringHelper.java#L286-L291
zaproxy/zaproxy
src/org/parosproxy/paros/view/MainFooterPanel.java
MainFooterPanel.createAlertLabel
private JLabel createAlertLabel(String toolTipText, URL imageUrl) throws NullPointerException { JLabel label = new JLabel("0", DisplayUtils.getScaledIcon(new ImageIcon(imageUrl)), JLabel.LEADING); label.setToolTipText(toolTipText); label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); return label; }
java
private JLabel createAlertLabel(String toolTipText, URL imageUrl) throws NullPointerException { JLabel label = new JLabel("0", DisplayUtils.getScaledIcon(new ImageIcon(imageUrl)), JLabel.LEADING); label.setToolTipText(toolTipText); label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); return label; }
[ "private", "JLabel", "createAlertLabel", "(", "String", "toolTipText", ",", "URL", "imageUrl", ")", "throws", "NullPointerException", "{", "JLabel", "label", "=", "new", "JLabel", "(", "\"0\"", ",", "DisplayUtils", ".", "getScaledIcon", "(", "new", "ImageIcon", ...
Creates a {@code JLabel} with text "0", an {@code ImageIcon} created from the specified URL, the specified tool tip text and an empty border that takes up 5 pixels to the right and left of the {@code JLabel}. @param toolTipText the tool tip text, if toolTipText is {@code null} no tool tip is displayed @param imageUrl the URL to the image @throws NullPointerException if imageUrl is {@code null}. @return the {@code JLabel} object @see JLabel#setToolTipText(String)
[ "Creates", "a", "{", "@code", "JLabel", "}", "with", "text", "0", "an", "{", "@code", "ImageIcon", "}", "created", "from", "the", "specified", "URL", "the", "specified", "tool", "tip", "text", "and", "an", "empty", "border", "that", "takes", "up", "5", ...
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/parosproxy/paros/view/MainFooterPanel.java#L221-L227
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/query/plan/PlanNode.java
PlanNode.findAllAtOrBelow
public List<PlanNode> findAllAtOrBelow( Traversal order, Type firstTypeToFind, Type... additionalTypesToFind ) { return findAllAtOrBelow(order, EnumSet.of(firstTypeToFind, additionalTypesToFind)); }
java
public List<PlanNode> findAllAtOrBelow( Traversal order, Type firstTypeToFind, Type... additionalTypesToFind ) { return findAllAtOrBelow(order, EnumSet.of(firstTypeToFind, additionalTypesToFind)); }
[ "public", "List", "<", "PlanNode", ">", "findAllAtOrBelow", "(", "Traversal", "order", ",", "Type", "firstTypeToFind", ",", "Type", "...", "additionalTypesToFind", ")", "{", "return", "findAllAtOrBelow", "(", "order", ",", "EnumSet", ".", "of", "(", "firstTypeTo...
Find all of the nodes with one of the specified types that are at or below this node. @param order the order to traverse; may not be null @param firstTypeToFind the first type of node to find; may not be null @param additionalTypesToFind the additional types of node to find; may not be null @return the collection of nodes that are at or below this node that all have one of the supplied types; never null but possibly empty
[ "Find", "all", "of", "the", "nodes", "with", "one", "of", "the", "specified", "types", "that", "are", "at", "or", "below", "this", "node", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/query/plan/PlanNode.java#L1399-L1403
HeidelTime/heideltime
src/de/unihd/dbs/uima/annotator/treetagger/TreeTaggerProperties.java
TreeTaggerProperties.getTokenizationProcess
@Deprecated public Process getTokenizationProcess(File inputFile) throws IOException { // assemble a command line for the tokenization script and execute it ArrayList<String> command = new ArrayList<String>(); command.add("perl"); if(this.utf8Switch != "") command.add(this.utf8Switch); command.add(this.rootPath + this.fileSeparator + "cmd" + this.fileSeparator + this.tokScriptName); if(this.languageSwitch != "") command.add(this.languageSwitch); if(new File(this.rootPath + this.fileSeparator + "lib" + this.fileSeparator, this.abbFileName).exists()) { command.add("-a"); command.add(this.rootPath + this.fileSeparator + "lib" + this.fileSeparator + this.abbFileName); } command.add(inputFile.getAbsolutePath()); String[] commandStr = new String[command.size()]; command.toArray(commandStr); Process p = Runtime.getRuntime().exec(commandStr); return p; }
java
@Deprecated public Process getTokenizationProcess(File inputFile) throws IOException { // assemble a command line for the tokenization script and execute it ArrayList<String> command = new ArrayList<String>(); command.add("perl"); if(this.utf8Switch != "") command.add(this.utf8Switch); command.add(this.rootPath + this.fileSeparator + "cmd" + this.fileSeparator + this.tokScriptName); if(this.languageSwitch != "") command.add(this.languageSwitch); if(new File(this.rootPath + this.fileSeparator + "lib" + this.fileSeparator, this.abbFileName).exists()) { command.add("-a"); command.add(this.rootPath + this.fileSeparator + "lib" + this.fileSeparator + this.abbFileName); } command.add(inputFile.getAbsolutePath()); String[] commandStr = new String[command.size()]; command.toArray(commandStr); Process p = Runtime.getRuntime().exec(commandStr); return p; }
[ "@", "Deprecated", "public", "Process", "getTokenizationProcess", "(", "File", "inputFile", ")", "throws", "IOException", "{", "// assemble a command line for the tokenization script and execute it", "ArrayList", "<", "String", ">", "command", "=", "new", "ArrayList", "<", ...
This method creates a process with some parameters for the tokenizer script. Deprecated: We use TreeTaggerTokenizer in the same package nowadays which implements the utf8-tokenize.perl script from the TreeTagger package. This fixes some issues with Perl's Unicode handling. @param inputFile @return @throws IOException
[ "This", "method", "creates", "a", "process", "with", "some", "parameters", "for", "the", "tokenizer", "script", "." ]
train
https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/de/unihd/dbs/uima/annotator/treetagger/TreeTaggerProperties.java#L59-L80
nicoulaj/checksum-maven-plugin
src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/FilesMojo.java
FilesMojo.getFilesToProcess
@Override protected List<ChecksumFile> getFilesToProcess() { final List<ChecksumFile> filesToProcess = new ArrayList<ChecksumFile>(); for ( final FileSet fileSet : fileSets ) { final DirectoryScanner scanner = new DirectoryScanner(); final String fileSetDirectory = (new File( fileSet.getDirectory() ) ).getPath(); scanner.setBasedir( fileSetDirectory ); String[] includes; if ( fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty() ) { final List<String> fileSetIncludes = fileSet.getIncludes(); includes = fileSetIncludes.toArray( new String[fileSetIncludes.size()] ); } else { includes = DEFAULT_INCLUDES; } scanner.setIncludes( includes ); if ( fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty() ) { final List<String> fileSetExcludes = fileSet.getExcludes(); scanner.setExcludes( fileSetExcludes.toArray( new String[fileSetExcludes.size()] ) ); } scanner.addDefaultExcludes(); scanner.scan(); for ( String filePath : scanner.getIncludedFiles() ) { filesToProcess.add( new ChecksumFile( (new File( fileSetDirectory ) ).getPath(), new File( fileSetDirectory, filePath ), null, null ) ); } } return filesToProcess; }
java
@Override protected List<ChecksumFile> getFilesToProcess() { final List<ChecksumFile> filesToProcess = new ArrayList<ChecksumFile>(); for ( final FileSet fileSet : fileSets ) { final DirectoryScanner scanner = new DirectoryScanner(); final String fileSetDirectory = (new File( fileSet.getDirectory() ) ).getPath(); scanner.setBasedir( fileSetDirectory ); String[] includes; if ( fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty() ) { final List<String> fileSetIncludes = fileSet.getIncludes(); includes = fileSetIncludes.toArray( new String[fileSetIncludes.size()] ); } else { includes = DEFAULT_INCLUDES; } scanner.setIncludes( includes ); if ( fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty() ) { final List<String> fileSetExcludes = fileSet.getExcludes(); scanner.setExcludes( fileSetExcludes.toArray( new String[fileSetExcludes.size()] ) ); } scanner.addDefaultExcludes(); scanner.scan(); for ( String filePath : scanner.getIncludedFiles() ) { filesToProcess.add( new ChecksumFile( (new File( fileSetDirectory ) ).getPath(), new File( fileSetDirectory, filePath ), null, null ) ); } } return filesToProcess; }
[ "@", "Override", "protected", "List", "<", "ChecksumFile", ">", "getFilesToProcess", "(", ")", "{", "final", "List", "<", "ChecksumFile", ">", "filesToProcess", "=", "new", "ArrayList", "<", "ChecksumFile", ">", "(", ")", ";", "for", "(", "final", "FileSet",...
Build the list of files from which digests should be generated. @return the list of files that should be processed.
[ "Build", "the", "list", "of", "files", "from", "which", "digests", "should", "be", "generated", "." ]
train
https://github.com/nicoulaj/checksum-maven-plugin/blob/8d8feab8a0a34e24ae41621e7372be6387e1fe55/src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/FilesMojo.java#L167-L206
JOML-CI/JOML
src/org/joml/Matrix3f.java
Matrix3f.setLookAlong
public Matrix3f setLookAlong(Vector3fc dir, Vector3fc up) { return setLookAlong(dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z()); }
java
public Matrix3f setLookAlong(Vector3fc dir, Vector3fc up) { return setLookAlong(dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z()); }
[ "public", "Matrix3f", "setLookAlong", "(", "Vector3fc", "dir", ",", "Vector3fc", "up", ")", "{", "return", "setLookAlong", "(", "dir", ".", "x", "(", ")", ",", "dir", ".", "y", "(", ")", ",", "dir", ".", "z", "(", ")", ",", "up", ".", "x", "(", ...
Set this matrix to a rotation transformation to make <code>-z</code> point along <code>dir</code>. <p> In order to apply the lookalong transformation to any previous existing transformation, use {@link #lookAlong(Vector3fc, Vector3fc)}. @see #setLookAlong(Vector3fc, Vector3fc) @see #lookAlong(Vector3fc, Vector3fc) @param dir the direction in space to look along @param up the direction of 'up' @return this
[ "Set", "this", "matrix", "to", "a", "rotation", "transformation", "to", "make", "<code", ">", "-", "z<", "/", "code", ">", "point", "along", "<code", ">", "dir<", "/", "code", ">", ".", "<p", ">", "In", "order", "to", "apply", "the", "lookalong", "tr...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3f.java#L3148-L3150
cloudant/java-cloudant
cloudant-client/src/main/java/com/cloudant/client/api/Database.java
Database.getPermissions
public Map<String, EnumSet<Permissions>> getPermissions() { JsonObject perms = getPermissionsObject(); return client.getGson().getAdapter(DeserializationTypes.PERMISSIONS_MAP_TOKEN).fromJsonTree (perms); }
java
public Map<String, EnumSet<Permissions>> getPermissions() { JsonObject perms = getPermissionsObject(); return client.getGson().getAdapter(DeserializationTypes.PERMISSIONS_MAP_TOKEN).fromJsonTree (perms); }
[ "public", "Map", "<", "String", ",", "EnumSet", "<", "Permissions", ">", ">", "getPermissions", "(", ")", "{", "JsonObject", "perms", "=", "getPermissionsObject", "(", ")", ";", "return", "client", ".", "getGson", "(", ")", ".", "getAdapter", "(", "Deseria...
Returns the Permissions of this database. <p> Note this method is only applicable to databases that support the <a target="_blank" href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#authorization"> Cloudant authorization API </a> such as Cloudant DBaaS. For unsupported databases consider using the /db/_security endpoint. </p> @return the map of userNames to their Permissions @throws UnsupportedOperationException if called on a database that does not provide the Cloudant authorization API @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#roles" target="_blank">Roles</a> @see <a href="https://console.bluemix.net/docs/services/Cloudant/api/authorization.html#viewing-permissions" target="_blank">Viewing permissions</a>
[ "Returns", "the", "Permissions", "of", "this", "database", ".", "<p", ">", "Note", "this", "method", "is", "only", "applicable", "to", "databases", "that", "support", "the", "<a", "target", "=", "_blank", "href", "=", "https", ":", "//", "console", ".", ...
train
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-client/src/main/java/com/cloudant/client/api/Database.java#L230-L234
rundeck/rundeck
core/src/main/java/com/dtolabs/utils/Mapper.java
Mapper.mapValues
public static Map mapValues(Mapper mapper, Map map) { return mapValues(mapper, map, false); }
java
public static Map mapValues(Mapper mapper, Map map) { return mapValues(mapper, map, false); }
[ "public", "static", "Map", "mapValues", "(", "Mapper", "mapper", ",", "Map", "map", ")", "{", "return", "mapValues", "(", "mapper", ",", "map", ",", "false", ")", ";", "}" ]
Create a new Map by mapping all values from the original map and maintaining the original key. @param mapper a Mapper to map the values @param map an Map @return a new Map with values mapped
[ "Create", "a", "new", "Map", "by", "mapping", "all", "values", "from", "the", "original", "map", "and", "maintaining", "the", "original", "key", "." ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/utils/Mapper.java#L410-L412
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/DateTime.java
DateTime.setField
public DateTime setField(int field, int value) { final Calendar calendar = toCalendar(); calendar.set(field, value); DateTime dt = this; if (false == mutable) { dt = ObjectUtil.clone(this); } return dt.setTimeInternal(calendar.getTimeInMillis()); }
java
public DateTime setField(int field, int value) { final Calendar calendar = toCalendar(); calendar.set(field, value); DateTime dt = this; if (false == mutable) { dt = ObjectUtil.clone(this); } return dt.setTimeInternal(calendar.getTimeInMillis()); }
[ "public", "DateTime", "setField", "(", "int", "field", ",", "int", "value", ")", "{", "final", "Calendar", "calendar", "=", "toCalendar", "(", ")", ";", "calendar", ".", "set", "(", "field", ",", "value", ")", ";", "DateTime", "dt", "=", "this", ";", ...
设置日期的某个部分<br> 如果此对象为可变对象,返回自身,否则返回新对象,设置是否可变对象见{@link #setMutable(boolean)} @param field 表示日期的哪个部分的int值 {@link Calendar} @param value 值 @return {@link DateTime}
[ "设置日期的某个部分<br", ">", "如果此对象为可变对象,返回自身,否则返回新对象,设置是否可变对象见", "{", "@link", "#setMutable", "(", "boolean", ")", "}" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateTime.java#L263-L272
dita-ot/dita-ot
src/main/java/org/dita/dost/util/StringUtils.java
StringUtils.setOrAppend
public static String setOrAppend(final String target, final String value, final boolean withSpace) { if (target == null) { return value; }if(value == null) { return target; } else { if (withSpace && !target.endsWith(STRING_BLANK)) { return target + STRING_BLANK + value; } else { return target + value; } } }
java
public static String setOrAppend(final String target, final String value, final boolean withSpace) { if (target == null) { return value; }if(value == null) { return target; } else { if (withSpace && !target.endsWith(STRING_BLANK)) { return target + STRING_BLANK + value; } else { return target + value; } } }
[ "public", "static", "String", "setOrAppend", "(", "final", "String", "target", ",", "final", "String", "value", ",", "final", "boolean", "withSpace", ")", "{", "if", "(", "target", "==", "null", ")", "{", "return", "value", ";", "}", "if", "(", "value", ...
If target is null, return the value; else append value to target. If withSpace is true, insert a blank between them. @param target target to be appended @param value value to append @param withSpace whether insert a blank @return processed string
[ "If", "target", "is", "null", "return", "the", "value", ";", "else", "append", "value", "to", "target", ".", "If", "withSpace", "is", "true", "insert", "a", "blank", "between", "them", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/StringUtils.java#L179-L191
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java
PhotosInterface.getInfo
public Photo getInfo(String photoId, String secret) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_INFO); parameters.put("photo_id", photoId); if (secret != null) { parameters.put("secret", secret); } Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element photoElement = response.getPayload(); return PhotoUtils.createPhoto(photoElement); }
java
public Photo getInfo(String photoId, String secret) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_INFO); parameters.put("photo_id", photoId); if (secret != null) { parameters.put("secret", secret); } Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element photoElement = response.getPayload(); return PhotoUtils.createPhoto(photoElement); }
[ "public", "Photo", "getInfo", "(", "String", "photoId", ",", "String", "secret", ")", "throws", "FlickrException", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "para...
Get all info for the specified photo. The calling user must have permission to view the photo. This method does not require authentication. @param photoId The photo Id @param secret The optional secret String @return The Photo @throws FlickrException
[ "Get", "all", "info", "for", "the", "specified", "photo", "." ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/photos/PhotosInterface.java#L565-L581
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java
SVGPath.ellipticalArc
public SVGPath ellipticalArc(double[] rxy, double ar, double la, double sp, double[] xy) { return append(PATH_ARC).append(rxy[0]).append(rxy[1]).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]); }
java
public SVGPath ellipticalArc(double[] rxy, double ar, double la, double sp, double[] xy) { return append(PATH_ARC).append(rxy[0]).append(rxy[1]).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]); }
[ "public", "SVGPath", "ellipticalArc", "(", "double", "[", "]", "rxy", ",", "double", "ar", ",", "double", "la", ",", "double", "sp", ",", "double", "[", "]", "xy", ")", "{", "return", "append", "(", "PATH_ARC", ")", ".", "append", "(", "rxy", "[", ...
Elliptical arc curve to the given coordinates. @param rxy radius @param ar x-axis-rotation @param la large arc flag, if angle &gt;= 180 deg @param sp sweep flag, if arc will be drawn in positive-angle direction @param xy new coordinates
[ "Elliptical", "arc", "curve", "to", "the", "given", "coordinates", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L576-L578
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoKeyUtil.java
OmemoKeyUtil.addInBounds
public static int addInBounds(int value, int added) { int avail = Integer.MAX_VALUE - value; if (avail < added) { return added - avail; } else { return value + added; } }
java
public static int addInBounds(int value, int added) { int avail = Integer.MAX_VALUE - value; if (avail < added) { return added - avail; } else { return value + added; } }
[ "public", "static", "int", "addInBounds", "(", "int", "value", ",", "int", "added", ")", "{", "int", "avail", "=", "Integer", ".", "MAX_VALUE", "-", "value", ";", "if", "(", "avail", "<", "added", ")", "{", "return", "added", "-", "avail", ";", "}", ...
Add integers modulo MAX_VALUE. @param value base integer @param added value that is added to the base value @return (value plus added) modulo Integer.MAX_VALUE
[ "Add", "integers", "modulo", "MAX_VALUE", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoKeyUtil.java#L383-L390
pravega/pravega
common/src/main/java/io/pravega/common/util/BitConverter.java
BitConverter.readShort
public static short readShort(ArrayView source, int position) { return (short) ((source.get(position) & 0xFF) << 8 | (source.get(position + 1) & 0xFF)); }
java
public static short readShort(ArrayView source, int position) { return (short) ((source.get(position) & 0xFF) << 8 | (source.get(position + 1) & 0xFF)); }
[ "public", "static", "short", "readShort", "(", "ArrayView", "source", ",", "int", "position", ")", "{", "return", "(", "short", ")", "(", "(", "source", ".", "get", "(", "position", ")", "&", "0xFF", ")", "<<", "8", "|", "(", "source", ".", "get", ...
Reads a 16-bit Short from the given ArrayView starting at the given position. @param source The ArrayView to read from. @param position The position in the ArrayView to start reading at. @return The read number.
[ "Reads", "a", "16", "-", "bit", "Short", "from", "the", "given", "ArrayView", "starting", "at", "the", "given", "position", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/BitConverter.java#L111-L114
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java
IPv6AddressSection.spanWithSequentialBlocks
public IPv6AddressSection[] spanWithSequentialBlocks(IPv6AddressSection other) throws AddressPositionException { if(other.addressSegmentIndex != addressSegmentIndex) { throw new AddressPositionException(other, other.addressSegmentIndex, addressSegmentIndex); } return getSpanningSequentialBlocks( this, other, IPv6AddressSection::getLower, IPv6AddressSection::getUpper, Address.ADDRESS_LOW_VALUE_COMPARATOR::compare, IPv6AddressSection::withoutPrefixLength, getAddressCreator()); }
java
public IPv6AddressSection[] spanWithSequentialBlocks(IPv6AddressSection other) throws AddressPositionException { if(other.addressSegmentIndex != addressSegmentIndex) { throw new AddressPositionException(other, other.addressSegmentIndex, addressSegmentIndex); } return getSpanningSequentialBlocks( this, other, IPv6AddressSection::getLower, IPv6AddressSection::getUpper, Address.ADDRESS_LOW_VALUE_COMPARATOR::compare, IPv6AddressSection::withoutPrefixLength, getAddressCreator()); }
[ "public", "IPv6AddressSection", "[", "]", "spanWithSequentialBlocks", "(", "IPv6AddressSection", "other", ")", "throws", "AddressPositionException", "{", "if", "(", "other", ".", "addressSegmentIndex", "!=", "addressSegmentIndex", ")", "{", "throw", "new", "AddressPosit...
Produces a list of range subnets that span from this series to the given series. @param other @return
[ "Produces", "a", "list", "of", "range", "subnets", "that", "span", "from", "this", "series", "to", "the", "given", "series", "." ]
train
https://github.com/seancfoley/IPAddress/blob/90493d0673511d673100c36d020dd93dd870111a/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6AddressSection.java#L2018-L2030
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java
ImageIOGreyScale.getImageTranscoders
public static Iterator<ImageTranscoder> getImageTranscoders(ImageReader reader, ImageWriter writer) { if (reader == null) { throw new IllegalArgumentException("reader == null!"); } if (writer == null) { throw new IllegalArgumentException("writer == null!"); } ImageReaderSpi readerSpi = reader.getOriginatingProvider(); ImageWriterSpi writerSpi = writer.getOriginatingProvider(); ServiceRegistry.Filter filter = new TranscoderFilter(readerSpi, writerSpi); Iterator iter; // Ensure category is present try { iter = theRegistry.getServiceProviders(ImageTranscoderSpi.class, filter, true); } catch (IllegalArgumentException e) { return new HashSet().iterator(); } return new ImageTranscoderIterator(iter); }
java
public static Iterator<ImageTranscoder> getImageTranscoders(ImageReader reader, ImageWriter writer) { if (reader == null) { throw new IllegalArgumentException("reader == null!"); } if (writer == null) { throw new IllegalArgumentException("writer == null!"); } ImageReaderSpi readerSpi = reader.getOriginatingProvider(); ImageWriterSpi writerSpi = writer.getOriginatingProvider(); ServiceRegistry.Filter filter = new TranscoderFilter(readerSpi, writerSpi); Iterator iter; // Ensure category is present try { iter = theRegistry.getServiceProviders(ImageTranscoderSpi.class, filter, true); } catch (IllegalArgumentException e) { return new HashSet().iterator(); } return new ImageTranscoderIterator(iter); }
[ "public", "static", "Iterator", "<", "ImageTranscoder", ">", "getImageTranscoders", "(", "ImageReader", "reader", ",", "ImageWriter", "writer", ")", "{", "if", "(", "reader", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"reader == nul...
Returns an <code>Iterator</code> containing all currently registered <code>ImageTranscoder</code>s that claim to be able to transcode between the metadata of the given <code>ImageReader</code> and <code>ImageWriter</code>. @param reader an <code>ImageReader</code>. @param writer an <code>ImageWriter</code>. @return an <code>Iterator</code> containing <code>ImageTranscoder</code>s. @exception IllegalArgumentException if <code>reader</code> or <code>writer</code> is <code>null</code>.
[ "Returns", "an", "<code", ">", "Iterator<", "/", "code", ">", "containing", "all", "currently", "registered", "<code", ">", "ImageTranscoder<", "/", "code", ">", "s", "that", "claim", "to", "be", "able", "to", "transcode", "between", "the", "metadata", "of",...
train
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/ImageIOGreyScale.java#L1092-L1111
GCRC/nunaliit
nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java
DbWebServlet.performMultiQuery
private void performMultiQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AuthenticationUtils.getUserFromRequest(request); String[] queriesStrings = request.getParameterValues("queries"); if( 1 != queriesStrings.length ) { throw new Exception("Parameter 'queries' must be specified exactly oncce"); } // Create list of Query instances List<Query> queries = parseQueriesJson(queriesStrings[0]); // Perform queries JSONObject result = new JSONObject(); { Map<String, DbTableAccess> tableAccessCache = new HashMap<String, DbTableAccess>(); for(Query query : queries) { String tableName = query.getTableName(); List<RecordSelector> whereMap = query.getWhereExpressions(); List<FieldSelector> fieldSelectors = query.getFieldSelectors(); List<FieldSelector> groupByColumnNames = query.getGroupByColumnNames(); List<OrderSpecifier> orderSpecifiers = query.getOrderBySpecifiers(); Integer limit = query.getLimit(); Integer offset = query.getOffset(); DbTableAccess tableAccess = tableAccessCache.get(tableName); if( null == tableAccess ) { tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); tableAccessCache.put(tableName, tableAccess); } try { JSONArray queriedObjects = tableAccess.query( whereMap ,fieldSelectors ,groupByColumnNames ,orderSpecifiers ,limit ,offset ); result.put(query.getQueryKey(), queriedObjects); } catch(Exception e) { result.put(query.getQueryKey(), errorToJson(e)); } } } sendJsonResponse(response, result); }
java
private void performMultiQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AuthenticationUtils.getUserFromRequest(request); String[] queriesStrings = request.getParameterValues("queries"); if( 1 != queriesStrings.length ) { throw new Exception("Parameter 'queries' must be specified exactly oncce"); } // Create list of Query instances List<Query> queries = parseQueriesJson(queriesStrings[0]); // Perform queries JSONObject result = new JSONObject(); { Map<String, DbTableAccess> tableAccessCache = new HashMap<String, DbTableAccess>(); for(Query query : queries) { String tableName = query.getTableName(); List<RecordSelector> whereMap = query.getWhereExpressions(); List<FieldSelector> fieldSelectors = query.getFieldSelectors(); List<FieldSelector> groupByColumnNames = query.getGroupByColumnNames(); List<OrderSpecifier> orderSpecifiers = query.getOrderBySpecifiers(); Integer limit = query.getLimit(); Integer offset = query.getOffset(); DbTableAccess tableAccess = tableAccessCache.get(tableName); if( null == tableAccess ) { tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); tableAccessCache.put(tableName, tableAccess); } try { JSONArray queriedObjects = tableAccess.query( whereMap ,fieldSelectors ,groupByColumnNames ,orderSpecifiers ,limit ,offset ); result.put(query.getQueryKey(), queriedObjects); } catch(Exception e) { result.put(query.getQueryKey(), errorToJson(e)); } } } sendJsonResponse(response, result); }
[ "private", "void", "performMultiQuery", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "User", "user", "=", "AuthenticationUtils", ".", "getUserFromRequest", "(", "request", ")", ";", "String", "[", "]"...
Perform multiple SQL queries via dbSec. queries = { key1: { table: <table name> ,select: [ <selectExpression> ,... ] ,where: [ '<columnName>,<comparator>' ,'<columnName>,<comparator>' ,... ] ,groupBy: [ <columnName> ,... ] } ,key2: { ... } , ... } <selectExpression> : <columnName> sum(<columnName>) min(<columnName>) max(<columnName>) <comparator> : eq(<value>) where value is a valid comparison value for the column's data type. ne(<value>) where value is a valid comparison value for the column's data type. ge(<value>) where value is a valid comparison value for the column's data type. le(<value>) where value is a valid comparison value for the column's data type. gt(<value>) where value is a valid comparison value for the column's data type. lt(<value>) where value is a valid comparison value for the column's data type. isNull. isNotNull. response = { key1: [ { c1: 1, c2: 2 } ,{ c1: 4, c2: 5 } ,... ] ,key2: { error: 'Error message' } ,... } @param request http request containing the query parameters. @param response http response to be sent. @throws Exception (for a variety of reasons detected while parsing and validating the http parms).
[ "Perform", "multiple", "SQL", "queries", "via", "dbSec", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java#L316-L363
OpenLiberty/open-liberty
dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java
DCacheBase.getEntry
public com.ibm.websphere.cache.CacheEntry getEntry(com.ibm.websphere.cache.EntryInfo ei) { return getEntry(ei, true); }
java
public com.ibm.websphere.cache.CacheEntry getEntry(com.ibm.websphere.cache.EntryInfo ei) { return getEntry(ei, true); }
[ "public", "com", ".", "ibm", ".", "websphere", ".", "cache", ".", "CacheEntry", "getEntry", "(", "com", ".", "ibm", ".", "websphere", ".", "cache", ".", "EntryInfo", "ei", ")", "{", "return", "getEntry", "(", "ei", ",", "true", ")", ";", "}" ]
This returns the cache entry identified by the specified entryInfo. It returns null if not in the cache. @param ei The entryInfo for the entry. @return The entry identified by the entryInfo.
[ "This", "returns", "the", "cache", "entry", "identified", "by", "the", "specified", "entryInfo", ".", "It", "returns", "null", "if", "not", "in", "the", "cache", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/DCacheBase.java#L336-L338
spring-projects/spring-retry
src/main/java/org/springframework/retry/backoff/UniformRandomBackOffPolicy.java
UniformRandomBackOffPolicy.doBackOff
protected void doBackOff() throws BackOffInterruptedException { try { long delta = maxBackOffPeriod == minBackOffPeriod ? 0 : random.nextInt((int) (maxBackOffPeriod - minBackOffPeriod)); sleeper.sleep(minBackOffPeriod + delta); } catch (InterruptedException e) { throw new BackOffInterruptedException("Thread interrupted while sleeping", e); } }
java
protected void doBackOff() throws BackOffInterruptedException { try { long delta = maxBackOffPeriod == minBackOffPeriod ? 0 : random.nextInt((int) (maxBackOffPeriod - minBackOffPeriod)); sleeper.sleep(minBackOffPeriod + delta); } catch (InterruptedException e) { throw new BackOffInterruptedException("Thread interrupted while sleeping", e); } }
[ "protected", "void", "doBackOff", "(", ")", "throws", "BackOffInterruptedException", "{", "try", "{", "long", "delta", "=", "maxBackOffPeriod", "==", "minBackOffPeriod", "?", "0", ":", "random", ".", "nextInt", "(", "(", "int", ")", "(", "maxBackOffPeriod", "-...
Pause for the {@link #setMinBackOffPeriod(long)}. @throws BackOffInterruptedException if interrupted during sleep.
[ "Pause", "for", "the", "{" ]
train
https://github.com/spring-projects/spring-retry/blob/e2b0555f96594c2321990d0deeac45fc44d4f123/src/main/java/org/springframework/retry/backoff/UniformRandomBackOffPolicy.java#L106-L115
adyliu/jafka
src/main/java/io/jafka/admin/AdminOperation.java
AdminOperation.deleteTopic
public int deleteTopic(String topic, String password) throws IOException { KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password)); return Utils.deserializeIntArray(response.k.buffer())[0]; }
java
public int deleteTopic(String topic, String password) throws IOException { KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password)); return Utils.deserializeIntArray(response.k.buffer())[0]; }
[ "public", "int", "deleteTopic", "(", "String", "topic", ",", "String", "password", ")", "throws", "IOException", "{", "KV", "<", "Receive", ",", "ErrorMapping", ">", "response", "=", "send", "(", "new", "DeleterRequest", "(", "topic", ",", "password", ")", ...
delete topic never used @param topic topic name @param password password @return number of partitions deleted @throws IOException if an I/O error
[ "delete", "topic", "never", "used" ]
train
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/admin/AdminOperation.java#L64-L67
overturetool/overture
ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java
VdmBreakpointPropertyPage.storeHitCount
private void storeHitCount(IVdmBreakpoint breakpoint) throws CoreException { int hitCount = -1; // if (fHitCountButton.getSelection()) // { try { hitCount = Integer.parseInt(fHitValueText.getText()); } catch (NumberFormatException e) { // JDIDebugUIPlugin.log(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, MessageFormat.format("JavaBreakpointPage allowed input of invalid string for hit count value: {0}.", new String[] { fHitCountText.getText() }), e)); //$NON-NLS-1$ } // } breakpoint.setHitValue(hitCount); breakpoint.setHitCondition(fHitValueButton.getSelection() ? IVdmBreakpoint.HIT_CONDITION_GREATER_OR_EQUAL : -1); }
java
private void storeHitCount(IVdmBreakpoint breakpoint) throws CoreException { int hitCount = -1; // if (fHitCountButton.getSelection()) // { try { hitCount = Integer.parseInt(fHitValueText.getText()); } catch (NumberFormatException e) { // JDIDebugUIPlugin.log(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IStatus.ERROR, MessageFormat.format("JavaBreakpointPage allowed input of invalid string for hit count value: {0}.", new String[] { fHitCountText.getText() }), e)); //$NON-NLS-1$ } // } breakpoint.setHitValue(hitCount); breakpoint.setHitCondition(fHitValueButton.getSelection() ? IVdmBreakpoint.HIT_CONDITION_GREATER_OR_EQUAL : -1); }
[ "private", "void", "storeHitCount", "(", "IVdmBreakpoint", "breakpoint", ")", "throws", "CoreException", "{", "int", "hitCount", "=", "-", "1", ";", "// if (fHitCountButton.getSelection())", "// {", "try", "{", "hitCount", "=", "Integer", ".", "parseInt", "(", "fH...
Stores the value of the hit count in the breakpoint. @param breakpoint the breakpoint to update @throws CoreException if an exception occurs while setting the hit count
[ "Stores", "the", "value", "of", "the", "hit", "count", "in", "the", "breakpoint", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/ide/debug/src/main/java/org/overture/ide/debug/ui/propertypages/VdmBreakpointPropertyPage.java#L183-L199
Azure/azure-sdk-for-java
redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java
RedisInner.listKeys
public RedisAccessKeysInner listKeys(String resourceGroupName, String name) { return listKeysWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body(); }
java
public RedisAccessKeysInner listKeys(String resourceGroupName, String name) { return listKeysWithServiceResponseAsync(resourceGroupName, name).toBlocking().single().body(); }
[ "public", "RedisAccessKeysInner", "listKeys", "(", "String", "resourceGroupName", ",", "String", "name", ")", "{", "return", "listKeysWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", ...
Retrieve a Redis cache's access keys. This operation requires write permission to the cache resource. @param resourceGroupName The name of the resource group. @param name The name of the Redis cache. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RedisAccessKeysInner object if successful.
[ "Retrieve", "a", "Redis", "cache", "s", "access", "keys", ".", "This", "operation", "requires", "write", "permission", "to", "the", "cache", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java#L1062-L1064
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/carouselControl/CarouselControlRenderer.java
CarouselControlRenderer.decode
@Override public void decode(FacesContext context, UIComponent component) { CarouselControl carouselControl = (CarouselControl) component; if (carouselControl.isDisabled()) { return; } new AJAXRenderer().decode(context, component); }
java
@Override public void decode(FacesContext context, UIComponent component) { CarouselControl carouselControl = (CarouselControl) component; if (carouselControl.isDisabled()) { return; } new AJAXRenderer().decode(context, component); }
[ "@", "Override", "public", "void", "decode", "(", "FacesContext", "context", ",", "UIComponent", "component", ")", "{", "CarouselControl", "carouselControl", "=", "(", "CarouselControl", ")", "component", ";", "if", "(", "carouselControl", ".", "isDisabled", "(", ...
This methods receives and processes input made by the user. More specifically, it checks whether the user has interacted with the current b:carouselControl. The default implementation simply stores the input value in the list of submitted values. If the validation checks are passed, the values in the <code>submittedValues</code> list are store in the backend bean. @param context the FacesContext. @param component the current b:carouselControl.
[ "This", "methods", "receives", "and", "processes", "input", "made", "by", "the", "user", ".", "More", "specifically", "it", "checks", "whether", "the", "user", "has", "interacted", "with", "the", "current", "b", ":", "carouselControl", ".", "The", "default", ...
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/carouselControl/CarouselControlRenderer.java#L48-L57
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/LogQueryBean.java
LogQueryBean.setLevels
public void setLevels(Level minLevel, Level maxLevel) throws IllegalArgumentException { if (minLevel != null && maxLevel != null && minLevel.intValue() > maxLevel.intValue()) { throw new IllegalArgumentException("Value of the minLevel parameter should specify level not larger than the value of the maxLevel parametere."); } this.minLevel = minLevel; this.maxLevel = maxLevel; }
java
public void setLevels(Level minLevel, Level maxLevel) throws IllegalArgumentException { if (minLevel != null && maxLevel != null && minLevel.intValue() > maxLevel.intValue()) { throw new IllegalArgumentException("Value of the minLevel parameter should specify level not larger than the value of the maxLevel parametere."); } this.minLevel = minLevel; this.maxLevel = maxLevel; }
[ "public", "void", "setLevels", "(", "Level", "minLevel", ",", "Level", "maxLevel", ")", "throws", "IllegalArgumentException", "{", "if", "(", "minLevel", "!=", "null", "&&", "maxLevel", "!=", "null", "&&", "minLevel", ".", "intValue", "(", ")", ">", "maxLeve...
sets the current value for the minimum and maximum levels @param minLevel minimum level @throws IllegalArgumentException if minLevel is bigger than maxLevel
[ "sets", "the", "current", "value", "for", "the", "minimum", "and", "maximum", "levels" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/LogQueryBean.java#L102-L108
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/context/ContextManager.java
ContextManager.destroySubcontext
public void destroySubcontext(String name) throws EntityHasDescendantsException, EntityNotFoundException, WIMSystemException { TimedDirContext ctx = getDirContext(); // checkWritePermission(ctx); // TODO Why are we not checking permissions here? try { try { ctx.destroySubcontext(new LdapName(name)); } catch (NamingException e) { if (!isConnectionException(e)) { throw e; } ctx = reCreateDirContext(ctx, e.toString()); ctx.destroySubcontext(new LdapName(name)); } } catch (ContextNotEmptyException e) { String msg = Tr.formatMessage(tc, WIMMessageKey.ENTITY_HAS_DESCENDENTS, WIMMessageHelper.generateMsgParms(name)); throw new EntityHasDescendantsException(WIMMessageKey.ENTITY_HAS_DESCENDENTS, msg, e); } catch (NameNotFoundException e) { String msg = Tr.formatMessage(tc, WIMMessageKey.LDAP_ENTRY_NOT_FOUND, WIMMessageHelper.generateMsgParms(name, e.toString(true))); throw new EntityNotFoundException(WIMMessageKey.LDAP_ENTRY_NOT_FOUND, msg, e); } catch (NamingException e) { String msg = Tr.formatMessage(tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true))); throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, msg, e); } finally { releaseDirContext(ctx); } }
java
public void destroySubcontext(String name) throws EntityHasDescendantsException, EntityNotFoundException, WIMSystemException { TimedDirContext ctx = getDirContext(); // checkWritePermission(ctx); // TODO Why are we not checking permissions here? try { try { ctx.destroySubcontext(new LdapName(name)); } catch (NamingException e) { if (!isConnectionException(e)) { throw e; } ctx = reCreateDirContext(ctx, e.toString()); ctx.destroySubcontext(new LdapName(name)); } } catch (ContextNotEmptyException e) { String msg = Tr.formatMessage(tc, WIMMessageKey.ENTITY_HAS_DESCENDENTS, WIMMessageHelper.generateMsgParms(name)); throw new EntityHasDescendantsException(WIMMessageKey.ENTITY_HAS_DESCENDENTS, msg, e); } catch (NameNotFoundException e) { String msg = Tr.formatMessage(tc, WIMMessageKey.LDAP_ENTRY_NOT_FOUND, WIMMessageHelper.generateMsgParms(name, e.toString(true))); throw new EntityNotFoundException(WIMMessageKey.LDAP_ENTRY_NOT_FOUND, msg, e); } catch (NamingException e) { String msg = Tr.formatMessage(tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true))); throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, msg, e); } finally { releaseDirContext(ctx); } }
[ "public", "void", "destroySubcontext", "(", "String", "name", ")", "throws", "EntityHasDescendantsException", ",", "EntityNotFoundException", ",", "WIMSystemException", "{", "TimedDirContext", "ctx", "=", "getDirContext", "(", ")", ";", "// checkWritePermission(ctx); // TOD...
Delete the given name from the LDAP tree. @param name The distinguished name to delete. @throws EntityHasDescendantsException The context being destroyed is not empty. @throws EntityNotFoundException If part of the name cannot be found to destroy the entity. @throws WIMSystemException If any other {@link NamingException} occurs or the context cannot be released.
[ "Delete", "the", "given", "name", "from", "the", "LDAP", "tree", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/context/ContextManager.java#L579-L604
UrielCh/ovh-java-sdk
ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java
ApiOvhIp.ip_mitigationProfiles_ipMitigationProfile_PUT
public void ip_mitigationProfiles_ipMitigationProfile_PUT(String ip, String ipMitigationProfile, OvhMitigationProfile body) throws IOException { String qPath = "/ip/{ip}/mitigationProfiles/{ipMitigationProfile}"; StringBuilder sb = path(qPath, ip, ipMitigationProfile); exec(qPath, "PUT", sb.toString(), body); }
java
public void ip_mitigationProfiles_ipMitigationProfile_PUT(String ip, String ipMitigationProfile, OvhMitigationProfile body) throws IOException { String qPath = "/ip/{ip}/mitigationProfiles/{ipMitigationProfile}"; StringBuilder sb = path(qPath, ip, ipMitigationProfile); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "ip_mitigationProfiles_ipMitigationProfile_PUT", "(", "String", "ip", ",", "String", "ipMitigationProfile", ",", "OvhMitigationProfile", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/ip/{ip}/mitigationProfiles/{ipMitigationProfile}\"",...
Alter this object properties REST: PUT /ip/{ip}/mitigationProfiles/{ipMitigationProfile} @param body [required] New object properties @param ip [required] @param ipMitigationProfile [required]
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ApiOvhIp.java#L915-L919
pushtorefresh/storio
storio-sqlite/src/main/java/com/pushtorefresh/storio3/sqlite/operations/put/PutResult.java
PutResult.newInsertResult
@NonNull public static PutResult newInsertResult( long insertedId, @NonNull String affectedTable, @Nullable Collection<String> affectedTags ) { checkNotNull(affectedTable, "Please specify affected table"); return new PutResult(insertedId, null, singleton(affectedTable), nonNullSet(affectedTags)); }
java
@NonNull public static PutResult newInsertResult( long insertedId, @NonNull String affectedTable, @Nullable Collection<String> affectedTags ) { checkNotNull(affectedTable, "Please specify affected table"); return new PutResult(insertedId, null, singleton(affectedTable), nonNullSet(affectedTags)); }
[ "@", "NonNull", "public", "static", "PutResult", "newInsertResult", "(", "long", "insertedId", ",", "@", "NonNull", "String", "affectedTable", ",", "@", "Nullable", "Collection", "<", "String", ">", "affectedTags", ")", "{", "checkNotNull", "(", "affectedTable", ...
Creates {@link PutResult} of insert. @param insertedId id of new row. @param affectedTable table that was affected. @param affectedTags notification tags that were affected. @return new {@link PutResult} instance.
[ "Creates", "{", "@link", "PutResult", "}", "of", "insert", "." ]
train
https://github.com/pushtorefresh/storio/blob/58f53d81bcc7b069c8bb271c46a90e37775abe8d/storio-sqlite/src/main/java/com/pushtorefresh/storio3/sqlite/operations/put/PutResult.java#L106-L114
kiegroup/drools
drools-core/src/main/java/org/drools/core/reteoo/LeftTupleSource.java
LeftTupleSource.addTupleSink
public void addTupleSink(final LeftTupleSink tupleSink, final BuildContext context) { this.sink = addTupleSink(this.sink, tupleSink, context); }
java
public void addTupleSink(final LeftTupleSink tupleSink, final BuildContext context) { this.sink = addTupleSink(this.sink, tupleSink, context); }
[ "public", "void", "addTupleSink", "(", "final", "LeftTupleSink", "tupleSink", ",", "final", "BuildContext", "context", ")", "{", "this", ".", "sink", "=", "addTupleSink", "(", "this", ".", "sink", ",", "tupleSink", ",", "context", ")", ";", "}" ]
Adds the <code>TupleSink</code> so that it may receive <code>Tuples</code> propagated from this <code>TupleSource</code>. @param tupleSink The <code>TupleSink</code> to receive propagated <code>Tuples</code>.
[ "Adds", "the", "<code", ">", "TupleSink<", "/", "code", ">", "so", "that", "it", "may", "receive", "<code", ">", "Tuples<", "/", "code", ">", "propagated", "from", "this", "<code", ">", "TupleSource<", "/", "code", ">", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/reteoo/LeftTupleSource.java#L146-L148
cojen/Cojen
src/main/java/org/cojen/util/QuickConstructorGenerator.java
QuickConstructorGenerator.getInstance
@SuppressWarnings("unchecked") public static synchronized <F> F getInstance(final Class<?> objectType, final Class<F> factory) { Cache<Class<?>, Object> innerCache = cCache.get(factory); if (innerCache == null) { innerCache = new SoftValueCache(5); cCache.put(factory, innerCache); } F instance = (F) innerCache.get(objectType); if (instance != null) { return instance; } if (objectType == null) { throw new IllegalArgumentException("No object type"); } if (factory == null) { throw new IllegalArgumentException("No factory type"); } if (!factory.isInterface()) { throw new IllegalArgumentException("Factory must be an interface"); } final Cache<Class<?>, Object> fInnerCache = innerCache; return AccessController.doPrivileged(new PrivilegedAction<F>() { public F run() { return getInstance(fInnerCache, objectType, factory); } }); }
java
@SuppressWarnings("unchecked") public static synchronized <F> F getInstance(final Class<?> objectType, final Class<F> factory) { Cache<Class<?>, Object> innerCache = cCache.get(factory); if (innerCache == null) { innerCache = new SoftValueCache(5); cCache.put(factory, innerCache); } F instance = (F) innerCache.get(objectType); if (instance != null) { return instance; } if (objectType == null) { throw new IllegalArgumentException("No object type"); } if (factory == null) { throw new IllegalArgumentException("No factory type"); } if (!factory.isInterface()) { throw new IllegalArgumentException("Factory must be an interface"); } final Cache<Class<?>, Object> fInnerCache = innerCache; return AccessController.doPrivileged(new PrivilegedAction<F>() { public F run() { return getInstance(fInnerCache, objectType, factory); } }); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "synchronized", "<", "F", ">", "F", "getInstance", "(", "final", "Class", "<", "?", ">", "objectType", ",", "final", "Class", "<", "F", ">", "factory", ")", "{", "Cache", "<", "Class...
Returns a factory instance for one type of object. Each method in the interface defines a constructor via its parameters. Any checked exceptions declared thrown by the constructor must also be declared by the method. The method return types can be the same type as the constructed object or a supertype. <p>Here is a contrived example for constructing strings. In practice, such a string factory is useless, since the "new" operator can be invoked directly. <pre> public interface StringFactory { String newEmptyString(); String newStringFromChars(char[] chars); String newStringFromBytes(byte[] bytes, String charsetName) throws UnsupportedEncodingException; } </pre> Here's an example of it being used: <pre> StringFactory sf = QuickConstructorGenerator.getInstance(String.class, StringFactory.class); ... String str = sf.newStringFromChars(new char[] {'h', 'e', 'l', 'l', 'o'}); </pre> @param objectType type of object to construct @param factory interface defining which objects can be constructed @throws IllegalArgumentException if factory type is not an interface or if it is malformed
[ "Returns", "a", "factory", "instance", "for", "one", "type", "of", "object", ".", "Each", "method", "in", "the", "interface", "defines", "a", "constructor", "via", "its", "parameters", ".", "Any", "checked", "exceptions", "declared", "thrown", "by", "the", "...
train
https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/QuickConstructorGenerator.java#L104-L134
cdk/cdk
storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Writer.java
MDLV2000Writer.formatMDLString
protected static String formatMDLString(String s, int le) { s = s.trim(); if (s.length() > le) return s.substring(0, le); int l; l = le - s.length(); for (int f = 0; f < l; f++) s += " "; return s; }
java
protected static String formatMDLString(String s, int le) { s = s.trim(); if (s.length() > le) return s.substring(0, le); int l; l = le - s.length(); for (int f = 0; f < l; f++) s += " "; return s; }
[ "protected", "static", "String", "formatMDLString", "(", "String", "s", ",", "int", "le", ")", "{", "s", "=", "s", ".", "trim", "(", ")", ";", "if", "(", "s", ".", "length", "(", ")", ">", "le", ")", "return", "s", ".", "substring", "(", "0", "...
Formats a String to fit into the connectiontable. @param s The String to be formated @param le The length of the String @return The String to be written in the connectiontable
[ "Formats", "a", "String", "to", "fit", "into", "the", "connectiontable", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Writer.java#L1158-L1166
m-m-m/util
reflect/src/main/java/net/sf/mmm/util/reflect/base/ManifestLoader.java
ManifestLoader.completeManifest
private static void completeManifest(Manifest manifest, URL url) { String path = url.getPath(); int start = 0; int end = path.length(); if (path.endsWith(JAR_SUFFIX)) { // 4 for ".jar" end = end - JAR_SUFFIX.length() + 4; start = path.lastIndexOf('/', end) + 1; } String source = path.substring(start, end); manifest.getMainAttributes().put(MANIFEST_SOURCE, source); }
java
private static void completeManifest(Manifest manifest, URL url) { String path = url.getPath(); int start = 0; int end = path.length(); if (path.endsWith(JAR_SUFFIX)) { // 4 for ".jar" end = end - JAR_SUFFIX.length() + 4; start = path.lastIndexOf('/', end) + 1; } String source = path.substring(start, end); manifest.getMainAttributes().put(MANIFEST_SOURCE, source); }
[ "private", "static", "void", "completeManifest", "(", "Manifest", "manifest", ",", "URL", "url", ")", "{", "String", "path", "=", "url", ".", "getPath", "(", ")", ";", "int", "start", "=", "0", ";", "int", "end", "=", "path", ".", "length", "(", ")",...
This method adds dynamic attributes to the given {@code manifest}. @param manifest is the {@link Manifest} to modify. @param url is the {@link URL} with the source of the manifest.
[ "This", "method", "adds", "dynamic", "attributes", "to", "the", "given", "{", "@code", "manifest", "}", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/reflect/src/main/java/net/sf/mmm/util/reflect/base/ManifestLoader.java#L88-L100
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/partition/Partitioner.java
Partitioner.getPartitions
@Deprecated public HashMap<Long, Long> getPartitions(long previousWatermark) { HashMap<Long, Long> defaultPartition = Maps.newHashMap(); if (!isWatermarkExists()) { defaultPartition.put(ConfigurationKeys.DEFAULT_WATERMARK_VALUE, ConfigurationKeys.DEFAULT_WATERMARK_VALUE); LOG.info("Watermark column or type not found - Default partition with low watermark and high watermark as " + ConfigurationKeys.DEFAULT_WATERMARK_VALUE); return defaultPartition; } ExtractType extractType = ExtractType.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_EXTRACT_TYPE).toUpperCase()); WatermarkType watermarkType = WatermarkType.valueOf( this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE, ConfigurationKeys.DEFAULT_WATERMARK_TYPE) .toUpperCase()); int interval = getUpdatedInterval(this.state.getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_PARTITION_INTERVAL, 0), extractType, watermarkType); int sourceMaxAllowedPartitions = this.state.getPropAsInt(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, 0); int maxPartitions = (sourceMaxAllowedPartitions != 0 ? sourceMaxAllowedPartitions : ConfigurationKeys.DEFAULT_MAX_NUMBER_OF_PARTITIONS); WatermarkPredicate watermark = new WatermarkPredicate(null, watermarkType); int deltaForNextWatermark = watermark.getDeltaNumForNextWatermark(); LOG.info("is watermark override: " + this.isWatermarkOverride()); LOG.info("is full extract: " + this.isFullDump()); long lowWatermark = this.getLowWatermark(extractType, watermarkType, previousWatermark, deltaForNextWatermark); long highWatermark = this.getHighWatermark(extractType, watermarkType); if (lowWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE || highWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE) { LOG.info( "Low watermark or high water mark is not found. Hence cannot generate partitions - Default partition with low watermark: " + lowWatermark + " and high watermark: " + highWatermark); defaultPartition.put(lowWatermark, highWatermark); return defaultPartition; } LOG.info("Generate partitions with low watermark: " + lowWatermark + "; high watermark: " + highWatermark + "; partition interval in hours: " + interval + "; Maximum number of allowed partitions: " + maxPartitions); return watermark.getPartitions(lowWatermark, highWatermark, interval, maxPartitions); }
java
@Deprecated public HashMap<Long, Long> getPartitions(long previousWatermark) { HashMap<Long, Long> defaultPartition = Maps.newHashMap(); if (!isWatermarkExists()) { defaultPartition.put(ConfigurationKeys.DEFAULT_WATERMARK_VALUE, ConfigurationKeys.DEFAULT_WATERMARK_VALUE); LOG.info("Watermark column or type not found - Default partition with low watermark and high watermark as " + ConfigurationKeys.DEFAULT_WATERMARK_VALUE); return defaultPartition; } ExtractType extractType = ExtractType.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_EXTRACT_TYPE).toUpperCase()); WatermarkType watermarkType = WatermarkType.valueOf( this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE, ConfigurationKeys.DEFAULT_WATERMARK_TYPE) .toUpperCase()); int interval = getUpdatedInterval(this.state.getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_PARTITION_INTERVAL, 0), extractType, watermarkType); int sourceMaxAllowedPartitions = this.state.getPropAsInt(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, 0); int maxPartitions = (sourceMaxAllowedPartitions != 0 ? sourceMaxAllowedPartitions : ConfigurationKeys.DEFAULT_MAX_NUMBER_OF_PARTITIONS); WatermarkPredicate watermark = new WatermarkPredicate(null, watermarkType); int deltaForNextWatermark = watermark.getDeltaNumForNextWatermark(); LOG.info("is watermark override: " + this.isWatermarkOverride()); LOG.info("is full extract: " + this.isFullDump()); long lowWatermark = this.getLowWatermark(extractType, watermarkType, previousWatermark, deltaForNextWatermark); long highWatermark = this.getHighWatermark(extractType, watermarkType); if (lowWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE || highWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE) { LOG.info( "Low watermark or high water mark is not found. Hence cannot generate partitions - Default partition with low watermark: " + lowWatermark + " and high watermark: " + highWatermark); defaultPartition.put(lowWatermark, highWatermark); return defaultPartition; } LOG.info("Generate partitions with low watermark: " + lowWatermark + "; high watermark: " + highWatermark + "; partition interval in hours: " + interval + "; Maximum number of allowed partitions: " + maxPartitions); return watermark.getPartitions(lowWatermark, highWatermark, interval, maxPartitions); }
[ "@", "Deprecated", "public", "HashMap", "<", "Long", ",", "Long", ">", "getPartitions", "(", "long", "previousWatermark", ")", "{", "HashMap", "<", "Long", ",", "Long", ">", "defaultPartition", "=", "Maps", ".", "newHashMap", "(", ")", ";", "if", "(", "!...
Get partitions with low and high water marks @param previousWatermark previous water mark from metadata @return map of partition intervals. map's key is interval begin time (in format {@link Partitioner#WATERMARKTIMEFORMAT}) map's value is interval end time (in format {@link Partitioner#WATERMARKTIMEFORMAT})
[ "Get", "partitions", "with", "low", "and", "high", "water", "marks" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/partition/Partitioner.java#L118-L159
droidpl/android-json-viewer
android-json-viewer/src/main/java/com/github/droidpl/android/jsonviewer/JSONViewerActivity.java
JSONViewerActivity.startActivity
public static void startActivity(@NonNull Context context, @Nullable JSONObject jsonObject) { Intent intent = new Intent(context, JSONViewerActivity.class); Bundle bundle = new Bundle(); if (jsonObject != null) { bundle.putString(JSON_OBJECT_STATE, jsonObject.toString()); } intent.putExtras(bundle); context.startActivity(intent); }
java
public static void startActivity(@NonNull Context context, @Nullable JSONObject jsonObject) { Intent intent = new Intent(context, JSONViewerActivity.class); Bundle bundle = new Bundle(); if (jsonObject != null) { bundle.putString(JSON_OBJECT_STATE, jsonObject.toString()); } intent.putExtras(bundle); context.startActivity(intent); }
[ "public", "static", "void", "startActivity", "(", "@", "NonNull", "Context", "context", ",", "@", "Nullable", "JSONObject", "jsonObject", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "context", ",", "JSONViewerActivity", ".", "class", ")", ";", "...
Starts the activity with a json object. @param context The context to start the activity. @param jsonObject The json object.
[ "Starts", "the", "activity", "with", "a", "json", "object", "." ]
train
https://github.com/droidpl/android-json-viewer/blob/7345a7a0e6636399015a03fad8243a47f5fcdd8f/android-json-viewer/src/main/java/com/github/droidpl/android/jsonviewer/JSONViewerActivity.java#L42-L50
sdl/Testy
src/main/java/com/sdl/selenium/bootstrap/button/UploadFile.java
UploadFile.newUpload
public boolean newUpload(String filePath) { WebLocator uploadButton = new WebLocator(this).setTag("span").setClasses("fileupload-new").setElPathSuffix("icon-folder-open", "count(.//i[@class='icon-folder-open']) > 0"); return upload(uploadButton, filePath); }
java
public boolean newUpload(String filePath) { WebLocator uploadButton = new WebLocator(this).setTag("span").setClasses("fileupload-new").setElPathSuffix("icon-folder-open", "count(.//i[@class='icon-folder-open']) > 0"); return upload(uploadButton, filePath); }
[ "public", "boolean", "newUpload", "(", "String", "filePath", ")", "{", "WebLocator", "uploadButton", "=", "new", "WebLocator", "(", "this", ")", ".", "setTag", "(", "\"span\"", ")", ".", "setClasses", "(", "\"fileupload-new\"", ")", ".", "setElPathSuffix", "("...
Upload file with AutoIT. Use only this: button.newUpload("C:\\text.txt"); @param filePath "C:\\text.txt" @return true | false
[ "Upload", "file", "with", "AutoIT", ".", "Use", "only", "this", ":", "button", ".", "newUpload", "(", "C", ":", "\\\\", "text", ".", "txt", ")", ";" ]
train
https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/bootstrap/button/UploadFile.java#L94-L97
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobStreamsInner.java
JobStreamsInner.listByJobAsync
public Observable<Page<JobStreamInner>> listByJobAsync(final String resourceGroupName, final String automationAccountName, final String jobId, final String filter) { return listByJobWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId, filter) .map(new Func1<ServiceResponse<Page<JobStreamInner>>, Page<JobStreamInner>>() { @Override public Page<JobStreamInner> call(ServiceResponse<Page<JobStreamInner>> response) { return response.body(); } }); }
java
public Observable<Page<JobStreamInner>> listByJobAsync(final String resourceGroupName, final String automationAccountName, final String jobId, final String filter) { return listByJobWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId, filter) .map(new Func1<ServiceResponse<Page<JobStreamInner>>, Page<JobStreamInner>>() { @Override public Page<JobStreamInner> call(ServiceResponse<Page<JobStreamInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "JobStreamInner", ">", ">", "listByJobAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "automationAccountName", ",", "final", "String", "jobId", ",", "final", "String", "filter", ")", "{", "re...
Retrieve a list of jobs streams identified by job id. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param jobId The job Id. @param filter The filter to apply on the operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobStreamInner&gt; object
[ "Retrieve", "a", "list", "of", "jobs", "streams", "identified", "by", "job", "id", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobStreamsInner.java#L350-L358
atomix/catalyst
common/src/main/java/io/atomix/catalyst/util/PropertiesReader.java
PropertiesReader.getProperty
private <T> T getProperty(String property, Function<String, T> transformer) { Assert.notNull(property, "property"); String value = properties.getProperty(property); if (value == null) throw new ConfigurationException("missing property: " + property); return transformer.apply(value); }
java
private <T> T getProperty(String property, Function<String, T> transformer) { Assert.notNull(property, "property"); String value = properties.getProperty(property); if (value == null) throw new ConfigurationException("missing property: " + property); return transformer.apply(value); }
[ "private", "<", "T", ">", "T", "getProperty", "(", "String", "property", ",", "Function", "<", "String", ",", "T", ">", "transformer", ")", "{", "Assert", ".", "notNull", "(", "property", ",", "\"property\"", ")", ";", "String", "value", "=", "properties...
Reads an arbitrary property. @param property The property name. @param transformer A transformer function with which to transform the property value to its appropriate type. @param <T> The property type. @return The property value. @throws ConfigurationException if the property is not present
[ "Reads", "an", "arbitrary", "property", "." ]
train
https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/common/src/main/java/io/atomix/catalyst/util/PropertiesReader.java#L498-L504
soi-toolkit/soi-toolkit-mule
commons/components/commons-xml/src/main/java/org/soitoolkit/commons/xml/XPathUtil.java
XPathUtil.getXml
public static String getXml(Node node, boolean indentXml, int indentSize) { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; if (indentXml) { transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", new Integer(indentSize).toString()); } else { transformer = tf.newTransformer(new StreamSource(XPathUtil.class.getResourceAsStream("remove-whitespace.xsl"))); } //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(node); transformer.transform(source, result); String xmlString = result.getWriter().toString(); return xmlString; } catch (Exception e) { throw new RuntimeException(e); } }
java
public static String getXml(Node node, boolean indentXml, int indentSize) { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; if (indentXml) { transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", new Integer(indentSize).toString()); } else { transformer = tf.newTransformer(new StreamSource(XPathUtil.class.getResourceAsStream("remove-whitespace.xsl"))); } //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(node); transformer.transform(source, result); String xmlString = result.getWriter().toString(); return xmlString; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "String", "getXml", "(", "Node", "node", ",", "boolean", "indentXml", ",", "int", "indentSize", ")", "{", "try", "{", "TransformerFactory", "tf", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "transformer", ";...
Creates a string representation of the dom node. NOTE: The string can be formatted and indented with a specified indent size, but be aware that this is depending on a Xalan implementation of the XSLT library. @param node @param indentXml @param indentSize @return
[ "Creates", "a", "string", "representation", "of", "the", "dom", "node", ".", "NOTE", ":", "The", "string", "can", "be", "formatted", "and", "indented", "with", "a", "specified", "indent", "size", "but", "be", "aware", "that", "this", "is", "depending", "on...
train
https://github.com/soi-toolkit/soi-toolkit-mule/blob/e891350dbf55e6307be94d193d056bdb785b37d3/commons/components/commons-xml/src/main/java/org/soitoolkit/commons/xml/XPathUtil.java#L212-L235
sirthias/parboiled
parboiled-core/src/main/java/org/parboiled/support/ParseTreeUtils.java
ParseTreeUtils.printNodeTree
public static <V> String printNodeTree(ParsingResult<V> parsingResult) { checkArgNotNull(parsingResult, "parsingResult"); return printNodeTree(parsingResult, Predicates.<Node<V>>alwaysTrue(), Predicates.<Node<V>>alwaysTrue()); }
java
public static <V> String printNodeTree(ParsingResult<V> parsingResult) { checkArgNotNull(parsingResult, "parsingResult"); return printNodeTree(parsingResult, Predicates.<Node<V>>alwaysTrue(), Predicates.<Node<V>>alwaysTrue()); }
[ "public", "static", "<", "V", ">", "String", "printNodeTree", "(", "ParsingResult", "<", "V", ">", "parsingResult", ")", "{", "checkArgNotNull", "(", "parsingResult", ",", "\"parsingResult\"", ")", ";", "return", "printNodeTree", "(", "parsingResult", ",", "Pred...
Creates a readable string represenation of the parse tree in the given {@link ParsingResult} object. @param parsingResult the parsing result containing the parse tree @return a new String
[ "Creates", "a", "readable", "string", "represenation", "of", "the", "parse", "tree", "in", "the", "given", "{", "@link", "ParsingResult", "}", "object", "." ]
train
https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/ParseTreeUtils.java#L326-L329
cdapio/tigon
tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/AbstractDistributedProgramRunner.java
AbstractDistributedProgramRunner.addCleanupListener
private TwillController addCleanupListener(TwillController controller, final File hConfFile, final File cConfFile, final Program program, final File programDir) { final AtomicBoolean deleted = new AtomicBoolean(false); controller.addListener(new ServiceListenerAdapter() { @Override public void running() { cleanup(); } @Override public void terminated(Service.State from) { cleanup(); } @Override public void failed(Service.State from, Throwable failure) { cleanup(); } private void cleanup() { if (deleted.compareAndSet(false, true)) { LOG.debug("Cleanup tmp files for {}: {} {} {}", program.getName(), hConfFile, cConfFile, program.getJarLocation().toURI()); hConfFile.delete(); cConfFile.delete(); try { program.getJarLocation().delete(); } catch (IOException e) { LOG.warn("Failed to delete program jar {}", program.getJarLocation().toURI(), e); } try { FileUtils.deleteDirectory(programDir); } catch (IOException e) { LOG.warn("Failed to delete program directory {}", programDir, e); } } } }, Threads.SAME_THREAD_EXECUTOR); return controller; }
java
private TwillController addCleanupListener(TwillController controller, final File hConfFile, final File cConfFile, final Program program, final File programDir) { final AtomicBoolean deleted = new AtomicBoolean(false); controller.addListener(new ServiceListenerAdapter() { @Override public void running() { cleanup(); } @Override public void terminated(Service.State from) { cleanup(); } @Override public void failed(Service.State from, Throwable failure) { cleanup(); } private void cleanup() { if (deleted.compareAndSet(false, true)) { LOG.debug("Cleanup tmp files for {}: {} {} {}", program.getName(), hConfFile, cConfFile, program.getJarLocation().toURI()); hConfFile.delete(); cConfFile.delete(); try { program.getJarLocation().delete(); } catch (IOException e) { LOG.warn("Failed to delete program jar {}", program.getJarLocation().toURI(), e); } try { FileUtils.deleteDirectory(programDir); } catch (IOException e) { LOG.warn("Failed to delete program directory {}", programDir, e); } } } }, Threads.SAME_THREAD_EXECUTOR); return controller; }
[ "private", "TwillController", "addCleanupListener", "(", "TwillController", "controller", ",", "final", "File", "hConfFile", ",", "final", "File", "cConfFile", ",", "final", "Program", "program", ",", "final", "File", "programDir", ")", "{", "final", "AtomicBoolean"...
Adds a listener to the given TwillController to delete local temp files when the program has started/terminated. The local temp files could be removed once the program is started, since Twill would keep the files in HDFS and no long needs the local temp files once program is started. @return The same TwillController instance.
[ "Adds", "a", "listener", "to", "the", "given", "TwillController", "to", "delete", "local", "temp", "files", "when", "the", "program", "has", "started", "/", "terminated", ".", "The", "local", "temp", "files", "could", "be", "removed", "once", "the", "program...
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-flow/src/main/java/co/cask/tigon/internal/app/runtime/distributed/AbstractDistributedProgramRunner.java#L184-L224
aspectran/aspectran
shell/src/main/java/com/aspectran/shell/command/option/HelpFormatter.java
HelpFormatter.appendOption
private void appendOption(StringBuilder sb, Option option, boolean required) { if (!required) { sb.append(OPTIONAL_BRACKET_OPEN); } if (option.getName() != null) { sb.append(OPTION_PREFIX).append(option.getName()); } else { sb.append(LONG_OPTION_PREFIX).append(option.getLongName()); } // if the Option has a value and a non blank arg name if (option.hasValue() && (option.getValueName() == null || !option.getValueName().isEmpty())) { sb.append(option.isWithEqualSign() ? '=' : LONG_OPTION_SEPARATOR); sb.append(ARG_BRACKET_OPEN).append(option.getValueName() != null ? option.getValueName() : getArgName()).append(ARG_BRACKET_CLOSE); } if (!required) { sb.append(OPTIONAL_BRACKET_CLOSE); } }
java
private void appendOption(StringBuilder sb, Option option, boolean required) { if (!required) { sb.append(OPTIONAL_BRACKET_OPEN); } if (option.getName() != null) { sb.append(OPTION_PREFIX).append(option.getName()); } else { sb.append(LONG_OPTION_PREFIX).append(option.getLongName()); } // if the Option has a value and a non blank arg name if (option.hasValue() && (option.getValueName() == null || !option.getValueName().isEmpty())) { sb.append(option.isWithEqualSign() ? '=' : LONG_OPTION_SEPARATOR); sb.append(ARG_BRACKET_OPEN).append(option.getValueName() != null ? option.getValueName() : getArgName()).append(ARG_BRACKET_CLOSE); } if (!required) { sb.append(OPTIONAL_BRACKET_CLOSE); } }
[ "private", "void", "appendOption", "(", "StringBuilder", "sb", ",", "Option", "option", ",", "boolean", "required", ")", "{", "if", "(", "!", "required", ")", "{", "sb", ".", "append", "(", "OPTIONAL_BRACKET_OPEN", ")", ";", "}", "if", "(", "option", "."...
Appends the usage clause for an Option to a StringBuilder. @param sb the StringBuilder to append to @param option the Option to append @param required whether the Option is required or not
[ "Appends", "the", "usage", "clause", "for", "an", "Option", "to", "a", "StringBuilder", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/shell/src/main/java/com/aspectran/shell/command/option/HelpFormatter.java#L289-L306
h2oai/h2o-2
src/main/java/water/fvec/Chunk.java
Chunk.set0
public final float set0(int idx, float f) { setWrite(); if( _chk2.set_impl(idx,f) ) return f; (_chk2 = inflate_impl(new NewChunk(this))).set_impl(idx,f); return f; }
java
public final float set0(int idx, float f) { setWrite(); if( _chk2.set_impl(idx,f) ) return f; (_chk2 = inflate_impl(new NewChunk(this))).set_impl(idx,f); return f; }
[ "public", "final", "float", "set0", "(", "int", "idx", ",", "float", "f", ")", "{", "setWrite", "(", ")", ";", "if", "(", "_chk2", ".", "set_impl", "(", "idx", ",", "f", ")", ")", "return", "f", ";", "(", "_chk2", "=", "inflate_impl", "(", "new",...
Set a floating element in a chunk given a 0-based chunk local index.
[ "Set", "a", "floating", "element", "in", "a", "chunk", "given", "a", "0", "-", "based", "chunk", "local", "index", "." ]
train
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/fvec/Chunk.java#L145-L150
sagiegurari/fax4j
src/main/java/org/fax4j/bridge/FaxBridgeImpl.java
FaxBridgeImpl.updateFaxJobWithFileInfo
@Override protected void updateFaxJobWithFileInfo(FaxJob faxJob,FileInfo fileInfo) { //get file File file=fileInfo.getFile(); if(file==null) { //get file name String fileName=fileInfo.getName(); //get file content byte[] content=fileInfo.getContent(); try { //create temporary file file=File.createTempFile("fax_",fileName); //write content to file IOHelper.writeFile(content,file); } catch(IOException exception) { throw new FaxException("Unable to write file content to temporary file.",exception); } } //update fax job faxJob.setFile(file); }
java
@Override protected void updateFaxJobWithFileInfo(FaxJob faxJob,FileInfo fileInfo) { //get file File file=fileInfo.getFile(); if(file==null) { //get file name String fileName=fileInfo.getName(); //get file content byte[] content=fileInfo.getContent(); try { //create temporary file file=File.createTempFile("fax_",fileName); //write content to file IOHelper.writeFile(content,file); } catch(IOException exception) { throw new FaxException("Unable to write file content to temporary file.",exception); } } //update fax job faxJob.setFile(file); }
[ "@", "Override", "protected", "void", "updateFaxJobWithFileInfo", "(", "FaxJob", "faxJob", ",", "FileInfo", "fileInfo", ")", "{", "//get file", "File", "file", "=", "fileInfo", ".", "getFile", "(", ")", ";", "if", "(", "file", "==", "null", ")", "{", "//ge...
This function stores the file in the local machine and updates the fax job with the new file data. @param faxJob The fax job object to be updated @param fileInfo The file information of the requested fax
[ "This", "function", "stores", "the", "file", "in", "the", "local", "machine", "and", "updates", "the", "fax", "job", "with", "the", "new", "file", "data", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/bridge/FaxBridgeImpl.java#L85-L115
jenkinsci/jenkins
core/src/main/java/hudson/util/NoClientBindSSLProtocolSocketFactory.java
NoClientBindSSLProtocolSocketFactory.createSocket
public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port); } else { // To be eventually deprecated when migrated to Java 1.4 or above Socket socket = ReflectionSocketFactory.createSocket( "javax.net.ssl.SSLSocketFactory", host, port, null, 0, timeout); if (socket == null) { socket = ControllerThreadSocketFactory.createSocket( this, host, port, null, 0, timeout); } return socket; } }
java
public Socket createSocket( final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port); } else { // To be eventually deprecated when migrated to Java 1.4 or above Socket socket = ReflectionSocketFactory.createSocket( "javax.net.ssl.SSLSocketFactory", host, port, null, 0, timeout); if (socket == null) { socket = ControllerThreadSocketFactory.createSocket( this, host, port, null, 0, timeout); } return socket; } }
[ "public", "Socket", "createSocket", "(", "final", "String", "host", ",", "final", "int", "port", ",", "final", "InetAddress", "localAddress", ",", "final", "int", "localPort", ",", "final", "HttpConnectionParams", "params", ")", "throws", "IOException", ",", "Un...
Attempts to get a new socket connection to the given host within the given time limit. <p> This method employs several techniques to circumvent the limitations of older JREs that do not support connect timeout. When running in JRE 1.4 or above reflection is used to call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older JREs a controller thread is executed. The controller thread attempts to create a new socket within the given limit of time. If socket constructor does not return until the timeout expires, the controller terminates and throws an {@link ConnectTimeoutException} </p> @param host the host name/IP @param port the port on the host @param localAddress the local host name/IP to bind the socket to, ignored. @param localPort the port on the local machine, ignored. @param params {@link HttpConnectionParams Http connection parameters} @return Socket a new socket @throws IOException if an I/O error occurs while creating the socket @throws UnknownHostException if the IP address of the host cannot be determined @since 3.0
[ "Attempts", "to", "get", "a", "new", "socket", "connection", "to", "the", "given", "host", "within", "the", "given", "time", "limit", ".", "<p", ">", "This", "method", "employs", "several", "techniques", "to", "circumvent", "the", "limitations", "of", "older...
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/util/NoClientBindSSLProtocolSocketFactory.java#L105-L128
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/io/IOUtils.java
IOUtils.writeStringToFileNoExceptions
public static void writeStringToFileNoExceptions(String contents, String path, String encoding) { OutputStream writer = null; try{ if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(path)); } else { writer = new BufferedOutputStream(new FileOutputStream(path)); } writer.write(contents.getBytes(encoding)); } catch (Exception e) { e.printStackTrace(); } finally { if(writer != null){ closeIgnoringExceptions(writer); } } }
java
public static void writeStringToFileNoExceptions(String contents, String path, String encoding) { OutputStream writer = null; try{ if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(path)); } else { writer = new BufferedOutputStream(new FileOutputStream(path)); } writer.write(contents.getBytes(encoding)); } catch (Exception e) { e.printStackTrace(); } finally { if(writer != null){ closeIgnoringExceptions(writer); } } }
[ "public", "static", "void", "writeStringToFileNoExceptions", "(", "String", "contents", ",", "String", "path", ",", "String", "encoding", ")", "{", "OutputStream", "writer", "=", "null", ";", "try", "{", "if", "(", "path", ".", "endsWith", "(", "\".gz\"", ")...
Writes a string to a file, squashing exceptions @param contents The string to write @param path The file path @param encoding The encoding to encode in
[ "Writes", "a", "string", "to", "a", "file", "squashing", "exceptions" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L190-L204
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.getPropertyLabel
private String getPropertyLabel(PropertyIdValue propertyIdValue) { PropertyRecord propertyRecord = this.propertyRecords .get(propertyIdValue); if (propertyRecord == null || propertyRecord.propertyDocument == null) { return propertyIdValue.getId(); } else { return getLabel(propertyIdValue, propertyRecord.propertyDocument); } }
java
private String getPropertyLabel(PropertyIdValue propertyIdValue) { PropertyRecord propertyRecord = this.propertyRecords .get(propertyIdValue); if (propertyRecord == null || propertyRecord.propertyDocument == null) { return propertyIdValue.getId(); } else { return getLabel(propertyIdValue, propertyRecord.propertyDocument); } }
[ "private", "String", "getPropertyLabel", "(", "PropertyIdValue", "propertyIdValue", ")", "{", "PropertyRecord", "propertyRecord", "=", "this", ".", "propertyRecords", ".", "get", "(", "propertyIdValue", ")", ";", "if", "(", "propertyRecord", "==", "null", "||", "p...
Returns a string that should be used as a label for the given property. @param propertyIdValue the property to label @return the label
[ "Returns", "a", "string", "that", "should", "be", "used", "as", "a", "label", "for", "the", "given", "property", "." ]
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L853-L861
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/SslPolicyClient.java
SslPolicyClient.insertSslPolicy
@BetaApi public final Operation insertSslPolicy(ProjectName project, SslPolicy sslPolicyResource) { InsertSslPolicyHttpRequest request = InsertSslPolicyHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .setSslPolicyResource(sslPolicyResource) .build(); return insertSslPolicy(request); }
java
@BetaApi public final Operation insertSslPolicy(ProjectName project, SslPolicy sslPolicyResource) { InsertSslPolicyHttpRequest request = InsertSslPolicyHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .setSslPolicyResource(sslPolicyResource) .build(); return insertSslPolicy(request); }
[ "@", "BetaApi", "public", "final", "Operation", "insertSslPolicy", "(", "ProjectName", "project", ",", "SslPolicy", "sslPolicyResource", ")", "{", "InsertSslPolicyHttpRequest", "request", "=", "InsertSslPolicyHttpRequest", ".", "newBuilder", "(", ")", ".", "setProject",...
Returns the specified SSL policy resource. Gets a list of available SSL policies by making a list() request. <p>Sample code: <pre><code> try (SslPolicyClient sslPolicyClient = SslPolicyClient.create()) { ProjectName project = ProjectName.of("[PROJECT]"); SslPolicy sslPolicyResource = SslPolicy.newBuilder().build(); Operation response = sslPolicyClient.insertSslPolicy(project, sslPolicyResource); } </code></pre> @param project Project ID for this request. @param sslPolicyResource A SSL policy specifies the server-side support for SSL features. This can be attached to a TargetHttpsProxy or a TargetSslProxy. This affects connections between clients and the HTTPS or SSL proxy load balancer. They do not affect the connection between the load balancers and the backends. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Returns", "the", "specified", "SSL", "policy", "resource", ".", "Gets", "a", "list", "of", "available", "SSL", "policies", "by", "making", "a", "list", "()", "request", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/SslPolicyClient.java#L378-L387
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java
EJSContainer.getUserTransactionThreadData
public static EJBThreadData getUserTransactionThreadData() { EJBThreadData threadData = getThreadData(); BeanO beanO = threadData.getCallbackBeanO(); if (beanO == null) { EJBException ex = new EJBException("EJB UserTransaction can only be used from an EJB"); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getUserTransactionThreadData: " + ex); throw ex; } try { beanO.getUserTransaction(); } catch (IllegalStateException ex) { EJBException ex2 = new EJBException("EJB UserTransaction cannot be used: " + ex, ex); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getUserTransactionThreadData: " + beanO + ": " + ex2); throw ex2; } return threadData; }
java
public static EJBThreadData getUserTransactionThreadData() { EJBThreadData threadData = getThreadData(); BeanO beanO = threadData.getCallbackBeanO(); if (beanO == null) { EJBException ex = new EJBException("EJB UserTransaction can only be used from an EJB"); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getUserTransactionThreadData: " + ex); throw ex; } try { beanO.getUserTransaction(); } catch (IllegalStateException ex) { EJBException ex2 = new EJBException("EJB UserTransaction cannot be used: " + ex, ex); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getUserTransactionThreadData: " + beanO + ": " + ex2); throw ex2; } return threadData; }
[ "public", "static", "EJBThreadData", "getUserTransactionThreadData", "(", ")", "{", "EJBThreadData", "threadData", "=", "getThreadData", "(", ")", ";", "BeanO", "beanO", "=", "threadData", ".", "getCallbackBeanO", "(", ")", ";", "if", "(", "beanO", "==", "null",...
Returns the EJB thread data if an EJB context is active on the current thread and that EJB may use UserTransaction. @return verified EJB thread data @throws EJBException if the pre-conditions aren't met
[ "Returns", "the", "EJB", "thread", "data", "if", "an", "EJB", "context", "is", "active", "on", "the", "current", "thread", "and", "that", "EJB", "may", "use", "UserTransaction", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/EJSContainer.java#L1373-L1394
beihaifeiwu/dolphin
dolphin-common/src/main/java/com/freetmp/common/core/OrderComparator.java
OrderComparator.getOrder
private int getOrder(Object obj, OrderSourceProvider sourceProvider) { Integer order = null; if (sourceProvider != null) { order = findOrder(sourceProvider.getOrderSource(obj)); } return (order != null ? order : getOrder(obj)); }
java
private int getOrder(Object obj, OrderSourceProvider sourceProvider) { Integer order = null; if (sourceProvider != null) { order = findOrder(sourceProvider.getOrderSource(obj)); } return (order != null ? order : getOrder(obj)); }
[ "private", "int", "getOrder", "(", "Object", "obj", ",", "OrderSourceProvider", "sourceProvider", ")", "{", "Integer", "order", "=", "null", ";", "if", "(", "sourceProvider", "!=", "null", ")", "{", "order", "=", "findOrder", "(", "sourceProvider", ".", "get...
Determine the order value for the given object. <p>The default implementation checks against the given {@link OrderSourceProvider} using {@link #findOrder} and falls back to a regular {@link #getOrder(Object)} call. @param obj the object to check @return the order value, or {@code Ordered.LOWEST_PRECEDENCE} as fallback
[ "Determine", "the", "order", "value", "for", "the", "given", "object", ".", "<p", ">", "The", "default", "implementation", "checks", "against", "the", "given", "{" ]
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/core/OrderComparator.java#L89-L95
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addErrorsInvalidQuerySortValue
public FessMessages addErrorsInvalidQuerySortValue(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_invalid_query_sort_value, arg0)); return this; }
java
public FessMessages addErrorsInvalidQuerySortValue(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_invalid_query_sort_value, arg0)); return this; }
[ "public", "FessMessages", "addErrorsInvalidQuerySortValue", "(", "String", "property", ",", "String", "arg0", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "ERRORS_invalid_query_sort_value", ",", ...
Add the created action message for the key 'errors.invalid_query_sort_value' with parameters. <pre> message: The given sort ({0}) is invalid. </pre> @param property The property name for the message. (NotNull) @param arg0 The parameter arg0 for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "errors", ".", "invalid_query_sort_value", "with", "parameters", ".", "<pre", ">", "message", ":", "The", "given", "sort", "(", "{", "0", "}", ")", "is", "invalid", ".", "<", "/", "pre", ...
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L2050-L2054
kiegroup/drools
kie-dmn/kie-dmn-backend/src/main/java/org/kie/dmn/backend/marshalling/v1_1/xstream/XStreamMarshaller.java
XStreamMarshaller.marshalMarshall
@Deprecated public void marshalMarshall(Object o, OutputStream out) { try { XStream xStream = newXStream(); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes()); OutputStreamWriter ows = new OutputStreamWriter(out, "UTF-8"); xStream.toXML(o, ows); } catch ( Exception e ) { e.printStackTrace(); } }
java
@Deprecated public void marshalMarshall(Object o, OutputStream out) { try { XStream xStream = newXStream(); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes()); OutputStreamWriter ows = new OutputStreamWriter(out, "UTF-8"); xStream.toXML(o, ows); } catch ( Exception e ) { e.printStackTrace(); } }
[ "@", "Deprecated", "public", "void", "marshalMarshall", "(", "Object", "o", ",", "OutputStream", "out", ")", "{", "try", "{", "XStream", "xStream", "=", "newXStream", "(", ")", ";", "out", ".", "write", "(", "\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n...
Unnecessary as was a tentative UTF-8 preamble output but still not working.
[ "Unnecessary", "as", "was", "a", "tentative", "UTF", "-", "8", "preamble", "output", "but", "still", "not", "working", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/kie-dmn/kie-dmn-backend/src/main/java/org/kie/dmn/backend/marshalling/v1_1/xstream/XStreamMarshaller.java#L197-L207
opendatatrentino/s-match
src/main/java/it/unitn/disi/smatch/matchers/element/gloss/BasicGlossMatcher.java
BasicGlossMatcher.isWordMoreGeneral
public boolean isWordMoreGeneral(String source, String target) throws MatcherLibraryException { try { List<ISense> sSenses = linguisticOracle.getSenses(source); List<ISense> tSenses = linguisticOracle.getSenses(target); for (ISense sSense : sSenses) { for (ISense tSense : tSenses) { if (senseMatcher.isSourceMoreGeneralThanTarget(sSense, tSense)) return true; } } return false; } catch (LinguisticOracleException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new MatcherLibraryException(errMessage, e); } catch (SenseMatcherException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new MatcherLibraryException(errMessage, e); } }
java
public boolean isWordMoreGeneral(String source, String target) throws MatcherLibraryException { try { List<ISense> sSenses = linguisticOracle.getSenses(source); List<ISense> tSenses = linguisticOracle.getSenses(target); for (ISense sSense : sSenses) { for (ISense tSense : tSenses) { if (senseMatcher.isSourceMoreGeneralThanTarget(sSense, tSense)) return true; } } return false; } catch (LinguisticOracleException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new MatcherLibraryException(errMessage, e); } catch (SenseMatcherException e) { final String errMessage = e.getClass().getSimpleName() + ": " + e.getMessage(); log.error(errMessage, e); throw new MatcherLibraryException(errMessage, e); } }
[ "public", "boolean", "isWordMoreGeneral", "(", "String", "source", ",", "String", "target", ")", "throws", "MatcherLibraryException", "{", "try", "{", "List", "<", "ISense", ">", "sSenses", "=", "linguisticOracle", ".", "getSenses", "(", "source", ")", ";", "L...
Checks the source is more general than the target or not. @param source sense of source @param target sense of target @return true if the source is more general than target @throws MatcherLibraryException MatcherLibraryException
[ "Checks", "the", "source", "is", "more", "general", "than", "the", "target", "or", "not", "." ]
train
https://github.com/opendatatrentino/s-match/blob/ba5982ef406b7010c2f92592e43887a485935aa1/src/main/java/it/unitn/disi/smatch/matchers/element/gloss/BasicGlossMatcher.java#L72-L92
qzagarese/hyaline-dto
hyaline-dto/src/main/java/org/hyalinedto/api/Hyaline.java
Hyaline.dtoFromScratch
public static <T> T dtoFromScratch(T entity, DTO dtoTemplate, String proxyClassName) throws HyalineException { try { return createDTO(entity, dtoTemplate, true, proxyClassName); } catch (CannotInstantiateProxyException | DTODefinitionException e) { e.printStackTrace(); throw new HyalineException(); } }
java
public static <T> T dtoFromScratch(T entity, DTO dtoTemplate, String proxyClassName) throws HyalineException { try { return createDTO(entity, dtoTemplate, true, proxyClassName); } catch (CannotInstantiateProxyException | DTODefinitionException e) { e.printStackTrace(); throw new HyalineException(); } }
[ "public", "static", "<", "T", ">", "T", "dtoFromScratch", "(", "T", "entity", ",", "DTO", "dtoTemplate", ",", "String", "proxyClassName", ")", "throws", "HyalineException", "{", "try", "{", "return", "createDTO", "(", "entity", ",", "dtoTemplate", ",", "true...
It lets you create a new DTO from scratch. This means that any annotation for JAXB, Jackson or whatever serialization framework you are using on your entity T will be ignored. The only annotation-based configuration that will be used is the one you are defining in this invocation. @param <T> the generic type @param entity the entity you are going proxy. @param dtoTemplate the DTO template passed as an anonymous class. @param proxyClassName the name you want to assign to newly generated class @return a proxy that extends the type of entity, holding the same instance variables values as entity and configured according to dtoTemplate @throws HyalineException if the dynamic type could be created.
[ "It", "lets", "you", "create", "a", "new", "DTO", "from", "scratch", ".", "This", "means", "that", "any", "annotation", "for", "JAXB", "Jackson", "or", "whatever", "serialization", "framework", "you", "are", "using", "on", "your", "entity", "T", "will", "b...
train
https://github.com/qzagarese/hyaline-dto/blob/3392de5b7f93cdb3a1c53aa977ee682c141df5f4/hyaline-dto/src/main/java/org/hyalinedto/api/Hyaline.java#L105-L112
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java
EventSubscriptionsInner.listRegionalByResourceGroupForTopicTypeAsync
public Observable<List<EventSubscriptionInner>> listRegionalByResourceGroupForTopicTypeAsync(String resourceGroupName, String location, String topicTypeName) { return listRegionalByResourceGroupForTopicTypeWithServiceResponseAsync(resourceGroupName, location, topicTypeName).map(new Func1<ServiceResponse<List<EventSubscriptionInner>>, List<EventSubscriptionInner>>() { @Override public List<EventSubscriptionInner> call(ServiceResponse<List<EventSubscriptionInner>> response) { return response.body(); } }); }
java
public Observable<List<EventSubscriptionInner>> listRegionalByResourceGroupForTopicTypeAsync(String resourceGroupName, String location, String topicTypeName) { return listRegionalByResourceGroupForTopicTypeWithServiceResponseAsync(resourceGroupName, location, topicTypeName).map(new Func1<ServiceResponse<List<EventSubscriptionInner>>, List<EventSubscriptionInner>>() { @Override public List<EventSubscriptionInner> call(ServiceResponse<List<EventSubscriptionInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "List", "<", "EventSubscriptionInner", ">", ">", "listRegionalByResourceGroupForTopicTypeAsync", "(", "String", "resourceGroupName", ",", "String", "location", ",", "String", "topicTypeName", ")", "{", "return", "listRegionalByResourceGroupForTo...
List all regional event subscriptions under an Azure subscription and resource group for a topic type. List all event subscriptions from the given location under a specific Azure subscription and resource group and topic type. @param resourceGroupName The name of the resource group within the user's subscription. @param location Name of the location @param topicTypeName Name of the topic type @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the List&lt;EventSubscriptionInner&gt; object
[ "List", "all", "regional", "event", "subscriptions", "under", "an", "Azure", "subscription", "and", "resource", "group", "for", "a", "topic", "type", ".", "List", "all", "event", "subscriptions", "from", "the", "given", "location", "under", "a", "specific", "A...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java#L1492-L1499
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javac/nio/PathFileObject.java
PathFileObject.createJarPathFileObject
static PathFileObject createJarPathFileObject(JavacPathFileManager fileManager, final Path path) { return new PathFileObject(fileManager, path) { @Override String inferBinaryName(Iterable<? extends Path> paths) { return toBinaryName(path); } }; }
java
static PathFileObject createJarPathFileObject(JavacPathFileManager fileManager, final Path path) { return new PathFileObject(fileManager, path) { @Override String inferBinaryName(Iterable<? extends Path> paths) { return toBinaryName(path); } }; }
[ "static", "PathFileObject", "createJarPathFileObject", "(", "JavacPathFileManager", "fileManager", ",", "final", "Path", "path", ")", "{", "return", "new", "PathFileObject", "(", "fileManager", ",", "path", ")", "{", "@", "Override", "String", "inferBinaryName", "("...
Create a PathFileObject in a file system such as a jar file, such that the binary name can be inferred from its position within the filesystem.
[ "Create", "a", "PathFileObject", "in", "a", "file", "system", "such", "as", "a", "jar", "file", "such", "that", "the", "binary", "name", "can", "be", "inferred", "from", "its", "position", "within", "the", "filesystem", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/nio/PathFileObject.java#L85-L93
drinkjava2/jBeanBox
jbeanbox/src/main/java/com/github/drinkjava2/jbeanbox/BeanBox.java
BeanBox.injectConstruct
public BeanBox injectConstruct(Class<?> clazz, Object... configs) { this.beanClass = clazz; if (configs.length == 0) { this.constructor = BeanBoxUtils.getConstructor(clazz); } else { Class<?>[] paramTypes = new Class<?>[configs.length / 2]; BeanBox[] params = new BeanBox[configs.length / 2]; int mid = configs.length / 2; for (int i = 0; i < mid; i++) paramTypes[i] = (Class<?>) configs[i]; for (int i = mid; i < configs.length; i++) { params[i - mid] = BeanBoxUtils.wrapParamToBox(configs[i]); params[i - mid].setType(paramTypes[i - mid]); } this.constructor = BeanBoxUtils.getConstructor(clazz, paramTypes); this.constructorParams = params; } return this; }
java
public BeanBox injectConstruct(Class<?> clazz, Object... configs) { this.beanClass = clazz; if (configs.length == 0) { this.constructor = BeanBoxUtils.getConstructor(clazz); } else { Class<?>[] paramTypes = new Class<?>[configs.length / 2]; BeanBox[] params = new BeanBox[configs.length / 2]; int mid = configs.length / 2; for (int i = 0; i < mid; i++) paramTypes[i] = (Class<?>) configs[i]; for (int i = mid; i < configs.length; i++) { params[i - mid] = BeanBoxUtils.wrapParamToBox(configs[i]); params[i - mid].setType(paramTypes[i - mid]); } this.constructor = BeanBoxUtils.getConstructor(clazz, paramTypes); this.constructorParams = params; } return this; }
[ "public", "BeanBox", "injectConstruct", "(", "Class", "<", "?", ">", "clazz", ",", "Object", "...", "configs", ")", "{", "this", ".", "beanClass", "=", "clazz", ";", "if", "(", "configs", ".", "length", "==", "0", ")", "{", "this", ".", "constructor", ...
This is Java configuration method equal to put @INJECT on a class's constructor, a usage example: injectConstruct(User.class, String.class, JBEANBOX.value("Sam"));
[ "This", "is", "Java", "configuration", "method", "equal", "to", "put" ]
train
https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/jbeanbox/BeanBox.java#L184-L202
alkacon/opencms-core
src/org/opencms/util/CmsStringUtil.java
CmsStringUtil.validateRegex
public static boolean validateRegex(String value, String regex, boolean allowEmpty) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) { return allowEmpty; } Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(value); return matcher.matches(); }
java
public static boolean validateRegex(String value, String regex, boolean allowEmpty) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) { return allowEmpty; } Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(value); return matcher.matches(); }
[ "public", "static", "boolean", "validateRegex", "(", "String", "value", ",", "String", "regex", ",", "boolean", "allowEmpty", ")", "{", "if", "(", "CmsStringUtil", ".", "isEmptyOrWhitespaceOnly", "(", "value", ")", ")", "{", "return", "allowEmpty", ";", "}", ...
Validates a value against a regular expression.<p> @param value the value to test @param regex the regular expression @param allowEmpty if an empty value is allowed @return <code>true</code> if the value satisfies the validation
[ "Validates", "a", "value", "against", "a", "regular", "expression", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsStringUtil.java#L2179-L2187
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/regex/RegExHelper.java
RegExHelper.getMatcher
@Nonnull public static Matcher getMatcher (@Nonnull @RegEx final String sRegEx, @Nonnull final String sValue) { ValueEnforcer.notNull (sValue, "Value"); return RegExCache.getPattern (sRegEx).matcher (sValue); }
java
@Nonnull public static Matcher getMatcher (@Nonnull @RegEx final String sRegEx, @Nonnull final String sValue) { ValueEnforcer.notNull (sValue, "Value"); return RegExCache.getPattern (sRegEx).matcher (sValue); }
[ "@", "Nonnull", "public", "static", "Matcher", "getMatcher", "(", "@", "Nonnull", "@", "RegEx", "final", "String", "sRegEx", ",", "@", "Nonnull", "final", "String", "sValue", ")", "{", "ValueEnforcer", ".", "notNull", "(", "sValue", ",", "\"Value\"", ")", ...
Get the Java Matcher object for the passed pair of regular expression and value. @param sRegEx The regular expression to use. May neither be <code>null</code> nor empty. @param sValue The value to create the matcher for. May not be <code>null</code>. @return A non-<code>null</code> matcher.
[ "Get", "the", "Java", "Matcher", "object", "for", "the", "passed", "pair", "of", "regular", "expression", "and", "value", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/regex/RegExHelper.java#L162-L168
netty/netty
transport/src/main/java/io/netty/channel/ChannelFlushPromiseNotifier.java
ChannelFlushPromiseNotifier.notifyPromises
public ChannelFlushPromiseNotifier notifyPromises(Throwable cause1, Throwable cause2) { notifyPromises0(cause1); for (;;) { FlushCheckpoint cp = flushCheckpoints.poll(); if (cp == null) { break; } if (tryNotify) { cp.promise().tryFailure(cause2); } else { cp.promise().setFailure(cause2); } } return this; }
java
public ChannelFlushPromiseNotifier notifyPromises(Throwable cause1, Throwable cause2) { notifyPromises0(cause1); for (;;) { FlushCheckpoint cp = flushCheckpoints.poll(); if (cp == null) { break; } if (tryNotify) { cp.promise().tryFailure(cause2); } else { cp.promise().setFailure(cause2); } } return this; }
[ "public", "ChannelFlushPromiseNotifier", "notifyPromises", "(", "Throwable", "cause1", ",", "Throwable", "cause2", ")", "{", "notifyPromises0", "(", "cause1", ")", ";", "for", "(", ";", ";", ")", "{", "FlushCheckpoint", "cp", "=", "flushCheckpoints", ".", "poll"...
Notify all {@link ChannelFuture}s that were registered with {@link #add(ChannelPromise, int)} and their pendingDatasize is smaller then the current writeCounter returned by {@link #writeCounter()} using the given cause1. After a {@link ChannelFuture} was notified it will be removed from this {@link ChannelFlushPromiseNotifier} and so not receive anymore notification. The rest of the remaining {@link ChannelFuture}s will be failed with the given {@link Throwable}. So after this operation this {@link ChannelFutureListener} is empty. @param cause1 the {@link Throwable} which will be used to fail all of the {@link ChannelFuture}s which pendingDataSize is smaller then the current writeCounter returned by {@link #writeCounter()} @param cause2 the {@link Throwable} which will be used to fail the remaining {@link ChannelFuture}s
[ "Notify", "all", "{", "@link", "ChannelFuture", "}", "s", "that", "were", "registered", "with", "{", "@link", "#add", "(", "ChannelPromise", "int", ")", "}", "and", "their", "pendingDatasize", "is", "smaller", "then", "the", "current", "writeCounter", "returne...
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/transport/src/main/java/io/netty/channel/ChannelFlushPromiseNotifier.java#L167-L181
fabric8io/kubernetes-client
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java
HasMetadataOperation.periodicWatchUntilReady
protected T periodicWatchUntilReady(int i, long started, long interval, long amount) { T item = fromServer().get(); if (Readiness.isReady(item)) { return item; } ReadinessWatcher<T> watcher = new ReadinessWatcher<>(item); try (Watch watch = watch(item.getMetadata().getResourceVersion(), watcher)) { try { return watcher.await(interval, TimeUnit.MILLISECONDS); } catch (KubernetesClientTimeoutException e) { if (i <= 0) { throw e; } } long remaining = (started + amount) - System.nanoTime(); long next = Math.max(0, Math.min(remaining, interval)); return periodicWatchUntilReady(i - 1, started, next, amount); } }
java
protected T periodicWatchUntilReady(int i, long started, long interval, long amount) { T item = fromServer().get(); if (Readiness.isReady(item)) { return item; } ReadinessWatcher<T> watcher = new ReadinessWatcher<>(item); try (Watch watch = watch(item.getMetadata().getResourceVersion(), watcher)) { try { return watcher.await(interval, TimeUnit.MILLISECONDS); } catch (KubernetesClientTimeoutException e) { if (i <= 0) { throw e; } } long remaining = (started + amount) - System.nanoTime(); long next = Math.max(0, Math.min(remaining, interval)); return periodicWatchUntilReady(i - 1, started, next, amount); } }
[ "protected", "T", "periodicWatchUntilReady", "(", "int", "i", ",", "long", "started", ",", "long", "interval", ",", "long", "amount", ")", "{", "T", "item", "=", "fromServer", "(", ")", ".", "get", "(", ")", ";", "if", "(", "Readiness", ".", "isReady",...
A wait method that combines watching and polling. The need for that is that in some cases a pure watcher approach consistently fails. @param i The number of iterations to perform. @param started Time in milliseconds where the watch started. @param interval The amount of time in millis to wait on each iteration. @param amount The maximum amount in millis of time since started to wait. @return The {@link ReplicationController} if ready.
[ "A", "wait", "method", "that", "combines", "watching", "and", "polling", ".", "The", "need", "for", "that", "is", "that", "in", "some", "cases", "a", "pure", "watcher", "approach", "consistently", "fails", "." ]
train
https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/HasMetadataOperation.java#L183-L203
fabric8io/kubernetes-client
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java
OperationSupport.handleGet
protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { Request.Builder requestBuilder = new Request.Builder().get().url(resourceUrl); return handleResponse(requestBuilder, type, parameters); }
java
protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { Request.Builder requestBuilder = new Request.Builder().get().url(resourceUrl); return handleResponse(requestBuilder, type, parameters); }
[ "protected", "<", "T", ">", "T", "handleGet", "(", "URL", "resourceUrl", ",", "Class", "<", "T", ">", "type", ",", "Map", "<", "String", ",", "String", ">", "parameters", ")", "throws", "ExecutionException", ",", "InterruptedException", ",", "KubernetesClien...
Send an http, optionally performing placeholder substitution to the response. @param resourceUrl resource URL to be processed @param type type of resource @param parameters A HashMap of strings containing parameters to be passed in request @param <T> template argument provided @return Returns a deserialized object as api server response of provided type. @throws ExecutionException Execution Exception @throws InterruptedException Interrupted Exception @throws KubernetesClientException KubernetesClientException @throws IOException IOException
[ "Send", "an", "http", "optionally", "performing", "placeholder", "substitution", "to", "the", "response", "." ]
train
https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/base/OperationSupport.java#L328-L331
thinkaurelius/titan
titan-core/src/main/java/com/thinkaurelius/titan/graphdb/idmanagement/IDManager.java
IDManager.checkSchemaTypeId
private static void checkSchemaTypeId(VertexIDType type, long count) { Preconditions.checkArgument(VertexIDType.Schema.is(type.suffix()),"Expected schema vertex but got: %s",type); Preconditions.checkArgument(type.isProper(),"Expected proper type but got: %s",type); Preconditions.checkArgument(count > 0 && count < SCHEMA_COUNT_BOUND, "Invalid id [%s] for type [%s] bound: %s", count, type, SCHEMA_COUNT_BOUND); }
java
private static void checkSchemaTypeId(VertexIDType type, long count) { Preconditions.checkArgument(VertexIDType.Schema.is(type.suffix()),"Expected schema vertex but got: %s",type); Preconditions.checkArgument(type.isProper(),"Expected proper type but got: %s",type); Preconditions.checkArgument(count > 0 && count < SCHEMA_COUNT_BOUND, "Invalid id [%s] for type [%s] bound: %s", count, type, SCHEMA_COUNT_BOUND); }
[ "private", "static", "void", "checkSchemaTypeId", "(", "VertexIDType", "type", ",", "long", "count", ")", "{", "Preconditions", ".", "checkArgument", "(", "VertexIDType", ".", "Schema", ".", "is", "(", "type", ".", "suffix", "(", ")", ")", ",", "\"Expected s...
/* --- TitanRelation Type id bit format --- [ 0 | count | ID padding ] (there is no partition)
[ "/", "*", "---", "TitanRelation", "Type", "id", "bit", "format", "---", "[", "0", "|", "count", "|", "ID", "padding", "]", "(", "there", "is", "no", "partition", ")" ]
train
https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-core/src/main/java/com/thinkaurelius/titan/graphdb/idmanagement/IDManager.java#L603-L608
Ashok-Varma/BottomNavigation
bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BadgeTextView.java
BadgeTextView.setDimens
void setDimens(int width, int height) { mAreDimensOverridden = true; mDesiredWidth = width; mDesiredHeight = height; requestLayout(); }
java
void setDimens(int width, int height) { mAreDimensOverridden = true; mDesiredWidth = width; mDesiredHeight = height; requestLayout(); }
[ "void", "setDimens", "(", "int", "width", ",", "int", "height", ")", "{", "mAreDimensOverridden", "=", "true", ";", "mDesiredWidth", "=", "width", ";", "mDesiredHeight", "=", "height", ";", "requestLayout", "(", ")", ";", "}" ]
if width and height of the view needs to be changed @param width new width that needs to be set @param height new height that needs to be set
[ "if", "width", "and", "height", "of", "the", "view", "needs", "to", "be", "changed" ]
train
https://github.com/Ashok-Varma/BottomNavigation/blob/a5c486a6dfa1ebe7049e2e025e0d967111ecfd0b/bottom-navigation-bar/src/main/java/com/ashokvarma/bottomnavigation/BadgeTextView.java#L63-L68
EdwardRaff/JSAT
JSAT/src/jsat/linear/distancemetrics/TrainableDistanceMetric.java
TrainableDistanceMetric.trainIfNeeded
public static void trainIfNeeded(DistanceMetric dm, DataSet dataset, boolean parallel) { if(!(dm instanceof TrainableDistanceMetric)) return; TrainableDistanceMetric tdm = (TrainableDistanceMetric) dm; if(!tdm.needsTraining()) return; if(dataset instanceof RegressionDataSet) tdm.train((RegressionDataSet) dataset, parallel); else if(dataset instanceof ClassificationDataSet) tdm.train((ClassificationDataSet) dataset, parallel); else tdm.train(dataset, parallel); }
java
public static void trainIfNeeded(DistanceMetric dm, DataSet dataset, boolean parallel) { if(!(dm instanceof TrainableDistanceMetric)) return; TrainableDistanceMetric tdm = (TrainableDistanceMetric) dm; if(!tdm.needsTraining()) return; if(dataset instanceof RegressionDataSet) tdm.train((RegressionDataSet) dataset, parallel); else if(dataset instanceof ClassificationDataSet) tdm.train((ClassificationDataSet) dataset, parallel); else tdm.train(dataset, parallel); }
[ "public", "static", "void", "trainIfNeeded", "(", "DistanceMetric", "dm", ",", "DataSet", "dataset", ",", "boolean", "parallel", ")", "{", "if", "(", "!", "(", "dm", "instanceof", "TrainableDistanceMetric", ")", ")", "return", ";", "TrainableDistanceMetric", "td...
Static helper method for training a distance metric only if it is needed. This method can be safely called for any Distance Metric. @param dm the distance metric to train @param dataset the data set to train from @param parallel {@code true} if multiple threads should be used for training. {@code false} if it should be done in a single-threaded manner.
[ "Static", "helper", "method", "for", "training", "a", "distance", "metric", "only", "if", "it", "is", "needed", ".", "This", "method", "can", "be", "safely", "called", "for", "any", "Distance", "Metric", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/distancemetrics/TrainableDistanceMetric.java#L160-L173
Erudika/para
para-core/src/main/java/com/erudika/para/utils/Config.java
Config.getConfigDouble
public static double getConfigDouble(String key, double defaultValue) { return NumberUtils.toDouble(getConfigParam(key, Double.toString(defaultValue))); }
java
public static double getConfigDouble(String key, double defaultValue) { return NumberUtils.toDouble(getConfigParam(key, Double.toString(defaultValue))); }
[ "public", "static", "double", "getConfigDouble", "(", "String", "key", ",", "double", "defaultValue", ")", "{", "return", "NumberUtils", ".", "toDouble", "(", "getConfigParam", "(", "key", ",", "Double", ".", "toString", "(", "defaultValue", ")", ")", ")", "...
Returns the double value of a configuration parameter. @param key the param key @param defaultValue the default param value @return the value of a param
[ "Returns", "the", "double", "value", "of", "a", "configuration", "parameter", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-core/src/main/java/com/erudika/para/utils/Config.java#L344-L346
grpc/grpc-java
okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/OptionalMethod.java
OptionalMethod.invokeOptionalWithoutCheckedException
public Object invokeOptionalWithoutCheckedException(T target, Object... args) { try { return invokeOptional(target, args); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } AssertionError error = new AssertionError("Unexpected exception"); error.initCause(targetException); throw error; } }
java
public Object invokeOptionalWithoutCheckedException(T target, Object... args) { try { return invokeOptional(target, args); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } AssertionError error = new AssertionError("Unexpected exception"); error.initCause(targetException); throw error; } }
[ "public", "Object", "invokeOptionalWithoutCheckedException", "(", "T", "target", ",", "Object", "...", "args", ")", "{", "try", "{", "return", "invokeOptional", "(", "target", ",", "args", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{"...
Invokes the method on {@code target}. If the method does not exist or is not public then {@code null} is returned. Any RuntimeException thrown by the method is thrown, checked exceptions are wrapped in an {@link AssertionError}. @throws IllegalArgumentException if the arguments are invalid
[ "Invokes", "the", "method", "on", "{", "@code", "target", "}", ".", "If", "the", "method", "does", "not", "exist", "or", "is", "not", "public", "then", "{", "@code", "null", "}", "is", "returned", ".", "Any", "RuntimeException", "thrown", "by", "the", ...
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/OptionalMethod.java#L90-L102
qubole/qds-sdk-java
src/main/java/com/qubole/qds/sdk/java/client/ResultLatch.java
ResultLatch.setPollSleep
public void setPollSleep(long time, TimeUnit unit) { if (unit.toMillis(time) < MIN_POLL_MS) { LOG.warning(String.format("Poll interval cannot be less than %d seconds. Setting it to %d seconds.", TimeUnit.MILLISECONDS.toSeconds(MIN_POLL_MS), TimeUnit.MILLISECONDS.toSeconds(MIN_POLL_MS))); pollMs.set(MIN_POLL_MS); } else { pollMs.set(unit.toMillis(time)); } }
java
public void setPollSleep(long time, TimeUnit unit) { if (unit.toMillis(time) < MIN_POLL_MS) { LOG.warning(String.format("Poll interval cannot be less than %d seconds. Setting it to %d seconds.", TimeUnit.MILLISECONDS.toSeconds(MIN_POLL_MS), TimeUnit.MILLISECONDS.toSeconds(MIN_POLL_MS))); pollMs.set(MIN_POLL_MS); } else { pollMs.set(unit.toMillis(time)); } }
[ "public", "void", "setPollSleep", "(", "long", "time", ",", "TimeUnit", "unit", ")", "{", "if", "(", "unit", ".", "toMillis", "(", "time", ")", "<", "MIN_POLL_MS", ")", "{", "LOG", ".", "warning", "(", "String", ".", "format", "(", "\"Poll interval canno...
Change the time that the query status is polled. The default is {@link #DEFAULT_POLL_MS}. @param time polling time @param unit time unit
[ "Change", "the", "time", "that", "the", "query", "status", "is", "polled", ".", "The", "default", "is", "{", "@link", "#DEFAULT_POLL_MS", "}", "." ]
train
https://github.com/qubole/qds-sdk-java/blob/c652374075c7b72071f73db960f5f3a43f922afd/src/main/java/com/qubole/qds/sdk/java/client/ResultLatch.java#L75-L86
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java
InternalService.getConversation
public Observable<ComapiResult<ConversationDetails>> getConversation(@NonNull final String conversationId) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueGetConversation(conversationId); } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); } else { return doGetConversation(token, conversationId); } }
java
public Observable<ComapiResult<ConversationDetails>> getConversation(@NonNull final String conversationId) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueGetConversation(conversationId); } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); } else { return doGetConversation(token, conversationId); } }
[ "public", "Observable", "<", "ComapiResult", "<", "ConversationDetails", ">", ">", "getConversation", "(", "@", "NonNull", "final", "String", "conversationId", ")", "{", "final", "String", "token", "=", "getToken", "(", ")", ";", "if", "(", "sessionController", ...
Returns observable to create a conversation. @param conversationId ID of a conversation to obtain. @return Observable to to create a conversation.
[ "Returns", "observable", "to", "create", "a", "conversation", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L474-L485
groovy/groovy-core
subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovy.java
Groovy.runStatements
protected void runStatements(Reader reader, PrintStream out) throws IOException { log.debug("runStatements()"); StringBuilder txt = new StringBuilder(); String line = ""; BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { line = getProject().replaceProperties(line); if (line.indexOf("--") >= 0) { txt.append("\n"); } } // Catch any statements not followed by ; if (!txt.toString().equals("")) { execGroovy(txt.toString(), out); } }
java
protected void runStatements(Reader reader, PrintStream out) throws IOException { log.debug("runStatements()"); StringBuilder txt = new StringBuilder(); String line = ""; BufferedReader in = new BufferedReader(reader); while ((line = in.readLine()) != null) { line = getProject().replaceProperties(line); if (line.indexOf("--") >= 0) { txt.append("\n"); } } // Catch any statements not followed by ; if (!txt.toString().equals("")) { execGroovy(txt.toString(), out); } }
[ "protected", "void", "runStatements", "(", "Reader", "reader", ",", "PrintStream", "out", ")", "throws", "IOException", "{", "log", ".", "debug", "(", "\"runStatements()\"", ")", ";", "StringBuilder", "txt", "=", "new", "StringBuilder", "(", ")", ";", "String"...
Read in lines and execute them. @param reader the reader from which to get the groovy source to exec @param out the outputstream to use @throws java.io.IOException if something goes wrong
[ "Read", "in", "lines", "and", "execute", "them", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovy.java#L354-L371
apache/groovy
src/main/java/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java
TypeTransformers.applyUnsharpFilter
public static MethodHandle applyUnsharpFilter(MethodHandle handle, int pos, MethodHandle transformer) { MethodType type = transformer.type(); Class given = handle.type().parameterType(pos); if (type.returnType() != given || type.parameterType(0) != given) { transformer = transformer.asType(MethodType.methodType(given, type.parameterType(0))); } return MethodHandles.filterArguments(handle, pos, transformer); }
java
public static MethodHandle applyUnsharpFilter(MethodHandle handle, int pos, MethodHandle transformer) { MethodType type = transformer.type(); Class given = handle.type().parameterType(pos); if (type.returnType() != given || type.parameterType(0) != given) { transformer = transformer.asType(MethodType.methodType(given, type.parameterType(0))); } return MethodHandles.filterArguments(handle, pos, transformer); }
[ "public", "static", "MethodHandle", "applyUnsharpFilter", "(", "MethodHandle", "handle", ",", "int", "pos", ",", "MethodHandle", "transformer", ")", "{", "MethodType", "type", "=", "transformer", ".", "type", "(", ")", ";", "Class", "given", "=", "handle", "."...
Apply a transformer as filter. The filter may not match exactly in the types. In this case needed additional type transformations are done by {@link MethodHandle#asType(MethodType)}
[ "Apply", "a", "transformer", "as", "filter", ".", "The", "filter", "may", "not", "match", "exactly", "in", "the", "types", ".", "In", "this", "case", "needed", "additional", "type", "transformations", "are", "done", "by", "{" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/vmplugin/v7/TypeTransformers.java#L198-L205
doubledutch/LazyJSON
src/main/java/me/doubledutch/lazyjson/LazyArray.java
LazyArray.getBoolean
public boolean getBoolean(int index){ LazyNode token=getValueToken(index); if(token.type==LazyNode.VALUE_TRUE)return true; if(token.type==LazyNode.VALUE_FALSE)return false; throw new LazyException("Requested value is not a boolean",token); }
java
public boolean getBoolean(int index){ LazyNode token=getValueToken(index); if(token.type==LazyNode.VALUE_TRUE)return true; if(token.type==LazyNode.VALUE_FALSE)return false; throw new LazyException("Requested value is not a boolean",token); }
[ "public", "boolean", "getBoolean", "(", "int", "index", ")", "{", "LazyNode", "token", "=", "getValueToken", "(", "index", ")", ";", "if", "(", "token", ".", "type", "==", "LazyNode", ".", "VALUE_TRUE", ")", "return", "true", ";", "if", "(", "token", "...
Returns the boolean value stored at the given index. @param index the location of the value in this array @return the value if it could be parsed as a boolean @throws LazyException if the index is out of bounds
[ "Returns", "the", "boolean", "value", "stored", "at", "the", "given", "index", "." ]
train
https://github.com/doubledutch/LazyJSON/blob/1a223f57fc0cb9941bc175739697ac95da5618cc/src/main/java/me/doubledutch/lazyjson/LazyArray.java#L500-L505
drinkjava2/jBeanBox
jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/util/CheckClassAdapter.java
CheckClassAdapter.checkClassTypeSignature
private static int checkClassTypeSignature(final String signature, int pos) { // ClassTypeSignature: // L Identifier ( / Identifier )* TypeArguments? ( . Identifier // TypeArguments? )* ; pos = checkChar('L', signature, pos); pos = checkIdentifier(signature, pos); while (getChar(signature, pos) == '/') { pos = checkIdentifier(signature, pos + 1); } if (getChar(signature, pos) == '<') { pos = checkTypeArguments(signature, pos); } while (getChar(signature, pos) == '.') { pos = checkIdentifier(signature, pos + 1); if (getChar(signature, pos) == '<') { pos = checkTypeArguments(signature, pos); } } return checkChar(';', signature, pos); }
java
private static int checkClassTypeSignature(final String signature, int pos) { // ClassTypeSignature: // L Identifier ( / Identifier )* TypeArguments? ( . Identifier // TypeArguments? )* ; pos = checkChar('L', signature, pos); pos = checkIdentifier(signature, pos); while (getChar(signature, pos) == '/') { pos = checkIdentifier(signature, pos + 1); } if (getChar(signature, pos) == '<') { pos = checkTypeArguments(signature, pos); } while (getChar(signature, pos) == '.') { pos = checkIdentifier(signature, pos + 1); if (getChar(signature, pos) == '<') { pos = checkTypeArguments(signature, pos); } } return checkChar(';', signature, pos); }
[ "private", "static", "int", "checkClassTypeSignature", "(", "final", "String", "signature", ",", "int", "pos", ")", "{", "// ClassTypeSignature:", "// L Identifier ( / Identifier )* TypeArguments? ( . Identifier", "// TypeArguments? )* ;", "pos", "=", "checkChar", "(", "'", ...
Checks a class type signature. @param signature a string containing the signature that must be checked. @param pos index of first character to be checked. @return the index of the first character after the checked part.
[ "Checks", "a", "class", "type", "signature", "." ]
train
https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/util/CheckClassAdapter.java#L846-L866
liyiorg/weixin-popular
src/main/java/weixin/popular/api/DataCubeAPI.java
DataCubeAPI.getCardMemberCardInfo
public static MemberCardInfoResult getCardMemberCardInfo(String access_token, MemberCardInfo memberCardCube) { return getCardMemberCardInfo(access_token, JsonUtil.toJSONString(memberCardCube)); }
java
public static MemberCardInfoResult getCardMemberCardInfo(String access_token, MemberCardInfo memberCardCube) { return getCardMemberCardInfo(access_token, JsonUtil.toJSONString(memberCardCube)); }
[ "public", "static", "MemberCardInfoResult", "getCardMemberCardInfo", "(", "String", "access_token", ",", "MemberCardInfo", "memberCardCube", ")", "{", "return", "getCardMemberCardInfo", "(", "access_token", ",", "JsonUtil", ".", "toJSONString", "(", "memberCardCube", ")",...
拉取会员卡数据<br> 1. 查询时间区间需&lt;=62天,否则报错;<br> 2. 传入时间格式需严格参照示例填写如”2015-06-15”,否则报错;<br> 3. 该接口只能拉取非当天的数据,不能拉取当天的卡券数据,否则报错。<br> @param access_token access_token @param memberCardCube memberCardCube @return result
[ "拉取会员卡数据<br", ">", "1", ".", "查询时间区间需&lt", ";", "=", "62天,否则报错;<br", ">", "2", ".", "传入时间格式需严格参照示例填写如”2015", "-", "06", "-", "15”,否则报错;<br", ">", "3", ".", "该接口只能拉取非当天的数据,不能拉取当天的卡券数据,否则报错。<br", ">" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/DataCubeAPI.java#L114-L116
alipay/sofa-rpc
extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/SofaNettyJaxrsServer.java
SofaNettyJaxrsServer.setChildChannelOptions
public void setChildChannelOptions(final Map<ChannelOption, Object> channelOptions) { this.childChannelOptions = channelOptions == null ? Collections.<ChannelOption, Object> emptyMap() : channelOptions; }
java
public void setChildChannelOptions(final Map<ChannelOption, Object> channelOptions) { this.childChannelOptions = channelOptions == null ? Collections.<ChannelOption, Object> emptyMap() : channelOptions; }
[ "public", "void", "setChildChannelOptions", "(", "final", "Map", "<", "ChannelOption", ",", "Object", ">", "channelOptions", ")", "{", "this", ".", "childChannelOptions", "=", "channelOptions", "==", "null", "?", "Collections", ".", "<", "ChannelOption", ",", "O...
Add child options to the {@link io.netty.bootstrap.ServerBootstrap}. @param channelOptions the additional child {@link io.netty.channel.ChannelOption}s. @see io.netty.bootstrap.ServerBootstrap#childOption(io.netty.channel.ChannelOption, Object)
[ "Add", "child", "options", "to", "the", "{", "@link", "io", ".", "netty", ".", "bootstrap", ".", "ServerBootstrap", "}", "." ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/SofaNettyJaxrsServer.java#L186-L189
carewebframework/carewebframework-core
org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/spring/BaseXmlParser.java
BaseXmlParser.findTag
protected Element findTag(String tagName, Element element) { Node result = element.getFirstChild(); while (result != null) { if (result instanceof Element && (tagName.equals(((Element) result).getNodeName()) || tagName .equals(((Element) result).getLocalName()))) { break; } result = result.getNextSibling(); } return (Element) result; }
java
protected Element findTag(String tagName, Element element) { Node result = element.getFirstChild(); while (result != null) { if (result instanceof Element && (tagName.equals(((Element) result).getNodeName()) || tagName .equals(((Element) result).getLocalName()))) { break; } result = result.getNextSibling(); } return (Element) result; }
[ "protected", "Element", "findTag", "(", "String", "tagName", ",", "Element", "element", ")", "{", "Node", "result", "=", "element", ".", "getFirstChild", "(", ")", ";", "while", "(", "result", "!=", "null", ")", "{", "if", "(", "result", "instanceof", "E...
Find the child element whose tag matches the specified tag name. @param tagName Tag name to locate. @param element Parent element whose children are to be searched. @return The matching node (first occurrence only) or null if not found.
[ "Find", "the", "child", "element", "whose", "tag", "matches", "the", "specified", "tag", "name", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.api-parent/org.carewebframework.api.core/src/main/java/org/carewebframework/api/spring/BaseXmlParser.java#L60-L73
jbundle/jbundle
base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HBaseGridScreen.java
HBaseGridScreen.printStartGridScreenData
public int printStartGridScreenData(PrintWriter out, int iPrintOptions) { if ((iPrintOptions & HtmlConstants.HTML_ADD_DESC_COLUMN) != 0) out.println("<td></td>"); // No description needed for a table if ((iPrintOptions & HtmlConstants.HTML_IN_TABLE_ROW) != 0) out.println("<td>"); iPrintOptions = iPrintOptions & (~HtmlConstants.HTML_IN_TABLE_ROW); // sub-controls not in a table row iPrintOptions = iPrintOptions & (~HtmlConstants.HTML_ADD_DESC_COLUMN); // Sub-controls - don't add desc. return iPrintOptions; }
java
public int printStartGridScreenData(PrintWriter out, int iPrintOptions) { if ((iPrintOptions & HtmlConstants.HTML_ADD_DESC_COLUMN) != 0) out.println("<td></td>"); // No description needed for a table if ((iPrintOptions & HtmlConstants.HTML_IN_TABLE_ROW) != 0) out.println("<td>"); iPrintOptions = iPrintOptions & (~HtmlConstants.HTML_IN_TABLE_ROW); // sub-controls not in a table row iPrintOptions = iPrintOptions & (~HtmlConstants.HTML_ADD_DESC_COLUMN); // Sub-controls - don't add desc. return iPrintOptions; }
[ "public", "int", "printStartGridScreenData", "(", "PrintWriter", "out", ",", "int", "iPrintOptions", ")", "{", "if", "(", "(", "iPrintOptions", "&", "HtmlConstants", ".", "HTML_ADD_DESC_COLUMN", ")", "!=", "0", ")", "out", ".", "println", "(", "\"<td></td>\"", ...
Display the start grid in input format. @return true if default params were found for this form. @param out The http output stream. @exception DBException File exception.
[ "Display", "the", "start", "grid", "in", "input", "format", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/view/html/src/main/java/org/jbundle/base/screen/view/html/HBaseGridScreen.java#L134-L143
alkacon/opencms-core
src/org/opencms/ui/CmsVaadinUtils.java
CmsVaadinUtils.filterUtf8ResourceStream
public static InputStream filterUtf8ResourceStream(InputStream stream, Function<String, String> transformation) { try { byte[] streamData = CmsFileUtil.readFully(stream); String dataAsString = new String(streamData, "UTF-8"); byte[] transformedData = transformation.apply(dataAsString).getBytes("UTF-8"); return new ByteArrayInputStream(transformedData); } catch (UnsupportedEncodingException e) { LOG.error(e.getLocalizedMessage(), e); return null; } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw new RuntimeException(e); } }
java
public static InputStream filterUtf8ResourceStream(InputStream stream, Function<String, String> transformation) { try { byte[] streamData = CmsFileUtil.readFully(stream); String dataAsString = new String(streamData, "UTF-8"); byte[] transformedData = transformation.apply(dataAsString).getBytes("UTF-8"); return new ByteArrayInputStream(transformedData); } catch (UnsupportedEncodingException e) { LOG.error(e.getLocalizedMessage(), e); return null; } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw new RuntimeException(e); } }
[ "public", "static", "InputStream", "filterUtf8ResourceStream", "(", "InputStream", "stream", ",", "Function", "<", "String", ",", "String", ">", "transformation", ")", "{", "try", "{", "byte", "[", "]", "streamData", "=", "CmsFileUtil", ".", "readFully", "(", ...
Reads the content of an input stream into a string (using UTF-8 encoding), performs a function on the string, and returns the result again as an input stream.<p> @param stream the stream producing the input data @param transformation the function to apply to the input @return the stream producing the transformed input data
[ "Reads", "the", "content", "of", "an", "input", "stream", "into", "a", "string", "(", "using", "UTF", "-", "8", "encoding", ")", "performs", "a", "function", "on", "the", "string", "and", "returns", "the", "result", "again", "as", "an", "input", "stream"...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsVaadinUtils.java#L361-L375
zxing/zxing
android/src/com/google/zxing/client/android/CaptureActivity.java
CaptureActivity.handleDecode
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); lastResult = rawResult; ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult); boolean fromLiveScan = barcode != null; if (fromLiveScan) { historyManager.addHistoryItem(rawResult, resultHandler); // Then not from history, so beep/vibrate and we have an image to draw on beepManager.playBeepSoundAndVibrate(); drawResultPoints(barcode, scaleFactor, rawResult); } switch (source) { case NATIVE_APP_INTENT: case PRODUCT_SEARCH_LINK: handleDecodeExternally(rawResult, resultHandler, barcode); break; case ZXING_LINK: if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) { handleDecodeInternally(rawResult, resultHandler, barcode); } else { handleDecodeExternally(rawResult, resultHandler, barcode); } break; case NONE: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_bulk_mode_scanned) + " (" + rawResult.getText() + ')', Toast.LENGTH_SHORT).show(); maybeSetClipboard(resultHandler); // Wait a moment or else it will scan the same barcode continuously about 3 times restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } else { handleDecodeInternally(rawResult, resultHandler, barcode); } break; } }
java
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); lastResult = rawResult; ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult); boolean fromLiveScan = barcode != null; if (fromLiveScan) { historyManager.addHistoryItem(rawResult, resultHandler); // Then not from history, so beep/vibrate and we have an image to draw on beepManager.playBeepSoundAndVibrate(); drawResultPoints(barcode, scaleFactor, rawResult); } switch (source) { case NATIVE_APP_INTENT: case PRODUCT_SEARCH_LINK: handleDecodeExternally(rawResult, resultHandler, barcode); break; case ZXING_LINK: if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) { handleDecodeInternally(rawResult, resultHandler, barcode); } else { handleDecodeExternally(rawResult, resultHandler, barcode); } break; case NONE: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_bulk_mode_scanned) + " (" + rawResult.getText() + ')', Toast.LENGTH_SHORT).show(); maybeSetClipboard(resultHandler); // Wait a moment or else it will scan the same barcode continuously about 3 times restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } else { handleDecodeInternally(rawResult, resultHandler, barcode); } break; } }
[ "public", "void", "handleDecode", "(", "Result", "rawResult", ",", "Bitmap", "barcode", ",", "float", "scaleFactor", ")", "{", "inactivityTimer", ".", "onActivity", "(", ")", ";", "lastResult", "=", "rawResult", ";", "ResultHandler", "resultHandler", "=", "Resul...
A valid barcode has been found, so give an indication of success and show the results. @param rawResult The contents of the barcode. @param scaleFactor amount by which thumbnail was scaled @param barcode A greyscale bitmap of the camera data which was decoded.
[ "A", "valid", "barcode", "has", "been", "found", "so", "give", "an", "indication", "of", "success", "and", "show", "the", "results", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/android/src/com/google/zxing/client/android/CaptureActivity.java#L443-L482
magik6k/JWWF
src/main/java/net/magik6k/jwwf/widgets/basic/panel/generic/LinePanel.java
LinePanel.put
public int put(Iterable<? extends Widget> widgets, int startIndex) throws IndexOutOfBoundsException { int index = startIndex; for (Widget widget : widgets) { put(widget, index); ++index; } return index; }
java
public int put(Iterable<? extends Widget> widgets, int startIndex) throws IndexOutOfBoundsException { int index = startIndex; for (Widget widget : widgets) { put(widget, index); ++index; } return index; }
[ "public", "int", "put", "(", "Iterable", "<", "?", "extends", "Widget", ">", "widgets", ",", "int", "startIndex", ")", "throws", "IndexOutOfBoundsException", "{", "int", "index", "=", "startIndex", ";", "for", "(", "Widget", "widget", ":", "widgets", ")", ...
Adds all widgets from given iterable @param widgets Iterable object containing widgets @param startIndex index at wich adding will start @return Index of last added element @throws IndexOutOfBoundsException when specified startIndex is negative or there is no more space
[ "Adds", "all", "widgets", "from", "given", "iterable" ]
train
https://github.com/magik6k/JWWF/blob/8ba334501396c3301495da8708733f6014f20665/src/main/java/net/magik6k/jwwf/widgets/basic/panel/generic/LinePanel.java#L42-L49
tomgibara/bits
src/main/java/com/tomgibara/bits/Bits.java
Bits.readerFrom
public static BitReader readerFrom(int[] ints, long size) { if (ints == null) throw new IllegalArgumentException("null ints"); checkSize(size, ((long) ints.length) << 5); return new IntArrayBitReader(ints, size); }
java
public static BitReader readerFrom(int[] ints, long size) { if (ints == null) throw new IllegalArgumentException("null ints"); checkSize(size, ((long) ints.length) << 5); return new IntArrayBitReader(ints, size); }
[ "public", "static", "BitReader", "readerFrom", "(", "int", "[", "]", "ints", ",", "long", "size", ")", "{", "if", "(", "ints", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"null ints\"", ")", ";", "checkSize", "(", "size", ",", "...
A {@link BitReader} that sources its bits from an array of ints. Bits are read from the int array starting at index zero. Within each int, the most significant bits are read first. @param ints the source ints @param size the number of bits that may be read, not negative and no greater than the number of bits supplied by the array @return a bit reader over the ints
[ "A", "{", "@link", "BitReader", "}", "that", "sources", "its", "bits", "from", "an", "array", "of", "ints", ".", "Bits", "are", "read", "from", "the", "int", "array", "starting", "at", "index", "zero", ".", "Within", "each", "int", "the", "most", "sign...
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/Bits.java#L760-L764
enioka/jqm
jqm-all/jqm-admin/src/main/java/com/enioka/admin/MetaService.java
MetaService.deleteAllMeta
public static void deleteAllMeta(DbConn cnx, boolean force) { if (force) { deleteAllTransac(cnx); } cnx.runUpdate("globalprm_delete_all"); cnx.runUpdate("dp_delete_all"); cnx.runUpdate("sjprm_delete_all"); cnx.runUpdate("sj_delete_all"); cnx.runUpdate("jdprm_delete_all"); cnx.runUpdate("node_delete_all"); cnx.runUpdate("jd_delete_all"); cnx.runUpdate("q_delete_all"); cnx.runUpdate("jndiprm_delete_all"); cnx.runUpdate("jndi_delete_all"); cnx.runUpdate("pki_delete_all"); // No corresponding DTO. cnx.runUpdate("perm_delete_all"); cnx.runUpdate("role_delete_all"); cnx.runUpdate("user_delete_all"); }
java
public static void deleteAllMeta(DbConn cnx, boolean force) { if (force) { deleteAllTransac(cnx); } cnx.runUpdate("globalprm_delete_all"); cnx.runUpdate("dp_delete_all"); cnx.runUpdate("sjprm_delete_all"); cnx.runUpdate("sj_delete_all"); cnx.runUpdate("jdprm_delete_all"); cnx.runUpdate("node_delete_all"); cnx.runUpdate("jd_delete_all"); cnx.runUpdate("q_delete_all"); cnx.runUpdate("jndiprm_delete_all"); cnx.runUpdate("jndi_delete_all"); cnx.runUpdate("pki_delete_all"); // No corresponding DTO. cnx.runUpdate("perm_delete_all"); cnx.runUpdate("role_delete_all"); cnx.runUpdate("user_delete_all"); }
[ "public", "static", "void", "deleteAllMeta", "(", "DbConn", "cnx", ",", "boolean", "force", ")", "{", "if", "(", "force", ")", "{", "deleteAllTransac", "(", "cnx", ")", ";", "}", "cnx", ".", "runUpdate", "(", "\"globalprm_delete_all\"", ")", ";", "cnx", ...
Empty the database. <br> No commit performed. @param cnx database session to use. Not committed. @param force set to true if you want to delete metadata even if there is still transactional data depending on it.
[ "Empty", "the", "database", ".", "<br", ">", "No", "commit", "performed", "." ]
train
https://github.com/enioka/jqm/blob/391733b8e291404b97c714c3727a241c4a861f98/jqm-all/jqm-admin/src/main/java/com/enioka/admin/MetaService.java#L60-L81
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/stats/impl/IntervalNameParser.java
IntervalNameParser.guessLengthFromName
static final int guessLengthFromName(String aName) { if (aName.startsWith(Constants.PREFIX_SNAPSHOT_INTERVAL)) return -1; int unitFactor; int value; try { value = Integer.parseInt(aName.substring(0, aName.length() - 1)); } catch (NumberFormatException e) { throw new UnknownIntervalLengthException("Unsupported Interval name format: " + aName); } char lastChar = aName.charAt(aName.length() - 1); TimeUnit unit = lookupMap.get(Character.toLowerCase(lastChar)); if (unit==null) throw new UnknownIntervalLengthException(aName + ", " + lastChar + " is not a supported unit."); unitFactor = unit.getFactor(); if (value == 0) throw new UnknownIntervalLengthException(aName + ", zero duration is not allowed."); return value * unitFactor; }
java
static final int guessLengthFromName(String aName) { if (aName.startsWith(Constants.PREFIX_SNAPSHOT_INTERVAL)) return -1; int unitFactor; int value; try { value = Integer.parseInt(aName.substring(0, aName.length() - 1)); } catch (NumberFormatException e) { throw new UnknownIntervalLengthException("Unsupported Interval name format: " + aName); } char lastChar = aName.charAt(aName.length() - 1); TimeUnit unit = lookupMap.get(Character.toLowerCase(lastChar)); if (unit==null) throw new UnknownIntervalLengthException(aName + ", " + lastChar + " is not a supported unit."); unitFactor = unit.getFactor(); if (value == 0) throw new UnknownIntervalLengthException(aName + ", zero duration is not allowed."); return value * unitFactor; }
[ "static", "final", "int", "guessLengthFromName", "(", "String", "aName", ")", "{", "if", "(", "aName", ".", "startsWith", "(", "Constants", ".", "PREFIX_SNAPSHOT_INTERVAL", ")", ")", "return", "-", "1", ";", "int", "unitFactor", ";", "int", "value", ";", "...
This method parses the given Interval name and returns the length of such an Interval in seconds. @param aName the name of the Interval @return the appropriate length @throws UnknownIntervalLengthException if the name could not be parsed
[ "This", "method", "parses", "the", "given", "Interval", "name", "and", "returns", "the", "length", "of", "such", "an", "Interval", "in", "seconds", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/stats/impl/IntervalNameParser.java#L118-L144
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/event/SelectOnUpdateHandler.java
SelectOnUpdateHandler.init
public void init(Record record, Record recordToSync, boolean bUpdateOnSelect) { super.init(record, null, recordToSync, bUpdateOnSelect, DBConstants.SELECT_TYPE); }
java
public void init(Record record, Record recordToSync, boolean bUpdateOnSelect) { super.init(record, null, recordToSync, bUpdateOnSelect, DBConstants.SELECT_TYPE); }
[ "public", "void", "init", "(", "Record", "record", ",", "Record", "recordToSync", ",", "boolean", "bUpdateOnSelect", ")", "{", "super", ".", "init", "(", "record", ",", "null", ",", "recordToSync", ",", "bUpdateOnSelect", ",", "DBConstants", ".", "SELECT_TYPE"...
SelectOnUpdateHandler - Constructor. @param recordToSync The record to synchronize with this one. @param bUpdateOnSelect If true, update or add a record in progress before syncing this record.
[ "SelectOnUpdateHandler", "-", "Constructor", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/event/SelectOnUpdateHandler.java#L50-L53
pierre/eventtracker
common/src/main/java/com/ning/metrics/eventtracker/DiskSpoolEventWriterProvider.java
DiskSpoolEventWriterProvider.get
@Override public DiskSpoolEventWriter get() { return new DiskSpoolEventWriter(new EventHandler() { @Override public void handle(final File file, final CallbackHandler handler) { eventSender.send(file, handler); } }, config.getSpoolDirectoryName(), config.isFlushEnabled(), config.getFlushIntervalInSeconds(), executor, SyncType.valueOf(config.getSyncType()), config.getSyncBatchSize(), new NoCompressionCodec(), serializer); }
java
@Override public DiskSpoolEventWriter get() { return new DiskSpoolEventWriter(new EventHandler() { @Override public void handle(final File file, final CallbackHandler handler) { eventSender.send(file, handler); } }, config.getSpoolDirectoryName(), config.isFlushEnabled(), config.getFlushIntervalInSeconds(), executor, SyncType.valueOf(config.getSyncType()), config.getSyncBatchSize(), new NoCompressionCodec(), serializer); }
[ "@", "Override", "public", "DiskSpoolEventWriter", "get", "(", ")", "{", "return", "new", "DiskSpoolEventWriter", "(", "new", "EventHandler", "(", ")", "{", "@", "Override", "public", "void", "handle", "(", "final", "File", "file", ",", "final", "CallbackHandl...
Provides an instance of a DiskSpoolEventWriter, which forwards local buffered events (in files) to the collector, via an EventSender. @return instance of a DiskSpoolEventWriter
[ "Provides", "an", "instance", "of", "a", "DiskSpoolEventWriter", "which", "forwards", "local", "buffered", "events", "(", "in", "files", ")", "to", "the", "collector", "via", "an", "EventSender", "." ]
train
https://github.com/pierre/eventtracker/blob/d47e74f11b05500fc31eeb43448aa6316a1318f6/common/src/main/java/com/ning/metrics/eventtracker/DiskSpoolEventWriterProvider.java#L58-L70
gallandarakhneorg/afc
core/text/src/main/java/org/arakhne/afc/text/TextUtil.java
TextUtil.cutString
@Pure public static String cutString(String text, int column) { final StringBuilder buffer = new StringBuilder(); cutStringAlgo(text, new CutStringColumnCritera(column), new CutStringToString(buffer)); return buffer.toString(); }
java
@Pure public static String cutString(String text, int column) { final StringBuilder buffer = new StringBuilder(); cutStringAlgo(text, new CutStringColumnCritera(column), new CutStringToString(buffer)); return buffer.toString(); }
[ "@", "Pure", "public", "static", "String", "cutString", "(", "String", "text", ",", "int", "column", ")", "{", "final", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "cutStringAlgo", "(", "text", ",", "new", "CutStringColumnCritera", ...
Format the text to be sure that each line is not more longer than the specified quantity of characters. @param text is the string to cut @param column is the column number that corresponds to the splitting point. @return the given {@code text} splitted in lines separated by <code>\n</code>.
[ "Format", "the", "text", "to", "be", "sure", "that", "each", "line", "is", "not", "more", "longer", "than", "the", "specified", "quantity", "of", "characters", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/text/src/main/java/org/arakhne/afc/text/TextUtil.java#L380-L385
apiman/apiman
manager/api/war/src/main/java/io/apiman/manager/api/war/WarCdiFactory.java
WarCdiFactory.initEsStorage
private static EsStorage initEsStorage(WarApiManagerConfig config, EsStorage esStorage) { if (sESStorage == null) { sESStorage = esStorage; sESStorage.setIndexName(config.getStorageESIndexName()); if (config.isInitializeStorageES()) { sESStorage.initialize(); } } return sESStorage; }
java
private static EsStorage initEsStorage(WarApiManagerConfig config, EsStorage esStorage) { if (sESStorage == null) { sESStorage = esStorage; sESStorage.setIndexName(config.getStorageESIndexName()); if (config.isInitializeStorageES()) { sESStorage.initialize(); } } return sESStorage; }
[ "private", "static", "EsStorage", "initEsStorage", "(", "WarApiManagerConfig", "config", ",", "EsStorage", "esStorage", ")", "{", "if", "(", "sESStorage", "==", "null", ")", "{", "sESStorage", "=", "esStorage", ";", "sESStorage", ".", "setIndexName", "(", "confi...
Initializes the ES storage (if required). @param config @param esStorage
[ "Initializes", "the", "ES", "storage", "(", "if", "required", ")", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/war/src/main/java/io/apiman/manager/api/war/WarCdiFactory.java#L284-L293
graknlabs/grakn
server/src/graql/gremlin/sets/EquivalentFragmentSets.java
EquivalentFragmentSets.isa
public static EquivalentFragmentSet isa( VarProperty varProperty, Variable instance, Variable type, boolean mayHaveEdgeInstances) { return new AutoValue_IsaFragmentSet(varProperty, instance, type, mayHaveEdgeInstances); }
java
public static EquivalentFragmentSet isa( VarProperty varProperty, Variable instance, Variable type, boolean mayHaveEdgeInstances) { return new AutoValue_IsaFragmentSet(varProperty, instance, type, mayHaveEdgeInstances); }
[ "public", "static", "EquivalentFragmentSet", "isa", "(", "VarProperty", "varProperty", ",", "Variable", "instance", ",", "Variable", "type", ",", "boolean", "mayHaveEdgeInstances", ")", "{", "return", "new", "AutoValue_IsaFragmentSet", "(", "varProperty", ",", "instan...
An {@link EquivalentFragmentSet} that indicates a variable is a direct instance of a type.
[ "An", "{" ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/sets/EquivalentFragmentSets.java#L113-L116
xmlunit/xmlunit
xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLAssert.java
XMLAssert.assertXMLEqual
public static void assertXMLEqual(String err, Reader control, Reader test) throws SAXException, IOException { Diff diff = new Diff(control, test); assertXMLEqual(err, diff, true); }
java
public static void assertXMLEqual(String err, Reader control, Reader test) throws SAXException, IOException { Diff diff = new Diff(control, test); assertXMLEqual(err, diff, true); }
[ "public", "static", "void", "assertXMLEqual", "(", "String", "err", ",", "Reader", "control", ",", "Reader", "test", ")", "throws", "SAXException", ",", "IOException", "{", "Diff", "diff", "=", "new", "Diff", "(", "control", ",", "test", ")", ";", "assertX...
Assert that two XML documents are similar @param err Message to be displayed on assertion failure @param control XML to be compared against @param test XML to be tested @throws SAXException @throws IOException
[ "Assert", "that", "two", "XML", "documents", "are", "similar" ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLAssert.java#L256-L260
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java
Util.alphaMixColors
public static int alphaMixColors(int backgroundColor, int foregroundColor) { final byte ALPHA_CHANNEL = 24; final byte RED_CHANNEL = 16; final byte GREEN_CHANNEL = 8; final byte BLUE_CHANNEL = 0; final double ap1 = (double) (backgroundColor >> ALPHA_CHANNEL & 0xff) / 255d; final double ap2 = (double) (foregroundColor >> ALPHA_CHANNEL & 0xff) / 255d; final double ap = ap2 + (ap1 * (1 - ap2)); final double amount1 = (ap1 * (1 - ap2)) / ap; final double amount2 = amount1 / ap; int a = ((int) (ap * 255d)) & 0xff; int r = ((int) (((float) (backgroundColor >> RED_CHANNEL & 0xff) * amount1) + ((float) (foregroundColor >> RED_CHANNEL & 0xff) * amount2))) & 0xff; int g = ((int) (((float) (backgroundColor >> GREEN_CHANNEL & 0xff) * amount1) + ((float) (foregroundColor >> GREEN_CHANNEL & 0xff) * amount2))) & 0xff; int b = ((int) (((float) (backgroundColor & 0xff) * amount1) + ((float) (foregroundColor & 0xff) * amount2))) & 0xff; return a << ALPHA_CHANNEL | r << RED_CHANNEL | g << GREEN_CHANNEL | b << BLUE_CHANNEL; }
java
public static int alphaMixColors(int backgroundColor, int foregroundColor) { final byte ALPHA_CHANNEL = 24; final byte RED_CHANNEL = 16; final byte GREEN_CHANNEL = 8; final byte BLUE_CHANNEL = 0; final double ap1 = (double) (backgroundColor >> ALPHA_CHANNEL & 0xff) / 255d; final double ap2 = (double) (foregroundColor >> ALPHA_CHANNEL & 0xff) / 255d; final double ap = ap2 + (ap1 * (1 - ap2)); final double amount1 = (ap1 * (1 - ap2)) / ap; final double amount2 = amount1 / ap; int a = ((int) (ap * 255d)) & 0xff; int r = ((int) (((float) (backgroundColor >> RED_CHANNEL & 0xff) * amount1) + ((float) (foregroundColor >> RED_CHANNEL & 0xff) * amount2))) & 0xff; int g = ((int) (((float) (backgroundColor >> GREEN_CHANNEL & 0xff) * amount1) + ((float) (foregroundColor >> GREEN_CHANNEL & 0xff) * amount2))) & 0xff; int b = ((int) (((float) (backgroundColor & 0xff) * amount1) + ((float) (foregroundColor & 0xff) * amount2))) & 0xff; return a << ALPHA_CHANNEL | r << RED_CHANNEL | g << GREEN_CHANNEL | b << BLUE_CHANNEL; }
[ "public", "static", "int", "alphaMixColors", "(", "int", "backgroundColor", ",", "int", "foregroundColor", ")", "{", "final", "byte", "ALPHA_CHANNEL", "=", "24", ";", "final", "byte", "RED_CHANNEL", "=", "16", ";", "final", "byte", "GREEN_CHANNEL", "=", "8", ...
/* Use alpha channel to compute percentage RGB share in blending. * Background color may be visible only if foreground alpha is smaller than 100%
[ "/", "*", "Use", "alpha", "channel", "to", "compute", "percentage", "RGB", "share", "in", "blending", ".", "*", "Background", "color", "may", "be", "visible", "only", "if", "foreground", "alpha", "is", "smaller", "than", "100%" ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L466-L489
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
DebugUtil.printClassName
public static void printClassName(final Object pObject, final PrintStream pPrintStream) { if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(getClassName(pObject)); }
java
public static void printClassName(final Object pObject, final PrintStream pPrintStream) { if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(getClassName(pObject)); }
[ "public", "static", "void", "printClassName", "(", "final", "Object", "pObject", ",", "final", "PrintStream", "pPrintStream", ")", "{", "if", "(", "pPrintStream", "==", "null", ")", "{", "System", ".", "err", ".", "println", "(", "PRINTSTREAM_IS_NULL_ERROR_MESSA...
Prints the top-wrapped class name of a {@code java.lang.Object} to a {@code java.io.PrintStream}. <p> @param pObject the {@code java.lang.Object} to be printed. @param pPrintStream the {@code java.io.PrintStream} for flushing the results. @see <a href="http://java.sun.com/products/jdk/1.3/docs/api/java/lang/Class.html">{@code java.lang.Class}</a>
[ "Prints", "the", "top", "-", "wrapped", "class", "name", "of", "a", "{" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L1268-L1275
casmi/casmi
src/main/java/casmi/graphics/element/Quad.java
Quad.setConer
public void setConer(int index, Vector3D v) { if (index <= 0) { this.x1 = v.getX(); this.y1 = v.getY(); } else if (index == 1) { this.x2 = v.getX(); this.y2 = v.getY(); } else if (index == 2) { this.x3 = v.getX(); this.y3 = v.getY(); } else if (3 <= index) { this.x4 = v.getX(); this.y4 = v.getY(); } calcG(); }
java
public void setConer(int index, Vector3D v) { if (index <= 0) { this.x1 = v.getX(); this.y1 = v.getY(); } else if (index == 1) { this.x2 = v.getX(); this.y2 = v.getY(); } else if (index == 2) { this.x3 = v.getX(); this.y3 = v.getY(); } else if (3 <= index) { this.x4 = v.getX(); this.y4 = v.getY(); } calcG(); }
[ "public", "void", "setConer", "(", "int", "index", ",", "Vector3D", "v", ")", "{", "if", "(", "index", "<=", "0", ")", "{", "this", ".", "x1", "=", "v", ".", "getX", "(", ")", ";", "this", ".", "y1", "=", "v", ".", "getY", "(", ")", ";", "}...
Sets coordinates of a corner. @param index The index of a corner. @param v The coordinates of a corner.
[ "Sets", "coordinates", "of", "a", "corner", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Quad.java#L199-L214
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchContext.java
IdentityPatchContext.getTargetFile
public File getTargetFile(final MiscContentItem item) { final State state = this.state; if (state == State.NEW || state == State.ROLLBACK_ONLY) { return getTargetFile(miscTargetRoot, item); } else { throw new IllegalStateException(); // internal wrong usage, no i18n } }
java
public File getTargetFile(final MiscContentItem item) { final State state = this.state; if (state == State.NEW || state == State.ROLLBACK_ONLY) { return getTargetFile(miscTargetRoot, item); } else { throw new IllegalStateException(); // internal wrong usage, no i18n } }
[ "public", "File", "getTargetFile", "(", "final", "MiscContentItem", "item", ")", "{", "final", "State", "state", "=", "this", ".", "state", ";", "if", "(", "state", "==", "State", ".", "NEW", "||", "state", "==", "State", ".", "ROLLBACK_ONLY", ")", "{", ...
Get the target file for misc items. @param item the misc item @return the target location
[ "Get", "the", "target", "file", "for", "misc", "items", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchContext.java#L566-L573
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java
DomHelper.createOrUpdateSingleChild
public Element createOrUpdateSingleChild(Element parent, String type) { Element result = null; if (parent.getElementsByTagName(type).getLength() == 0) { switch (namespace) { case HTML: result = Dom.createElementNS(Dom.NS_HTML, type); break; case SVG: result = Dom.createElementNS(Dom.NS_SVG, type); break; case VML: result = Dom.createElementNS(Dom.NS_VML, type); break; } parent.appendChild(result); return result; } else { return (Element) (parent.getElementsByTagName(type).getItem(0)); } }
java
public Element createOrUpdateSingleChild(Element parent, String type) { Element result = null; if (parent.getElementsByTagName(type).getLength() == 0) { switch (namespace) { case HTML: result = Dom.createElementNS(Dom.NS_HTML, type); break; case SVG: result = Dom.createElementNS(Dom.NS_SVG, type); break; case VML: result = Dom.createElementNS(Dom.NS_VML, type); break; } parent.appendChild(result); return result; } else { return (Element) (parent.getElementsByTagName(type).getItem(0)); } }
[ "public", "Element", "createOrUpdateSingleChild", "(", "Element", "parent", ",", "String", "type", ")", "{", "Element", "result", "=", "null", ";", "if", "(", "parent", ".", "getElementsByTagName", "(", "type", ")", ".", "getLength", "(", ")", "==", "0", "...
Create or update a one-of child element in the DOM. Needs no id as it will be created/deleted with the parent. @param parent the parent element @param type the type of the element (tag name, e.g. 'image') @return the created or updated element or null if creation failed
[ "Create", "or", "update", "a", "one", "-", "of", "child", "element", "in", "the", "DOM", ".", "Needs", "no", "id", "as", "it", "will", "be", "created", "/", "deleted", "with", "the", "parent", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L108-L127
hawkular/hawkular-apm
api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java
AbstractAnalyticsService.obtainEndpoints
protected void obtainEndpoints(List<Node> nodes, List<EndpointInfo> endpoints) { for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); if (node.getUri() != null) { EndpointInfo ei=new EndpointInfo(); ei.setEndpoint(EndpointUtil.encodeEndpoint(node.getUri(), node.getOperation())); if (!endpoints.contains(ei)) { initEndpointInfo(ei); endpoints.add(ei); } } if (node instanceof ContainerNode) { obtainEndpoints(((ContainerNode) node).getNodes(), endpoints); } } }
java
protected void obtainEndpoints(List<Node> nodes, List<EndpointInfo> endpoints) { for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); if (node.getUri() != null) { EndpointInfo ei=new EndpointInfo(); ei.setEndpoint(EndpointUtil.encodeEndpoint(node.getUri(), node.getOperation())); if (!endpoints.contains(ei)) { initEndpointInfo(ei); endpoints.add(ei); } } if (node instanceof ContainerNode) { obtainEndpoints(((ContainerNode) node).getNodes(), endpoints); } } }
[ "protected", "void", "obtainEndpoints", "(", "List", "<", "Node", ">", "nodes", ",", "List", "<", "EndpointInfo", ">", "endpoints", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodes", ".", "size", "(", ")", ";", "i", "++", ")", "{...
This method collects the information regarding endpoints. @param nodes The nodes @param endpoints The list of endpoints
[ "This", "method", "collects", "the", "information", "regarding", "endpoints", "." ]
train
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L447-L465