repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
audit4j/audit4j-core
src/main/java/org/audit4j/core/annotation/DeIdentifyUtil.java
DeIdentifyUtil.deidentifyLeft
public static String deidentifyLeft(String str, int size) { """ Deidentify left. @param str the str @param size the size @return the string @since 2.0.0 """ int repeat; if (size > str.length()) { repeat = str.length(); } else { repeat = size; } return StringUtils.overlay(str, StringUtils.repeat('*', repeat), 0, size); }
java
public static String deidentifyLeft(String str, int size) { int repeat; if (size > str.length()) { repeat = str.length(); } else { repeat = size; } return StringUtils.overlay(str, StringUtils.repeat('*', repeat), 0, size); }
[ "public", "static", "String", "deidentifyLeft", "(", "String", "str", ",", "int", "size", ")", "{", "int", "repeat", ";", "if", "(", "size", ">", "str", ".", "length", "(", ")", ")", "{", "repeat", "=", "str", ".", "length", "(", ")", ";", "}", "else", "{", "repeat", "=", "size", ";", "}", "return", "StringUtils", ".", "overlay", "(", "str", ",", "StringUtils", ".", "repeat", "(", "'", "'", ",", "repeat", ")", ",", "0", ",", "size", ")", ";", "}" ]
Deidentify left. @param str the str @param size the size @return the string @since 2.0.0
[ "Deidentify", "left", "." ]
train
https://github.com/audit4j/audit4j-core/blob/dc8569108851e64cb0ecc7a39048db0ad070fba2/src/main/java/org/audit4j/core/annotation/DeIdentifyUtil.java#L49-L57
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java
DomHelper.drawGroup
public void drawGroup(Object parent, Object object, Style style) { """ Creates a group element in the technology (SVG/VML/...) of this context. A group is meant to group other elements together, and in this case applying a style on them. @param parent parent group object @param object group object @param style Add a style to a group. """ createOrUpdateGroup(parent, object, null, style); }
java
public void drawGroup(Object parent, Object object, Style style) { createOrUpdateGroup(parent, object, null, style); }
[ "public", "void", "drawGroup", "(", "Object", "parent", ",", "Object", "object", ",", "Style", "style", ")", "{", "createOrUpdateGroup", "(", "parent", ",", "object", ",", "null", ",", "style", ")", ";", "}" ]
Creates a group element in the technology (SVG/VML/...) of this context. A group is meant to group other elements together, and in this case applying a style on them. @param parent parent group object @param object group object @param style Add a style to a group.
[ "Creates", "a", "group", "element", "in", "the", "technology", "(", "SVG", "/", "VML", "/", "...", ")", "of", "this", "context", ".", "A", "group", "is", "meant", "to", "group", "other", "elements", "together", "and", "in", "this", "case", "applying", "a", "style", "on", "them", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L251-L253
fuinorg/utils4j
src/main/java/org/fuin/utils4j/Utils4J.java
Utils4J.decryptPasswordBased
public static byte[] decryptPasswordBased(final String algorithm, final byte[] encryptedData, final char[] password, final byte[] salt, final int count) { """ Decrypts some data based on a password. @param algorithm PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" - Cannot be <code>null</code>. @param encryptedData Data to decrypt - Cannot be <code>null</code>. @param password Password - Cannot be <code>null</code>. @param salt Salt usable with algorithm - Cannot be <code>null</code>. @param count Iterations. @return Encrypted data. """ checkNotNull("algorithm", algorithm); checkNotNull("encryptedData", encryptedData); checkNotNull("password", password); checkNotNull("salt", salt); try { final Cipher cipher = createCipher(algorithm, Cipher.DECRYPT_MODE, password, salt, count); return cipher.doFinal(encryptedData); } catch (final Exception ex) { throw new RuntimeException("Error decrypting the password!", ex); } }
java
public static byte[] decryptPasswordBased(final String algorithm, final byte[] encryptedData, final char[] password, final byte[] salt, final int count) { checkNotNull("algorithm", algorithm); checkNotNull("encryptedData", encryptedData); checkNotNull("password", password); checkNotNull("salt", salt); try { final Cipher cipher = createCipher(algorithm, Cipher.DECRYPT_MODE, password, salt, count); return cipher.doFinal(encryptedData); } catch (final Exception ex) { throw new RuntimeException("Error decrypting the password!", ex); } }
[ "public", "static", "byte", "[", "]", "decryptPasswordBased", "(", "final", "String", "algorithm", ",", "final", "byte", "[", "]", "encryptedData", ",", "final", "char", "[", "]", "password", ",", "final", "byte", "[", "]", "salt", ",", "final", "int", "count", ")", "{", "checkNotNull", "(", "\"algorithm\"", ",", "algorithm", ")", ";", "checkNotNull", "(", "\"encryptedData\"", ",", "encryptedData", ")", ";", "checkNotNull", "(", "\"password\"", ",", "password", ")", ";", "checkNotNull", "(", "\"salt\"", ",", "salt", ")", ";", "try", "{", "final", "Cipher", "cipher", "=", "createCipher", "(", "algorithm", ",", "Cipher", ".", "DECRYPT_MODE", ",", "password", ",", "salt", ",", "count", ")", ";", "return", "cipher", ".", "doFinal", "(", "encryptedData", ")", ";", "}", "catch", "(", "final", "Exception", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error decrypting the password!\"", ",", "ex", ")", ";", "}", "}" ]
Decrypts some data based on a password. @param algorithm PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" - Cannot be <code>null</code>. @param encryptedData Data to decrypt - Cannot be <code>null</code>. @param password Password - Cannot be <code>null</code>. @param salt Salt usable with algorithm - Cannot be <code>null</code>. @param count Iterations. @return Encrypted data.
[ "Decrypts", "some", "data", "based", "on", "a", "password", "." ]
train
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L444-L458
grails/grails-core
grails-core/src/main/groovy/org/grails/plugins/BasePluginFilter.java
BasePluginFilter.filterPluginList
public List<GrailsPlugin> filterPluginList(List<GrailsPlugin> original) { """ Template method shared by subclasses of <code>BasePluginFilter</code>. """ originalPlugins = Collections.unmodifiableList(original); addedNames = new HashSet<String>(); buildNameMap(); buildExplicitlyNamedList(); buildDerivedPluginList(); List<GrailsPlugin> pluginList = new ArrayList<GrailsPlugin>(); pluginList.addAll(explicitlyNamedPlugins); pluginList.addAll(derivedPlugins); return getPluginList(originalPlugins, pluginList); }
java
public List<GrailsPlugin> filterPluginList(List<GrailsPlugin> original) { originalPlugins = Collections.unmodifiableList(original); addedNames = new HashSet<String>(); buildNameMap(); buildExplicitlyNamedList(); buildDerivedPluginList(); List<GrailsPlugin> pluginList = new ArrayList<GrailsPlugin>(); pluginList.addAll(explicitlyNamedPlugins); pluginList.addAll(derivedPlugins); return getPluginList(originalPlugins, pluginList); }
[ "public", "List", "<", "GrailsPlugin", ">", "filterPluginList", "(", "List", "<", "GrailsPlugin", ">", "original", ")", "{", "originalPlugins", "=", "Collections", ".", "unmodifiableList", "(", "original", ")", ";", "addedNames", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "buildNameMap", "(", ")", ";", "buildExplicitlyNamedList", "(", ")", ";", "buildDerivedPluginList", "(", ")", ";", "List", "<", "GrailsPlugin", ">", "pluginList", "=", "new", "ArrayList", "<", "GrailsPlugin", ">", "(", ")", ";", "pluginList", ".", "addAll", "(", "explicitlyNamedPlugins", ")", ";", "pluginList", ".", "addAll", "(", "derivedPlugins", ")", ";", "return", "getPluginList", "(", "originalPlugins", ",", "pluginList", ")", ";", "}" ]
Template method shared by subclasses of <code>BasePluginFilter</code>.
[ "Template", "method", "shared", "by", "subclasses", "of", "<code", ">", "BasePluginFilter<", "/", "code", ">", "." ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/plugins/BasePluginFilter.java#L93-L107
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/variant/css/CssSkinGenerator.java
CssSkinGenerator.updateSkinVariants
private void updateSkinVariants(ResourceBrowser rsBrowser, String path, Set<String> skinVariants) { """ Update the skin variants from the directory path given in parameter @param rsBrowser the resource browser @param path the skin path @param skinVariants the set of skin variants to update """ Set<String> skinPaths = rsBrowser.getResourceNames(path); for (Iterator<String> itSkinPath = skinPaths.iterator(); itSkinPath.hasNext();) { String skinPath = path + itSkinPath.next(); if (rsBrowser.isDirectory(skinPath)) { String skinDirName = PathNormalizer.getPathName(skinPath); skinVariants.add(skinDirName); } } }
java
private void updateSkinVariants(ResourceBrowser rsBrowser, String path, Set<String> skinVariants) { Set<String> skinPaths = rsBrowser.getResourceNames(path); for (Iterator<String> itSkinPath = skinPaths.iterator(); itSkinPath.hasNext();) { String skinPath = path + itSkinPath.next(); if (rsBrowser.isDirectory(skinPath)) { String skinDirName = PathNormalizer.getPathName(skinPath); skinVariants.add(skinDirName); } } }
[ "private", "void", "updateSkinVariants", "(", "ResourceBrowser", "rsBrowser", ",", "String", "path", ",", "Set", "<", "String", ">", "skinVariants", ")", "{", "Set", "<", "String", ">", "skinPaths", "=", "rsBrowser", ".", "getResourceNames", "(", "path", ")", ";", "for", "(", "Iterator", "<", "String", ">", "itSkinPath", "=", "skinPaths", ".", "iterator", "(", ")", ";", "itSkinPath", ".", "hasNext", "(", ")", ";", ")", "{", "String", "skinPath", "=", "path", "+", "itSkinPath", ".", "next", "(", ")", ";", "if", "(", "rsBrowser", ".", "isDirectory", "(", "skinPath", ")", ")", "{", "String", "skinDirName", "=", "PathNormalizer", ".", "getPathName", "(", "skinPath", ")", ";", "skinVariants", ".", "add", "(", "skinDirName", ")", ";", "}", "}", "}" ]
Update the skin variants from the directory path given in parameter @param rsBrowser the resource browser @param path the skin path @param skinVariants the set of skin variants to update
[ "Update", "the", "skin", "variants", "from", "the", "directory", "path", "given", "in", "parameter" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/variant/css/CssSkinGenerator.java#L597-L607
languagetool-org/languagetool
languagetool-core/src/main/java/org/languagetool/rules/AbstractUnitConversionRule.java
AbstractUnitConversionRule.addUnit
protected void addUnit(String pattern, Unit base, String symbol, double factor, boolean metric) { """ Associate a notation with a given unit. @param pattern Regex for recognizing the unit. Word boundaries and numbers are added to this pattern by addUnit itself. @param base Unit to associate with the pattern @param symbol Suffix used for suggestion. @param factor Convenience parameter for prefixes for metric units, unit is multiplied with this. Defaults to 1 if not used. @param metric Register this notation for suggestion. """ Unit unit = base.multiply(factor); unitPatterns.put(Pattern.compile("\\b" + NUMBER_REGEX + "\\s{0," + WHITESPACE_LIMIT + "}" + pattern + "\\b"), unit); unitSymbols.putIfAbsent(unit, new ArrayList<>()); unitSymbols.get(unit).add(symbol); if (metric && !metricUnits.contains(unit)) { metricUnits.add(unit); } }
java
protected void addUnit(String pattern, Unit base, String symbol, double factor, boolean metric) { Unit unit = base.multiply(factor); unitPatterns.put(Pattern.compile("\\b" + NUMBER_REGEX + "\\s{0," + WHITESPACE_LIMIT + "}" + pattern + "\\b"), unit); unitSymbols.putIfAbsent(unit, new ArrayList<>()); unitSymbols.get(unit).add(symbol); if (metric && !metricUnits.contains(unit)) { metricUnits.add(unit); } }
[ "protected", "void", "addUnit", "(", "String", "pattern", ",", "Unit", "base", ",", "String", "symbol", ",", "double", "factor", ",", "boolean", "metric", ")", "{", "Unit", "unit", "=", "base", ".", "multiply", "(", "factor", ")", ";", "unitPatterns", ".", "put", "(", "Pattern", ".", "compile", "(", "\"\\\\b\"", "+", "NUMBER_REGEX", "+", "\"\\\\s{0,\"", "+", "WHITESPACE_LIMIT", "+", "\"}\"", "+", "pattern", "+", "\"\\\\b\"", ")", ",", "unit", ")", ";", "unitSymbols", ".", "putIfAbsent", "(", "unit", ",", "new", "ArrayList", "<>", "(", ")", ")", ";", "unitSymbols", ".", "get", "(", "unit", ")", ".", "add", "(", "symbol", ")", ";", "if", "(", "metric", "&&", "!", "metricUnits", ".", "contains", "(", "unit", ")", ")", "{", "metricUnits", ".", "add", "(", "unit", ")", ";", "}", "}" ]
Associate a notation with a given unit. @param pattern Regex for recognizing the unit. Word boundaries and numbers are added to this pattern by addUnit itself. @param base Unit to associate with the pattern @param symbol Suffix used for suggestion. @param factor Convenience parameter for prefixes for metric units, unit is multiplied with this. Defaults to 1 if not used. @param metric Register this notation for suggestion.
[ "Associate", "a", "notation", "with", "a", "given", "unit", "." ]
train
https://github.com/languagetool-org/languagetool/blob/b7a3d63883d242fb2525877c6382681c57a0a142/languagetool-core/src/main/java/org/languagetool/rules/AbstractUnitConversionRule.java#L183-L191
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java
BaseDataPublisher.getMergedMetadataForPartitionAndBranch
private String getMergedMetadataForPartitionAndBranch(String partitionId, int branchId) { """ /* Get the merged metadata given a workunit state and branch id. This method assumes all intermediate metadata has already been passed to the MetadataMerger. If metadata mergers are not configured, instead return the metadata from job config that was passed in by the user. """ String mergedMd = null; MetadataMerger<String> mergerForBranch = metadataMergers.get(new PartitionIdentifier(partitionId, branchId)); if (mergerForBranch != null) { mergedMd = mergerForBranch.getMergedMetadata(); if (mergedMd == null) { LOG.warn("Metadata merger for branch {} returned null - bug in merger?", branchId); } } return mergedMd; }
java
private String getMergedMetadataForPartitionAndBranch(String partitionId, int branchId) { String mergedMd = null; MetadataMerger<String> mergerForBranch = metadataMergers.get(new PartitionIdentifier(partitionId, branchId)); if (mergerForBranch != null) { mergedMd = mergerForBranch.getMergedMetadata(); if (mergedMd == null) { LOG.warn("Metadata merger for branch {} returned null - bug in merger?", branchId); } } return mergedMd; }
[ "private", "String", "getMergedMetadataForPartitionAndBranch", "(", "String", "partitionId", ",", "int", "branchId", ")", "{", "String", "mergedMd", "=", "null", ";", "MetadataMerger", "<", "String", ">", "mergerForBranch", "=", "metadataMergers", ".", "get", "(", "new", "PartitionIdentifier", "(", "partitionId", ",", "branchId", ")", ")", ";", "if", "(", "mergerForBranch", "!=", "null", ")", "{", "mergedMd", "=", "mergerForBranch", ".", "getMergedMetadata", "(", ")", ";", "if", "(", "mergedMd", "==", "null", ")", "{", "LOG", ".", "warn", "(", "\"Metadata merger for branch {} returned null - bug in merger?\"", ",", "branchId", ")", ";", "}", "}", "return", "mergedMd", ";", "}" ]
/* Get the merged metadata given a workunit state and branch id. This method assumes all intermediate metadata has already been passed to the MetadataMerger. If metadata mergers are not configured, instead return the metadata from job config that was passed in by the user.
[ "/", "*", "Get", "the", "merged", "metadata", "given", "a", "workunit", "state", "and", "branch", "id", ".", "This", "method", "assumes", "all", "intermediate", "metadata", "has", "already", "been", "passed", "to", "the", "MetadataMerger", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java#L755-L766
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/ParcelUtils.java
ParcelUtils.writeDate
public static void writeDate (final Parcel parcel, final Date date) { """ Writes a date to a parcel at its current position. More efficient than writing it as a {@link Serializable}. Deals nicely with a null date, as long as {@link #readDate(Parcel)} is used to retrieve it afterwards. @param parcel the parcel to write the date to. Must be non-null. @param date the date to write to the parcel. Can be null. @see #readDate(Parcel) """ if (parcel == null) return; parcel.writeByte(date == null ? MARKER_NO_ELEMENT_STORED : MARKER_AN_ELEMENT_STORED); if (date != null) parcel.writeLong(date.getTime()); }
java
public static void writeDate (final Parcel parcel, final Date date) { if (parcel == null) return; parcel.writeByte(date == null ? MARKER_NO_ELEMENT_STORED : MARKER_AN_ELEMENT_STORED); if (date != null) parcel.writeLong(date.getTime()); }
[ "public", "static", "void", "writeDate", "(", "final", "Parcel", "parcel", ",", "final", "Date", "date", ")", "{", "if", "(", "parcel", "==", "null", ")", "return", ";", "parcel", ".", "writeByte", "(", "date", "==", "null", "?", "MARKER_NO_ELEMENT_STORED", ":", "MARKER_AN_ELEMENT_STORED", ")", ";", "if", "(", "date", "!=", "null", ")", "parcel", ".", "writeLong", "(", "date", ".", "getTime", "(", ")", ")", ";", "}" ]
Writes a date to a parcel at its current position. More efficient than writing it as a {@link Serializable}. Deals nicely with a null date, as long as {@link #readDate(Parcel)} is used to retrieve it afterwards. @param parcel the parcel to write the date to. Must be non-null. @param date the date to write to the parcel. Can be null. @see #readDate(Parcel)
[ "Writes", "a", "date", "to", "a", "parcel", "at", "its", "current", "position", ".", "More", "efficient", "than", "writing", "it", "as", "a", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/ParcelUtils.java#L49-L53
uber/NullAway
nullaway/src/main/java/com/uber/nullaway/NullAway.java
NullAway.matchMemberReference
@Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { """ for method references, we check that the referenced method correctly overrides the corresponding functional interface method """ if (!matchWithinClass) { return Description.NO_MATCH; } Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(tree); Symbol.MethodSymbol funcInterfaceSymbol = NullabilityUtil.getFunctionalInterfaceMethod(tree, state.getTypes()); handler.onMatchMethodReference(this, tree, state, referencedMethod); return checkOverriding(funcInterfaceSymbol, referencedMethod, tree, state); }
java
@Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { if (!matchWithinClass) { return Description.NO_MATCH; } Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(tree); Symbol.MethodSymbol funcInterfaceSymbol = NullabilityUtil.getFunctionalInterfaceMethod(tree, state.getTypes()); handler.onMatchMethodReference(this, tree, state, referencedMethod); return checkOverriding(funcInterfaceSymbol, referencedMethod, tree, state); }
[ "@", "Override", "public", "Description", "matchMemberReference", "(", "MemberReferenceTree", "tree", ",", "VisitorState", "state", ")", "{", "if", "(", "!", "matchWithinClass", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "Symbol", ".", "MethodSymbol", "referencedMethod", "=", "ASTHelpers", ".", "getSymbol", "(", "tree", ")", ";", "Symbol", ".", "MethodSymbol", "funcInterfaceSymbol", "=", "NullabilityUtil", ".", "getFunctionalInterfaceMethod", "(", "tree", ",", "state", ".", "getTypes", "(", ")", ")", ";", "handler", ".", "onMatchMethodReference", "(", "this", ",", "tree", ",", "state", ",", "referencedMethod", ")", ";", "return", "checkOverriding", "(", "funcInterfaceSymbol", ",", "referencedMethod", ",", "tree", ",", "state", ")", ";", "}" ]
for method references, we check that the referenced method correctly overrides the corresponding functional interface method
[ "for", "method", "references", "we", "check", "that", "the", "referenced", "method", "correctly", "overrides", "the", "corresponding", "functional", "interface", "method" ]
train
https://github.com/uber/NullAway/blob/c3979b4241f80411dbba6aac3ff653acbb88d00b/nullaway/src/main/java/com/uber/nullaway/NullAway.java#L692-L702
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java
BNFHeadersImpl.parseCRLFTokenExtract
protected TokenCodes parseCRLFTokenExtract(WsByteBuffer buff, int log) throws MalformedMessageException { """ Parse and extract a CRLF delimited token. <p> Returns either the TOKEN_RC_DELIM or the TOKEN_RC_MOREDATA return codes. @param buff @param log - whether to debug log contents or not @return TokenCodes @throws MalformedMessageException """ // if we're just starting, then skip leading white space characters // otherwise ignore them (i.e we might be in the middle of // "Mozilla/5.0 (Win" if (null == this.parsedToken) { if (!skipWhiteSpace(buff)) { return TokenCodes.TOKEN_RC_MOREDATA; } } int start = findCurrentBufferPosition(buff); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "parseCRLFTokenExtract: start:" + start + " lim:" + this.byteLimit + " pos:" + this.bytePosition); } TokenCodes rc = findCRLFTokenLength(buff); // Set the parsedToken from the token parsed from this ByteBuffer saveParsedToken(buff, start, TokenCodes.TOKEN_RC_DELIM.equals(rc), log); return rc; }
java
protected TokenCodes parseCRLFTokenExtract(WsByteBuffer buff, int log) throws MalformedMessageException { // if we're just starting, then skip leading white space characters // otherwise ignore them (i.e we might be in the middle of // "Mozilla/5.0 (Win" if (null == this.parsedToken) { if (!skipWhiteSpace(buff)) { return TokenCodes.TOKEN_RC_MOREDATA; } } int start = findCurrentBufferPosition(buff); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "parseCRLFTokenExtract: start:" + start + " lim:" + this.byteLimit + " pos:" + this.bytePosition); } TokenCodes rc = findCRLFTokenLength(buff); // Set the parsedToken from the token parsed from this ByteBuffer saveParsedToken(buff, start, TokenCodes.TOKEN_RC_DELIM.equals(rc), log); return rc; }
[ "protected", "TokenCodes", "parseCRLFTokenExtract", "(", "WsByteBuffer", "buff", ",", "int", "log", ")", "throws", "MalformedMessageException", "{", "// if we're just starting, then skip leading white space characters", "// otherwise ignore them (i.e we might be in the middle of", "// \"Mozilla/5.0 (Win\"", "if", "(", "null", "==", "this", ".", "parsedToken", ")", "{", "if", "(", "!", "skipWhiteSpace", "(", "buff", ")", ")", "{", "return", "TokenCodes", ".", "TOKEN_RC_MOREDATA", ";", "}", "}", "int", "start", "=", "findCurrentBufferPosition", "(", "buff", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"parseCRLFTokenExtract: start:\"", "+", "start", "+", "\" lim:\"", "+", "this", ".", "byteLimit", "+", "\" pos:\"", "+", "this", ".", "bytePosition", ")", ";", "}", "TokenCodes", "rc", "=", "findCRLFTokenLength", "(", "buff", ")", ";", "// Set the parsedToken from the token parsed from this ByteBuffer", "saveParsedToken", "(", "buff", ",", "start", ",", "TokenCodes", ".", "TOKEN_RC_DELIM", ".", "equals", "(", "rc", ")", ",", "log", ")", ";", "return", "rc", ";", "}" ]
Parse and extract a CRLF delimited token. <p> Returns either the TOKEN_RC_DELIM or the TOKEN_RC_MOREDATA return codes. @param buff @param log - whether to debug log contents or not @return TokenCodes @throws MalformedMessageException
[ "Parse", "and", "extract", "a", "CRLF", "delimited", "token", ".", "<p", ">", "Returns", "either", "the", "TOKEN_RC_DELIM", "or", "the", "TOKEN_RC_MOREDATA", "return", "codes", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/genericbnf/internal/BNFHeadersImpl.java#L3616-L3636
roskenet/springboot-javafx-support
src/main/java/de/felixroske/jfxsupport/AbstractFxmlView.java
AbstractFxmlView.showViewAndWait
public void showViewAndWait(Window window, Modality modality) { """ Shows the FxmlView instance being the child stage of the given {@link Window} and waits to be closed before returning to the caller. @param window The owner of the FxmlView instance @param modality See {@code javafx.stage.Modality}. """ if (isPrimaryStageView) { showView(modality); // this modality will be ignored anyway return; } if (stage == null || currentStageModality != modality || !Objects.equals(stage.getOwner(), window)) { stage = createStage(modality); stage.initOwner(window); } stage.showAndWait(); }
java
public void showViewAndWait(Window window, Modality modality) { if (isPrimaryStageView) { showView(modality); // this modality will be ignored anyway return; } if (stage == null || currentStageModality != modality || !Objects.equals(stage.getOwner(), window)) { stage = createStage(modality); stage.initOwner(window); } stage.showAndWait(); }
[ "public", "void", "showViewAndWait", "(", "Window", "window", ",", "Modality", "modality", ")", "{", "if", "(", "isPrimaryStageView", ")", "{", "showView", "(", "modality", ")", ";", "// this modality will be ignored anyway", "return", ";", "}", "if", "(", "stage", "==", "null", "||", "currentStageModality", "!=", "modality", "||", "!", "Objects", ".", "equals", "(", "stage", ".", "getOwner", "(", ")", ",", "window", ")", ")", "{", "stage", "=", "createStage", "(", "modality", ")", ";", "stage", ".", "initOwner", "(", "window", ")", ";", "}", "stage", ".", "showAndWait", "(", ")", ";", "}" ]
Shows the FxmlView instance being the child stage of the given {@link Window} and waits to be closed before returning to the caller. @param window The owner of the FxmlView instance @param modality See {@code javafx.stage.Modality}.
[ "Shows", "the", "FxmlView", "instance", "being", "the", "child", "stage", "of", "the", "given", "{", "@link", "Window", "}", "and", "waits", "to", "be", "closed", "before", "returning", "to", "the", "caller", "." ]
train
https://github.com/roskenet/springboot-javafx-support/blob/aed1da178ecb204eb00508b3ce1e2a11d4fa9619/src/main/java/de/felixroske/jfxsupport/AbstractFxmlView.java#L234-L244
fabric8io/fabric8-forge
addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelXmlHelper.java
CamelXmlHelper.xmlAsModel
public static Object xmlAsModel(Node node, ClassLoader classLoader) throws JAXBException { """ Turns the xml into EIP model classes @param node the node representing the XML @param classLoader the class loader @return the EIP model class @throws JAXBException is throw if error unmarshalling XML to Object """ JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_CONTEXT_PACKAGES, classLoader); Unmarshaller marshaller = jaxbContext.createUnmarshaller(); Object answer = marshaller.unmarshal(node); return answer; }
java
public static Object xmlAsModel(Node node, ClassLoader classLoader) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_CONTEXT_PACKAGES, classLoader); Unmarshaller marshaller = jaxbContext.createUnmarshaller(); Object answer = marshaller.unmarshal(node); return answer; }
[ "public", "static", "Object", "xmlAsModel", "(", "Node", "node", ",", "ClassLoader", "classLoader", ")", "throws", "JAXBException", "{", "JAXBContext", "jaxbContext", "=", "JAXBContext", ".", "newInstance", "(", "JAXB_CONTEXT_PACKAGES", ",", "classLoader", ")", ";", "Unmarshaller", "marshaller", "=", "jaxbContext", ".", "createUnmarshaller", "(", ")", ";", "Object", "answer", "=", "marshaller", ".", "unmarshal", "(", "node", ")", ";", "return", "answer", ";", "}" ]
Turns the xml into EIP model classes @param node the node representing the XML @param classLoader the class loader @return the EIP model class @throws JAXBException is throw if error unmarshalling XML to Object
[ "Turns", "the", "xml", "into", "EIP", "model", "classes" ]
train
https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelXmlHelper.java#L503-L510
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/variant/css/CssSkinGenerator.java
CssSkinGenerator.getSkinRootDir
public String getSkinRootDir(String path, Set<String> skinRootDirs) { """ Returns the skin root dir of the path given in parameter @param path the resource path @param skinRootDirs the set of skin root directories @return the skin root dir """ String skinRootDir = null; for (String skinDir : skinRootDirs) { if (path.startsWith(skinDir)) { skinRootDir = skinDir; } } return skinRootDir; }
java
public String getSkinRootDir(String path, Set<String> skinRootDirs) { String skinRootDir = null; for (String skinDir : skinRootDirs) { if (path.startsWith(skinDir)) { skinRootDir = skinDir; } } return skinRootDir; }
[ "public", "String", "getSkinRootDir", "(", "String", "path", ",", "Set", "<", "String", ">", "skinRootDirs", ")", "{", "String", "skinRootDir", "=", "null", ";", "for", "(", "String", "skinDir", ":", "skinRootDirs", ")", "{", "if", "(", "path", ".", "startsWith", "(", "skinDir", ")", ")", "{", "skinRootDir", "=", "skinDir", ";", "}", "}", "return", "skinRootDir", ";", "}" ]
Returns the skin root dir of the path given in parameter @param path the resource path @param skinRootDirs the set of skin root directories @return the skin root dir
[ "Returns", "the", "skin", "root", "dir", "of", "the", "path", "given", "in", "parameter" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/variant/css/CssSkinGenerator.java#L482-L490
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java
StringGroovyMethods.padRight
public static String padRight(CharSequence self, Number numberOfChars, CharSequence padding) { """ Pad a CharSequence to a minimum length specified by <tt>numberOfChars</tt>, adding the supplied padding CharSequence as many times as needed to the right. If the CharSequence is already the same size or bigger than the target <tt>numberOfChars</tt>, then the toString() of the original CharSequence is returned. An example: <pre> ['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5, '#') + it.size() } </pre> will produce output like: <pre> A####1 BB###2 CCC##3 DDDD#4 </pre> @param self a CharSequence object @param numberOfChars the total minimum number of characters of the resulting CharSequence @param padding the characters used for padding @return the CharSequence padded to the right as a String @since 1.8.2 """ String s = self.toString(); int numChars = numberOfChars.intValue(); if (numChars <= s.length()) { return s; } else { return s + getPadding(padding.toString(), numChars - s.length()); } }
java
public static String padRight(CharSequence self, Number numberOfChars, CharSequence padding) { String s = self.toString(); int numChars = numberOfChars.intValue(); if (numChars <= s.length()) { return s; } else { return s + getPadding(padding.toString(), numChars - s.length()); } }
[ "public", "static", "String", "padRight", "(", "CharSequence", "self", ",", "Number", "numberOfChars", ",", "CharSequence", "padding", ")", "{", "String", "s", "=", "self", ".", "toString", "(", ")", ";", "int", "numChars", "=", "numberOfChars", ".", "intValue", "(", ")", ";", "if", "(", "numChars", "<=", "s", ".", "length", "(", ")", ")", "{", "return", "s", ";", "}", "else", "{", "return", "s", "+", "getPadding", "(", "padding", ".", "toString", "(", ")", ",", "numChars", "-", "s", ".", "length", "(", ")", ")", ";", "}", "}" ]
Pad a CharSequence to a minimum length specified by <tt>numberOfChars</tt>, adding the supplied padding CharSequence as many times as needed to the right. If the CharSequence is already the same size or bigger than the target <tt>numberOfChars</tt>, then the toString() of the original CharSequence is returned. An example: <pre> ['A', 'BB', 'CCC', 'DDDD'].each{ println it.padRight(5, '#') + it.size() } </pre> will produce output like: <pre> A####1 BB###2 CCC##3 DDDD#4 </pre> @param self a CharSequence object @param numberOfChars the total minimum number of characters of the resulting CharSequence @param padding the characters used for padding @return the CharSequence padded to the right as a String @since 1.8.2
[ "Pad", "a", "CharSequence", "to", "a", "minimum", "length", "specified", "by", "<tt", ">", "numberOfChars<", "/", "tt", ">", "adding", "the", "supplied", "padding", "CharSequence", "as", "many", "times", "as", "needed", "to", "the", "right", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java#L2289-L2297
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/shredder/XMLUpdateShredder.java
XMLUpdateShredder.addNewElement
private void addNewElement(final EAdd paramAdd, final StartElement paramStartElement) throws TTException { """ Add a new element node. @param paramAdd determines wether node is added as first child or right sibling @param paramStartElement the current {@link StartElement} @throws TTException if inserting node fails """ assert paramStartElement != null; final QName name = paramStartElement.getName(); long key; if (mFirstChildAppend == EShredderInsert.ADDASRIGHTSIBLING) { key = mWtx.insertElementAsRightSibling(name); } else { if (paramAdd == EAdd.ASFIRSTCHILD) { key = mWtx.insertElementAsFirstChild(name); } else { key = mWtx.insertElementAsRightSibling(name); } } // Parse namespaces. for (final Iterator<?> it = paramStartElement.getNamespaces(); it.hasNext();) { final Namespace namespace = (Namespace)it.next(); mWtx.insertNamespace(new QName(namespace.getNamespaceURI(), "", namespace.getPrefix())); mWtx.moveTo(key); } // Parse attributes. for (final Iterator<?> it = paramStartElement.getAttributes(); it.hasNext();) { final Attribute attribute = (Attribute)it.next(); mWtx.insertAttribute(attribute.getName(), attribute.getValue()); mWtx.moveTo(key); } }
java
private void addNewElement(final EAdd paramAdd, final StartElement paramStartElement) throws TTException { assert paramStartElement != null; final QName name = paramStartElement.getName(); long key; if (mFirstChildAppend == EShredderInsert.ADDASRIGHTSIBLING) { key = mWtx.insertElementAsRightSibling(name); } else { if (paramAdd == EAdd.ASFIRSTCHILD) { key = mWtx.insertElementAsFirstChild(name); } else { key = mWtx.insertElementAsRightSibling(name); } } // Parse namespaces. for (final Iterator<?> it = paramStartElement.getNamespaces(); it.hasNext();) { final Namespace namespace = (Namespace)it.next(); mWtx.insertNamespace(new QName(namespace.getNamespaceURI(), "", namespace.getPrefix())); mWtx.moveTo(key); } // Parse attributes. for (final Iterator<?> it = paramStartElement.getAttributes(); it.hasNext();) { final Attribute attribute = (Attribute)it.next(); mWtx.insertAttribute(attribute.getName(), attribute.getValue()); mWtx.moveTo(key); } }
[ "private", "void", "addNewElement", "(", "final", "EAdd", "paramAdd", ",", "final", "StartElement", "paramStartElement", ")", "throws", "TTException", "{", "assert", "paramStartElement", "!=", "null", ";", "final", "QName", "name", "=", "paramStartElement", ".", "getName", "(", ")", ";", "long", "key", ";", "if", "(", "mFirstChildAppend", "==", "EShredderInsert", ".", "ADDASRIGHTSIBLING", ")", "{", "key", "=", "mWtx", ".", "insertElementAsRightSibling", "(", "name", ")", ";", "}", "else", "{", "if", "(", "paramAdd", "==", "EAdd", ".", "ASFIRSTCHILD", ")", "{", "key", "=", "mWtx", ".", "insertElementAsFirstChild", "(", "name", ")", ";", "}", "else", "{", "key", "=", "mWtx", ".", "insertElementAsRightSibling", "(", "name", ")", ";", "}", "}", "// Parse namespaces.", "for", "(", "final", "Iterator", "<", "?", ">", "it", "=", "paramStartElement", ".", "getNamespaces", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "final", "Namespace", "namespace", "=", "(", "Namespace", ")", "it", ".", "next", "(", ")", ";", "mWtx", ".", "insertNamespace", "(", "new", "QName", "(", "namespace", ".", "getNamespaceURI", "(", ")", ",", "\"\"", ",", "namespace", ".", "getPrefix", "(", ")", ")", ")", ";", "mWtx", ".", "moveTo", "(", "key", ")", ";", "}", "// Parse attributes.", "for", "(", "final", "Iterator", "<", "?", ">", "it", "=", "paramStartElement", ".", "getAttributes", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "final", "Attribute", "attribute", "=", "(", "Attribute", ")", "it", ".", "next", "(", ")", ";", "mWtx", ".", "insertAttribute", "(", "attribute", ".", "getName", "(", ")", ",", "attribute", ".", "getValue", "(", ")", ")", ";", "mWtx", ".", "moveTo", "(", "key", ")", ";", "}", "}" ]
Add a new element node. @param paramAdd determines wether node is added as first child or right sibling @param paramStartElement the current {@link StartElement} @throws TTException if inserting node fails
[ "Add", "a", "new", "element", "node", "." ]
train
https://github.com/sebastiangraf/treetank/blob/9b96d631b6c2a8502a0cc958dcb02bd6a6fd8b60/interfacemodules/xml/src/main/java/org/treetank/service/xml/shredder/XMLUpdateShredder.java#L1141-L1169
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsTriggerHelper.java
JenkinsTriggerHelper.triggerJobAndWaitUntilFinished
public BuildWithDetails triggerJobAndWaitUntilFinished(String jobName, Map<String, String> params, Map<String, File> fileParams) throws IOException, InterruptedException { """ This method will trigger a build of the given job and will wait until the builds is ended or if the build has been cancelled. @param jobName The name of the job which should be triggered. @param params the job parameters @param fileParams the job file parameters @return In case of an cancelled job you will get {@link BuildWithDetails#getResult()} {@link BuildResult#CANCELLED}. So you have to check first if the build result is {@code CANCELLED}. @throws IOException in case of errors. @throws InterruptedException In case of interrupts. """ return triggerJobAndWaitUntilFinished(jobName, params, fileParams, false); }
java
public BuildWithDetails triggerJobAndWaitUntilFinished(String jobName, Map<String, String> params, Map<String, File> fileParams) throws IOException, InterruptedException { return triggerJobAndWaitUntilFinished(jobName, params, fileParams, false); }
[ "public", "BuildWithDetails", "triggerJobAndWaitUntilFinished", "(", "String", "jobName", ",", "Map", "<", "String", ",", "String", ">", "params", ",", "Map", "<", "String", ",", "File", ">", "fileParams", ")", "throws", "IOException", ",", "InterruptedException", "{", "return", "triggerJobAndWaitUntilFinished", "(", "jobName", ",", "params", ",", "fileParams", ",", "false", ")", ";", "}" ]
This method will trigger a build of the given job and will wait until the builds is ended or if the build has been cancelled. @param jobName The name of the job which should be triggered. @param params the job parameters @param fileParams the job file parameters @return In case of an cancelled job you will get {@link BuildWithDetails#getResult()} {@link BuildResult#CANCELLED}. So you have to check first if the build result is {@code CANCELLED}. @throws IOException in case of errors. @throws InterruptedException In case of interrupts.
[ "This", "method", "will", "trigger", "a", "build", "of", "the", "given", "job", "and", "will", "wait", "until", "the", "builds", "is", "ended", "or", "if", "the", "build", "has", "been", "cancelled", "." ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsTriggerHelper.java#L131-L134
JM-Lab/utils-java8
src/main/java/kr/jm/utils/collections/JMTimeSeries.java
JMTimeSeries.getOrPutGetNew
public V getOrPutGetNew(Long timestamp, Supplier<V> newSupplier) { """ Gets or put get new. @param timestamp the timestamp @param newSupplier the new supplier @return the or put get new """ return JMMap.getOrPutGetNew(this.timeSeriesMap, buildKeyTimestamp(timestamp), newSupplier); }
java
public V getOrPutGetNew(Long timestamp, Supplier<V> newSupplier) { return JMMap.getOrPutGetNew(this.timeSeriesMap, buildKeyTimestamp(timestamp), newSupplier); }
[ "public", "V", "getOrPutGetNew", "(", "Long", "timestamp", ",", "Supplier", "<", "V", ">", "newSupplier", ")", "{", "return", "JMMap", ".", "getOrPutGetNew", "(", "this", ".", "timeSeriesMap", ",", "buildKeyTimestamp", "(", "timestamp", ")", ",", "newSupplier", ")", ";", "}" ]
Gets or put get new. @param timestamp the timestamp @param newSupplier the new supplier @return the or put get new
[ "Gets", "or", "put", "get", "new", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/collections/JMTimeSeries.java#L78-L81
baratine/baratine
framework/src/main/java/com/caucho/v5/util/QDate.java
QDate.setDate
public long setDate(long year, long month, long day) { """ Sets date in the local time. @param year @param month where January = 0 @param day day of month where the 1st = 1 """ year += (long) Math.floor(month / 12.0); month -= (long) 12 * Math.floor(month / 12.0); _year = year; _month = month; _dayOfMonth = day - 1; calculateJoin(); calculateSplit(_localTimeOfEpoch); return _localTimeOfEpoch; }
java
public long setDate(long year, long month, long day) { year += (long) Math.floor(month / 12.0); month -= (long) 12 * Math.floor(month / 12.0); _year = year; _month = month; _dayOfMonth = day - 1; calculateJoin(); calculateSplit(_localTimeOfEpoch); return _localTimeOfEpoch; }
[ "public", "long", "setDate", "(", "long", "year", ",", "long", "month", ",", "long", "day", ")", "{", "year", "+=", "(", "long", ")", "Math", ".", "floor", "(", "month", "/", "12.0", ")", ";", "month", "-=", "(", "long", ")", "12", "*", "Math", ".", "floor", "(", "month", "/", "12.0", ")", ";", "_year", "=", "year", ";", "_month", "=", "month", ";", "_dayOfMonth", "=", "day", "-", "1", ";", "calculateJoin", "(", ")", ";", "calculateSplit", "(", "_localTimeOfEpoch", ")", ";", "return", "_localTimeOfEpoch", ";", "}" ]
Sets date in the local time. @param year @param month where January = 0 @param day day of month where the 1st = 1
[ "Sets", "date", "in", "the", "local", "time", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/framework/src/main/java/com/caucho/v5/util/QDate.java#L1689-L1702
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java
FaceListsImpl.addFaceFromStream
public PersistedFace addFaceFromStream(String faceListId, byte[] image, AddFaceFromStreamOptionalParameter addFaceFromStreamOptionalParameter) { """ Add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire. @param faceListId Id referencing a particular face list. @param image An image stream. @param addFaceFromStreamOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PersistedFace object if successful. """ return addFaceFromStreamWithServiceResponseAsync(faceListId, image, addFaceFromStreamOptionalParameter).toBlocking().single().body(); }
java
public PersistedFace addFaceFromStream(String faceListId, byte[] image, AddFaceFromStreamOptionalParameter addFaceFromStreamOptionalParameter) { return addFaceFromStreamWithServiceResponseAsync(faceListId, image, addFaceFromStreamOptionalParameter).toBlocking().single().body(); }
[ "public", "PersistedFace", "addFaceFromStream", "(", "String", "faceListId", ",", "byte", "[", "]", "image", ",", "AddFaceFromStreamOptionalParameter", "addFaceFromStreamOptionalParameter", ")", "{", "return", "addFaceFromStreamWithServiceResponseAsync", "(", "faceListId", ",", "image", ",", "addFaceFromStreamOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire. @param faceListId Id referencing a particular face list. @param image An image stream. @param addFaceFromStreamOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PersistedFace object if successful.
[ "Add", "a", "face", "to", "a", "face", "list", ".", "The", "input", "face", "is", "specified", "as", "an", "image", "with", "a", "targetFace", "rectangle", ".", "It", "returns", "a", "persistedFaceId", "representing", "the", "added", "face", "and", "persistedFaceId", "will", "not", "expire", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java#L933-L935
elki-project/elki
addons/3dpc/src/main/java/de/lmu/ifi/dbs/elki/visualization/parallel3d/layout/CompactCircularMSTLayout3DPC.java
CompactCircularMSTLayout3DPC.computePositions
public static void computePositions(Node node, int depth, double aoff, double awid, double radius, double radiusinc) { """ Compute the layout positions @param node Node to start with @param depth Depth of the node @param aoff Angular offset @param awid Angular width @param radius Current radius @param radiusinc Radius per depth step """ node.x = FastMath.sin(aoff) * radius; node.y = FastMath.cos(aoff) * radius; // Angular width per weight double cwid = awid / node.weight; // Avoid overly wide angles - shrink radius if necessary. double div = 1; if(node.weight > 1) { double s = FastMath.sin(awid * .5), c = FastMath.cos(awid * .5); double dx = s * (depth + 1), dy = c * (depth + 1) - depth; double d = FastMath.sqrt(dx * dx + dy * dy) / MathUtil.SQRT2; div = Math.max(div, d); } // Angular position of current child: double cang = aoff - awid * .5 / div; final double adjwid = cwid / div; for(Node c : node.children) { computePositions(c, depth + 1, cang + adjwid * c.weight * .5, adjwid * c.weight, radius + radiusinc, radiusinc); cang += adjwid * c.weight; } }
java
public static void computePositions(Node node, int depth, double aoff, double awid, double radius, double radiusinc) { node.x = FastMath.sin(aoff) * radius; node.y = FastMath.cos(aoff) * radius; // Angular width per weight double cwid = awid / node.weight; // Avoid overly wide angles - shrink radius if necessary. double div = 1; if(node.weight > 1) { double s = FastMath.sin(awid * .5), c = FastMath.cos(awid * .5); double dx = s * (depth + 1), dy = c * (depth + 1) - depth; double d = FastMath.sqrt(dx * dx + dy * dy) / MathUtil.SQRT2; div = Math.max(div, d); } // Angular position of current child: double cang = aoff - awid * .5 / div; final double adjwid = cwid / div; for(Node c : node.children) { computePositions(c, depth + 1, cang + adjwid * c.weight * .5, adjwid * c.weight, radius + radiusinc, radiusinc); cang += adjwid * c.weight; } }
[ "public", "static", "void", "computePositions", "(", "Node", "node", ",", "int", "depth", ",", "double", "aoff", ",", "double", "awid", ",", "double", "radius", ",", "double", "radiusinc", ")", "{", "node", ".", "x", "=", "FastMath", ".", "sin", "(", "aoff", ")", "*", "radius", ";", "node", ".", "y", "=", "FastMath", ".", "cos", "(", "aoff", ")", "*", "radius", ";", "// Angular width per weight", "double", "cwid", "=", "awid", "/", "node", ".", "weight", ";", "// Avoid overly wide angles - shrink radius if necessary.", "double", "div", "=", "1", ";", "if", "(", "node", ".", "weight", ">", "1", ")", "{", "double", "s", "=", "FastMath", ".", "sin", "(", "awid", "*", ".5", ")", ",", "c", "=", "FastMath", ".", "cos", "(", "awid", "*", ".5", ")", ";", "double", "dx", "=", "s", "*", "(", "depth", "+", "1", ")", ",", "dy", "=", "c", "*", "(", "depth", "+", "1", ")", "-", "depth", ";", "double", "d", "=", "FastMath", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", "/", "MathUtil", ".", "SQRT2", ";", "div", "=", "Math", ".", "max", "(", "div", ",", "d", ")", ";", "}", "// Angular position of current child:", "double", "cang", "=", "aoff", "-", "awid", "*", ".5", "/", "div", ";", "final", "double", "adjwid", "=", "cwid", "/", "div", ";", "for", "(", "Node", "c", ":", "node", ".", "children", ")", "{", "computePositions", "(", "c", ",", "depth", "+", "1", ",", "cang", "+", "adjwid", "*", "c", ".", "weight", "*", ".5", ",", "adjwid", "*", "c", ".", "weight", ",", "radius", "+", "radiusinc", ",", "radiusinc", ")", ";", "cang", "+=", "adjwid", "*", "c", ".", "weight", ";", "}", "}" ]
Compute the layout positions @param node Node to start with @param depth Depth of the node @param aoff Angular offset @param awid Angular width @param radius Current radius @param radiusinc Radius per depth step
[ "Compute", "the", "layout", "positions" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/3dpc/src/main/java/de/lmu/ifi/dbs/elki/visualization/parallel3d/layout/CompactCircularMSTLayout3DPC.java#L115-L136
alkacon/opencms-core
src/org/opencms/workplace/CmsWorkplaceManager.java
CmsWorkplaceManager.addExportPoint
public void addExportPoint(String uri, String destination) { """ Adds newly created export point to the workplace configuration.<p> @param uri the export point uri @param destination the export point destination """ CmsExportPoint point = new CmsExportPoint(uri, destination); m_exportPoints.add(point); if (CmsLog.INIT.isInfoEnabled() && (point.getDestinationPath() != null)) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_ADD_EXPORT_POINT_2, point.getUri(), point.getDestinationPath())); } }
java
public void addExportPoint(String uri, String destination) { CmsExportPoint point = new CmsExportPoint(uri, destination); m_exportPoints.add(point); if (CmsLog.INIT.isInfoEnabled() && (point.getDestinationPath() != null)) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_ADD_EXPORT_POINT_2, point.getUri(), point.getDestinationPath())); } }
[ "public", "void", "addExportPoint", "(", "String", "uri", ",", "String", "destination", ")", "{", "CmsExportPoint", "point", "=", "new", "CmsExportPoint", "(", "uri", ",", "destination", ")", ";", "m_exportPoints", ".", "add", "(", "point", ")", ";", "if", "(", "CmsLog", ".", "INIT", ".", "isInfoEnabled", "(", ")", "&&", "(", "point", ".", "getDestinationPath", "(", ")", "!=", "null", ")", ")", "{", "CmsLog", ".", "INIT", ".", "info", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "key", "(", "Messages", ".", "INIT_ADD_EXPORT_POINT_2", ",", "point", ".", "getUri", "(", ")", ",", "point", ".", "getDestinationPath", "(", ")", ")", ")", ";", "}", "}" ]
Adds newly created export point to the workplace configuration.<p> @param uri the export point uri @param destination the export point destination
[ "Adds", "newly", "created", "export", "point", "to", "the", "workplace", "configuration", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsWorkplaceManager.java#L560-L571
joniles/mpxj
src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java
ProjectTreeController.addResources
private void addResources(MpxjTreeNode parentNode, ProjectFile file) { """ Add resources to the tree. @param parentNode parent tree node @param file resource container """ for (Resource resource : file.getResources()) { final Resource r = resource; MpxjTreeNode childNode = new MpxjTreeNode(resource) { @Override public String toString() { return r.getName(); } }; parentNode.add(childNode); } }
java
private void addResources(MpxjTreeNode parentNode, ProjectFile file) { for (Resource resource : file.getResources()) { final Resource r = resource; MpxjTreeNode childNode = new MpxjTreeNode(resource) { @Override public String toString() { return r.getName(); } }; parentNode.add(childNode); } }
[ "private", "void", "addResources", "(", "MpxjTreeNode", "parentNode", ",", "ProjectFile", "file", ")", "{", "for", "(", "Resource", "resource", ":", "file", ".", "getResources", "(", ")", ")", "{", "final", "Resource", "r", "=", "resource", ";", "MpxjTreeNode", "childNode", "=", "new", "MpxjTreeNode", "(", "resource", ")", "{", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "r", ".", "getName", "(", ")", ";", "}", "}", ";", "parentNode", ".", "add", "(", "childNode", ")", ";", "}", "}" ]
Add resources to the tree. @param parentNode parent tree node @param file resource container
[ "Add", "resources", "to", "the", "tree", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/explorer/ProjectTreeController.java#L221-L235
ReactiveX/RxJavaFX
src/main/java/io/reactivex/rxjavafx/transformers/FxObservableTransformers.java
FxObservableTransformers.doOnErrorCount
public static <T> ObservableTransformer<T,T> doOnErrorCount(Consumer<Integer> onError) { """ Performs an action on onError with the provided emission count @param onError @param <T> """ return obs -> obs.lift(new OperatorEmissionCounter<>(new CountObserver(null,null,onError))); }
java
public static <T> ObservableTransformer<T,T> doOnErrorCount(Consumer<Integer> onError) { return obs -> obs.lift(new OperatorEmissionCounter<>(new CountObserver(null,null,onError))); }
[ "public", "static", "<", "T", ">", "ObservableTransformer", "<", "T", ",", "T", ">", "doOnErrorCount", "(", "Consumer", "<", "Integer", ">", "onError", ")", "{", "return", "obs", "->", "obs", ".", "lift", "(", "new", "OperatorEmissionCounter", "<>", "(", "new", "CountObserver", "(", "null", ",", "null", ",", "onError", ")", ")", ")", ";", "}" ]
Performs an action on onError with the provided emission count @param onError @param <T>
[ "Performs", "an", "action", "on", "onError", "with", "the", "provided", "emission", "count" ]
train
https://github.com/ReactiveX/RxJavaFX/blob/8f44d4cc1caba9a8919f01cb1897aaea5514c7e5/src/main/java/io/reactivex/rxjavafx/transformers/FxObservableTransformers.java#L131-L133
bluelinelabs/Conductor
conductor/src/main/java/com/bluelinelabs/conductor/changehandler/TransitionChangeHandler.java
TransitionChangeHandler.prepareForTransition
public void prepareForTransition(@NonNull ViewGroup container, @Nullable View from, @Nullable View to, @NonNull Transition transition, boolean isPush, @NonNull OnTransitionPreparedListener onTransitionPreparedListener) { """ Called before a transition occurs. This can be used to reorder views, set their transition names, etc. The transition will begin when {@code onTransitionPreparedListener} is called. @param container The container these Views are hosted in @param from The previous View in the container or {@code null} if there was no Controller before this transition @param to The next View that should be put in the container or {@code null} if no Controller is being transitioned to @param transition The transition that is being prepared for @param isPush True if this is a push transaction, false if it's a pop """ onTransitionPreparedListener.onPrepared(); }
java
public void prepareForTransition(@NonNull ViewGroup container, @Nullable View from, @Nullable View to, @NonNull Transition transition, boolean isPush, @NonNull OnTransitionPreparedListener onTransitionPreparedListener) { onTransitionPreparedListener.onPrepared(); }
[ "public", "void", "prepareForTransition", "(", "@", "NonNull", "ViewGroup", "container", ",", "@", "Nullable", "View", "from", ",", "@", "Nullable", "View", "to", ",", "@", "NonNull", "Transition", "transition", ",", "boolean", "isPush", ",", "@", "NonNull", "OnTransitionPreparedListener", "onTransitionPreparedListener", ")", "{", "onTransitionPreparedListener", ".", "onPrepared", "(", ")", ";", "}" ]
Called before a transition occurs. This can be used to reorder views, set their transition names, etc. The transition will begin when {@code onTransitionPreparedListener} is called. @param container The container these Views are hosted in @param from The previous View in the container or {@code null} if there was no Controller before this transition @param to The next View that should be put in the container or {@code null} if no Controller is being transitioned to @param transition The transition that is being prepared for @param isPush True if this is a push transaction, false if it's a pop
[ "Called", "before", "a", "transition", "occurs", ".", "This", "can", "be", "used", "to", "reorder", "views", "set", "their", "transition", "names", "etc", ".", "The", "transition", "will", "begin", "when", "{", "@code", "onTransitionPreparedListener", "}", "is", "called", "." ]
train
https://github.com/bluelinelabs/Conductor/blob/94c9121bb16f93b481954513a8e3905846829fb2/conductor/src/main/java/com/bluelinelabs/conductor/changehandler/TransitionChangeHandler.java#L120-L122
j-easy/easy-random
easy-random-core/src/main/java/org/jeasy/random/randomizers/AbstractRandomizer.java
AbstractRandomizer.nextDouble
protected double nextDouble(final double min, final double max) { """ Return a random double in the given range. @param min value @param max value @return random double in the given range """ double value = min + (random.nextDouble() * (max - min)); if (value < min) { return min; } else if (value > max) { return max; } else { return value; } // NB: ThreadLocalRandom.current().nextDouble(min, max)) cannot be use because the seed is not configurable // and is created per thread (see Javadoc) }
java
protected double nextDouble(final double min, final double max) { double value = min + (random.nextDouble() * (max - min)); if (value < min) { return min; } else if (value > max) { return max; } else { return value; } // NB: ThreadLocalRandom.current().nextDouble(min, max)) cannot be use because the seed is not configurable // and is created per thread (see Javadoc) }
[ "protected", "double", "nextDouble", "(", "final", "double", "min", ",", "final", "double", "max", ")", "{", "double", "value", "=", "min", "+", "(", "random", ".", "nextDouble", "(", ")", "*", "(", "max", "-", "min", ")", ")", ";", "if", "(", "value", "<", "min", ")", "{", "return", "min", ";", "}", "else", "if", "(", "value", ">", "max", ")", "{", "return", "max", ";", "}", "else", "{", "return", "value", ";", "}", "// NB: ThreadLocalRandom.current().nextDouble(min, max)) cannot be use because the seed is not configurable", "// and is created per thread (see Javadoc)", "}" ]
Return a random double in the given range. @param min value @param max value @return random double in the given range
[ "Return", "a", "random", "double", "in", "the", "given", "range", "." ]
train
https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/randomizers/AbstractRandomizer.java#L65-L76
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java
ValueEnforcer.isEqual
public static <T> T isEqual (final T aValue, @Nullable final T aExpectedValue, final String sName) { """ Check that the passed value is the same as the provided expected value using <code>equals</code> to check comparison. @param <T> Type to be checked and returned @param aValue The value to check. @param sName The name of the value (e.g. the parameter name) @param aExpectedValue The expected value. May be <code>null</code>. @return The passed value and maybe <code>null</code> if the expected value is null. @throws IllegalArgumentException if the passed value is not <code>null</code>. """ if (isEnabled ()) return isEqual (aValue, aExpectedValue, () -> sName); return aValue; }
java
public static <T> T isEqual (final T aValue, @Nullable final T aExpectedValue, final String sName) { if (isEnabled ()) return isEqual (aValue, aExpectedValue, () -> sName); return aValue; }
[ "public", "static", "<", "T", ">", "T", "isEqual", "(", "final", "T", "aValue", ",", "@", "Nullable", "final", "T", "aExpectedValue", ",", "final", "String", "sName", ")", "{", "if", "(", "isEnabled", "(", ")", ")", "return", "isEqual", "(", "aValue", ",", "aExpectedValue", ",", "(", ")", "->", "sName", ")", ";", "return", "aValue", ";", "}" ]
Check that the passed value is the same as the provided expected value using <code>equals</code> to check comparison. @param <T> Type to be checked and returned @param aValue The value to check. @param sName The name of the value (e.g. the parameter name) @param aExpectedValue The expected value. May be <code>null</code>. @return The passed value and maybe <code>null</code> if the expected value is null. @throws IllegalArgumentException if the passed value is not <code>null</code>.
[ "Check", "that", "the", "passed", "value", "is", "the", "same", "as", "the", "provided", "expected", "value", "using", "<code", ">", "equals<", "/", "code", ">", "to", "check", "comparison", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/ValueEnforcer.java#L1482-L1487
SeleniumHQ/fluent-selenium
java/src/main/java/org/seleniumhq/selenium/fluent/FluentSelect.java
FluentSelect.selectByValue
public FluentSelect selectByValue(final String value) { """ <p> Select all options that have a value matching the argument. That is, when given "foo" this would select an option like: </p> &lt;option value="foo"&gt;Bar&lt;/option&gt; @param value The value to match against """ executeAndWrapReThrowIfNeeded(new SelectByValue(value), Context.singular(context, "selectByValue", null, value), true); return new FluentSelect(super.delegate, currentElement.getFound(), this.context, monitor, booleanInsteadOfNotFoundException); }
java
public FluentSelect selectByValue(final String value) { executeAndWrapReThrowIfNeeded(new SelectByValue(value), Context.singular(context, "selectByValue", null, value), true); return new FluentSelect(super.delegate, currentElement.getFound(), this.context, monitor, booleanInsteadOfNotFoundException); }
[ "public", "FluentSelect", "selectByValue", "(", "final", "String", "value", ")", "{", "executeAndWrapReThrowIfNeeded", "(", "new", "SelectByValue", "(", "value", ")", ",", "Context", ".", "singular", "(", "context", ",", "\"selectByValue\"", ",", "null", ",", "value", ")", ",", "true", ")", ";", "return", "new", "FluentSelect", "(", "super", ".", "delegate", ",", "currentElement", ".", "getFound", "(", ")", ",", "this", ".", "context", ",", "monitor", ",", "booleanInsteadOfNotFoundException", ")", ";", "}" ]
<p> Select all options that have a value matching the argument. That is, when given "foo" this would select an option like: </p> &lt;option value="foo"&gt;Bar&lt;/option&gt; @param value The value to match against
[ "<p", ">", "Select", "all", "options", "that", "have", "a", "value", "matching", "the", "argument", ".", "That", "is", "when", "given", "foo", "this", "would", "select", "an", "option", "like", ":", "<", "/", "p", ">", "&lt", ";", "option", "value", "=", "foo", "&gt", ";", "Bar&lt", ";", "/", "option&gt", ";" ]
train
https://github.com/SeleniumHQ/fluent-selenium/blob/fcb171471a7d1abb2800bcbca21b3ae3e6c12472/java/src/main/java/org/seleniumhq/selenium/fluent/FluentSelect.java#L113-L116
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
Validator.expectRegex
public void expectRegex(String name, Pattern pattern) { """ Validates a field by a given regular expression pattern It is required to pass a pre-compiled pattern, e.g. Pattern pattern = Pattern.compile("[a-Z,0-9]") @param name The field to check @param pattern The pre-compiled pattern """ expectRegex(name, pattern, messages.get(Validation.REGEX_KEY.name(), name)); }
java
public void expectRegex(String name, Pattern pattern) { expectRegex(name, pattern, messages.get(Validation.REGEX_KEY.name(), name)); }
[ "public", "void", "expectRegex", "(", "String", "name", ",", "Pattern", "pattern", ")", "{", "expectRegex", "(", "name", ",", "pattern", ",", "messages", ".", "get", "(", "Validation", ".", "REGEX_KEY", ".", "name", "(", ")", ",", "name", ")", ")", ";", "}" ]
Validates a field by a given regular expression pattern It is required to pass a pre-compiled pattern, e.g. Pattern pattern = Pattern.compile("[a-Z,0-9]") @param name The field to check @param pattern The pre-compiled pattern
[ "Validates", "a", "field", "by", "a", "given", "regular", "expression", "pattern" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L377-L379
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java
ElementMatchers.namedIgnoreCase
public static <T extends NamedElement> ElementMatcher.Junction<T> namedIgnoreCase(String name) { """ Matches a {@link NamedElement} for its name. The name's capitalization is ignored. @param name The expected name. @param <T> The type of the matched object. @return An element matcher for a named element's name. """ return new NameMatcher<T>(new StringMatcher(name, StringMatcher.Mode.EQUALS_FULLY_IGNORE_CASE)); }
java
public static <T extends NamedElement> ElementMatcher.Junction<T> namedIgnoreCase(String name) { return new NameMatcher<T>(new StringMatcher(name, StringMatcher.Mode.EQUALS_FULLY_IGNORE_CASE)); }
[ "public", "static", "<", "T", "extends", "NamedElement", ">", "ElementMatcher", ".", "Junction", "<", "T", ">", "namedIgnoreCase", "(", "String", "name", ")", "{", "return", "new", "NameMatcher", "<", "T", ">", "(", "new", "StringMatcher", "(", "name", ",", "StringMatcher", ".", "Mode", ".", "EQUALS_FULLY_IGNORE_CASE", ")", ")", ";", "}" ]
Matches a {@link NamedElement} for its name. The name's capitalization is ignored. @param name The expected name. @param <T> The type of the matched object. @return An element matcher for a named element's name.
[ "Matches", "a", "{", "@link", "NamedElement", "}", "for", "its", "name", ".", "The", "name", "s", "capitalization", "is", "ignored", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/matcher/ElementMatchers.java#L666-L668
apache/flink
flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java
PropertiesUtil.getLong
public static long getLong(Properties config, String key, long defaultValue, Logger logger) { """ Get long from properties. This method only logs if the long is not valid. @param config Properties @param key key in Properties @param defaultValue default value if value is not set @return default or value of key """ try { return getLong(config, key, defaultValue); } catch (IllegalArgumentException iae) { logger.warn(iae.getMessage()); return defaultValue; } }
java
public static long getLong(Properties config, String key, long defaultValue, Logger logger) { try { return getLong(config, key, defaultValue); } catch (IllegalArgumentException iae) { logger.warn(iae.getMessage()); return defaultValue; } }
[ "public", "static", "long", "getLong", "(", "Properties", "config", ",", "String", "key", ",", "long", "defaultValue", ",", "Logger", "logger", ")", "{", "try", "{", "return", "getLong", "(", "config", ",", "key", ",", "defaultValue", ")", ";", "}", "catch", "(", "IllegalArgumentException", "iae", ")", "{", "logger", ".", "warn", "(", "iae", ".", "getMessage", "(", ")", ")", ";", "return", "defaultValue", ";", "}", "}" ]
Get long from properties. This method only logs if the long is not valid. @param config Properties @param key key in Properties @param defaultValue default value if value is not set @return default or value of key
[ "Get", "long", "from", "properties", ".", "This", "method", "only", "logs", "if", "the", "long", "is", "not", "valid", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/PropertiesUtil.java#L84-L91
lets-blade/blade
src/main/java/com/blade/mvc/route/RouteBuilder.java
RouteBuilder.addRouter
public void addRouter(final Class<?> routeType, Object controller) { """ Parse all routing in a controller @param routeType resolve the routing class, e.g RouteHandler.class or some controller class """ Method[] methods = routeType.getDeclaredMethods(); if (BladeKit.isEmpty(methods)) { return; } String nameSpace = null, suffix = null; if (null != routeType.getAnnotation(Path.class)) { nameSpace = routeType.getAnnotation(Path.class).value(); suffix = routeType.getAnnotation(Path.class).suffix(); } if (null == nameSpace) { log.warn("Route [{}] not path annotation", routeType.getName()); return; } for (Method method : methods) { com.blade.mvc.annotation.Route mapping = method.getAnnotation(com.blade.mvc.annotation.Route.class); GetRoute getRoute = method.getAnnotation(GetRoute.class); PostRoute postRoute = method.getAnnotation(PostRoute.class); PutRoute putRoute = method.getAnnotation(PutRoute.class); DeleteRoute deleteRoute = method.getAnnotation(DeleteRoute.class); this.parseRoute(RouteStruct.builder().mapping(mapping) .getRoute(getRoute).postRoute(postRoute) .putRoute(putRoute).deleteRoute(deleteRoute) .nameSpace(nameSpace) .suffix(suffix).routeType(routeType) .controller(controller).method(method) .build()); } }
java
public void addRouter(final Class<?> routeType, Object controller) { Method[] methods = routeType.getDeclaredMethods(); if (BladeKit.isEmpty(methods)) { return; } String nameSpace = null, suffix = null; if (null != routeType.getAnnotation(Path.class)) { nameSpace = routeType.getAnnotation(Path.class).value(); suffix = routeType.getAnnotation(Path.class).suffix(); } if (null == nameSpace) { log.warn("Route [{}] not path annotation", routeType.getName()); return; } for (Method method : methods) { com.blade.mvc.annotation.Route mapping = method.getAnnotation(com.blade.mvc.annotation.Route.class); GetRoute getRoute = method.getAnnotation(GetRoute.class); PostRoute postRoute = method.getAnnotation(PostRoute.class); PutRoute putRoute = method.getAnnotation(PutRoute.class); DeleteRoute deleteRoute = method.getAnnotation(DeleteRoute.class); this.parseRoute(RouteStruct.builder().mapping(mapping) .getRoute(getRoute).postRoute(postRoute) .putRoute(putRoute).deleteRoute(deleteRoute) .nameSpace(nameSpace) .suffix(suffix).routeType(routeType) .controller(controller).method(method) .build()); } }
[ "public", "void", "addRouter", "(", "final", "Class", "<", "?", ">", "routeType", ",", "Object", "controller", ")", "{", "Method", "[", "]", "methods", "=", "routeType", ".", "getDeclaredMethods", "(", ")", ";", "if", "(", "BladeKit", ".", "isEmpty", "(", "methods", ")", ")", "{", "return", ";", "}", "String", "nameSpace", "=", "null", ",", "suffix", "=", "null", ";", "if", "(", "null", "!=", "routeType", ".", "getAnnotation", "(", "Path", ".", "class", ")", ")", "{", "nameSpace", "=", "routeType", ".", "getAnnotation", "(", "Path", ".", "class", ")", ".", "value", "(", ")", ";", "suffix", "=", "routeType", ".", "getAnnotation", "(", "Path", ".", "class", ")", ".", "suffix", "(", ")", ";", "}", "if", "(", "null", "==", "nameSpace", ")", "{", "log", ".", "warn", "(", "\"Route [{}] not path annotation\"", ",", "routeType", ".", "getName", "(", ")", ")", ";", "return", ";", "}", "for", "(", "Method", "method", ":", "methods", ")", "{", "com", ".", "blade", ".", "mvc", ".", "annotation", ".", "Route", "mapping", "=", "method", ".", "getAnnotation", "(", "com", ".", "blade", ".", "mvc", ".", "annotation", ".", "Route", ".", "class", ")", ";", "GetRoute", "getRoute", "=", "method", ".", "getAnnotation", "(", "GetRoute", ".", "class", ")", ";", "PostRoute", "postRoute", "=", "method", ".", "getAnnotation", "(", "PostRoute", ".", "class", ")", ";", "PutRoute", "putRoute", "=", "method", ".", "getAnnotation", "(", "PutRoute", ".", "class", ")", ";", "DeleteRoute", "deleteRoute", "=", "method", ".", "getAnnotation", "(", "DeleteRoute", ".", "class", ")", ";", "this", ".", "parseRoute", "(", "RouteStruct", ".", "builder", "(", ")", ".", "mapping", "(", "mapping", ")", ".", "getRoute", "(", "getRoute", ")", ".", "postRoute", "(", "postRoute", ")", ".", "putRoute", "(", "putRoute", ")", ".", "deleteRoute", "(", "deleteRoute", ")", ".", "nameSpace", "(", "nameSpace", ")", ".", "suffix", "(", "suffix", ")", ".", "routeType", "(", "routeType", ")", ".", "controller", "(", "controller", ")", ".", "method", "(", "method", ")", ".", "build", "(", ")", ")", ";", "}", "}" ]
Parse all routing in a controller @param routeType resolve the routing class, e.g RouteHandler.class or some controller class
[ "Parse", "all", "routing", "in", "a", "controller" ]
train
https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/mvc/route/RouteBuilder.java#L53-L87
nikolavp/approval
approval-core/src/main/java/com/github/approval/reporters/Reporters.java
Reporters.imageMagick
public static Reporter imageMagick() { """ A reporter that compares images. Currently this uses <a href="http://www.imagemagick.org/script/binary-releases.php">imagemagick</a> for comparison. If you only want to view the new image on first approval and when there is a difference, then you better use the {@link #fileLauncher()} reporter which will do this for you. @return the reporter that uses ImagemMagick for comparison """ return SwingInteractiveReporter.wrap(new Reporter() { private final Reporter other = fileLauncher(); @Override public void notTheSame(byte[] oldValue, File fileForVerification, byte[] newValue, File fileForApproval) { try { final File compareResult = File.createTempFile("compareResult", fileForVerification.getName()); final Process compare = ExecutableDifferenceReporter.runProcess("compare", fileForApproval.getCanonicalPath(), fileForVerification.getAbsolutePath(), compareResult.getAbsolutePath()); final int result = compare.waitFor(); if (result != 0) { throw new IllegalStateException("Couldn't execute compare!"); } other.approveNew(/* unused */newValue, /* only used value*/compareResult, /* unused */fileForVerification); } catch (IOException | InterruptedException e) { throw new AssertionError("Couldn't create file!", e); } } @Override public void approveNew(byte[] value, File fileForApproval, File fileForVerification) { other.approveNew(value, fileForApproval, fileForVerification); } @Override public boolean canApprove(File fileForApproval) { return other.canApprove(fileForApproval); } }); }
java
public static Reporter imageMagick() { return SwingInteractiveReporter.wrap(new Reporter() { private final Reporter other = fileLauncher(); @Override public void notTheSame(byte[] oldValue, File fileForVerification, byte[] newValue, File fileForApproval) { try { final File compareResult = File.createTempFile("compareResult", fileForVerification.getName()); final Process compare = ExecutableDifferenceReporter.runProcess("compare", fileForApproval.getCanonicalPath(), fileForVerification.getAbsolutePath(), compareResult.getAbsolutePath()); final int result = compare.waitFor(); if (result != 0) { throw new IllegalStateException("Couldn't execute compare!"); } other.approveNew(/* unused */newValue, /* only used value*/compareResult, /* unused */fileForVerification); } catch (IOException | InterruptedException e) { throw new AssertionError("Couldn't create file!", e); } } @Override public void approveNew(byte[] value, File fileForApproval, File fileForVerification) { other.approveNew(value, fileForApproval, fileForVerification); } @Override public boolean canApprove(File fileForApproval) { return other.canApprove(fileForApproval); } }); }
[ "public", "static", "Reporter", "imageMagick", "(", ")", "{", "return", "SwingInteractiveReporter", ".", "wrap", "(", "new", "Reporter", "(", ")", "{", "private", "final", "Reporter", "other", "=", "fileLauncher", "(", ")", ";", "@", "Override", "public", "void", "notTheSame", "(", "byte", "[", "]", "oldValue", ",", "File", "fileForVerification", ",", "byte", "[", "]", "newValue", ",", "File", "fileForApproval", ")", "{", "try", "{", "final", "File", "compareResult", "=", "File", ".", "createTempFile", "(", "\"compareResult\"", ",", "fileForVerification", ".", "getName", "(", ")", ")", ";", "final", "Process", "compare", "=", "ExecutableDifferenceReporter", ".", "runProcess", "(", "\"compare\"", ",", "fileForApproval", ".", "getCanonicalPath", "(", ")", ",", "fileForVerification", ".", "getAbsolutePath", "(", ")", ",", "compareResult", ".", "getAbsolutePath", "(", ")", ")", ";", "final", "int", "result", "=", "compare", ".", "waitFor", "(", ")", ";", "if", "(", "result", "!=", "0", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Couldn't execute compare!\"", ")", ";", "}", "other", ".", "approveNew", "(", "/* unused */", "newValue", ",", "/* only used value*/", "compareResult", ",", "/* unused */", "fileForVerification", ")", ";", "}", "catch", "(", "IOException", "|", "InterruptedException", "e", ")", "{", "throw", "new", "AssertionError", "(", "\"Couldn't create file!\"", ",", "e", ")", ";", "}", "}", "@", "Override", "public", "void", "approveNew", "(", "byte", "[", "]", "value", ",", "File", "fileForApproval", ",", "File", "fileForVerification", ")", "{", "other", ".", "approveNew", "(", "value", ",", "fileForApproval", ",", "fileForVerification", ")", ";", "}", "@", "Override", "public", "boolean", "canApprove", "(", "File", "fileForApproval", ")", "{", "return", "other", ".", "canApprove", "(", "fileForApproval", ")", ";", "}", "}", ")", ";", "}" ]
A reporter that compares images. Currently this uses <a href="http://www.imagemagick.org/script/binary-releases.php">imagemagick</a> for comparison. If you only want to view the new image on first approval and when there is a difference, then you better use the {@link #fileLauncher()} reporter which will do this for you. @return the reporter that uses ImagemMagick for comparison
[ "A", "reporter", "that", "compares", "images", ".", "Currently", "this", "uses", "<a", "href", "=", "http", ":", "//", "www", ".", "imagemagick", ".", "org", "/", "script", "/", "binary", "-", "releases", ".", "php", ">", "imagemagick<", "/", "a", ">", "for", "comparison", ".", "If", "you", "only", "want", "to", "view", "the", "new", "image", "on", "first", "approval", "and", "when", "there", "is", "a", "difference", "then", "you", "better", "use", "the", "{", "@link", "#fileLauncher", "()", "}", "reporter", "which", "will", "do", "this", "for", "you", "." ]
train
https://github.com/nikolavp/approval/blob/5e32ecc3bc7f631e94a7049894fdd99a3aa5b1b8/approval-core/src/main/java/com/github/approval/reporters/Reporters.java#L153-L184
lucee/Lucee
core/src/main/java/lucee/runtime/op/Caster.java
Caster.toXML
public static Node toXML(Object value, Node defaultValue) { """ cast Object to a XML Node @param value @param defaultValue @return XML Node """ try { return toXML(value); } catch (PageException e) { return defaultValue; } }
java
public static Node toXML(Object value, Node defaultValue) { try { return toXML(value); } catch (PageException e) { return defaultValue; } }
[ "public", "static", "Node", "toXML", "(", "Object", "value", ",", "Node", "defaultValue", ")", "{", "try", "{", "return", "toXML", "(", "value", ")", ";", "}", "catch", "(", "PageException", "e", ")", "{", "return", "defaultValue", ";", "}", "}" ]
cast Object to a XML Node @param value @param defaultValue @return XML Node
[ "cast", "Object", "to", "a", "XML", "Node" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L4442-L4449
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java
SecStrucCalc.trackHBondEnergy
private void trackHBondEnergy(int i, int j, double energy) { """ Store Hbonds in the Groups. DSSP allows two HBonds per aminoacids to allow bifurcated bonds. """ if (groups[i].getPDBName().equals("PRO")) { logger.debug("Ignore: PRO {}",groups[i].getResidueNumber()); return; } SecStrucState stateOne = getSecStrucState(i); SecStrucState stateTwo = getSecStrucState(j); double acc1e = stateOne.getAccept1().getEnergy(); double acc2e = stateOne.getAccept2().getEnergy(); double don1e = stateTwo.getDonor1().getEnergy(); double don2e = stateTwo.getDonor2().getEnergy(); //Acceptor: N-H-->O if (energy < acc1e) { logger.debug("{} < {}",energy,acc1e); stateOne.setAccept2(stateOne.getAccept1()); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(j); stateOne.setAccept1(bond); } else if ( energy < acc2e ) { logger.debug("{} < {}",energy,acc2e); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(j); stateOne.setAccept2(bond); } //The other side of the bond: donor O-->N-H if (energy < don1e) { logger.debug("{} < {}",energy,don1e); stateTwo.setDonor2(stateTwo.getDonor1()); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(i); stateTwo.setDonor1(bond); } else if ( energy < don2e ) { logger.debug("{} < {}",energy,don2e); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(i); stateTwo.setDonor2(bond); } }
java
private void trackHBondEnergy(int i, int j, double energy) { if (groups[i].getPDBName().equals("PRO")) { logger.debug("Ignore: PRO {}",groups[i].getResidueNumber()); return; } SecStrucState stateOne = getSecStrucState(i); SecStrucState stateTwo = getSecStrucState(j); double acc1e = stateOne.getAccept1().getEnergy(); double acc2e = stateOne.getAccept2().getEnergy(); double don1e = stateTwo.getDonor1().getEnergy(); double don2e = stateTwo.getDonor2().getEnergy(); //Acceptor: N-H-->O if (energy < acc1e) { logger.debug("{} < {}",energy,acc1e); stateOne.setAccept2(stateOne.getAccept1()); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(j); stateOne.setAccept1(bond); } else if ( energy < acc2e ) { logger.debug("{} < {}",energy,acc2e); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(j); stateOne.setAccept2(bond); } //The other side of the bond: donor O-->N-H if (energy < don1e) { logger.debug("{} < {}",energy,don1e); stateTwo.setDonor2(stateTwo.getDonor1()); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(i); stateTwo.setDonor1(bond); } else if ( energy < don2e ) { logger.debug("{} < {}",energy,don2e); HBond bond = new HBond(); bond.setEnergy(energy); bond.setPartner(i); stateTwo.setDonor2(bond); } }
[ "private", "void", "trackHBondEnergy", "(", "int", "i", ",", "int", "j", ",", "double", "energy", ")", "{", "if", "(", "groups", "[", "i", "]", ".", "getPDBName", "(", ")", ".", "equals", "(", "\"PRO\"", ")", ")", "{", "logger", ".", "debug", "(", "\"Ignore: PRO {}\"", ",", "groups", "[", "i", "]", ".", "getResidueNumber", "(", ")", ")", ";", "return", ";", "}", "SecStrucState", "stateOne", "=", "getSecStrucState", "(", "i", ")", ";", "SecStrucState", "stateTwo", "=", "getSecStrucState", "(", "j", ")", ";", "double", "acc1e", "=", "stateOne", ".", "getAccept1", "(", ")", ".", "getEnergy", "(", ")", ";", "double", "acc2e", "=", "stateOne", ".", "getAccept2", "(", ")", ".", "getEnergy", "(", ")", ";", "double", "don1e", "=", "stateTwo", ".", "getDonor1", "(", ")", ".", "getEnergy", "(", ")", ";", "double", "don2e", "=", "stateTwo", ".", "getDonor2", "(", ")", ".", "getEnergy", "(", ")", ";", "//Acceptor: N-H-->O", "if", "(", "energy", "<", "acc1e", ")", "{", "logger", ".", "debug", "(", "\"{} < {}\"", ",", "energy", ",", "acc1e", ")", ";", "stateOne", ".", "setAccept2", "(", "stateOne", ".", "getAccept1", "(", ")", ")", ";", "HBond", "bond", "=", "new", "HBond", "(", ")", ";", "bond", ".", "setEnergy", "(", "energy", ")", ";", "bond", ".", "setPartner", "(", "j", ")", ";", "stateOne", ".", "setAccept1", "(", "bond", ")", ";", "}", "else", "if", "(", "energy", "<", "acc2e", ")", "{", "logger", ".", "debug", "(", "\"{} < {}\"", ",", "energy", ",", "acc2e", ")", ";", "HBond", "bond", "=", "new", "HBond", "(", ")", ";", "bond", ".", "setEnergy", "(", "energy", ")", ";", "bond", ".", "setPartner", "(", "j", ")", ";", "stateOne", ".", "setAccept2", "(", "bond", ")", ";", "}", "//The other side of the bond: donor O-->N-H", "if", "(", "energy", "<", "don1e", ")", "{", "logger", ".", "debug", "(", "\"{} < {}\"", ",", "energy", ",", "don1e", ")", ";", "stateTwo", ".", "setDonor2", "(", "stateTwo", ".", "getDonor1", "(", ")", ")", ";", "HBond", "bond", "=", "new", "HBond", "(", ")", ";", "bond", ".", "setEnergy", "(", "energy", ")", ";", "bond", ".", "setPartner", "(", "i", ")", ";", "stateTwo", ".", "setDonor1", "(", "bond", ")", ";", "}", "else", "if", "(", "energy", "<", "don2e", ")", "{", "logger", ".", "debug", "(", "\"{} < {}\"", ",", "energy", ",", "don2e", ")", ";", "HBond", "bond", "=", "new", "HBond", "(", ")", ";", "bond", ".", "setEnergy", "(", "energy", ")", ";", "bond", ".", "setPartner", "(", "i", ")", ";", "stateTwo", ".", "setDonor2", "(", "bond", ")", ";", "}", "}" ]
Store Hbonds in the Groups. DSSP allows two HBonds per aminoacids to allow bifurcated bonds.
[ "Store", "Hbonds", "in", "the", "Groups", ".", "DSSP", "allows", "two", "HBonds", "per", "aminoacids", "to", "allow", "bifurcated", "bonds", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java#L877-L935
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/network/bridgegroup_binding.java
bridgegroup_binding.get
public static bridgegroup_binding get(nitro_service service, Long id) throws Exception { """ Use this API to fetch bridgegroup_binding resource of given name . """ bridgegroup_binding obj = new bridgegroup_binding(); obj.set_id(id); bridgegroup_binding response = (bridgegroup_binding) obj.get_resource(service); return response; }
java
public static bridgegroup_binding get(nitro_service service, Long id) throws Exception{ bridgegroup_binding obj = new bridgegroup_binding(); obj.set_id(id); bridgegroup_binding response = (bridgegroup_binding) obj.get_resource(service); return response; }
[ "public", "static", "bridgegroup_binding", "get", "(", "nitro_service", "service", ",", "Long", "id", ")", "throws", "Exception", "{", "bridgegroup_binding", "obj", "=", "new", "bridgegroup_binding", "(", ")", ";", "obj", ".", "set_id", "(", "id", ")", ";", "bridgegroup_binding", "response", "=", "(", "bridgegroup_binding", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch bridgegroup_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "bridgegroup_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/network/bridgegroup_binding.java#L137-L142
basho/riak-java-client
src/main/java/com/basho/riak/client/api/RiakClient.java
RiakClient.newClient
public static RiakClient newClient(int port, String... remoteAddresses) throws UnknownHostException { """ Static factory method to create a new client instance. This method produces a client connected to the supplied addresses on the supplied port. @param remoteAddresses a list of IP addresses or hostnames @param port the (protocol buffers) port to connect to on the supplied hosts. @return a new client instance @throws UnknownHostException if a supplied hostname cannot be resolved. """ return newClient(port, Arrays.asList(remoteAddresses)); }
java
public static RiakClient newClient(int port, String... remoteAddresses) throws UnknownHostException { return newClient(port, Arrays.asList(remoteAddresses)); }
[ "public", "static", "RiakClient", "newClient", "(", "int", "port", ",", "String", "...", "remoteAddresses", ")", "throws", "UnknownHostException", "{", "return", "newClient", "(", "port", ",", "Arrays", ".", "asList", "(", "remoteAddresses", ")", ")", ";", "}" ]
Static factory method to create a new client instance. This method produces a client connected to the supplied addresses on the supplied port. @param remoteAddresses a list of IP addresses or hostnames @param port the (protocol buffers) port to connect to on the supplied hosts. @return a new client instance @throws UnknownHostException if a supplied hostname cannot be resolved.
[ "Static", "factory", "method", "to", "create", "a", "new", "client", "instance", ".", "This", "method", "produces", "a", "client", "connected", "to", "the", "supplied", "addresses", "on", "the", "supplied", "port", "." ]
train
https://github.com/basho/riak-java-client/blob/bed6cd60f360bacf1b873ab92dd74f2526651e71/src/main/java/com/basho/riak/client/api/RiakClient.java#L205-L208
svenkubiak/mangooio-mongodb-extension
src/main/java/de/svenkubiak/mangooio/mongodb/MongoDB.java
MongoDB.findById
public <T extends Object> T findById(Object id, Class<T> clazz) { """ Retrieves a mapped Morphia object from MongoDB. If the id is not of type ObjectId, it will be converted to ObjectId @param id The id of the object @param clazz The mapped Morphia class @param <T> JavaDoc requires this - please ignore @return The requested class from MongoDB or null if none found """ Preconditions.checkNotNull(clazz, "Tryed to find an object by id, but given class is null"); Preconditions.checkNotNull(id, "Tryed to find an object by id, but given id is null"); return this.datastore.get(clazz, (id instanceof ObjectId) ? id : new ObjectId(String.valueOf(id))); }
java
public <T extends Object> T findById(Object id, Class<T> clazz) { Preconditions.checkNotNull(clazz, "Tryed to find an object by id, but given class is null"); Preconditions.checkNotNull(id, "Tryed to find an object by id, but given id is null"); return this.datastore.get(clazz, (id instanceof ObjectId) ? id : new ObjectId(String.valueOf(id))); }
[ "public", "<", "T", "extends", "Object", ">", "T", "findById", "(", "Object", "id", ",", "Class", "<", "T", ">", "clazz", ")", "{", "Preconditions", ".", "checkNotNull", "(", "clazz", ",", "\"Tryed to find an object by id, but given class is null\"", ")", ";", "Preconditions", ".", "checkNotNull", "(", "id", ",", "\"Tryed to find an object by id, but given id is null\"", ")", ";", "return", "this", ".", "datastore", ".", "get", "(", "clazz", ",", "(", "id", "instanceof", "ObjectId", ")", "?", "id", ":", "new", "ObjectId", "(", "String", ".", "valueOf", "(", "id", ")", ")", ")", ";", "}" ]
Retrieves a mapped Morphia object from MongoDB. If the id is not of type ObjectId, it will be converted to ObjectId @param id The id of the object @param clazz The mapped Morphia class @param <T> JavaDoc requires this - please ignore @return The requested class from MongoDB or null if none found
[ "Retrieves", "a", "mapped", "Morphia", "object", "from", "MongoDB", ".", "If", "the", "id", "is", "not", "of", "type", "ObjectId", "it", "will", "be", "converted", "to", "ObjectId" ]
train
https://github.com/svenkubiak/mangooio-mongodb-extension/blob/4a281b63c20cdbb4b82c4c0d100726ec464bfa12/src/main/java/de/svenkubiak/mangooio/mongodb/MongoDB.java#L128-L133
mongodb/stitch-android-sdk
android/core/src/main/java/com/mongodb/stitch/android/core/Stitch.java
Stitch.initializeAppClient
public static StitchAppClient initializeAppClient( @Nonnull final String clientAppId ) { """ Initializes an app client for Stitch to use when using {@link Stitch#getAppClient(String)}}. Can only be called once per client app id. @param clientAppId the client app id to initialize an app client for. @return the app client that was just initialized. """ return initializeAppClient(clientAppId, new StitchAppClientConfiguration.Builder().build()); }
java
public static StitchAppClient initializeAppClient( @Nonnull final String clientAppId ) { return initializeAppClient(clientAppId, new StitchAppClientConfiguration.Builder().build()); }
[ "public", "static", "StitchAppClient", "initializeAppClient", "(", "@", "Nonnull", "final", "String", "clientAppId", ")", "{", "return", "initializeAppClient", "(", "clientAppId", ",", "new", "StitchAppClientConfiguration", ".", "Builder", "(", ")", ".", "build", "(", ")", ")", ";", "}" ]
Initializes an app client for Stitch to use when using {@link Stitch#getAppClient(String)}}. Can only be called once per client app id. @param clientAppId the client app id to initialize an app client for. @return the app client that was just initialized.
[ "Initializes", "an", "app", "client", "for", "Stitch", "to", "use", "when", "using", "{", "@link", "Stitch#getAppClient", "(", "String", ")", "}}", ".", "Can", "only", "be", "called", "once", "per", "client", "app", "id", "." ]
train
https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/android/core/src/main/java/com/mongodb/stitch/android/core/Stitch.java#L191-L195
cybazeitalia/emaze-dysfunctional
src/main/java/net/emaze/dysfunctional/Spies.java
Spies.spy2nd
public static <T1, T2, R> BiFunction<T1, T2, R> spy2nd(BiFunction<T1, T2, R> function, Box<T2> param2) { """ Proxies a binary function spying for second parameter. @param <T1> the function first parameter type @param <T2> the function second parameter type @param <R> the function result type @param function the function that will be spied @param param2 a box that will be containing the second spied parameter @return the proxied function """ return spy(function, Box.<R>empty(), Box.<T1>empty(), param2); }
java
public static <T1, T2, R> BiFunction<T1, T2, R> spy2nd(BiFunction<T1, T2, R> function, Box<T2> param2) { return spy(function, Box.<R>empty(), Box.<T1>empty(), param2); }
[ "public", "static", "<", "T1", ",", "T2", ",", "R", ">", "BiFunction", "<", "T1", ",", "T2", ",", "R", ">", "spy2nd", "(", "BiFunction", "<", "T1", ",", "T2", ",", "R", ">", "function", ",", "Box", "<", "T2", ">", "param2", ")", "{", "return", "spy", "(", "function", ",", "Box", ".", "<", "R", ">", "empty", "(", ")", ",", "Box", ".", "<", "T1", ">", "empty", "(", ")", ",", "param2", ")", ";", "}" ]
Proxies a binary function spying for second parameter. @param <T1> the function first parameter type @param <T2> the function second parameter type @param <R> the function result type @param function the function that will be spied @param param2 a box that will be containing the second spied parameter @return the proxied function
[ "Proxies", "a", "binary", "function", "spying", "for", "second", "parameter", "." ]
train
https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Spies.java#L281-L283
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
Matchers.hasAnnotation
public static Matcher<Tree> hasAnnotation(TypeMirror annotationMirror) { """ Determines if an expression has an annotation referred to by the given mirror. Accounts for binary names and annotations inherited due to @Inherited. @param annotationMirror mirror referring to the annotation type """ return new Matcher<Tree>() { @Override public boolean matches(Tree tree, VisitorState state) { JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context); TypeElement typeElem = (TypeElement) javacEnv.getTypeUtils().asElement(annotationMirror); String name = annotationMirror.toString(); if (typeElem != null) { // Get the binary name if possible ($ to separate nested members). See b/36160747 name = javacEnv.getElementUtils().getBinaryName(typeElem).toString(); } return ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), name, state); } }; }
java
public static Matcher<Tree> hasAnnotation(TypeMirror annotationMirror) { return new Matcher<Tree>() { @Override public boolean matches(Tree tree, VisitorState state) { JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context); TypeElement typeElem = (TypeElement) javacEnv.getTypeUtils().asElement(annotationMirror); String name = annotationMirror.toString(); if (typeElem != null) { // Get the binary name if possible ($ to separate nested members). See b/36160747 name = javacEnv.getElementUtils().getBinaryName(typeElem).toString(); } return ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), name, state); } }; }
[ "public", "static", "Matcher", "<", "Tree", ">", "hasAnnotation", "(", "TypeMirror", "annotationMirror", ")", "{", "return", "new", "Matcher", "<", "Tree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "Tree", "tree", ",", "VisitorState", "state", ")", "{", "JavacProcessingEnvironment", "javacEnv", "=", "JavacProcessingEnvironment", ".", "instance", "(", "state", ".", "context", ")", ";", "TypeElement", "typeElem", "=", "(", "TypeElement", ")", "javacEnv", ".", "getTypeUtils", "(", ")", ".", "asElement", "(", "annotationMirror", ")", ";", "String", "name", "=", "annotationMirror", ".", "toString", "(", ")", ";", "if", "(", "typeElem", "!=", "null", ")", "{", "// Get the binary name if possible ($ to separate nested members). See b/36160747", "name", "=", "javacEnv", ".", "getElementUtils", "(", ")", ".", "getBinaryName", "(", "typeElem", ")", ".", "toString", "(", ")", ";", "}", "return", "ASTHelpers", ".", "hasAnnotation", "(", "ASTHelpers", ".", "getDeclaredSymbol", "(", "tree", ")", ",", "name", ",", "state", ")", ";", "}", "}", ";", "}" ]
Determines if an expression has an annotation referred to by the given mirror. Accounts for binary names and annotations inherited due to @Inherited. @param annotationMirror mirror referring to the annotation type
[ "Determines", "if", "an", "expression", "has", "an", "annotation", "referred", "to", "by", "the", "given", "mirror", ".", "Accounts", "for", "binary", "names", "and", "annotations", "inherited", "due", "to", "@Inherited", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java#L772-L786
wcm-io/wcm-io-tooling
commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/PackageInstaller.java
PackageInstaller.installFile
public void installFile(PackageFile packageFile) { """ Deploy file via package manager. @param packageFile AEM content package """ File file = packageFile.getFile(); if (!file.exists()) { throw new PackageManagerException("File does not exist: " + file.getAbsolutePath()); } try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) { // before install: if bundles are still stopping/starting, wait for completion pkgmgr.waitForBundlesActivation(httpClient); if (packageFile.isInstall()) { log.info("Upload and install " + (packageFile.isForce() ? "(force) " : "") + file.getName() + " to " + props.getPackageManagerUrl()); } else { log.info("Upload " + file.getName() + " to " + props.getPackageManagerUrl()); } VendorPackageInstaller installer = VendorInstallerFactory.getPackageInstaller(props.getPackageManagerUrl()); if (installer != null) { installer.installPackage(packageFile, pkgmgr, httpClient, props, log); } } catch (IOException ex) { throw new PackageManagerException("Install operation failed.", ex); } }
java
public void installFile(PackageFile packageFile) { File file = packageFile.getFile(); if (!file.exists()) { throw new PackageManagerException("File does not exist: " + file.getAbsolutePath()); } try (CloseableHttpClient httpClient = pkgmgr.getHttpClient()) { // before install: if bundles are still stopping/starting, wait for completion pkgmgr.waitForBundlesActivation(httpClient); if (packageFile.isInstall()) { log.info("Upload and install " + (packageFile.isForce() ? "(force) " : "") + file.getName() + " to " + props.getPackageManagerUrl()); } else { log.info("Upload " + file.getName() + " to " + props.getPackageManagerUrl()); } VendorPackageInstaller installer = VendorInstallerFactory.getPackageInstaller(props.getPackageManagerUrl()); if (installer != null) { installer.installPackage(packageFile, pkgmgr, httpClient, props, log); } } catch (IOException ex) { throw new PackageManagerException("Install operation failed.", ex); } }
[ "public", "void", "installFile", "(", "PackageFile", "packageFile", ")", "{", "File", "file", "=", "packageFile", ".", "getFile", "(", ")", ";", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "throw", "new", "PackageManagerException", "(", "\"File does not exist: \"", "+", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "try", "(", "CloseableHttpClient", "httpClient", "=", "pkgmgr", ".", "getHttpClient", "(", ")", ")", "{", "// before install: if bundles are still stopping/starting, wait for completion", "pkgmgr", ".", "waitForBundlesActivation", "(", "httpClient", ")", ";", "if", "(", "packageFile", ".", "isInstall", "(", ")", ")", "{", "log", ".", "info", "(", "\"Upload and install \"", "+", "(", "packageFile", ".", "isForce", "(", ")", "?", "\"(force) \"", ":", "\"\"", ")", "+", "file", ".", "getName", "(", ")", "+", "\" to \"", "+", "props", ".", "getPackageManagerUrl", "(", ")", ")", ";", "}", "else", "{", "log", ".", "info", "(", "\"Upload \"", "+", "file", ".", "getName", "(", ")", "+", "\" to \"", "+", "props", ".", "getPackageManagerUrl", "(", ")", ")", ";", "}", "VendorPackageInstaller", "installer", "=", "VendorInstallerFactory", ".", "getPackageInstaller", "(", "props", ".", "getPackageManagerUrl", "(", ")", ")", ";", "if", "(", "installer", "!=", "null", ")", "{", "installer", ".", "installPackage", "(", "packageFile", ",", "pkgmgr", ",", "httpClient", ",", "props", ",", "log", ")", ";", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "PackageManagerException", "(", "\"Install operation failed.\"", ",", "ex", ")", ";", "}", "}" ]
Deploy file via package manager. @param packageFile AEM content package
[ "Deploy", "file", "via", "package", "manager", "." ]
train
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/crx-packmgr-helper/src/main/java/io/wcm/tooling/commons/packmgr/install/PackageInstaller.java#L66-L92
mpetazzoni/ttorrent
ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java
TrackerRequestProcessor.serveError
private void serveError(Status status, HTTPTrackerErrorMessage error, RequestHandler requestHandler) throws IOException { """ Write a {@link HTTPTrackerErrorMessage} to the response with the given HTTP status code. @param status The HTTP status code to return. @param error The error reported by the tracker. """ requestHandler.serveResponse(status.getCode(), status.getDescription(), error.getData()); }
java
private void serveError(Status status, HTTPTrackerErrorMessage error, RequestHandler requestHandler) throws IOException { requestHandler.serveResponse(status.getCode(), status.getDescription(), error.getData()); }
[ "private", "void", "serveError", "(", "Status", "status", ",", "HTTPTrackerErrorMessage", "error", ",", "RequestHandler", "requestHandler", ")", "throws", "IOException", "{", "requestHandler", ".", "serveResponse", "(", "status", ".", "getCode", "(", ")", ",", "status", ".", "getDescription", "(", ")", ",", "error", ".", "getData", "(", ")", ")", ";", "}" ]
Write a {@link HTTPTrackerErrorMessage} to the response with the given HTTP status code. @param status The HTTP status code to return. @param error The error reported by the tracker.
[ "Write", "a", "{", "@link", "HTTPTrackerErrorMessage", "}", "to", "the", "response", "with", "the", "given", "HTTP", "status", "code", "." ]
train
https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java#L290-L292
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java
PropertyListSerialization.serializeBoolean
private static void serializeBoolean(final Boolean val, final ContentHandler handler) throws SAXException { """ Serialize a Boolean as a true or false element. @param val boolean to serialize. @param handler destination of serialization events. @throws SAXException if exception during serialization. """ String tag = "false"; if (val.booleanValue()) { tag = "true"; } final AttributesImpl attributes = new AttributesImpl(); handler.startElement(null, tag, tag, attributes); handler.endElement(null, tag, tag); }
java
private static void serializeBoolean(final Boolean val, final ContentHandler handler) throws SAXException { String tag = "false"; if (val.booleanValue()) { tag = "true"; } final AttributesImpl attributes = new AttributesImpl(); handler.startElement(null, tag, tag, attributes); handler.endElement(null, tag, tag); }
[ "private", "static", "void", "serializeBoolean", "(", "final", "Boolean", "val", ",", "final", "ContentHandler", "handler", ")", "throws", "SAXException", "{", "String", "tag", "=", "\"false\"", ";", "if", "(", "val", ".", "booleanValue", "(", ")", ")", "{", "tag", "=", "\"true\"", ";", "}", "final", "AttributesImpl", "attributes", "=", "new", "AttributesImpl", "(", ")", ";", "handler", ".", "startElement", "(", "null", ",", "tag", ",", "tag", ",", "attributes", ")", ";", "handler", ".", "endElement", "(", "null", ",", "tag", ",", "tag", ")", ";", "}" ]
Serialize a Boolean as a true or false element. @param val boolean to serialize. @param handler destination of serialization events. @throws SAXException if exception during serialization.
[ "Serialize", "a", "Boolean", "as", "a", "true", "or", "false", "element", "." ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/apple/PropertyListSerialization.java#L91-L99
jOOQ/jOOR
jOOR-java-6/src/main/java/org/joor/Reflect.java
Reflect.as
@SuppressWarnings("unchecked") public <P> P as(final Class<P> proxyType) { """ Create a proxy for the wrapped object allowing to typesafely invoke methods on it using a custom interface @param proxyType The interface type that is implemented by the proxy @return A proxy for the wrapped object """ final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @Override @SuppressWarnings("null") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); // Actual method name matches always come first try { return on(type, object).call(name, args).get(); } // [#14] Emulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler); }
java
@SuppressWarnings("unchecked") public <P> P as(final Class<P> proxyType) { final boolean isMap = (object instanceof Map); final InvocationHandler handler = new InvocationHandler() { @Override @SuppressWarnings("null") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); // Actual method name matches always come first try { return on(type, object).call(name, args).get(); } // [#14] Emulate POJO behaviour on wrapped map objects catch (ReflectException e) { if (isMap) { Map<String, Object> map = (Map<String, Object>) object; int length = (args == null ? 0 : args.length); if (length == 0 && name.startsWith("get")) { return map.get(property(name.substring(3))); } else if (length == 0 && name.startsWith("is")) { return map.get(property(name.substring(2))); } else if (length == 1 && name.startsWith("set")) { map.put(property(name.substring(3)), args[0]); return null; } } throw e; } } }; return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[] { proxyType }, handler); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "P", ">", "P", "as", "(", "final", "Class", "<", "P", ">", "proxyType", ")", "{", "final", "boolean", "isMap", "=", "(", "object", "instanceof", "Map", ")", ";", "final", "InvocationHandler", "handler", "=", "new", "InvocationHandler", "(", ")", "{", "@", "Override", "@", "SuppressWarnings", "(", "\"null\"", ")", "public", "Object", "invoke", "(", "Object", "proxy", ",", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "String", "name", "=", "method", ".", "getName", "(", ")", ";", "// Actual method name matches always come first", "try", "{", "return", "on", "(", "type", ",", "object", ")", ".", "call", "(", "name", ",", "args", ")", ".", "get", "(", ")", ";", "}", "// [#14] Emulate POJO behaviour on wrapped map objects", "catch", "(", "ReflectException", "e", ")", "{", "if", "(", "isMap", ")", "{", "Map", "<", "String", ",", "Object", ">", "map", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "object", ";", "int", "length", "=", "(", "args", "==", "null", "?", "0", ":", "args", ".", "length", ")", ";", "if", "(", "length", "==", "0", "&&", "name", ".", "startsWith", "(", "\"get\"", ")", ")", "{", "return", "map", ".", "get", "(", "property", "(", "name", ".", "substring", "(", "3", ")", ")", ")", ";", "}", "else", "if", "(", "length", "==", "0", "&&", "name", ".", "startsWith", "(", "\"is\"", ")", ")", "{", "return", "map", ".", "get", "(", "property", "(", "name", ".", "substring", "(", "2", ")", ")", ")", ";", "}", "else", "if", "(", "length", "==", "1", "&&", "name", ".", "startsWith", "(", "\"set\"", ")", ")", "{", "map", ".", "put", "(", "property", "(", "name", ".", "substring", "(", "3", ")", ")", ",", "args", "[", "0", "]", ")", ";", "return", "null", ";", "}", "}", "throw", "e", ";", "}", "}", "}", ";", "return", "(", "P", ")", "Proxy", ".", "newProxyInstance", "(", "proxyType", ".", "getClassLoader", "(", ")", ",", "new", "Class", "[", "]", "{", "proxyType", "}", ",", "handler", ")", ";", "}" ]
Create a proxy for the wrapped object allowing to typesafely invoke methods on it using a custom interface @param proxyType The interface type that is implemented by the proxy @return A proxy for the wrapped object
[ "Create", "a", "proxy", "for", "the", "wrapped", "object", "allowing", "to", "typesafely", "invoke", "methods", "on", "it", "using", "a", "custom", "interface" ]
train
https://github.com/jOOQ/jOOR/blob/40b42be12ecc9939560ff86921bbc57c99a21b85/jOOR-java-6/src/main/java/org/joor/Reflect.java#L721-L783
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/CertificateOperations.java
CertificateOperations.getCertificate
public Certificate getCertificate(String thumbprintAlgorithm, String thumbprint) throws BatchErrorException, IOException { """ Gets the specified {@link Certificate}. @param thumbprintAlgorithm The algorithm used to derive the thumbprint parameter. This must be sha1. @param thumbprint The thumbprint of the certificate to get. @return A {@link Certificate} containing information about the specified certificate in the Azure Batch account. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. """ return getCertificate(thumbprintAlgorithm, thumbprint, null, null); }
java
public Certificate getCertificate(String thumbprintAlgorithm, String thumbprint) throws BatchErrorException, IOException { return getCertificate(thumbprintAlgorithm, thumbprint, null, null); }
[ "public", "Certificate", "getCertificate", "(", "String", "thumbprintAlgorithm", ",", "String", "thumbprint", ")", "throws", "BatchErrorException", ",", "IOException", "{", "return", "getCertificate", "(", "thumbprintAlgorithm", ",", "thumbprint", ",", "null", ",", "null", ")", ";", "}" ]
Gets the specified {@link Certificate}. @param thumbprintAlgorithm The algorithm used to derive the thumbprint parameter. This must be sha1. @param thumbprint The thumbprint of the certificate to get. @return A {@link Certificate} containing information about the specified certificate in the Azure Batch account. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Gets", "the", "specified", "{", "@link", "Certificate", "}", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/CertificateOperations.java#L244-L246
apache/flink
flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java
Configuration.writeXml
public void writeXml(String propertyName, Writer out) throws IOException, IllegalArgumentException { """ Write out the non-default properties in this configuration to the given {@link Writer}. <li> When property name is not empty and the property exists in the configuration, this method writes the property and its attributes to the {@link Writer}. </li> <p> <li> When property name is null or empty, this method writes all the configuration properties and their attributes to the {@link Writer}. </li> <p> <li> When property name is not empty but the property doesn't exist in the configuration, this method throws an {@link IllegalArgumentException}. </li> <p> @param out the writer to write to. """ Document doc = asXmlDocument(propertyName); try { DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); // Important to not hold Configuration log while writing result, since // 'out' may be an HDFS stream which needs to lock this configuration // from another thread. transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } }
java
public void writeXml(String propertyName, Writer out) throws IOException, IllegalArgumentException { Document doc = asXmlDocument(propertyName); try { DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); // Important to not hold Configuration log while writing result, since // 'out' may be an HDFS stream which needs to lock this configuration // from another thread. transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } }
[ "public", "void", "writeXml", "(", "String", "propertyName", ",", "Writer", "out", ")", "throws", "IOException", ",", "IllegalArgumentException", "{", "Document", "doc", "=", "asXmlDocument", "(", "propertyName", ")", ";", "try", "{", "DOMSource", "source", "=", "new", "DOMSource", "(", "doc", ")", ";", "StreamResult", "result", "=", "new", "StreamResult", "(", "out", ")", ";", "TransformerFactory", "transFactory", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "transformer", "=", "transFactory", ".", "newTransformer", "(", ")", ";", "// Important to not hold Configuration log while writing result, since", "// 'out' may be an HDFS stream which needs to lock this configuration", "// from another thread.", "transformer", ".", "transform", "(", "source", ",", "result", ")", ";", "}", "catch", "(", "TransformerException", "te", ")", "{", "throw", "new", "IOException", "(", "te", ")", ";", "}", "}" ]
Write out the non-default properties in this configuration to the given {@link Writer}. <li> When property name is not empty and the property exists in the configuration, this method writes the property and its attributes to the {@link Writer}. </li> <p> <li> When property name is null or empty, this method writes all the configuration properties and their attributes to the {@link Writer}. </li> <p> <li> When property name is not empty but the property doesn't exist in the configuration, this method throws an {@link IllegalArgumentException}. </li> <p> @param out the writer to write to.
[ "Write", "out", "the", "non", "-", "default", "properties", "in", "this", "configuration", "to", "the", "given", "{", "@link", "Writer", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-fs-hadoop-shaded/src/main/java/org/apache/hadoop/conf/Configuration.java#L3124-L3141
morimekta/utils
io-util/src/main/java/net/morimekta/util/io/IOUtils.java
IOUtils.skipUntil
public static boolean skipUntil(InputStream in, byte separator) throws IOException { """ Skip all bytes in stream until (and including) given byte is found. @param in Input stream to read from. @param separator Byte to skip until. @return True iff the separator was encountered. @throws IOException if unable to read from stream. """ int r; while((r = in.read()) >= 0) { if(((byte) r) == separator) { return true; } } return false; }
java
public static boolean skipUntil(InputStream in, byte separator) throws IOException { int r; while((r = in.read()) >= 0) { if(((byte) r) == separator) { return true; } } return false; }
[ "public", "static", "boolean", "skipUntil", "(", "InputStream", "in", ",", "byte", "separator", ")", "throws", "IOException", "{", "int", "r", ";", "while", "(", "(", "r", "=", "in", ".", "read", "(", ")", ")", ">=", "0", ")", "{", "if", "(", "(", "(", "byte", ")", "r", ")", "==", "separator", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Skip all bytes in stream until (and including) given byte is found. @param in Input stream to read from. @param separator Byte to skip until. @return True iff the separator was encountered. @throws IOException if unable to read from stream.
[ "Skip", "all", "bytes", "in", "stream", "until", "(", "and", "including", ")", "given", "byte", "is", "found", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/io/IOUtils.java#L101-L107
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/BaseJsonBo.java
BaseJsonBo.getSubAttrAsDate
public Date getSubAttrAsDate(String attrName, String dPath, String dateTimeFormat) { """ Get a sub-attribute as a date using d-path. If sub-attr's value is a string, parse it as a {@link Date} using the specified date-time format. @param attrName @param dPath @param dateTimeFormat @return """ Lock lock = lockForRead(); try { return JacksonUtils.getDate(getAttribute(attrName), dPath, dateTimeFormat); } finally { lock.unlock(); } }
java
public Date getSubAttrAsDate(String attrName, String dPath, String dateTimeFormat) { Lock lock = lockForRead(); try { return JacksonUtils.getDate(getAttribute(attrName), dPath, dateTimeFormat); } finally { lock.unlock(); } }
[ "public", "Date", "getSubAttrAsDate", "(", "String", "attrName", ",", "String", "dPath", ",", "String", "dateTimeFormat", ")", "{", "Lock", "lock", "=", "lockForRead", "(", ")", ";", "try", "{", "return", "JacksonUtils", ".", "getDate", "(", "getAttribute", "(", "attrName", ")", ",", "dPath", ",", "dateTimeFormat", ")", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Get a sub-attribute as a date using d-path. If sub-attr's value is a string, parse it as a {@link Date} using the specified date-time format. @param attrName @param dPath @param dateTimeFormat @return
[ "Get", "a", "sub", "-", "attribute", "as", "a", "date", "using", "d", "-", "path", ".", "If", "sub", "-", "attr", "s", "value", "is", "a", "string", "parse", "it", "as", "a", "{", "@link", "Date", "}", "using", "the", "specified", "date", "-", "time", "format", "." ]
train
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseJsonBo.java#L185-L192
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/media/MediaClient.java
MediaClient.getThumbnailJob
public GetThumbnailJobResponse getThumbnailJob(GetThumbnailJobRequest request) { """ Get information of thumbnail job. @param request The request object containing all options for creating new water mark. @return The information of the thumbnail job. """ checkStringNotEmpty(request.getJobId(), "The parameter jobId should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, THUMBNAIL, request.getJobId()); return invokeHttpClient(internalRequest, GetThumbnailJobResponse.class); }
java
public GetThumbnailJobResponse getThumbnailJob(GetThumbnailJobRequest request) { checkStringNotEmpty(request.getJobId(), "The parameter jobId should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, THUMBNAIL, request.getJobId()); return invokeHttpClient(internalRequest, GetThumbnailJobResponse.class); }
[ "public", "GetThumbnailJobResponse", "getThumbnailJob", "(", "GetThumbnailJobRequest", "request", ")", "{", "checkStringNotEmpty", "(", "request", ".", "getJobId", "(", ")", ",", "\"The parameter jobId should NOT be null or empty string.\"", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest", "(", "HttpMethodName", ".", "GET", ",", "request", ",", "THUMBNAIL", ",", "request", ".", "getJobId", "(", ")", ")", ";", "return", "invokeHttpClient", "(", "internalRequest", ",", "GetThumbnailJobResponse", ".", "class", ")", ";", "}" ]
Get information of thumbnail job. @param request The request object containing all options for creating new water mark. @return The information of the thumbnail job.
[ "Get", "information", "of", "thumbnail", "job", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/media/MediaClient.java#L1287-L1293
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/ie/ner/CMMClassifier.java
CMMClassifier.loadClassifier
@SuppressWarnings("unchecked") @Override public void loadClassifier(ObjectInputStream ois, Properties props) throws ClassCastException, IOException, ClassNotFoundException { """ Load a classifier from the given Stream. <i>Implementation note: </i> This method <i>does not</i> close the Stream that it reads from. @param ois The ObjectInputStream to load the serialized classifier from @throws IOException If there are problems accessing the input stream @throws ClassCastException If there are problems interpreting the serialized data @throws ClassNotFoundException If there are problems interpreting the serialized data """ classifier = (LinearClassifier<String, String>) ois.readObject(); flags = (SeqClassifierFlags) ois.readObject(); featureFactory = (FeatureFactory) ois.readObject(); if (props != null) { flags.setProperties(props); } reinit(); classIndex = (Index<String>) ois.readObject(); answerArrays = (Set<List<String>>) ois.readObject(); knownLCWords = (Set<String>) ois.readObject(); }
java
@SuppressWarnings("unchecked") @Override public void loadClassifier(ObjectInputStream ois, Properties props) throws ClassCastException, IOException, ClassNotFoundException { classifier = (LinearClassifier<String, String>) ois.readObject(); flags = (SeqClassifierFlags) ois.readObject(); featureFactory = (FeatureFactory) ois.readObject(); if (props != null) { flags.setProperties(props); } reinit(); classIndex = (Index<String>) ois.readObject(); answerArrays = (Set<List<String>>) ois.readObject(); knownLCWords = (Set<String>) ois.readObject(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "void", "loadClassifier", "(", "ObjectInputStream", "ois", ",", "Properties", "props", ")", "throws", "ClassCastException", ",", "IOException", ",", "ClassNotFoundException", "{", "classifier", "=", "(", "LinearClassifier", "<", "String", ",", "String", ">", ")", "ois", ".", "readObject", "(", ")", ";", "flags", "=", "(", "SeqClassifierFlags", ")", "ois", ".", "readObject", "(", ")", ";", "featureFactory", "=", "(", "FeatureFactory", ")", "ois", ".", "readObject", "(", ")", ";", "if", "(", "props", "!=", "null", ")", "{", "flags", ".", "setProperties", "(", "props", ")", ";", "}", "reinit", "(", ")", ";", "classIndex", "=", "(", "Index", "<", "String", ">", ")", "ois", ".", "readObject", "(", ")", ";", "answerArrays", "=", "(", "Set", "<", "List", "<", "String", ">", ">", ")", "ois", ".", "readObject", "(", ")", ";", "knownLCWords", "=", "(", "Set", "<", "String", ">", ")", "ois", ".", "readObject", "(", ")", ";", "}" ]
Load a classifier from the given Stream. <i>Implementation note: </i> This method <i>does not</i> close the Stream that it reads from. @param ois The ObjectInputStream to load the serialized classifier from @throws IOException If there are problems accessing the input stream @throws ClassCastException If there are problems interpreting the serialized data @throws ClassNotFoundException If there are problems interpreting the serialized data
[ "Load", "a", "classifier", "from", "the", "given", "Stream", ".", "<i", ">", "Implementation", "note", ":", "<", "/", "i", ">", "This", "method", "<i", ">", "does", "not<", "/", "i", ">", "close", "the", "Stream", "that", "it", "reads", "from", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/ner/CMMClassifier.java#L1077-L1093
LearnLib/automatalib
util/src/main/java/net/automatalib/util/automata/transducers/MealyFilter.java
MealyFilter.pruneTransitionsWithOutput
public static <I, O> CompactMealy<I, O> pruneTransitionsWithOutput(MealyMachine<?, I, ?, O> in, Alphabet<I> inputs, Collection<? super O> outputs) { """ Returns a Mealy machine with all transitions removed that have one of the specified output values. The resulting Mealy machine will not contain any unreachable states. @param in the input Mealy machine @param inputs the input alphabet @param outputs the outputs to remove @return a Mealy machine with all transitions removed that have one of the specified outputs. """ return filterByOutput(in, inputs, o -> !outputs.contains(o)); }
java
public static <I, O> CompactMealy<I, O> pruneTransitionsWithOutput(MealyMachine<?, I, ?, O> in, Alphabet<I> inputs, Collection<? super O> outputs) { return filterByOutput(in, inputs, o -> !outputs.contains(o)); }
[ "public", "static", "<", "I", ",", "O", ">", "CompactMealy", "<", "I", ",", "O", ">", "pruneTransitionsWithOutput", "(", "MealyMachine", "<", "?", ",", "I", ",", "?", ",", "O", ">", "in", ",", "Alphabet", "<", "I", ">", "inputs", ",", "Collection", "<", "?", "super", "O", ">", "outputs", ")", "{", "return", "filterByOutput", "(", "in", ",", "inputs", ",", "o", "->", "!", "outputs", ".", "contains", "(", "o", ")", ")", ";", "}" ]
Returns a Mealy machine with all transitions removed that have one of the specified output values. The resulting Mealy machine will not contain any unreachable states. @param in the input Mealy machine @param inputs the input alphabet @param outputs the outputs to remove @return a Mealy machine with all transitions removed that have one of the specified outputs.
[ "Returns", "a", "Mealy", "machine", "with", "all", "transitions", "removed", "that", "have", "one", "of", "the", "specified", "output", "values", ".", "The", "resulting", "Mealy", "machine", "will", "not", "contain", "any", "unreachable", "states", "." ]
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/automata/transducers/MealyFilter.java#L79-L83
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/StereoDisparityWtoNaiveFive.java
StereoDisparityWtoNaiveFive.processPixel
private void processPixel( int c_x , int c_y , int maxDisparity ) { """ Computes fit score for each possible disparity @param c_x Center of region on left image. x-axis @param c_y Center of region on left image. y-axis @param maxDisparity Max allowed disparity """ for( int i = minDisparity; i < maxDisparity; i++ ) { score[i] = computeScore( c_x , c_x-i,c_y); } }
java
private void processPixel( int c_x , int c_y , int maxDisparity ) { for( int i = minDisparity; i < maxDisparity; i++ ) { score[i] = computeScore( c_x , c_x-i,c_y); } }
[ "private", "void", "processPixel", "(", "int", "c_x", ",", "int", "c_y", ",", "int", "maxDisparity", ")", "{", "for", "(", "int", "i", "=", "minDisparity", ";", "i", "<", "maxDisparity", ";", "i", "++", ")", "{", "score", "[", "i", "]", "=", "computeScore", "(", "c_x", ",", "c_x", "-", "i", ",", "c_y", ")", ";", "}", "}" ]
Computes fit score for each possible disparity @param c_x Center of region on left image. x-axis @param c_y Center of region on left image. y-axis @param maxDisparity Max allowed disparity
[ "Computes", "fit", "score", "for", "each", "possible", "disparity" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/StereoDisparityWtoNaiveFive.java#L105-L110
wildfly/wildfly-maven-plugin
core/src/main/java/org/wildfly/plugin/core/DeploymentOperations.java
DeploymentOperations.addDeployOperationStep
static void addDeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) { """ Adds the deploy operation as a step to the composite operation. @param builder the builder to add the step to @param deployment the deployment to deploy """ final String name = deployment.getName(); final Set<String> serverGroups = deployment.getServerGroups(); // If the server groups are empty this is a standalone deployment if (serverGroups.isEmpty()) { final ModelNode address = createAddress(DEPLOYMENT, name); builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address)); } else { for (String serverGroup : serverGroups) { final ModelNode address = createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, name); builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address)); } } }
java
static void addDeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) { final String name = deployment.getName(); final Set<String> serverGroups = deployment.getServerGroups(); // If the server groups are empty this is a standalone deployment if (serverGroups.isEmpty()) { final ModelNode address = createAddress(DEPLOYMENT, name); builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address)); } else { for (String serverGroup : serverGroups) { final ModelNode address = createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, name); builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address)); } } }
[ "static", "void", "addDeployOperationStep", "(", "final", "CompositeOperationBuilder", "builder", ",", "final", "DeploymentDescription", "deployment", ")", "{", "final", "String", "name", "=", "deployment", ".", "getName", "(", ")", ";", "final", "Set", "<", "String", ">", "serverGroups", "=", "deployment", ".", "getServerGroups", "(", ")", ";", "// If the server groups are empty this is a standalone deployment", "if", "(", "serverGroups", ".", "isEmpty", "(", ")", ")", "{", "final", "ModelNode", "address", "=", "createAddress", "(", "DEPLOYMENT", ",", "name", ")", ";", "builder", ".", "addStep", "(", "createOperation", "(", "DEPLOYMENT_DEPLOY_OPERATION", ",", "address", ")", ")", ";", "}", "else", "{", "for", "(", "String", "serverGroup", ":", "serverGroups", ")", "{", "final", "ModelNode", "address", "=", "createAddress", "(", "SERVER_GROUP", ",", "serverGroup", ",", "DEPLOYMENT", ",", "name", ")", ";", "builder", ".", "addStep", "(", "createOperation", "(", "DEPLOYMENT_DEPLOY_OPERATION", ",", "address", ")", ")", ";", "}", "}", "}" ]
Adds the deploy operation as a step to the composite operation. @param builder the builder to add the step to @param deployment the deployment to deploy
[ "Adds", "the", "deploy", "operation", "as", "a", "step", "to", "the", "composite", "operation", "." ]
train
https://github.com/wildfly/wildfly-maven-plugin/blob/c0e2d7ee28e511092561801959eae253b2b56def/core/src/main/java/org/wildfly/plugin/core/DeploymentOperations.java#L336-L350
sawano/java-commons
src/main/java/se/sawano/java/commons/lang/validate/Validate.java
Validate.validIndex
public static <T extends CharSequence> T validIndex(final T chars, final int index) { """ <p>Validates that the index is within the bounds of the argument character sequence; otherwise throwing an exception.</p> <pre>Validate.validIndex(myStr, 2);</pre> <p>If the character sequence is {@code null}, then the message of the exception is &quot;The validated object is null&quot;.</p><p>If the index is invalid, then the message of the exception is &quot;The validated character sequence index is invalid: &quot; followed by the index.</p> @param <T> the character sequence type @param chars the character sequence to check, validated not null by this method @param index the index to check @return the validated character sequence (never {@code null} for method chaining) @throws NullPointerValidationException if the character sequence is {@code null} @throws IndexOutOfBoundsException if the index is invalid @see #validIndex(CharSequence, int, String, Object...) """ return INSTANCE.validIndex(chars, index); }
java
public static <T extends CharSequence> T validIndex(final T chars, final int index) { return INSTANCE.validIndex(chars, index); }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "validIndex", "(", "final", "T", "chars", ",", "final", "int", "index", ")", "{", "return", "INSTANCE", ".", "validIndex", "(", "chars", ",", "index", ")", ";", "}" ]
<p>Validates that the index is within the bounds of the argument character sequence; otherwise throwing an exception.</p> <pre>Validate.validIndex(myStr, 2);</pre> <p>If the character sequence is {@code null}, then the message of the exception is &quot;The validated object is null&quot;.</p><p>If the index is invalid, then the message of the exception is &quot;The validated character sequence index is invalid: &quot; followed by the index.</p> @param <T> the character sequence type @param chars the character sequence to check, validated not null by this method @param index the index to check @return the validated character sequence (never {@code null} for method chaining) @throws NullPointerValidationException if the character sequence is {@code null} @throws IndexOutOfBoundsException if the index is invalid @see #validIndex(CharSequence, int, String, Object...)
[ "<p", ">", "Validates", "that", "the", "index", "is", "within", "the", "bounds", "of", "the", "argument", "character", "sequence", ";", "otherwise", "throwing", "an", "exception", ".", "<", "/", "p", ">", "<pre", ">", "Validate", ".", "validIndex", "(", "myStr", "2", ")", ";", "<", "/", "pre", ">", "<p", ">", "If", "the", "character", "sequence", "is", "{", "@code", "null", "}", "then", "the", "message", "of", "the", "exception", "is", "&quot", ";", "The", "validated", "object", "is", "null&quot", ";", ".", "<", "/", "p", ">", "<p", ">", "If", "the", "index", "is", "invalid", "then", "the", "message", "of", "the", "exception", "is", "&quot", ";", "The", "validated", "character", "sequence", "index", "is", "invalid", ":", "&quot", ";", "followed", "by", "the", "index", ".", "<", "/", "p", ">" ]
train
https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L1312-L1314
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java
ComputerVisionImpl.tagImageInStream
public TagResult tagImageInStream(byte[] image, TagImageInStreamOptionalParameter tagImageInStreamOptionalParameter) { """ This operation generates a list of words, or tags, that are relevant to the content of the supplied image. The Computer Vision API can return tags based on objects, living beings, scenery or actions found in images. Unlike categories, tags are not organized according to a hierarchical classification system, but correspond to image content. Tags may contain hints to avoid ambiguity or provide context, for example the tag 'cello' may be accompanied by the hint 'musical instrument'. All tags are in English. @param image An image stream. @param tagImageInStreamOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ComputerVisionErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the TagResult object if successful. """ return tagImageInStreamWithServiceResponseAsync(image, tagImageInStreamOptionalParameter).toBlocking().single().body(); }
java
public TagResult tagImageInStream(byte[] image, TagImageInStreamOptionalParameter tagImageInStreamOptionalParameter) { return tagImageInStreamWithServiceResponseAsync(image, tagImageInStreamOptionalParameter).toBlocking().single().body(); }
[ "public", "TagResult", "tagImageInStream", "(", "byte", "[", "]", "image", ",", "TagImageInStreamOptionalParameter", "tagImageInStreamOptionalParameter", ")", "{", "return", "tagImageInStreamWithServiceResponseAsync", "(", "image", ",", "tagImageInStreamOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
This operation generates a list of words, or tags, that are relevant to the content of the supplied image. The Computer Vision API can return tags based on objects, living beings, scenery or actions found in images. Unlike categories, tags are not organized according to a hierarchical classification system, but correspond to image content. Tags may contain hints to avoid ambiguity or provide context, for example the tag 'cello' may be accompanied by the hint 'musical instrument'. All tags are in English. @param image An image stream. @param tagImageInStreamOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ComputerVisionErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the TagResult object if successful.
[ "This", "operation", "generates", "a", "list", "of", "words", "or", "tags", "that", "are", "relevant", "to", "the", "content", "of", "the", "supplied", "image", ".", "The", "Computer", "Vision", "API", "can", "return", "tags", "based", "on", "objects", "living", "beings", "scenery", "or", "actions", "found", "in", "images", ".", "Unlike", "categories", "tags", "are", "not", "organized", "according", "to", "a", "hierarchical", "classification", "system", "but", "correspond", "to", "image", "content", ".", "Tags", "may", "contain", "hints", "to", "avoid", "ambiguity", "or", "provide", "context", "for", "example", "the", "tag", "cello", "may", "be", "accompanied", "by", "the", "hint", "musical", "instrument", ".", "All", "tags", "are", "in", "English", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L426-L428
Azure/azure-sdk-for-java
signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java
SignalRsInner.regenerateKeyAsync
public Observable<SignalRKeysInner> regenerateKeyAsync(String resourceGroupName, String resourceName) { """ Regenerate SignalR service access key. PrimaryKey and SecondaryKey cannot be regenerated at the same time. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param resourceName The name of the SignalR resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return regenerateKeyWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<SignalRKeysInner>, SignalRKeysInner>() { @Override public SignalRKeysInner call(ServiceResponse<SignalRKeysInner> response) { return response.body(); } }); }
java
public Observable<SignalRKeysInner> regenerateKeyAsync(String resourceGroupName, String resourceName) { return regenerateKeyWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<SignalRKeysInner>, SignalRKeysInner>() { @Override public SignalRKeysInner call(ServiceResponse<SignalRKeysInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "SignalRKeysInner", ">", "regenerateKeyAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "regenerateKeyWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "SignalRKeysInner", ">", ",", "SignalRKeysInner", ">", "(", ")", "{", "@", "Override", "public", "SignalRKeysInner", "call", "(", "ServiceResponse", "<", "SignalRKeysInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Regenerate SignalR service access key. PrimaryKey and SecondaryKey cannot be regenerated at the same time. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param resourceName The name of the SignalR resource. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Regenerate", "SignalR", "service", "access", "key", ".", "PrimaryKey", "and", "SecondaryKey", "cannot", "be", "regenerated", "at", "the", "same", "time", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/signalr/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/signalr/v2018_03_01_preview/implementation/SignalRsInner.java#L621-L628
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/error/SingleError.java
SingleError.equalsLinkedException
@OverrideOnDemand protected boolean equalsLinkedException (@Nullable final Throwable t1, @Nullable final Throwable t2) { """ Overridable implementation of Throwable for the Linked exception field. This can be overridden to implement a different algorithm. This is customizable because there is no default way of comparing Exceptions in Java. If you override this method you must also override {@link #hashCodeLinkedException(HashCodeGenerator, Throwable)}! @param t1 First Throwable. May be <code>null</code>. @param t2 Second Throwable. May be <code>null</code>. @return <code>true</code> if they are equals (or both null) """ if (EqualsHelper.identityEqual (t1, t2)) return true; if (t1 == null || t2 == null) return false; return t1.getClass ().equals (t2.getClass ()) && EqualsHelper.equals (t1.getMessage (), t2.getMessage ()); }
java
@OverrideOnDemand protected boolean equalsLinkedException (@Nullable final Throwable t1, @Nullable final Throwable t2) { if (EqualsHelper.identityEqual (t1, t2)) return true; if (t1 == null || t2 == null) return false; return t1.getClass ().equals (t2.getClass ()) && EqualsHelper.equals (t1.getMessage (), t2.getMessage ()); }
[ "@", "OverrideOnDemand", "protected", "boolean", "equalsLinkedException", "(", "@", "Nullable", "final", "Throwable", "t1", ",", "@", "Nullable", "final", "Throwable", "t2", ")", "{", "if", "(", "EqualsHelper", ".", "identityEqual", "(", "t1", ",", "t2", ")", ")", "return", "true", ";", "if", "(", "t1", "==", "null", "||", "t2", "==", "null", ")", "return", "false", ";", "return", "t1", ".", "getClass", "(", ")", ".", "equals", "(", "t2", ".", "getClass", "(", ")", ")", "&&", "EqualsHelper", ".", "equals", "(", "t1", ".", "getMessage", "(", ")", ",", "t2", ".", "getMessage", "(", ")", ")", ";", "}" ]
Overridable implementation of Throwable for the Linked exception field. This can be overridden to implement a different algorithm. This is customizable because there is no default way of comparing Exceptions in Java. If you override this method you must also override {@link #hashCodeLinkedException(HashCodeGenerator, Throwable)}! @param t1 First Throwable. May be <code>null</code>. @param t2 Second Throwable. May be <code>null</code>. @return <code>true</code> if they are equals (or both null)
[ "Overridable", "implementation", "of", "Throwable", "for", "the", "Linked", "exception", "field", ".", "This", "can", "be", "overridden", "to", "implement", "a", "different", "algorithm", ".", "This", "is", "customizable", "because", "there", "is", "no", "default", "way", "of", "comparing", "Exceptions", "in", "Java", ".", "If", "you", "override", "this", "method", "you", "must", "also", "override", "{", "@link", "#hashCodeLinkedException", "(", "HashCodeGenerator", "Throwable", ")", "}", "!" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/error/SingleError.java#L126-L134
shrinkwrap/descriptors
metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/PackageInfo.java
PackageInfo.deleteExistingPackageInfo
public static void deleteExistingPackageInfo(final String destDirectory, final boolean verbose) { """ Deletes package.html or package-info.java from the given directory. @param destDirectory @param verbose """ final File htmlFile = new File(destDirectory + File.separatorChar + PACKAGE_HTML_NAME); final File javaFile = new File(destDirectory + File.separatorChar + PACKAGE_JAVA_NAME); final Boolean isHtmlDeleted = FileUtils.deleteQuietly(htmlFile); final Boolean isJavaDeleted = FileUtils.deleteQuietly(javaFile); if (verbose) { log.info(String.format("File %s deleted: %s", htmlFile.getAbsolutePath(), isHtmlDeleted.toString())); log.info(String.format("File %s deleted: %s", javaFile.getAbsolutePath(), isJavaDeleted.toString())); } }
java
public static void deleteExistingPackageInfo(final String destDirectory, final boolean verbose) { final File htmlFile = new File(destDirectory + File.separatorChar + PACKAGE_HTML_NAME); final File javaFile = new File(destDirectory + File.separatorChar + PACKAGE_JAVA_NAME); final Boolean isHtmlDeleted = FileUtils.deleteQuietly(htmlFile); final Boolean isJavaDeleted = FileUtils.deleteQuietly(javaFile); if (verbose) { log.info(String.format("File %s deleted: %s", htmlFile.getAbsolutePath(), isHtmlDeleted.toString())); log.info(String.format("File %s deleted: %s", javaFile.getAbsolutePath(), isJavaDeleted.toString())); } }
[ "public", "static", "void", "deleteExistingPackageInfo", "(", "final", "String", "destDirectory", ",", "final", "boolean", "verbose", ")", "{", "final", "File", "htmlFile", "=", "new", "File", "(", "destDirectory", "+", "File", ".", "separatorChar", "+", "PACKAGE_HTML_NAME", ")", ";", "final", "File", "javaFile", "=", "new", "File", "(", "destDirectory", "+", "File", ".", "separatorChar", "+", "PACKAGE_JAVA_NAME", ")", ";", "final", "Boolean", "isHtmlDeleted", "=", "FileUtils", ".", "deleteQuietly", "(", "htmlFile", ")", ";", "final", "Boolean", "isJavaDeleted", "=", "FileUtils", ".", "deleteQuietly", "(", "javaFile", ")", ";", "if", "(", "verbose", ")", "{", "log", ".", "info", "(", "String", ".", "format", "(", "\"File %s deleted: %s\"", ",", "htmlFile", ".", "getAbsolutePath", "(", ")", ",", "isHtmlDeleted", ".", "toString", "(", ")", ")", ")", ";", "log", ".", "info", "(", "String", ".", "format", "(", "\"File %s deleted: %s\"", ",", "javaFile", ".", "getAbsolutePath", "(", ")", ",", "isJavaDeleted", ".", "toString", "(", ")", ")", ")", ";", "}", "}" ]
Deletes package.html or package-info.java from the given directory. @param destDirectory @param verbose
[ "Deletes", "package", ".", "html", "or", "package", "-", "info", ".", "java", "from", "the", "given", "directory", "." ]
train
https://github.com/shrinkwrap/descriptors/blob/023ba080e6396b9f4dd8275dc4e5c0ebb6b5e6ba/metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/PackageInfo.java#L91-L101
biojava/biojava
biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java
WorkSheet.addCell
public void addCell(String row, String col, String value) throws Exception { """ Add data to a cell @param row @param col @param value @throws Exception """ HeaderInfo rowIndex = rowLookup.get(row); HeaderInfo colIndex = columnLookup.get(col); if (rowIndex == null) { throw new Exception("Row " + row + " not found in worksheet"); } if (colIndex == null) { throw new Exception("Column " + col + " not found in worksheet"); } data[rowIndex.getIndex()][colIndex.getIndex()] = new CompactCharSequence(value); }
java
public void addCell(String row, String col, String value) throws Exception { HeaderInfo rowIndex = rowLookup.get(row); HeaderInfo colIndex = columnLookup.get(col); if (rowIndex == null) { throw new Exception("Row " + row + " not found in worksheet"); } if (colIndex == null) { throw new Exception("Column " + col + " not found in worksheet"); } data[rowIndex.getIndex()][colIndex.getIndex()] = new CompactCharSequence(value); }
[ "public", "void", "addCell", "(", "String", "row", ",", "String", "col", ",", "String", "value", ")", "throws", "Exception", "{", "HeaderInfo", "rowIndex", "=", "rowLookup", ".", "get", "(", "row", ")", ";", "HeaderInfo", "colIndex", "=", "columnLookup", ".", "get", "(", "col", ")", ";", "if", "(", "rowIndex", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Row \"", "+", "row", "+", "\" not found in worksheet\"", ")", ";", "}", "if", "(", "colIndex", "==", "null", ")", "{", "throw", "new", "Exception", "(", "\"Column \"", "+", "col", "+", "\" not found in worksheet\"", ")", ";", "}", "data", "[", "rowIndex", ".", "getIndex", "(", ")", "]", "[", "colIndex", ".", "getIndex", "(", ")", "]", "=", "new", "CompactCharSequence", "(", "value", ")", ";", "}" ]
Add data to a cell @param row @param col @param value @throws Exception
[ "Add", "data", "to", "a", "cell" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java#L754-L766
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java
AbstractTable.getTableVisibleColumns
protected List<TableColumn> getTableVisibleColumns() { """ Based on table state (max/min) columns to be shown are returned. @return List<TableColumn> list of visible columns """ final List<TableColumn> columnList = new ArrayList<>(); if (!isMaximized()) { columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.getMessage("header.name"), getColumnNameMinimizedSize())); return columnList; } columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.getMessage("header.name"), 0.2F)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_BY, i18n.getMessage("header.createdBy"), 0.1F)); columnList.add( new TableColumn(SPUILabelDefinitions.VAR_CREATED_DATE, i18n.getMessage("header.createdDate"), 0.1F)); columnList.add( new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.getMessage("header.modifiedBy"), 0.1F)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.getMessage("header.modifiedDate"), 0.1F)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.getMessage("header.description"), 0.2F)); setItemDescriptionGenerator((source, itemId, propertyId) -> { if (SPUILabelDefinitions.VAR_CREATED_BY.equals(propertyId)) { return getItem(itemId).getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY).getValue().toString(); } if (SPUILabelDefinitions.VAR_LAST_MODIFIED_BY.equals(propertyId)) { return getItem(itemId).getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY).getValue().toString(); } return null; }); return columnList; }
java
protected List<TableColumn> getTableVisibleColumns() { final List<TableColumn> columnList = new ArrayList<>(); if (!isMaximized()) { columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.getMessage("header.name"), getColumnNameMinimizedSize())); return columnList; } columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.getMessage("header.name"), 0.2F)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_BY, i18n.getMessage("header.createdBy"), 0.1F)); columnList.add( new TableColumn(SPUILabelDefinitions.VAR_CREATED_DATE, i18n.getMessage("header.createdDate"), 0.1F)); columnList.add( new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.getMessage("header.modifiedBy"), 0.1F)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.getMessage("header.modifiedDate"), 0.1F)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.getMessage("header.description"), 0.2F)); setItemDescriptionGenerator((source, itemId, propertyId) -> { if (SPUILabelDefinitions.VAR_CREATED_BY.equals(propertyId)) { return getItem(itemId).getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY).getValue().toString(); } if (SPUILabelDefinitions.VAR_LAST_MODIFIED_BY.equals(propertyId)) { return getItem(itemId).getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY).getValue().toString(); } return null; }); return columnList; }
[ "protected", "List", "<", "TableColumn", ">", "getTableVisibleColumns", "(", ")", "{", "final", "List", "<", "TableColumn", ">", "columnList", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "!", "isMaximized", "(", ")", ")", "{", "columnList", ".", "add", "(", "new", "TableColumn", "(", "SPUILabelDefinitions", ".", "VAR_NAME", ",", "i18n", ".", "getMessage", "(", "\"header.name\"", ")", ",", "getColumnNameMinimizedSize", "(", ")", ")", ")", ";", "return", "columnList", ";", "}", "columnList", ".", "add", "(", "new", "TableColumn", "(", "SPUILabelDefinitions", ".", "VAR_NAME", ",", "i18n", ".", "getMessage", "(", "\"header.name\"", ")", ",", "0.2F", ")", ")", ";", "columnList", ".", "add", "(", "new", "TableColumn", "(", "SPUILabelDefinitions", ".", "VAR_CREATED_BY", ",", "i18n", ".", "getMessage", "(", "\"header.createdBy\"", ")", ",", "0.1F", ")", ")", ";", "columnList", ".", "add", "(", "new", "TableColumn", "(", "SPUILabelDefinitions", ".", "VAR_CREATED_DATE", ",", "i18n", ".", "getMessage", "(", "\"header.createdDate\"", ")", ",", "0.1F", ")", ")", ";", "columnList", ".", "add", "(", "new", "TableColumn", "(", "SPUILabelDefinitions", ".", "VAR_LAST_MODIFIED_BY", ",", "i18n", ".", "getMessage", "(", "\"header.modifiedBy\"", ")", ",", "0.1F", ")", ")", ";", "columnList", ".", "add", "(", "new", "TableColumn", "(", "SPUILabelDefinitions", ".", "VAR_LAST_MODIFIED_DATE", ",", "i18n", ".", "getMessage", "(", "\"header.modifiedDate\"", ")", ",", "0.1F", ")", ")", ";", "columnList", ".", "add", "(", "new", "TableColumn", "(", "SPUILabelDefinitions", ".", "VAR_DESC", ",", "i18n", ".", "getMessage", "(", "\"header.description\"", ")", ",", "0.2F", ")", ")", ";", "setItemDescriptionGenerator", "(", "(", "source", ",", "itemId", ",", "propertyId", ")", "->", "{", "if", "(", "SPUILabelDefinitions", ".", "VAR_CREATED_BY", ".", "equals", "(", "propertyId", ")", ")", "{", "return", "getItem", "(", "itemId", ")", ".", "getItemProperty", "(", "SPUILabelDefinitions", ".", "VAR_CREATED_BY", ")", ".", "getValue", "(", ")", ".", "toString", "(", ")", ";", "}", "if", "(", "SPUILabelDefinitions", ".", "VAR_LAST_MODIFIED_BY", ".", "equals", "(", "propertyId", ")", ")", "{", "return", "getItem", "(", "itemId", ")", ".", "getItemProperty", "(", "SPUILabelDefinitions", ".", "VAR_LAST_MODIFIED_BY", ")", ".", "getValue", "(", ")", ".", "toString", "(", ")", ";", "}", "return", "null", ";", "}", ")", ";", "return", "columnList", ";", "}" ]
Based on table state (max/min) columns to be shown are returned. @return List<TableColumn> list of visible columns
[ "Based", "on", "table", "state", "(", "max", "/", "min", ")", "columns", "to", "be", "shown", "are", "returned", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java#L480-L506
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/LottieAnimationView.java
LottieAnimationView.updateBitmap
@Nullable public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) { """ Allows you to modify or clear a bitmap that was loaded for an image either automatically through {@link #setImageAssetsFolder(String)} or with an {@link ImageAssetDelegate}. @return the previous Bitmap or null. """ return lottieDrawable.updateBitmap(id, bitmap); }
java
@Nullable public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) { return lottieDrawable.updateBitmap(id, bitmap); }
[ "@", "Nullable", "public", "Bitmap", "updateBitmap", "(", "String", "id", ",", "@", "Nullable", "Bitmap", "bitmap", ")", "{", "return", "lottieDrawable", ".", "updateBitmap", "(", "id", ",", "bitmap", ")", ";", "}" ]
Allows you to modify or clear a bitmap that was loaded for an image either automatically through {@link #setImageAssetsFolder(String)} or with an {@link ImageAssetDelegate}. @return the previous Bitmap or null.
[ "Allows", "you", "to", "modify", "or", "clear", "a", "bitmap", "that", "was", "loaded", "for", "an", "image", "either", "automatically", "through", "{", "@link", "#setImageAssetsFolder", "(", "String", ")", "}", "or", "with", "an", "{", "@link", "ImageAssetDelegate", "}", "." ]
train
https://github.com/airbnb/lottie-android/blob/126dabdc9f586c87822f85fe1128cdad439d30fa/lottie/src/main/java/com/airbnb/lottie/LottieAnimationView.java#L660-L663
eFaps/eFaps-Kernel
src/main/java/org/efaps/update/schema/program/AbstractSourceImporter.java
AbstractSourceImporter.readCode
protected void readCode() throws InstallationException { """ Read the code from the file defined through {@link #url} with character set {@link #ENCODING}. @throws InstallationException if the source code could not read from URL @see #url @see #ENCODING """ try { final char[] buf = new char[1024]; final InputStream input = getUrl().openStream(); final Reader reader = new InputStreamReader(input, AbstractSourceImporter.ENCODING); int length; while ((length = reader.read(buf)) > 0) { this.code.append(buf, 0, length); } reader.close(); } catch (final IOException e) { throw new InstallationException("Could not read source code from url '" + this.url + "'.", e); } }
java
protected void readCode() throws InstallationException { try { final char[] buf = new char[1024]; final InputStream input = getUrl().openStream(); final Reader reader = new InputStreamReader(input, AbstractSourceImporter.ENCODING); int length; while ((length = reader.read(buf)) > 0) { this.code.append(buf, 0, length); } reader.close(); } catch (final IOException e) { throw new InstallationException("Could not read source code from url '" + this.url + "'.", e); } }
[ "protected", "void", "readCode", "(", ")", "throws", "InstallationException", "{", "try", "{", "final", "char", "[", "]", "buf", "=", "new", "char", "[", "1024", "]", ";", "final", "InputStream", "input", "=", "getUrl", "(", ")", ".", "openStream", "(", ")", ";", "final", "Reader", "reader", "=", "new", "InputStreamReader", "(", "input", ",", "AbstractSourceImporter", ".", "ENCODING", ")", ";", "int", "length", ";", "while", "(", "(", "length", "=", "reader", ".", "read", "(", "buf", ")", ")", ">", "0", ")", "{", "this", ".", "code", ".", "append", "(", "buf", ",", "0", ",", "length", ")", ";", "}", "reader", ".", "close", "(", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "throw", "new", "InstallationException", "(", "\"Could not read source code from url '\"", "+", "this", ".", "url", "+", "\"'.\"", ",", "e", ")", ";", "}", "}" ]
Read the code from the file defined through {@link #url} with character set {@link #ENCODING}. @throws InstallationException if the source code could not read from URL @see #url @see #ENCODING
[ "Read", "the", "code", "from", "the", "file", "defined", "through", "{", "@link", "#url", "}", "with", "character", "set", "{", "@link", "#ENCODING", "}", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/update/schema/program/AbstractSourceImporter.java#L119-L136
restfb/restfb
src/main/java/com/restfb/util/ReflectionUtils.java
ReflectionUtils.getAccessors
public static List<Method> getAccessors(Class<?> clazz) { """ Gets all accessor methods for the given {@code clazz}. @param clazz The class for which accessors are extracted. @return All accessor methods for the given {@code clazz}. """ if (clazz == null) { throw new IllegalArgumentException("The 'clazz' parameter cannot be null."); } List<Method> methods = new ArrayList<>(); for (Method method : clazz.getMethods()) { String methodName = method.getName(); if (!"getClass".equals(methodName) && !"hashCode".equals(methodName) && method.getReturnType() != null && !Void.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0 && ((methodName.startsWith("get") && methodName.length() > 3) || (methodName.startsWith("is") && methodName.length() > 2) || (methodName.startsWith("has") && methodName.length() > 3))) { methods.add(method); } } // Order the methods alphabetically by name sort(methods, new Comparator<Method>() { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(Method method1, Method method2) { return method1.getName().compareTo(method2.getName()); } }); return unmodifiableList(methods); }
java
public static List<Method> getAccessors(Class<?> clazz) { if (clazz == null) { throw new IllegalArgumentException("The 'clazz' parameter cannot be null."); } List<Method> methods = new ArrayList<>(); for (Method method : clazz.getMethods()) { String methodName = method.getName(); if (!"getClass".equals(methodName) && !"hashCode".equals(methodName) && method.getReturnType() != null && !Void.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0 && ((methodName.startsWith("get") && methodName.length() > 3) || (methodName.startsWith("is") && methodName.length() > 2) || (methodName.startsWith("has") && methodName.length() > 3))) { methods.add(method); } } // Order the methods alphabetically by name sort(methods, new Comparator<Method>() { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(Method method1, Method method2) { return method1.getName().compareTo(method2.getName()); } }); return unmodifiableList(methods); }
[ "public", "static", "List", "<", "Method", ">", "getAccessors", "(", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "clazz", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The 'clazz' parameter cannot be null.\"", ")", ";", "}", "List", "<", "Method", ">", "methods", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Method", "method", ":", "clazz", ".", "getMethods", "(", ")", ")", "{", "String", "methodName", "=", "method", ".", "getName", "(", ")", ";", "if", "(", "!", "\"getClass\"", ".", "equals", "(", "methodName", ")", "&&", "!", "\"hashCode\"", ".", "equals", "(", "methodName", ")", "&&", "method", ".", "getReturnType", "(", ")", "!=", "null", "&&", "!", "Void", ".", "class", ".", "equals", "(", "method", ".", "getReturnType", "(", ")", ")", "&&", "method", ".", "getParameterTypes", "(", ")", ".", "length", "==", "0", "&&", "(", "(", "methodName", ".", "startsWith", "(", "\"get\"", ")", "&&", "methodName", ".", "length", "(", ")", ">", "3", ")", "||", "(", "methodName", ".", "startsWith", "(", "\"is\"", ")", "&&", "methodName", ".", "length", "(", ")", ">", "2", ")", "||", "(", "methodName", ".", "startsWith", "(", "\"has\"", ")", "&&", "methodName", ".", "length", "(", ")", ">", "3", ")", ")", ")", "{", "methods", ".", "add", "(", "method", ")", ";", "}", "}", "// Order the methods alphabetically by name", "sort", "(", "methods", ",", "new", "Comparator", "<", "Method", ">", "(", ")", "{", "/**\n * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)\n */", "@", "Override", "public", "int", "compare", "(", "Method", "method1", ",", "Method", "method2", ")", "{", "return", "method1", ".", "getName", "(", ")", ".", "compareTo", "(", "method2", ".", "getName", "(", ")", ")", ";", "}", "}", ")", ";", "return", "unmodifiableList", "(", "methods", ")", ";", "}" ]
Gets all accessor methods for the given {@code clazz}. @param clazz The class for which accessors are extracted. @return All accessor methods for the given {@code clazz}.
[ "Gets", "all", "accessor", "methods", "for", "the", "given", "{", "@code", "clazz", "}", "." ]
train
https://github.com/restfb/restfb/blob/fb77ba5486d1339e7deb81b9830670fa209b1047/src/main/java/com/restfb/util/ReflectionUtils.java#L217-L246
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java
ComputationGraph.scoreExamples
public INDArray scoreExamples(DataSet data, boolean addRegularizationTerms) { """ Calculate the score for each example in a DataSet individually. Unlike {@link #score(DataSet)} and {@link #score(DataSet, boolean)} this method does not average/sum over examples. This method allows for examples to be scored individually (at test time only), which may be useful for example for autoencoder architectures and the like.<br> Each row of the output (assuming addRegularizationTerms == true) is equivalent to calling score(DataSet) with a single example. @param data The data to score @param addRegularizationTerms If true: add l1/l2 regularization terms (if any) to the score. If false: don't add regularization terms @return An INDArray (column vector) of size input.numRows(); the ith entry is the score (loss value) of the ith example """ if (numInputArrays != 1 || numOutputArrays != 1) throw new UnsupportedOperationException("Cannot score ComputationGraph network with " + " DataSet: network does not have 1 input and 1 output arrays"); return scoreExamples(ComputationGraphUtil.toMultiDataSet(data), addRegularizationTerms); }
java
public INDArray scoreExamples(DataSet data, boolean addRegularizationTerms) { if (numInputArrays != 1 || numOutputArrays != 1) throw new UnsupportedOperationException("Cannot score ComputationGraph network with " + " DataSet: network does not have 1 input and 1 output arrays"); return scoreExamples(ComputationGraphUtil.toMultiDataSet(data), addRegularizationTerms); }
[ "public", "INDArray", "scoreExamples", "(", "DataSet", "data", ",", "boolean", "addRegularizationTerms", ")", "{", "if", "(", "numInputArrays", "!=", "1", "||", "numOutputArrays", "!=", "1", ")", "throw", "new", "UnsupportedOperationException", "(", "\"Cannot score ComputationGraph network with \"", "+", "\" DataSet: network does not have 1 input and 1 output arrays\"", ")", ";", "return", "scoreExamples", "(", "ComputationGraphUtil", ".", "toMultiDataSet", "(", "data", ")", ",", "addRegularizationTerms", ")", ";", "}" ]
Calculate the score for each example in a DataSet individually. Unlike {@link #score(DataSet)} and {@link #score(DataSet, boolean)} this method does not average/sum over examples. This method allows for examples to be scored individually (at test time only), which may be useful for example for autoencoder architectures and the like.<br> Each row of the output (assuming addRegularizationTerms == true) is equivalent to calling score(DataSet) with a single example. @param data The data to score @param addRegularizationTerms If true: add l1/l2 regularization terms (if any) to the score. If false: don't add regularization terms @return An INDArray (column vector) of size input.numRows(); the ith entry is the score (loss value) of the ith example
[ "Calculate", "the", "score", "for", "each", "example", "in", "a", "DataSet", "individually", ".", "Unlike", "{", "@link", "#score", "(", "DataSet", ")", "}", "and", "{", "@link", "#score", "(", "DataSet", "boolean", ")", "}", "this", "method", "does", "not", "average", "/", "sum", "over", "examples", ".", "This", "method", "allows", "for", "examples", "to", "be", "scored", "individually", "(", "at", "test", "time", "only", ")", "which", "may", "be", "useful", "for", "example", "for", "autoencoder", "architectures", "and", "the", "like", ".", "<br", ">", "Each", "row", "of", "the", "output", "(", "assuming", "addRegularizationTerms", "==", "true", ")", "is", "equivalent", "to", "calling", "score", "(", "DataSet", ")", "with", "a", "single", "example", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java#L3037-L3042
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/IOManager.java
IOManager.createBlockChannelWriter
public BlockChannelWriter<MemorySegment> createBlockChannelWriter(FileIOChannel.ID channelID) throws IOException { """ Creates a block channel writer that writes to the given channel. The writer adds the written segment to its return-queue afterwards (to allow for asynchronous implementations). @param channelID The descriptor for the channel to write to. @return A block channel writer that writes to the given channel. @throws IOException Thrown, if the channel for the writer could not be opened. """ return createBlockChannelWriter(channelID, new LinkedBlockingQueue<MemorySegment>()); }
java
public BlockChannelWriter<MemorySegment> createBlockChannelWriter(FileIOChannel.ID channelID) throws IOException { return createBlockChannelWriter(channelID, new LinkedBlockingQueue<MemorySegment>()); }
[ "public", "BlockChannelWriter", "<", "MemorySegment", ">", "createBlockChannelWriter", "(", "FileIOChannel", ".", "ID", "channelID", ")", "throws", "IOException", "{", "return", "createBlockChannelWriter", "(", "channelID", ",", "new", "LinkedBlockingQueue", "<", "MemorySegment", ">", "(", ")", ")", ";", "}" ]
Creates a block channel writer that writes to the given channel. The writer adds the written segment to its return-queue afterwards (to allow for asynchronous implementations). @param channelID The descriptor for the channel to write to. @return A block channel writer that writes to the given channel. @throws IOException Thrown, if the channel for the writer could not be opened.
[ "Creates", "a", "block", "channel", "writer", "that", "writes", "to", "the", "given", "channel", ".", "The", "writer", "adds", "the", "written", "segment", "to", "its", "return", "-", "queue", "afterwards", "(", "to", "allow", "for", "asynchronous", "implementations", ")", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/IOManager.java#L170-L172
looly/hutool
hutool-core/src/main/java/cn/hutool/core/convert/Convert.java
Convert.convertCharset
public static String convertCharset(String str, String sourceCharset, String destCharset) { """ 给定字符串转换字符编码<br> 如果参数为空,则返回原字符串,不报错。 @param str 被转码的字符串 @param sourceCharset 原字符集 @param destCharset 目标字符集 @return 转换后的字符串 @see CharsetUtil#convert(String, String, String) """ if (StrUtil.hasBlank(str, sourceCharset, destCharset)) { return str; } return CharsetUtil.convert(str, sourceCharset, destCharset); }
java
public static String convertCharset(String str, String sourceCharset, String destCharset) { if (StrUtil.hasBlank(str, sourceCharset, destCharset)) { return str; } return CharsetUtil.convert(str, sourceCharset, destCharset); }
[ "public", "static", "String", "convertCharset", "(", "String", "str", ",", "String", "sourceCharset", ",", "String", "destCharset", ")", "{", "if", "(", "StrUtil", ".", "hasBlank", "(", "str", ",", "sourceCharset", ",", "destCharset", ")", ")", "{", "return", "str", ";", "}", "return", "CharsetUtil", ".", "convert", "(", "str", ",", "sourceCharset", ",", "destCharset", ")", ";", "}" ]
给定字符串转换字符编码<br> 如果参数为空,则返回原字符串,不报错。 @param str 被转码的字符串 @param sourceCharset 原字符集 @param destCharset 目标字符集 @return 转换后的字符串 @see CharsetUtil#convert(String, String, String)
[ "给定字符串转换字符编码<br", ">", "如果参数为空,则返回原字符串,不报错。" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/Convert.java#L780-L786
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/rename/RenameFileExtensions.java
RenameFileExtensions.forceToMoveFile
public static boolean forceToMoveFile(final File srcFile, final File destinationFile) throws IOException, FileIsADirectoryException { """ Moves the given source file to the given destination file. @param srcFile The source file. @param destinationFile The destination file. @return true if the file was moved otherwise false. @throws IOException Signals that an I/O exception has occurred. @throws FileIsADirectoryException the file is A directory exception """ boolean moved = RenameFileExtensions.renameFile(srcFile, destinationFile, true); return moved; }
java
public static boolean forceToMoveFile(final File srcFile, final File destinationFile) throws IOException, FileIsADirectoryException { boolean moved = RenameFileExtensions.renameFile(srcFile, destinationFile, true); return moved; }
[ "public", "static", "boolean", "forceToMoveFile", "(", "final", "File", "srcFile", ",", "final", "File", "destinationFile", ")", "throws", "IOException", ",", "FileIsADirectoryException", "{", "boolean", "moved", "=", "RenameFileExtensions", ".", "renameFile", "(", "srcFile", ",", "destinationFile", ",", "true", ")", ";", "return", "moved", ";", "}" ]
Moves the given source file to the given destination file. @param srcFile The source file. @param destinationFile The destination file. @return true if the file was moved otherwise false. @throws IOException Signals that an I/O exception has occurred. @throws FileIsADirectoryException the file is A directory exception
[ "Moves", "the", "given", "source", "file", "to", "the", "given", "destination", "file", "." ]
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/rename/RenameFileExtensions.java#L246-L251
googleapis/google-cloud-java
google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java
ViewDefinition.of
public static ViewDefinition of(String query, List<UserDefinedFunction> functions) { """ Creates a BigQuery view definition given a query and some user-defined functions. @param query the query used to generate the table @param functions user-defined functions that can be used by the query """ return newBuilder(query, functions).build(); }
java
public static ViewDefinition of(String query, List<UserDefinedFunction> functions) { return newBuilder(query, functions).build(); }
[ "public", "static", "ViewDefinition", "of", "(", "String", "query", ",", "List", "<", "UserDefinedFunction", ">", "functions", ")", "{", "return", "newBuilder", "(", "query", ",", "functions", ")", ".", "build", "(", ")", ";", "}" ]
Creates a BigQuery view definition given a query and some user-defined functions. @param query the query used to generate the table @param functions user-defined functions that can be used by the query
[ "Creates", "a", "BigQuery", "view", "definition", "given", "a", "query", "and", "some", "user", "-", "defined", "functions", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java#L184-L186
Wadpam/guja
guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java
GeneratedDUserDaoImpl.queryByProfileLink
public Iterable<DUser> queryByProfileLink(java.lang.String profileLink) { """ query-by method for field profileLink @param profileLink the specified attribute @return an Iterable of DUsers for the specified profileLink """ return queryByField(null, DUserMapper.Field.PROFILELINK.getFieldName(), profileLink); }
java
public Iterable<DUser> queryByProfileLink(java.lang.String profileLink) { return queryByField(null, DUserMapper.Field.PROFILELINK.getFieldName(), profileLink); }
[ "public", "Iterable", "<", "DUser", ">", "queryByProfileLink", "(", "java", ".", "lang", ".", "String", "profileLink", ")", "{", "return", "queryByField", "(", "null", ",", "DUserMapper", ".", "Field", ".", "PROFILELINK", ".", "getFieldName", "(", ")", ",", "profileLink", ")", ";", "}" ]
query-by method for field profileLink @param profileLink the specified attribute @return an Iterable of DUsers for the specified profileLink
[ "query", "-", "by", "method", "for", "field", "profileLink" ]
train
https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java#L214-L216
kuujo/vertigo
core/src/main/java/net/kuujo/vertigo/Vertigo.java
Vertigo.deployNetwork
public Vertigo deployNetwork(final NetworkConfig network, final Handler<AsyncResult<ActiveNetwork>> doneHandler) { """ Deploys a network to an anonymous local-only cluster.<p> If the given network configuration's name matches the name of a network that is already running in the cluster then the given configuration will be <b>merged</b> with the running network's configuration. This allows networks to be dynamically updated with partial configurations. If the configuration matches the already running configuration then no changes will occur, so it's not necessary to check whether a network is already running if the configuration has not been altered. @param network The configuration of the network to deploy. @param doneHandler An asynchronous handler to be called once the network has completed deployment. The handler will be called with an {@link ActiveNetwork} instance which can be used to add or remove components and connections from the network. @return The Vertigo instance. """ final String cluster = Addresses.createUniqueAddress(); container.deployVerticle(ClusterAgent.class.getName(), new JsonObject().putString("cluster", cluster).putBoolean("local", true), new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { if (result.failed()) { new DefaultFutureResult<ActiveNetwork>(result.cause()).setHandler(doneHandler); } else { deployNetwork(cluster, network, doneHandler); } } }); return this; }
java
public Vertigo deployNetwork(final NetworkConfig network, final Handler<AsyncResult<ActiveNetwork>> doneHandler) { final String cluster = Addresses.createUniqueAddress(); container.deployVerticle(ClusterAgent.class.getName(), new JsonObject().putString("cluster", cluster).putBoolean("local", true), new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { if (result.failed()) { new DefaultFutureResult<ActiveNetwork>(result.cause()).setHandler(doneHandler); } else { deployNetwork(cluster, network, doneHandler); } } }); return this; }
[ "public", "Vertigo", "deployNetwork", "(", "final", "NetworkConfig", "network", ",", "final", "Handler", "<", "AsyncResult", "<", "ActiveNetwork", ">", ">", "doneHandler", ")", "{", "final", "String", "cluster", "=", "Addresses", ".", "createUniqueAddress", "(", ")", ";", "container", ".", "deployVerticle", "(", "ClusterAgent", ".", "class", ".", "getName", "(", ")", ",", "new", "JsonObject", "(", ")", ".", "putString", "(", "\"cluster\"", ",", "cluster", ")", ".", "putBoolean", "(", "\"local\"", ",", "true", ")", ",", "new", "Handler", "<", "AsyncResult", "<", "String", ">", ">", "(", ")", "{", "@", "Override", "public", "void", "handle", "(", "AsyncResult", "<", "String", ">", "result", ")", "{", "if", "(", "result", ".", "failed", "(", ")", ")", "{", "new", "DefaultFutureResult", "<", "ActiveNetwork", ">", "(", "result", ".", "cause", "(", ")", ")", ".", "setHandler", "(", "doneHandler", ")", ";", "}", "else", "{", "deployNetwork", "(", "cluster", ",", "network", ",", "doneHandler", ")", ";", "}", "}", "}", ")", ";", "return", "this", ";", "}" ]
Deploys a network to an anonymous local-only cluster.<p> If the given network configuration's name matches the name of a network that is already running in the cluster then the given configuration will be <b>merged</b> with the running network's configuration. This allows networks to be dynamically updated with partial configurations. If the configuration matches the already running configuration then no changes will occur, so it's not necessary to check whether a network is already running if the configuration has not been altered. @param network The configuration of the network to deploy. @param doneHandler An asynchronous handler to be called once the network has completed deployment. The handler will be called with an {@link ActiveNetwork} instance which can be used to add or remove components and connections from the network. @return The Vertigo instance.
[ "Deploys", "a", "network", "to", "an", "anonymous", "local", "-", "only", "cluster", ".", "<p", ">" ]
train
https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/Vertigo.java#L429-L442
steveohara/j2mod
src/main/java/com/ghgande/j2mod/modbus/facade/AbstractModbusMaster.java
AbstractModbusMaster.writeMultipleCoils
public void writeMultipleCoils(int unitId, int ref, BitVector coils) throws ModbusException { """ Writes a given number of coil states to the slave. Note that the number of coils to be written is given implicitly, through {@link BitVector#size()}. @param unitId the slave unit id. @param ref the offset of the coil to start writing to. @param coils a <tt>BitVector</tt> which holds the coil states to be written. @throws ModbusException if an I/O error, a slave exception or a transaction error occurs. """ checkTransaction(); if (writeMultipleCoilsRequest == null) { writeMultipleCoilsRequest = new WriteMultipleCoilsRequest(); } writeMultipleCoilsRequest.setUnitID(unitId); writeMultipleCoilsRequest.setReference(ref); writeMultipleCoilsRequest.setCoils(coils); transaction.setRequest(writeMultipleCoilsRequest); transaction.execute(); }
java
public void writeMultipleCoils(int unitId, int ref, BitVector coils) throws ModbusException { checkTransaction(); if (writeMultipleCoilsRequest == null) { writeMultipleCoilsRequest = new WriteMultipleCoilsRequest(); } writeMultipleCoilsRequest.setUnitID(unitId); writeMultipleCoilsRequest.setReference(ref); writeMultipleCoilsRequest.setCoils(coils); transaction.setRequest(writeMultipleCoilsRequest); transaction.execute(); }
[ "public", "void", "writeMultipleCoils", "(", "int", "unitId", ",", "int", "ref", ",", "BitVector", "coils", ")", "throws", "ModbusException", "{", "checkTransaction", "(", ")", ";", "if", "(", "writeMultipleCoilsRequest", "==", "null", ")", "{", "writeMultipleCoilsRequest", "=", "new", "WriteMultipleCoilsRequest", "(", ")", ";", "}", "writeMultipleCoilsRequest", ".", "setUnitID", "(", "unitId", ")", ";", "writeMultipleCoilsRequest", ".", "setReference", "(", "ref", ")", ";", "writeMultipleCoilsRequest", ".", "setCoils", "(", "coils", ")", ";", "transaction", ".", "setRequest", "(", "writeMultipleCoilsRequest", ")", ";", "transaction", ".", "execute", "(", ")", ";", "}" ]
Writes a given number of coil states to the slave. Note that the number of coils to be written is given implicitly, through {@link BitVector#size()}. @param unitId the slave unit id. @param ref the offset of the coil to start writing to. @param coils a <tt>BitVector</tt> which holds the coil states to be written. @throws ModbusException if an I/O error, a slave exception or a transaction error occurs.
[ "Writes", "a", "given", "number", "of", "coil", "states", "to", "the", "slave", "." ]
train
https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/facade/AbstractModbusMaster.java#L142-L152
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FacesBackingBean.java
FacesBackingBean.ensureFailover
public void ensureFailover( HttpServletRequest request ) { """ Ensures that any changes to this object will be replicated in a cluster (for failover), even if the replication scheme uses a change-detection algorithm that relies on HttpSession.setAttribute to be aware of changes. Note that this method is used by the framework and does not need to be called explicitly in most cases. @param request the current HttpServletRequest """ StorageHandler sh = Handlers.get( getServletContext() ).getStorageHandler(); HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request ); RequestContext rc = new RequestContext( unwrappedRequest, null ); String attr = ScopedServletUtils.getScopedSessionAttrName( InternalConstants.FACES_BACKING_ATTR, unwrappedRequest ); sh.ensureFailover( rc, attr, this ); }
java
public void ensureFailover( HttpServletRequest request ) { StorageHandler sh = Handlers.get( getServletContext() ).getStorageHandler(); HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request ); RequestContext rc = new RequestContext( unwrappedRequest, null ); String attr = ScopedServletUtils.getScopedSessionAttrName( InternalConstants.FACES_BACKING_ATTR, unwrappedRequest ); sh.ensureFailover( rc, attr, this ); }
[ "public", "void", "ensureFailover", "(", "HttpServletRequest", "request", ")", "{", "StorageHandler", "sh", "=", "Handlers", ".", "get", "(", "getServletContext", "(", ")", ")", ".", "getStorageHandler", "(", ")", ";", "HttpServletRequest", "unwrappedRequest", "=", "PageFlowUtils", ".", "unwrapMultipart", "(", "request", ")", ";", "RequestContext", "rc", "=", "new", "RequestContext", "(", "unwrappedRequest", ",", "null", ")", ";", "String", "attr", "=", "ScopedServletUtils", ".", "getScopedSessionAttrName", "(", "InternalConstants", ".", "FACES_BACKING_ATTR", ",", "unwrappedRequest", ")", ";", "sh", ".", "ensureFailover", "(", "rc", ",", "attr", ",", "this", ")", ";", "}" ]
Ensures that any changes to this object will be replicated in a cluster (for failover), even if the replication scheme uses a change-detection algorithm that relies on HttpSession.setAttribute to be aware of changes. Note that this method is used by the framework and does not need to be called explicitly in most cases. @param request the current HttpServletRequest
[ "Ensures", "that", "any", "changes", "to", "this", "object", "will", "be", "replicated", "in", "a", "cluster", "(", "for", "failover", ")", "even", "if", "the", "replication", "scheme", "uses", "a", "change", "-", "detection", "algorithm", "that", "relies", "on", "HttpSession", ".", "setAttribute", "to", "be", "aware", "of", "changes", ".", "Note", "that", "this", "method", "is", "used", "by", "the", "framework", "and", "does", "not", "need", "to", "be", "called", "explicitly", "in", "most", "cases", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FacesBackingBean.java#L103-L111
grandstaish/paperparcel
paperparcel-compiler/src/main/java/paperparcel/Utils.java
Utils.getAnnotationWithSimpleName
@Nullable static AnnotationMirror getAnnotationWithSimpleName(Element element, String name) { """ Finds an annotation with the given name on the given element, or null if not found. """ for (AnnotationMirror mirror : element.getAnnotationMirrors()) { String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString(); if (name.equals(annotationName)) { return mirror; } } return null; }
java
@Nullable static AnnotationMirror getAnnotationWithSimpleName(Element element, String name) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { String annotationName = mirror.getAnnotationType().asElement().getSimpleName().toString(); if (name.equals(annotationName)) { return mirror; } } return null; }
[ "@", "Nullable", "static", "AnnotationMirror", "getAnnotationWithSimpleName", "(", "Element", "element", ",", "String", "name", ")", "{", "for", "(", "AnnotationMirror", "mirror", ":", "element", ".", "getAnnotationMirrors", "(", ")", ")", "{", "String", "annotationName", "=", "mirror", ".", "getAnnotationType", "(", ")", ".", "asElement", "(", ")", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "name", ".", "equals", "(", "annotationName", ")", ")", "{", "return", "mirror", ";", "}", "}", "return", "null", ";", "}" ]
Finds an annotation with the given name on the given element, or null if not found.
[ "Finds", "an", "annotation", "with", "the", "given", "name", "on", "the", "given", "element", "or", "null", "if", "not", "found", "." ]
train
https://github.com/grandstaish/paperparcel/blob/917686ced81b335b6708d81d6cc0e3e496f7280d/paperparcel-compiler/src/main/java/paperparcel/Utils.java#L684-L692
googleads/googleads-java-lib
extensions/adwords_rate_limiter/src/main/java/com/google/api/ads/adwords/extension/ratelimiter/ApiRetryStrategyManager.java
ApiRetryStrategyManager.getRetryStrategy
public static @Nullable ApiRetryStrategy getRetryStrategy(String name, boolean isUtility) { """ Get the {@link ApiRetryStrategy} for the specified AdWords API service / utility name. @param name the specified AdWords API service / utility name @param isUtility whether this is for some AdWords API utility, i.e., from calling {@link com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface#getUtility(com.google.api.ads.adwords.lib.client.AdWordsSession, Class)}. @return the corresponding {@link ApiRetryStrategy} object, or null if it's not supported by this rate limiter extension """ ApiRateLimitBucket bucket = getRateLimitBucket(name, isUtility); return bucket == null ? null : bucketToStrategy.get(bucket); }
java
public static @Nullable ApiRetryStrategy getRetryStrategy(String name, boolean isUtility) { ApiRateLimitBucket bucket = getRateLimitBucket(name, isUtility); return bucket == null ? null : bucketToStrategy.get(bucket); }
[ "public", "static", "@", "Nullable", "ApiRetryStrategy", "getRetryStrategy", "(", "String", "name", ",", "boolean", "isUtility", ")", "{", "ApiRateLimitBucket", "bucket", "=", "getRateLimitBucket", "(", "name", ",", "isUtility", ")", ";", "return", "bucket", "==", "null", "?", "null", ":", "bucketToStrategy", ".", "get", "(", "bucket", ")", ";", "}" ]
Get the {@link ApiRetryStrategy} for the specified AdWords API service / utility name. @param name the specified AdWords API service / utility name @param isUtility whether this is for some AdWords API utility, i.e., from calling {@link com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface#getUtility(com.google.api.ads.adwords.lib.client.AdWordsSession, Class)}. @return the corresponding {@link ApiRetryStrategy} object, or null if it's not supported by this rate limiter extension
[ "Get", "the", "{", "@link", "ApiRetryStrategy", "}", "for", "the", "specified", "AdWords", "API", "service", "/", "utility", "name", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/extensions/adwords_rate_limiter/src/main/java/com/google/api/ads/adwords/extension/ratelimiter/ApiRetryStrategyManager.java#L65-L68
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSet.java
NodeSet.addNodeInDocOrder
public int addNodeInDocOrder(Node node, XPathContext support) { """ Add the node into a vector of nodes where it should occur in document order. @param node The node to be added. @param support The XPath runtime context. @return The index where it was inserted. @throws RuntimeException thrown if this NodeSet is not of a mutable type. """ if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!"); return addNodeInDocOrder(node, true, support); }
java
public int addNodeInDocOrder(Node node, XPathContext support) { if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!"); return addNodeInDocOrder(node, true, support); }
[ "public", "int", "addNodeInDocOrder", "(", "Node", "node", ",", "XPathContext", "support", ")", "{", "if", "(", "!", "m_mutable", ")", "throw", "new", "RuntimeException", "(", "XSLMessages", ".", "createXPATHMessage", "(", "XPATHErrorResources", ".", "ER_NODESET_NOT_MUTABLE", ",", "null", ")", ")", ";", "//\"This NodeSet is not mutable!\");", "return", "addNodeInDocOrder", "(", "node", ",", "true", ",", "support", ")", ";", "}" ]
Add the node into a vector of nodes where it should occur in document order. @param node The node to be added. @param support The XPath runtime context. @return The index where it was inserted. @throws RuntimeException thrown if this NodeSet is not of a mutable type.
[ "Add", "the", "node", "into", "a", "vector", "of", "nodes", "where", "it", "should", "occur", "in", "document", "order", ".", "@param", "node", "The", "node", "to", "be", "added", ".", "@param", "support", "The", "XPath", "runtime", "context", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSet.java#L706-L713
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/util/NativeCodeLoader.java
NativeCodeLoader.loadLibraryFromFile
public static void loadLibraryFromFile(final String directory, final String filename) throws IOException { """ Loads a native library from a file. @param directory the directory in which the library is supposed to be located @param filename filename of the library to be loaded @throws IOException thrown if an internal native library cannot be extracted """ final String libraryPath = directory + File.separator + filename; synchronized (loadedLibrarySet) { final File outputFile = new File(directory, filename); if (!outputFile.exists()) { // Try to extract the library from the system resources final ClassLoader cl = ClassLoader.getSystemClassLoader(); final InputStream in = cl.getResourceAsStream(JAR_PREFIX + filename); if (in == null) { throw new IOException("Unable to extract native library " + filename + " to " + directory); } final OutputStream out = new FileOutputStream(outputFile); copy(in, out); } System.load(libraryPath); loadedLibrarySet.add(filename); } }
java
public static void loadLibraryFromFile(final String directory, final String filename) throws IOException { final String libraryPath = directory + File.separator + filename; synchronized (loadedLibrarySet) { final File outputFile = new File(directory, filename); if (!outputFile.exists()) { // Try to extract the library from the system resources final ClassLoader cl = ClassLoader.getSystemClassLoader(); final InputStream in = cl.getResourceAsStream(JAR_PREFIX + filename); if (in == null) { throw new IOException("Unable to extract native library " + filename + " to " + directory); } final OutputStream out = new FileOutputStream(outputFile); copy(in, out); } System.load(libraryPath); loadedLibrarySet.add(filename); } }
[ "public", "static", "void", "loadLibraryFromFile", "(", "final", "String", "directory", ",", "final", "String", "filename", ")", "throws", "IOException", "{", "final", "String", "libraryPath", "=", "directory", "+", "File", ".", "separator", "+", "filename", ";", "synchronized", "(", "loadedLibrarySet", ")", "{", "final", "File", "outputFile", "=", "new", "File", "(", "directory", ",", "filename", ")", ";", "if", "(", "!", "outputFile", ".", "exists", "(", ")", ")", "{", "// Try to extract the library from the system resources", "final", "ClassLoader", "cl", "=", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ";", "final", "InputStream", "in", "=", "cl", ".", "getResourceAsStream", "(", "JAR_PREFIX", "+", "filename", ")", ";", "if", "(", "in", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Unable to extract native library \"", "+", "filename", "+", "\" to \"", "+", "directory", ")", ";", "}", "final", "OutputStream", "out", "=", "new", "FileOutputStream", "(", "outputFile", ")", ";", "copy", "(", "in", ",", "out", ")", ";", "}", "System", ".", "load", "(", "libraryPath", ")", ";", "loadedLibrarySet", ".", "add", "(", "filename", ")", ";", "}", "}" ]
Loads a native library from a file. @param directory the directory in which the library is supposed to be located @param filename filename of the library to be loaded @throws IOException thrown if an internal native library cannot be extracted
[ "Loads", "a", "native", "library", "from", "a", "file", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/util/NativeCodeLoader.java#L61-L84
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ManagementResources.java
ManagementResources.setAdministratorPrivilege
@PUT @Path("/administratorprivilege") @Produces(MediaType.APPLICATION_JSON) @Description("Grants administrative privileges.") public Response setAdministratorPrivilege(@Context HttpServletRequest req, @FormParam("username") String userName, @FormParam("privileged") boolean privileged) { """ Updates the admin privileges for the user. @param req The HTTP request. @param userName Name of the user whom the admin privileges will be updated. Cannot be null or empty. @param privileged boolean variable indicating admin privileges. @return Response object indicating whether the operation was successful or not. @throws IllegalArgumentException Throws IllegalArgument exception when the input is not valid. @throws WebApplicationException Throws this exception if the user does not exist or the user is not authorized to carry out this operation. """ if (userName == null || userName.isEmpty()) { throw new IllegalArgumentException("User name cannot be null or empty."); } validatePrivilegedUser(req); PrincipalUser user = userService.findUserByUsername(userName); if (user == null) { throw new WebApplicationException("User does not exist.", Status.NOT_FOUND); } managementService.setAdministratorPrivilege(user, privileged); return Response.status(Status.OK).build(); }
java
@PUT @Path("/administratorprivilege") @Produces(MediaType.APPLICATION_JSON) @Description("Grants administrative privileges.") public Response setAdministratorPrivilege(@Context HttpServletRequest req, @FormParam("username") String userName, @FormParam("privileged") boolean privileged) { if (userName == null || userName.isEmpty()) { throw new IllegalArgumentException("User name cannot be null or empty."); } validatePrivilegedUser(req); PrincipalUser user = userService.findUserByUsername(userName); if (user == null) { throw new WebApplicationException("User does not exist.", Status.NOT_FOUND); } managementService.setAdministratorPrivilege(user, privileged); return Response.status(Status.OK).build(); }
[ "@", "PUT", "@", "Path", "(", "\"/administratorprivilege\"", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Description", "(", "\"Grants administrative privileges.\"", ")", "public", "Response", "setAdministratorPrivilege", "(", "@", "Context", "HttpServletRequest", "req", ",", "@", "FormParam", "(", "\"username\"", ")", "String", "userName", ",", "@", "FormParam", "(", "\"privileged\"", ")", "boolean", "privileged", ")", "{", "if", "(", "userName", "==", "null", "||", "userName", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"User name cannot be null or empty.\"", ")", ";", "}", "validatePrivilegedUser", "(", "req", ")", ";", "PrincipalUser", "user", "=", "userService", ".", "findUserByUsername", "(", "userName", ")", ";", "if", "(", "user", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"User does not exist.\"", ",", "Status", ".", "NOT_FOUND", ")", ";", "}", "managementService", ".", "setAdministratorPrivilege", "(", "user", ",", "privileged", ")", ";", "return", "Response", ".", "status", "(", "Status", ".", "OK", ")", ".", "build", "(", ")", ";", "}" ]
Updates the admin privileges for the user. @param req The HTTP request. @param userName Name of the user whom the admin privileges will be updated. Cannot be null or empty. @param privileged boolean variable indicating admin privileges. @return Response object indicating whether the operation was successful or not. @throws IllegalArgumentException Throws IllegalArgument exception when the input is not valid. @throws WebApplicationException Throws this exception if the user does not exist or the user is not authorized to carry out this operation.
[ "Updates", "the", "admin", "privileges", "for", "the", "user", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/ManagementResources.java#L84-L103
google/error-prone
check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java
BugChecker.describeMatch
@CheckReturnValue protected Description describeMatch(Tree node, Fix fix) { """ Helper to create a Description for the common case where there is a fix. """ return buildDescription(node).addFix(fix).build(); }
java
@CheckReturnValue protected Description describeMatch(Tree node, Fix fix) { return buildDescription(node).addFix(fix).build(); }
[ "@", "CheckReturnValue", "protected", "Description", "describeMatch", "(", "Tree", "node", ",", "Fix", "fix", ")", "{", "return", "buildDescription", "(", "node", ")", ".", "addFix", "(", "fix", ")", ".", "build", "(", ")", ";", "}" ]
Helper to create a Description for the common case where there is a fix.
[ "Helper", "to", "create", "a", "Description", "for", "the", "common", "case", "where", "there", "is", "a", "fix", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java#L111-L114
aws/aws-sdk-java
aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/CreateTagsRequest.java
CreateTagsRequest.withTags
public CreateTagsRequest withTags(java.util.Map<String, String> tags) { """ The key-value pair for the resource tag. @param tags The key-value pair for the resource tag. @return Returns a reference to this object so that method calls can be chained together. """ setTags(tags); return this; }
java
public CreateTagsRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "CreateTagsRequest", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
The key-value pair for the resource tag. @param tags The key-value pair for the resource tag. @return Returns a reference to this object so that method calls can be chained together.
[ "The", "key", "-", "value", "pair", "for", "the", "resource", "tag", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mq/src/main/java/com/amazonaws/services/mq/model/CreateTagsRequest.java#L97-L100
Harium/keel
src/main/java/com/harium/keel/catalano/math/Tools.java
Tools.TruncatedPower
public static double TruncatedPower(double value, double degree) { """ Truncated power function. @param value Value. @param degree Degree. @return Result. """ double x = Math.pow(value, degree); return (x > 0) ? x : 0.0; }
java
public static double TruncatedPower(double value, double degree) { double x = Math.pow(value, degree); return (x > 0) ? x : 0.0; }
[ "public", "static", "double", "TruncatedPower", "(", "double", "value", ",", "double", "degree", ")", "{", "double", "x", "=", "Math", ".", "pow", "(", "value", ",", "degree", ")", ";", "return", "(", "x", ">", "0", ")", "?", "x", ":", "0.0", ";", "}" ]
Truncated power function. @param value Value. @param degree Degree. @return Result.
[ "Truncated", "power", "function", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/Tools.java#L528-L531
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/UNode.java
UNode.addArrayNode
public UNode addArrayNode(String name, String tagName) { """ Create a new ARRAY node with the given name and tag name and add it as a child of this node. This node must be a MAP or ARRAY. This is a convenience method that calls {@link UNode#createArrayNode(String, String)} and then {@link #addChildNode(UNode)}. @param name Name of new ARRAY node. @param tagName Tag name of new ARRAY node (for XML). @return New ARRAY node, added as a child of this node. """ return addChildNode(UNode.createArrayNode(name, tagName)); }
java
public UNode addArrayNode(String name, String tagName) { return addChildNode(UNode.createArrayNode(name, tagName)); }
[ "public", "UNode", "addArrayNode", "(", "String", "name", ",", "String", "tagName", ")", "{", "return", "addChildNode", "(", "UNode", ".", "createArrayNode", "(", "name", ",", "tagName", ")", ")", ";", "}" ]
Create a new ARRAY node with the given name and tag name and add it as a child of this node. This node must be a MAP or ARRAY. This is a convenience method that calls {@link UNode#createArrayNode(String, String)} and then {@link #addChildNode(UNode)}. @param name Name of new ARRAY node. @param tagName Tag name of new ARRAY node (for XML). @return New ARRAY node, added as a child of this node.
[ "Create", "a", "new", "ARRAY", "node", "with", "the", "given", "name", "and", "tag", "name", "and", "add", "it", "as", "a", "child", "of", "this", "node", ".", "This", "node", "must", "be", "a", "MAP", "or", "ARRAY", ".", "This", "is", "a", "convenience", "method", "that", "calls", "{", "@link", "UNode#createArrayNode", "(", "String", "String", ")", "}", "and", "then", "{", "@link", "#addChildNode", "(", "UNode", ")", "}", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/UNode.java#L821-L823
UrielCh/ovh-java-sdk
ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java
ApiOvhEmaildomain.delegatedAccount_email_filter_name_rule_GET
public ArrayList<Long> delegatedAccount_email_filter_name_rule_GET(String email, String name) throws IOException { """ Get rules REST: GET /email/domain/delegatedAccount/{email}/filter/{name}/rule @param email [required] Email @param name [required] Filter name """ String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}/rule"; StringBuilder sb = path(qPath, email, name); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
java
public ArrayList<Long> delegatedAccount_email_filter_name_rule_GET(String email, String name) throws IOException { String qPath = "/email/domain/delegatedAccount/{email}/filter/{name}/rule"; StringBuilder sb = path(qPath, email, name); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
[ "public", "ArrayList", "<", "Long", ">", "delegatedAccount_email_filter_name_rule_GET", "(", "String", "email", ",", "String", "name", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/domain/delegatedAccount/{email}/filter/{name}/rule\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "email", ",", "name", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t3", ")", ";", "}" ]
Get rules REST: GET /email/domain/delegatedAccount/{email}/filter/{name}/rule @param email [required] Email @param name [required] Filter name
[ "Get", "rules" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L208-L213
zamrokk/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/shim/ChaincodeStub.java
ChaincodeStub.putState
public void putState(String key, String value) { """ Puts the given state into a ledger, automatically wrapping it in a ByteString @param key reference key @param value value to be put """ handler.handlePutState(key, ByteString.copyFromUtf8(value), uuid); }
java
public void putState(String key, String value) { handler.handlePutState(key, ByteString.copyFromUtf8(value), uuid); }
[ "public", "void", "putState", "(", "String", "key", ",", "String", "value", ")", "{", "handler", ".", "handlePutState", "(", "key", ",", "ByteString", ".", "copyFromUtf8", "(", "value", ")", ",", "uuid", ")", ";", "}" ]
Puts the given state into a ledger, automatically wrapping it in a ByteString @param key reference key @param value value to be put
[ "Puts", "the", "given", "state", "into", "a", "ledger", "automatically", "wrapping", "it", "in", "a", "ByteString" ]
train
https://github.com/zamrokk/fabric-sdk-java/blob/d4993ca602f72d412cd682e1b92e805e48b27afa/src/main/java/org/hyperledger/fabric/sdk/shim/ChaincodeStub.java#L72-L74
looly/hutool
hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java
ImgUtil.slice
public static void slice(File srcImageFile, File descDir, int destWidth, int destHeight) { """ 图像切片(指定切片的宽度和高度) @param srcImageFile 源图像 @param descDir 切片目标文件夹 @param destWidth 目标切片宽度。默认200 @param destHeight 目标切片高度。默认150 """ slice(read(srcImageFile), descDir, destWidth, destHeight); }
java
public static void slice(File srcImageFile, File descDir, int destWidth, int destHeight) { slice(read(srcImageFile), descDir, destWidth, destHeight); }
[ "public", "static", "void", "slice", "(", "File", "srcImageFile", ",", "File", "descDir", ",", "int", "destWidth", ",", "int", "destHeight", ")", "{", "slice", "(", "read", "(", "srcImageFile", ")", ",", "descDir", ",", "destWidth", ",", "destHeight", ")", ";", "}" ]
图像切片(指定切片的宽度和高度) @param srcImageFile 源图像 @param descDir 切片目标文件夹 @param destWidth 目标切片宽度。默认200 @param destHeight 目标切片高度。默认150
[ "图像切片(指定切片的宽度和高度)" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L370-L372
sdl/odata
odata_client_api/src/main/java/com/sdl/odata/client/property/PropertyUtils.java
PropertyUtils.getIntegerProperty
public static Integer getIntegerProperty(Properties properties, String key) { """ Get an integer property from the properties. @param properties the provided properties @return the integer property """ String property = getStringProperty(properties, key); if (property == null) { return null; } Integer value; try { value = Integer.parseInt(property); } catch (RuntimeException e) { throw new ODataClientRuntimeException("Unable to parse property. " + property, e); } return value; }
java
public static Integer getIntegerProperty(Properties properties, String key) { String property = getStringProperty(properties, key); if (property == null) { return null; } Integer value; try { value = Integer.parseInt(property); } catch (RuntimeException e) { throw new ODataClientRuntimeException("Unable to parse property. " + property, e); } return value; }
[ "public", "static", "Integer", "getIntegerProperty", "(", "Properties", "properties", ",", "String", "key", ")", "{", "String", "property", "=", "getStringProperty", "(", "properties", ",", "key", ")", ";", "if", "(", "property", "==", "null", ")", "{", "return", "null", ";", "}", "Integer", "value", ";", "try", "{", "value", "=", "Integer", ".", "parseInt", "(", "property", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "new", "ODataClientRuntimeException", "(", "\"Unable to parse property. \"", "+", "property", ",", "e", ")", ";", "}", "return", "value", ";", "}" ]
Get an integer property from the properties. @param properties the provided properties @return the integer property
[ "Get", "an", "integer", "property", "from", "the", "properties", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_client_api/src/main/java/com/sdl/odata/client/property/PropertyUtils.java#L42-L54
NoraUi/NoraUi
src/main/java/com/github/noraui/utils/Utilities.java
Utilities.getLocator
public static By getLocator(PageElement element, Object... args) { """ This method read a application descriptor file and return a {@link org.openqa.selenium.By} object (xpath, id, link ...). @param element is PageElement find in page. @param args list of description (xpath, id, link ...) for code. @return a {@link org.openqa.selenium.By} object (xpath, id, link ...) """ logger.debug("getLocator [{}]", element.getPage().getApplication()); logger.debug("getLocator [{}]", element.getPage().getPageKey()); logger.debug("getLocator [{}]", element.getKey()); return getLocator(element.getPage().getApplication(), element.getPage().getPageKey() + element.getKey(), args); }
java
public static By getLocator(PageElement element, Object... args) { logger.debug("getLocator [{}]", element.getPage().getApplication()); logger.debug("getLocator [{}]", element.getPage().getPageKey()); logger.debug("getLocator [{}]", element.getKey()); return getLocator(element.getPage().getApplication(), element.getPage().getPageKey() + element.getKey(), args); }
[ "public", "static", "By", "getLocator", "(", "PageElement", "element", ",", "Object", "...", "args", ")", "{", "logger", ".", "debug", "(", "\"getLocator [{}]\"", ",", "element", ".", "getPage", "(", ")", ".", "getApplication", "(", ")", ")", ";", "logger", ".", "debug", "(", "\"getLocator [{}]\"", ",", "element", ".", "getPage", "(", ")", ".", "getPageKey", "(", ")", ")", ";", "logger", ".", "debug", "(", "\"getLocator [{}]\"", ",", "element", ".", "getKey", "(", ")", ")", ";", "return", "getLocator", "(", "element", ".", "getPage", "(", ")", ".", "getApplication", "(", ")", ",", "element", ".", "getPage", "(", ")", ".", "getPageKey", "(", ")", "+", "element", ".", "getKey", "(", ")", ",", "args", ")", ";", "}" ]
This method read a application descriptor file and return a {@link org.openqa.selenium.By} object (xpath, id, link ...). @param element is PageElement find in page. @param args list of description (xpath, id, link ...) for code. @return a {@link org.openqa.selenium.By} object (xpath, id, link ...)
[ "This", "method", "read", "a", "application", "descriptor", "file", "and", "return", "a", "{", "@link", "org", ".", "openqa", ".", "selenium", ".", "By", "}", "object", "(", "xpath", "id", "link", "...", ")", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/utils/Utilities.java#L136-L141
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java
VirtualMachineScaleSetsInner.beginRedeploy
public OperationStatusResponseInner beginRedeploy(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) { """ Redeploy one or more virtual machines in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @param instanceIds The virtual machine scale set instance ids. Omitting the virtual machine scale set instance ids will result in the operation being performed on all virtual machines in the virtual machine scale set. @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 OperationStatusResponseInner object if successful. """ return beginRedeployWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).toBlocking().single().body(); }
java
public OperationStatusResponseInner beginRedeploy(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) { return beginRedeployWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).toBlocking().single().body(); }
[ "public", "OperationStatusResponseInner", "beginRedeploy", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ",", "List", "<", "String", ">", "instanceIds", ")", "{", "return", "beginRedeployWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetName", ",", "instanceIds", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Redeploy one or more virtual machines in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @param instanceIds The virtual machine scale set instance ids. Omitting the virtual machine scale set instance ids will result in the operation being performed on all virtual machines in the virtual machine scale set. @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 OperationStatusResponseInner object if successful.
[ "Redeploy", "one", "or", "more", "virtual", "machines", "in", "a", "VM", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java#L3097-L3099
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
Validator.expectExactMatch
public void expectExactMatch(String name, String anotherName, String message) { """ Validates to fields to exactly (case-sensitive) match @param name The field to check @param anotherName The other field to check against @param message A custom error message instead of the default one """ String value = Optional.ofNullable(get(name)).orElse(""); String anotherValue = Optional.ofNullable(get(anotherName)).orElse(""); if (( StringUtils.isBlank(value) && StringUtils.isBlank(anotherValue) ) || ( StringUtils.isNotBlank(value) && !value.equals(anotherValue) )) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.EXACT_MATCH_KEY.name(), name, anotherName))); } }
java
public void expectExactMatch(String name, String anotherName, String message) { String value = Optional.ofNullable(get(name)).orElse(""); String anotherValue = Optional.ofNullable(get(anotherName)).orElse(""); if (( StringUtils.isBlank(value) && StringUtils.isBlank(anotherValue) ) || ( StringUtils.isNotBlank(value) && !value.equals(anotherValue) )) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.EXACT_MATCH_KEY.name(), name, anotherName))); } }
[ "public", "void", "expectExactMatch", "(", "String", "name", ",", "String", "anotherName", ",", "String", "message", ")", "{", "String", "value", "=", "Optional", ".", "ofNullable", "(", "get", "(", "name", ")", ")", ".", "orElse", "(", "\"\"", ")", ";", "String", "anotherValue", "=", "Optional", ".", "ofNullable", "(", "get", "(", "anotherName", ")", ")", ".", "orElse", "(", "\"\"", ")", ";", "if", "(", "(", "StringUtils", ".", "isBlank", "(", "value", ")", "&&", "StringUtils", ".", "isBlank", "(", "anotherValue", ")", ")", "||", "(", "StringUtils", ".", "isNotBlank", "(", "value", ")", "&&", "!", "value", ".", "equals", "(", "anotherValue", ")", ")", ")", "{", "addError", "(", "name", ",", "Optional", ".", "ofNullable", "(", "message", ")", ".", "orElse", "(", "messages", ".", "get", "(", "Validation", ".", "EXACT_MATCH_KEY", ".", "name", "(", ")", ",", "name", ",", "anotherName", ")", ")", ")", ";", "}", "}" ]
Validates to fields to exactly (case-sensitive) match @param name The field to check @param anotherName The other field to check against @param message A custom error message instead of the default one
[ "Validates", "to", "fields", "to", "exactly", "(", "case", "-", "sensitive", ")", "match" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L182-L189
tanhaichao/leopard-data
leopard-redis/src/main/java/io/leopard/redis/util/RedisUtil.java
RedisUtil.createJedisPool
public static IJedisPool createJedisPool(String server, int timeout, int maxActive, String password) { """ 创建连接池. @param server 服务器 @param timeout 超时时间 @param maxActive 最大连接数 @return """ if (maxActive <= 0) { maxActive = 128; } if (timeout <= 0) { timeout = 10000; } String[] serverInfo = server.split(":"); String host = serverInfo[0].trim(); int port; try { port = Integer.parseInt(serverInfo[1].trim()); } catch (NumberFormatException e) { logger.error("redis server:" + server); throw e; } if (password == null || password.length() == 0) { if (serverInfo.length > 2) { password = serverInfo[2].trim(); } } // return new JedisPoolStatImpl(host, port, timeout, maxActive); return new JedisPoolApacheImpl(host, port, timeout, maxActive, password); }
java
public static IJedisPool createJedisPool(String server, int timeout, int maxActive, String password) { if (maxActive <= 0) { maxActive = 128; } if (timeout <= 0) { timeout = 10000; } String[] serverInfo = server.split(":"); String host = serverInfo[0].trim(); int port; try { port = Integer.parseInt(serverInfo[1].trim()); } catch (NumberFormatException e) { logger.error("redis server:" + server); throw e; } if (password == null || password.length() == 0) { if (serverInfo.length > 2) { password = serverInfo[2].trim(); } } // return new JedisPoolStatImpl(host, port, timeout, maxActive); return new JedisPoolApacheImpl(host, port, timeout, maxActive, password); }
[ "public", "static", "IJedisPool", "createJedisPool", "(", "String", "server", ",", "int", "timeout", ",", "int", "maxActive", ",", "String", "password", ")", "{", "if", "(", "maxActive", "<=", "0", ")", "{", "maxActive", "=", "128", ";", "}", "if", "(", "timeout", "<=", "0", ")", "{", "timeout", "=", "10000", ";", "}", "String", "[", "]", "serverInfo", "=", "server", ".", "split", "(", "\":\"", ")", ";", "String", "host", "=", "serverInfo", "[", "0", "]", ".", "trim", "(", ")", ";", "int", "port", ";", "try", "{", "port", "=", "Integer", ".", "parseInt", "(", "serverInfo", "[", "1", "]", ".", "trim", "(", ")", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "logger", ".", "error", "(", "\"redis server:\"", "+", "server", ")", ";", "throw", "e", ";", "}", "if", "(", "password", "==", "null", "||", "password", ".", "length", "(", ")", "==", "0", ")", "{", "if", "(", "serverInfo", ".", "length", ">", "2", ")", "{", "password", "=", "serverInfo", "[", "2", "]", ".", "trim", "(", ")", ";", "}", "}", "// return new JedisPoolStatImpl(host, port, timeout, maxActive);\r", "return", "new", "JedisPoolApacheImpl", "(", "host", ",", "port", ",", "timeout", ",", "maxActive", ",", "password", ")", ";", "}" ]
创建连接池. @param server 服务器 @param timeout 超时时间 @param maxActive 最大连接数 @return
[ "创建连接池", "." ]
train
https://github.com/tanhaichao/leopard-data/blob/2fae872f34f68ca6a23bcfe4554d47821b503281/leopard-redis/src/main/java/io/leopard/redis/util/RedisUtil.java#L44-L70
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/ConstantPool.java
ConstantPool.addConstantConstructor
public ConstantMethodInfo addConstantConstructor(String className, TypeDesc[] params) { """ Get or create a constant from the constant pool representing a constructor in any class. """ return addConstantMethod(className, "<init>", null, params); }
java
public ConstantMethodInfo addConstantConstructor(String className, TypeDesc[] params) { return addConstantMethod(className, "<init>", null, params); }
[ "public", "ConstantMethodInfo", "addConstantConstructor", "(", "String", "className", ",", "TypeDesc", "[", "]", "params", ")", "{", "return", "addConstantMethod", "(", "className", ",", "\"<init>\"", ",", "null", ",", "params", ")", ";", "}" ]
Get or create a constant from the constant pool representing a constructor in any class.
[ "Get", "or", "create", "a", "constant", "from", "the", "constant", "pool", "representing", "a", "constructor", "in", "any", "class", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantPool.java#L171-L174
opsmatters/newrelic-api
src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java
HttpContext.executeGetRequest
protected <T> Optional<T> executeGetRequest(URI uri, GenericType<T> returnType) { """ Execute a GET request and return the result. @param <T> The type parameter used for the return object @param uri The URI to call @param returnType The type to marshall the result back into @return The return type """ return executeGetRequest(uri, null, null, returnType); }
java
protected <T> Optional<T> executeGetRequest(URI uri, GenericType<T> returnType) { return executeGetRequest(uri, null, null, returnType); }
[ "protected", "<", "T", ">", "Optional", "<", "T", ">", "executeGetRequest", "(", "URI", "uri", ",", "GenericType", "<", "T", ">", "returnType", ")", "{", "return", "executeGetRequest", "(", "uri", ",", "null", ",", "null", ",", "returnType", ")", ";", "}" ]
Execute a GET request and return the result. @param <T> The type parameter used for the return object @param uri The URI to call @param returnType The type to marshall the result back into @return The return type
[ "Execute", "a", "GET", "request", "and", "return", "the", "result", "." ]
train
https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java#L328-L331
sundrio/sundrio
annotations/builder/src/main/java/io/sundr/builder/internal/functions/ToPojo.java
ToPojo.readPrimitiveArrayProperty
private static String readPrimitiveArrayProperty(String ref, TypeDef source, Property property) { """ Returns the string representation of the code that reads a primitive array property. @param ref The reference. @param source The type of the reference. @param property The property to read. @return The code. """ StringBuilder sb = new StringBuilder(); Method getter = getterOf(source, property); sb.append("Arrays.asList(") .append(ref).append(".").append(getter.getName()).append("())") .append(".stream()").append(".collect(Collectors.toList())).toArray(new "+getter.getReturnType().toString()+"[])"); return sb.toString(); }
java
private static String readPrimitiveArrayProperty(String ref, TypeDef source, Property property) { StringBuilder sb = new StringBuilder(); Method getter = getterOf(source, property); sb.append("Arrays.asList(") .append(ref).append(".").append(getter.getName()).append("())") .append(".stream()").append(".collect(Collectors.toList())).toArray(new "+getter.getReturnType().toString()+"[])"); return sb.toString(); }
[ "private", "static", "String", "readPrimitiveArrayProperty", "(", "String", "ref", ",", "TypeDef", "source", ",", "Property", "property", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "Method", "getter", "=", "getterOf", "(", "source", ",", "property", ")", ";", "sb", ".", "append", "(", "\"Arrays.asList(\"", ")", ".", "append", "(", "ref", ")", ".", "append", "(", "\".\"", ")", ".", "append", "(", "getter", ".", "getName", "(", ")", ")", ".", "append", "(", "\"())\"", ")", ".", "append", "(", "\".stream()\"", ")", ".", "append", "(", "\".collect(Collectors.toList())).toArray(new \"", "+", "getter", ".", "getReturnType", "(", ")", ".", "toString", "(", ")", "+", "\"[])\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Returns the string representation of the code that reads a primitive array property. @param ref The reference. @param source The type of the reference. @param property The property to read. @return The code.
[ "Returns", "the", "string", "representation", "of", "the", "code", "that", "reads", "a", "primitive", "array", "property", "." ]
train
https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/annotations/builder/src/main/java/io/sundr/builder/internal/functions/ToPojo.java#L659-L666
motown-io/motown
utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java
ResponseBuilder.getPreviousPageOffset
private static int getPreviousPageOffset(final int offset, final int limit) { """ Gets the previous page offset. @param offset the current offset. @param limit the limit. @return the previous page offset. """ return hasFullPreviousPage(offset, limit) ? getPreviousFullPageOffset(offset, limit) : getFirstPageOffset(); }
java
private static int getPreviousPageOffset(final int offset, final int limit) { return hasFullPreviousPage(offset, limit) ? getPreviousFullPageOffset(offset, limit) : getFirstPageOffset(); }
[ "private", "static", "int", "getPreviousPageOffset", "(", "final", "int", "offset", ",", "final", "int", "limit", ")", "{", "return", "hasFullPreviousPage", "(", "offset", ",", "limit", ")", "?", "getPreviousFullPageOffset", "(", "offset", ",", "limit", ")", ":", "getFirstPageOffset", "(", ")", ";", "}" ]
Gets the previous page offset. @param offset the current offset. @param limit the limit. @return the previous page offset.
[ "Gets", "the", "previous", "page", "offset", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/utils/rest/src/main/java/io/motown/utils/rest/response/ResponseBuilder.java#L92-L94
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/JobConfigurationUtils.java
JobConfigurationUtils.combineSysAndJobProperties
public static Properties combineSysAndJobProperties(Properties sysProps, Properties jobProps) { """ Get a new {@link Properties} instance by combining a given system configuration {@link Properties} object (first) and a job configuration {@link Properties} object (second). @param sysProps the given system configuration {@link Properties} object @param jobProps the given job configuration {@link Properties} object @return a new {@link Properties} instance """ Properties combinedJobProps = new Properties(); combinedJobProps.putAll(sysProps); combinedJobProps.putAll(jobProps); return combinedJobProps; }
java
public static Properties combineSysAndJobProperties(Properties sysProps, Properties jobProps) { Properties combinedJobProps = new Properties(); combinedJobProps.putAll(sysProps); combinedJobProps.putAll(jobProps); return combinedJobProps; }
[ "public", "static", "Properties", "combineSysAndJobProperties", "(", "Properties", "sysProps", ",", "Properties", "jobProps", ")", "{", "Properties", "combinedJobProps", "=", "new", "Properties", "(", ")", ";", "combinedJobProps", ".", "putAll", "(", "sysProps", ")", ";", "combinedJobProps", ".", "putAll", "(", "jobProps", ")", ";", "return", "combinedJobProps", ";", "}" ]
Get a new {@link Properties} instance by combining a given system configuration {@link Properties} object (first) and a job configuration {@link Properties} object (second). @param sysProps the given system configuration {@link Properties} object @param jobProps the given job configuration {@link Properties} object @return a new {@link Properties} instance
[ "Get", "a", "new", "{", "@link", "Properties", "}", "instance", "by", "combining", "a", "given", "system", "configuration", "{", "@link", "Properties", "}", "object", "(", "first", ")", "and", "a", "job", "configuration", "{", "@link", "Properties", "}", "object", "(", "second", ")", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobConfigurationUtils.java#L52-L57
Azure/azure-sdk-for-java
servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java
ClientFactory.acceptSessionFromEntityPath
public static IMessageSession acceptSessionFromEntityPath(MessagingFactory messagingFactory, String entityPath, String sessionId) throws InterruptedException, ServiceBusException { """ Accept a {@link IMessageSession} from service bus using the client settings with specified session id. Session Id can be null, if null, service will return the first available session. @param messagingFactory messaging factory (which represents a connection) on which the session receiver needs to be created. @param entityPath path of entity @param sessionId session id, if null, service will return the first available session, otherwise, service will return specified session @return IMessageSession instance @throws InterruptedException if the current thread was interrupted while waiting @throws ServiceBusException if the session cannot be accepted """ return acceptSessionFromEntityPath(messagingFactory, entityPath, sessionId, DEFAULTRECEIVEMODE); }
java
public static IMessageSession acceptSessionFromEntityPath(MessagingFactory messagingFactory, String entityPath, String sessionId) throws InterruptedException, ServiceBusException { return acceptSessionFromEntityPath(messagingFactory, entityPath, sessionId, DEFAULTRECEIVEMODE); }
[ "public", "static", "IMessageSession", "acceptSessionFromEntityPath", "(", "MessagingFactory", "messagingFactory", ",", "String", "entityPath", ",", "String", "sessionId", ")", "throws", "InterruptedException", ",", "ServiceBusException", "{", "return", "acceptSessionFromEntityPath", "(", "messagingFactory", ",", "entityPath", ",", "sessionId", ",", "DEFAULTRECEIVEMODE", ")", ";", "}" ]
Accept a {@link IMessageSession} from service bus using the client settings with specified session id. Session Id can be null, if null, service will return the first available session. @param messagingFactory messaging factory (which represents a connection) on which the session receiver needs to be created. @param entityPath path of entity @param sessionId session id, if null, service will return the first available session, otherwise, service will return specified session @return IMessageSession instance @throws InterruptedException if the current thread was interrupted while waiting @throws ServiceBusException if the session cannot be accepted
[ "Accept", "a", "{" ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L597-L599
janus-project/guava.janusproject.io
guava/src/com/google/common/collect/Maps.java
Maps.filterKeys
@GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> filterKeys( NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { """ Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the other. <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have iterators that don't support {@code remove()}, but all other methods are supported by the map and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map or its views, only mappings whose keys satisfy the filter will be removed from the underlying map. <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value mapping in the underlying map and determine which satisfy the filter. When a live view is <i>not</i> needed, it may be faster to copy the filtered map and use the copy. <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at {@link Predicate#apply}. Do not provide a predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. @since 14.0 """ // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); }
java
@GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> filterKeys( NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); }
[ "@", "GwtIncompatible", "(", "\"NavigableMap\"", ")", "public", "static", "<", "K", ",", "V", ">", "NavigableMap", "<", "K", ",", "V", ">", "filterKeys", "(", "NavigableMap", "<", "K", ",", "V", ">", "unfiltered", ",", "final", "Predicate", "<", "?", "super", "K", ">", "keyPredicate", ")", "{", "// TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better", "// performance.", "return", "filterEntries", "(", "unfiltered", ",", "Maps", ".", "<", "K", ">", "keyPredicateOnEntries", "(", "keyPredicate", ")", ")", ";", "}" ]
Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the other. <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have iterators that don't support {@code remove()}, but all other methods are supported by the map and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map or its views, only mappings whose keys satisfy the filter will be removed from the underlying map. <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value mapping in the underlying map and determine which satisfy the filter. When a live view is <i>not</i> needed, it may be faster to copy the filtered map and use the copy. <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at {@link Predicate#apply}. Do not provide a predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. @since 14.0
[ "Returns", "a", "navigable", "map", "containing", "the", "mappings", "in", "{", "@code", "unfiltered", "}", "whose", "keys", "satisfy", "a", "predicate", ".", "The", "returned", "map", "is", "a", "live", "view", "of", "{", "@code", "unfiltered", "}", ";", "changes", "to", "one", "affect", "the", "other", "." ]
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/collect/Maps.java#L2195-L2201
elki-project/elki
elki-classification/src/main/java/de/lmu/ifi/dbs/elki/evaluation/classification/holdout/AbstractHoldout.java
AbstractHoldout.allClassLabels
public static ArrayList<ClassLabel> allClassLabels(MultipleObjectsBundle bundle) { """ Get an array of all class labels in a given data set. @param bundle Bundle @return Class labels. """ int col = findClassLabelColumn(bundle); // TODO: automatically infer class labels? if(col < 0) { throw new AbortException("No class label found (try using ClassLabelFilter)."); } return allClassLabels(bundle, col); }
java
public static ArrayList<ClassLabel> allClassLabels(MultipleObjectsBundle bundle) { int col = findClassLabelColumn(bundle); // TODO: automatically infer class labels? if(col < 0) { throw new AbortException("No class label found (try using ClassLabelFilter)."); } return allClassLabels(bundle, col); }
[ "public", "static", "ArrayList", "<", "ClassLabel", ">", "allClassLabels", "(", "MultipleObjectsBundle", "bundle", ")", "{", "int", "col", "=", "findClassLabelColumn", "(", "bundle", ")", ";", "// TODO: automatically infer class labels?", "if", "(", "col", "<", "0", ")", "{", "throw", "new", "AbortException", "(", "\"No class label found (try using ClassLabelFilter).\"", ")", ";", "}", "return", "allClassLabels", "(", "bundle", ",", "col", ")", ";", "}" ]
Get an array of all class labels in a given data set. @param bundle Bundle @return Class labels.
[ "Get", "an", "array", "of", "all", "class", "labels", "in", "a", "given", "data", "set", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-classification/src/main/java/de/lmu/ifi/dbs/elki/evaluation/classification/holdout/AbstractHoldout.java#L87-L94
alkacon/opencms-core
src/org/opencms/file/wrapper/CmsResourceWrapperModules.java
CmsResourceWrapperModules.createFakeBinaryFile
protected CmsResource createFakeBinaryFile(String rootPath, long dateLastModified) throws CmsLoaderException { """ Creates a fake CmsResource of type 'binary'.<p> @param rootPath the root path @param dateLastModified the last modification date to use @return the fake resource @throws CmsLoaderException if the binary type is missing """ CmsUUID structureId = CmsUUID.getConstantUUID("s-" + rootPath); CmsUUID resourceId = CmsUUID.getConstantUUID("r-" + rootPath); @SuppressWarnings("deprecation") int type = OpenCms.getResourceManager().getResourceType(CmsResourceTypeBinary.getStaticTypeName()).getTypeId(); boolean isFolder = false; int flags = 0; CmsUUID projectId = CmsProject.ONLINE_PROJECT_ID; CmsResourceState state = CmsResource.STATE_UNCHANGED; long dateCreated = 0; long dateReleased = 1; long dateContent = 1; int version = 0; CmsUUID userCreated = CmsUUID.getNullUUID(); CmsUUID userLastModified = CmsUUID.getNullUUID(); long dateExpired = Integer.MAX_VALUE; int linkCount = 0; int size = 1; CmsResource resource = new CmsResource( structureId, resourceId, rootPath, type, isFolder, flags, projectId, state, dateCreated, userCreated, dateLastModified, userLastModified, dateReleased, dateExpired, linkCount, size, dateContent, version); return resource; }
java
protected CmsResource createFakeBinaryFile(String rootPath, long dateLastModified) throws CmsLoaderException { CmsUUID structureId = CmsUUID.getConstantUUID("s-" + rootPath); CmsUUID resourceId = CmsUUID.getConstantUUID("r-" + rootPath); @SuppressWarnings("deprecation") int type = OpenCms.getResourceManager().getResourceType(CmsResourceTypeBinary.getStaticTypeName()).getTypeId(); boolean isFolder = false; int flags = 0; CmsUUID projectId = CmsProject.ONLINE_PROJECT_ID; CmsResourceState state = CmsResource.STATE_UNCHANGED; long dateCreated = 0; long dateReleased = 1; long dateContent = 1; int version = 0; CmsUUID userCreated = CmsUUID.getNullUUID(); CmsUUID userLastModified = CmsUUID.getNullUUID(); long dateExpired = Integer.MAX_VALUE; int linkCount = 0; int size = 1; CmsResource resource = new CmsResource( structureId, resourceId, rootPath, type, isFolder, flags, projectId, state, dateCreated, userCreated, dateLastModified, userLastModified, dateReleased, dateExpired, linkCount, size, dateContent, version); return resource; }
[ "protected", "CmsResource", "createFakeBinaryFile", "(", "String", "rootPath", ",", "long", "dateLastModified", ")", "throws", "CmsLoaderException", "{", "CmsUUID", "structureId", "=", "CmsUUID", ".", "getConstantUUID", "(", "\"s-\"", "+", "rootPath", ")", ";", "CmsUUID", "resourceId", "=", "CmsUUID", ".", "getConstantUUID", "(", "\"r-\"", "+", "rootPath", ")", ";", "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "int", "type", "=", "OpenCms", ".", "getResourceManager", "(", ")", ".", "getResourceType", "(", "CmsResourceTypeBinary", ".", "getStaticTypeName", "(", ")", ")", ".", "getTypeId", "(", ")", ";", "boolean", "isFolder", "=", "false", ";", "int", "flags", "=", "0", ";", "CmsUUID", "projectId", "=", "CmsProject", ".", "ONLINE_PROJECT_ID", ";", "CmsResourceState", "state", "=", "CmsResource", ".", "STATE_UNCHANGED", ";", "long", "dateCreated", "=", "0", ";", "long", "dateReleased", "=", "1", ";", "long", "dateContent", "=", "1", ";", "int", "version", "=", "0", ";", "CmsUUID", "userCreated", "=", "CmsUUID", ".", "getNullUUID", "(", ")", ";", "CmsUUID", "userLastModified", "=", "CmsUUID", ".", "getNullUUID", "(", ")", ";", "long", "dateExpired", "=", "Integer", ".", "MAX_VALUE", ";", "int", "linkCount", "=", "0", ";", "int", "size", "=", "1", ";", "CmsResource", "resource", "=", "new", "CmsResource", "(", "structureId", ",", "resourceId", ",", "rootPath", ",", "type", ",", "isFolder", ",", "flags", ",", "projectId", ",", "state", ",", "dateCreated", ",", "userCreated", ",", "dateLastModified", ",", "userLastModified", ",", "dateReleased", ",", "dateExpired", ",", "linkCount", ",", "size", ",", "dateContent", ",", "version", ")", ";", "return", "resource", ";", "}" ]
Creates a fake CmsResource of type 'binary'.<p> @param rootPath the root path @param dateLastModified the last modification date to use @return the fake resource @throws CmsLoaderException if the binary type is missing
[ "Creates", "a", "fake", "CmsResource", "of", "type", "binary", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/wrapper/CmsResourceWrapperModules.java#L324-L365
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java
MSPDIReader.readResourceExtendedAttributes
private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx) { """ This method processes any extended attributes associated with a resource. @param xml MSPDI resource instance @param mpx MPX resource instance """ for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute()) { int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF; ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID); TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null); DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat); } }
java
private void readResourceExtendedAttributes(Project.Resources.Resource xml, Resource mpx) { for (Project.Resources.Resource.ExtendedAttribute attrib : xml.getExtendedAttribute()) { int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF; ResourceField mpxFieldID = MPPResourceField.getInstance(xmlFieldID); TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null); DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat); } }
[ "private", "void", "readResourceExtendedAttributes", "(", "Project", ".", "Resources", ".", "Resource", "xml", ",", "Resource", "mpx", ")", "{", "for", "(", "Project", ".", "Resources", ".", "Resource", ".", "ExtendedAttribute", "attrib", ":", "xml", ".", "getExtendedAttribute", "(", ")", ")", "{", "int", "xmlFieldID", "=", "Integer", ".", "parseInt", "(", "attrib", ".", "getFieldID", "(", ")", ")", "&", "0x0000FFFF", ";", "ResourceField", "mpxFieldID", "=", "MPPResourceField", ".", "getInstance", "(", "xmlFieldID", ")", ";", "TimeUnit", "durationFormat", "=", "DatatypeConverter", ".", "parseDurationTimeUnits", "(", "attrib", ".", "getDurationFormat", "(", ")", ",", "null", ")", ";", "DatatypeConverter", ".", "parseExtendedAttribute", "(", "m_projectFile", ",", "mpx", ",", "attrib", ".", "getValue", "(", ")", ",", "mpxFieldID", ",", "durationFormat", ")", ";", "}", "}" ]
This method processes any extended attributes associated with a resource. @param xml MSPDI resource instance @param mpx MPX resource instance
[ "This", "method", "processes", "any", "extended", "attributes", "associated", "with", "a", "resource", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L1006-L1015
carewebframework/carewebframework-vista
org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/BrokerSession.java
BrokerSession.netCall
protected synchronized Response netCall(Request request, int timeout) { """ Issues a request to the server, returning the response. @param request Request to be sent. @param timeout The timeout, in milliseconds, to await a response. @return Response returned by the server. """ Response response = null; if (serverCaps != null && serverCaps.isDebugMode()) { timeout = 0; } try { socket.setSoTimeout(timeout); DataOutputStream requestPacket = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); request.write(requestPacket, nextSequenceId()); requestPacket.flush(); DataInputStream responsePacket = new DataInputStream(new BufferedInputStream(socket.getInputStream())); response = new Response(responsePacket); if (response.getSequenceId() != request.getSequenceId()) { throw new IOException("Response is not for current request."); } } catch (Exception e) { netFlush(); throw MiscUtil.toUnchecked(e); } if (response.getResponseType() == ResponseType.ERROR) { throw new RPCException(response.getData()); } return response; }
java
protected synchronized Response netCall(Request request, int timeout) { Response response = null; if (serverCaps != null && serverCaps.isDebugMode()) { timeout = 0; } try { socket.setSoTimeout(timeout); DataOutputStream requestPacket = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); request.write(requestPacket, nextSequenceId()); requestPacket.flush(); DataInputStream responsePacket = new DataInputStream(new BufferedInputStream(socket.getInputStream())); response = new Response(responsePacket); if (response.getSequenceId() != request.getSequenceId()) { throw new IOException("Response is not for current request."); } } catch (Exception e) { netFlush(); throw MiscUtil.toUnchecked(e); } if (response.getResponseType() == ResponseType.ERROR) { throw new RPCException(response.getData()); } return response; }
[ "protected", "synchronized", "Response", "netCall", "(", "Request", "request", ",", "int", "timeout", ")", "{", "Response", "response", "=", "null", ";", "if", "(", "serverCaps", "!=", "null", "&&", "serverCaps", ".", "isDebugMode", "(", ")", ")", "{", "timeout", "=", "0", ";", "}", "try", "{", "socket", ".", "setSoTimeout", "(", "timeout", ")", ";", "DataOutputStream", "requestPacket", "=", "new", "DataOutputStream", "(", "new", "BufferedOutputStream", "(", "socket", ".", "getOutputStream", "(", ")", ")", ")", ";", "request", ".", "write", "(", "requestPacket", ",", "nextSequenceId", "(", ")", ")", ";", "requestPacket", ".", "flush", "(", ")", ";", "DataInputStream", "responsePacket", "=", "new", "DataInputStream", "(", "new", "BufferedInputStream", "(", "socket", ".", "getInputStream", "(", ")", ")", ")", ";", "response", "=", "new", "Response", "(", "responsePacket", ")", ";", "if", "(", "response", ".", "getSequenceId", "(", ")", "!=", "request", ".", "getSequenceId", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Response is not for current request.\"", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "netFlush", "(", ")", ";", "throw", "MiscUtil", ".", "toUnchecked", "(", "e", ")", ";", "}", "if", "(", "response", ".", "getResponseType", "(", ")", "==", "ResponseType", ".", "ERROR", ")", "{", "throw", "new", "RPCException", "(", "response", ".", "getData", "(", ")", ")", ";", "}", "return", "response", ";", "}" ]
Issues a request to the server, returning the response. @param request Request to be sent. @param timeout The timeout, in milliseconds, to await a response. @return Response returned by the server.
[ "Issues", "a", "request", "to", "the", "server", "returning", "the", "response", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/BrokerSession.java#L537-L565