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
cdk/cdk
descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java
XLogPDescriptor.getAtomTypeXCount
private int getAtomTypeXCount(IAtomContainer ac, IAtom atom) { """ Gets the atomType X Count attribute of the XLogPDescriptor object. @param ac Description of the Parameter @param atom Description of the Parameter @return The nitrogenOrOxygenCount value """ List<IAtom> neighbours = ac.getConnectedAtomsList(atom); int nocounter = 0; IBond bond; for (IAtom neighbour : neighbours) { if ((neighbour.getSymbol().equals("N") || neighbour.getSymbol().equals("O")) && !(Boolean) neighbour.getProperty("IS_IN_AROMATIC_RING")) { //if (ac.getMaximumBondOrder(neighbours[i]) == 1.0) { bond = ac.getBond(neighbour, atom); if (bond.getOrder() != IBond.Order.DOUBLE) { nocounter += 1; } } } return nocounter; }
java
private int getAtomTypeXCount(IAtomContainer ac, IAtom atom) { List<IAtom> neighbours = ac.getConnectedAtomsList(atom); int nocounter = 0; IBond bond; for (IAtom neighbour : neighbours) { if ((neighbour.getSymbol().equals("N") || neighbour.getSymbol().equals("O")) && !(Boolean) neighbour.getProperty("IS_IN_AROMATIC_RING")) { //if (ac.getMaximumBondOrder(neighbours[i]) == 1.0) { bond = ac.getBond(neighbour, atom); if (bond.getOrder() != IBond.Order.DOUBLE) { nocounter += 1; } } } return nocounter; }
[ "private", "int", "getAtomTypeXCount", "(", "IAtomContainer", "ac", ",", "IAtom", "atom", ")", "{", "List", "<", "IAtom", ">", "neighbours", "=", "ac", ".", "getConnectedAtomsList", "(", "atom", ")", ";", "int", "nocounter", "=", "0", ";", "IBond", "bond", ";", "for", "(", "IAtom", "neighbour", ":", "neighbours", ")", "{", "if", "(", "(", "neighbour", ".", "getSymbol", "(", ")", ".", "equals", "(", "\"N\"", ")", "||", "neighbour", ".", "getSymbol", "(", ")", ".", "equals", "(", "\"O\"", ")", ")", "&&", "!", "(", "Boolean", ")", "neighbour", ".", "getProperty", "(", "\"IS_IN_AROMATIC_RING\"", ")", ")", "{", "//if (ac.getMaximumBondOrder(neighbours[i]) == 1.0) {", "bond", "=", "ac", ".", "getBond", "(", "neighbour", ",", "atom", ")", ";", "if", "(", "bond", ".", "getOrder", "(", ")", "!=", "IBond", ".", "Order", ".", "DOUBLE", ")", "{", "nocounter", "+=", "1", ";", "}", "}", "}", "return", "nocounter", ";", "}" ]
Gets the atomType X Count attribute of the XLogPDescriptor object. @param ac Description of the Parameter @param atom Description of the Parameter @return The nitrogenOrOxygenCount value
[ "Gets", "the", "atomType", "X", "Count", "attribute", "of", "the", "XLogPDescriptor", "object", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/XLogPDescriptor.java#L1050-L1065
apereo/cas
support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/AbstractSamlProfileHandlerController.java
AbstractSamlProfileHandlerController.verifySamlAuthenticationRequest
protected Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> verifySamlAuthenticationRequest( final Pair<? extends SignableSAMLObject, MessageContext> authenticationContext, final HttpServletRequest request) throws Exception { """ Verify saml authentication request. @param authenticationContext the pair @param request the request @return the pair @throws Exception the exception """ val authnRequest = (AuthnRequest) authenticationContext.getKey(); val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest); LOGGER.debug("Located issuer [{}] from authentication request", issuer); val registeredService = verifySamlRegisteredService(issuer); LOGGER.debug("Fetching saml metadata adaptor for [{}]", issuer); val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get( samlProfileHandlerConfigurationContext.getSamlRegisteredServiceCachingMetadataResolver(), registeredService, authnRequest); if (adaptor.isEmpty()) { LOGGER.warn("No metadata could be found for [{}]", issuer); throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer); } val facade = adaptor.get(); verifyAuthenticationContextSignature(authenticationContext, request, authnRequest, facade); SamlUtils.logSamlObject(samlProfileHandlerConfigurationContext.getOpenSamlConfigBean(), authnRequest); return Pair.of(registeredService, facade); }
java
protected Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> verifySamlAuthenticationRequest( final Pair<? extends SignableSAMLObject, MessageContext> authenticationContext, final HttpServletRequest request) throws Exception { val authnRequest = (AuthnRequest) authenticationContext.getKey(); val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest); LOGGER.debug("Located issuer [{}] from authentication request", issuer); val registeredService = verifySamlRegisteredService(issuer); LOGGER.debug("Fetching saml metadata adaptor for [{}]", issuer); val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get( samlProfileHandlerConfigurationContext.getSamlRegisteredServiceCachingMetadataResolver(), registeredService, authnRequest); if (adaptor.isEmpty()) { LOGGER.warn("No metadata could be found for [{}]", issuer); throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer); } val facade = adaptor.get(); verifyAuthenticationContextSignature(authenticationContext, request, authnRequest, facade); SamlUtils.logSamlObject(samlProfileHandlerConfigurationContext.getOpenSamlConfigBean(), authnRequest); return Pair.of(registeredService, facade); }
[ "protected", "Pair", "<", "SamlRegisteredService", ",", "SamlRegisteredServiceServiceProviderMetadataFacade", ">", "verifySamlAuthenticationRequest", "(", "final", "Pair", "<", "?", "extends", "SignableSAMLObject", ",", "MessageContext", ">", "authenticationContext", ",", "final", "HttpServletRequest", "request", ")", "throws", "Exception", "{", "val", "authnRequest", "=", "(", "AuthnRequest", ")", "authenticationContext", ".", "getKey", "(", ")", ";", "val", "issuer", "=", "SamlIdPUtils", ".", "getIssuerFromSamlObject", "(", "authnRequest", ")", ";", "LOGGER", ".", "debug", "(", "\"Located issuer [{}] from authentication request\"", ",", "issuer", ")", ";", "val", "registeredService", "=", "verifySamlRegisteredService", "(", "issuer", ")", ";", "LOGGER", ".", "debug", "(", "\"Fetching saml metadata adaptor for [{}]\"", ",", "issuer", ")", ";", "val", "adaptor", "=", "SamlRegisteredServiceServiceProviderMetadataFacade", ".", "get", "(", "samlProfileHandlerConfigurationContext", ".", "getSamlRegisteredServiceCachingMetadataResolver", "(", ")", ",", "registeredService", ",", "authnRequest", ")", ";", "if", "(", "adaptor", ".", "isEmpty", "(", ")", ")", "{", "LOGGER", ".", "warn", "(", "\"No metadata could be found for [{}]\"", ",", "issuer", ")", ";", "throw", "new", "UnauthorizedServiceException", "(", "UnauthorizedServiceException", ".", "CODE_UNAUTHZ_SERVICE", ",", "\"Cannot find metadata linked to \"", "+", "issuer", ")", ";", "}", "val", "facade", "=", "adaptor", ".", "get", "(", ")", ";", "verifyAuthenticationContextSignature", "(", "authenticationContext", ",", "request", ",", "authnRequest", ",", "facade", ")", ";", "SamlUtils", ".", "logSamlObject", "(", "samlProfileHandlerConfigurationContext", ".", "getOpenSamlConfigBean", "(", ")", ",", "authnRequest", ")", ";", "return", "Pair", ".", "of", "(", "registeredService", ",", "facade", ")", ";", "}" ]
Verify saml authentication request. @param authenticationContext the pair @param request the request @return the pair @throws Exception the exception
[ "Verify", "saml", "authentication", "request", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/AbstractSamlProfileHandlerController.java#L339-L360
simbiose/Encryption
Encryption/main/se/simbio/encryption/Encryption.java
Encryption.encryptAsync
public void encryptAsync(final String data, final Callback callback) { """ This is a sugar method that calls encrypt method in background, it is a good idea to use this one instead the default method because encryption can take several time and with this method the process occurs in a AsyncTask, other advantage is the Callback with separated methods, one for success and other for the exception @param data the String to be encrypted @param callback the Callback to handle the results """ if (callback == null) return; new Thread(new Runnable() { @Override public void run() { try { String encrypt = encrypt(data); if (encrypt == null) { callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data")); } callback.onSuccess(encrypt); } catch (Exception e) { callback.onError(e); } } }).start(); }
java
public void encryptAsync(final String data, final Callback callback) { if (callback == null) return; new Thread(new Runnable() { @Override public void run() { try { String encrypt = encrypt(data); if (encrypt == null) { callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data")); } callback.onSuccess(encrypt); } catch (Exception e) { callback.onError(e); } } }).start(); }
[ "public", "void", "encryptAsync", "(", "final", "String", "data", ",", "final", "Callback", "callback", ")", "{", "if", "(", "callback", "==", "null", ")", "return", ";", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "String", "encrypt", "=", "encrypt", "(", "data", ")", ";", "if", "(", "encrypt", "==", "null", ")", "{", "callback", ".", "onError", "(", "new", "Exception", "(", "\"Encrypt return null, it normally occurs when you send a null data\"", ")", ")", ";", "}", "callback", ".", "onSuccess", "(", "encrypt", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "callback", ".", "onError", "(", "e", ")", ";", "}", "}", "}", ")", ".", "start", "(", ")", ";", "}" ]
This is a sugar method that calls encrypt method in background, it is a good idea to use this one instead the default method because encryption can take several time and with this method the process occurs in a AsyncTask, other advantage is the Callback with separated methods, one for success and other for the exception @param data the String to be encrypted @param callback the Callback to handle the results
[ "This", "is", "a", "sugar", "method", "that", "calls", "encrypt", "method", "in", "background", "it", "is", "a", "good", "idea", "to", "use", "this", "one", "instead", "the", "default", "method", "because", "encryption", "can", "take", "several", "time", "and", "with", "this", "method", "the", "process", "occurs", "in", "a", "AsyncTask", "other", "advantage", "is", "the", "Callback", "with", "separated", "methods", "one", "for", "success", "and", "other", "for", "the", "exception" ]
train
https://github.com/simbiose/Encryption/blob/a344761a10add131cbe9962f895b416e5217d0e9/Encryption/main/se/simbio/encryption/Encryption.java#L123-L139
aws/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/NonCompliantResource.java
NonCompliantResource.withAdditionalInfo
public NonCompliantResource withAdditionalInfo(java.util.Map<String, String> additionalInfo) { """ <p> Additional information about the non-compliant resource. </p> @param additionalInfo Additional information about the non-compliant resource. @return Returns a reference to this object so that method calls can be chained together. """ setAdditionalInfo(additionalInfo); return this; }
java
public NonCompliantResource withAdditionalInfo(java.util.Map<String, String> additionalInfo) { setAdditionalInfo(additionalInfo); return this; }
[ "public", "NonCompliantResource", "withAdditionalInfo", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "additionalInfo", ")", "{", "setAdditionalInfo", "(", "additionalInfo", ")", ";", "return", "this", ";", "}" ]
<p> Additional information about the non-compliant resource. </p> @param additionalInfo Additional information about the non-compliant resource. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Additional", "information", "about", "the", "non", "-", "compliant", "resource", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/NonCompliantResource.java#L181-L184
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/shared/MultiTable.java
MultiTable.getInfoFromHandle
public Object getInfoFromHandle(Object bookmark, boolean bGetTable, int iHandleType) throws DBException { """ Get the table or object ID portion of the bookmark. @exception DBException File exception. """ if (iHandleType == DBConstants.OBJECT_ID_HANDLE) { if (!(bookmark instanceof String)) return null; int iLastColon = ((String)bookmark).lastIndexOf(BaseTable.HANDLE_SEPARATOR); if (iLastColon == -1) return null; if (bGetTable) return ((String)bookmark).substring(0, iLastColon); else return ((String)bookmark).substring(iLastColon+1); } return bookmark; }
java
public Object getInfoFromHandle(Object bookmark, boolean bGetTable, int iHandleType) throws DBException { if (iHandleType == DBConstants.OBJECT_ID_HANDLE) { if (!(bookmark instanceof String)) return null; int iLastColon = ((String)bookmark).lastIndexOf(BaseTable.HANDLE_SEPARATOR); if (iLastColon == -1) return null; if (bGetTable) return ((String)bookmark).substring(0, iLastColon); else return ((String)bookmark).substring(iLastColon+1); } return bookmark; }
[ "public", "Object", "getInfoFromHandle", "(", "Object", "bookmark", ",", "boolean", "bGetTable", ",", "int", "iHandleType", ")", "throws", "DBException", "{", "if", "(", "iHandleType", "==", "DBConstants", ".", "OBJECT_ID_HANDLE", ")", "{", "if", "(", "!", "(", "bookmark", "instanceof", "String", ")", ")", "return", "null", ";", "int", "iLastColon", "=", "(", "(", "String", ")", "bookmark", ")", ".", "lastIndexOf", "(", "BaseTable", ".", "HANDLE_SEPARATOR", ")", ";", "if", "(", "iLastColon", "==", "-", "1", ")", "return", "null", ";", "if", "(", "bGetTable", ")", "return", "(", "(", "String", ")", "bookmark", ")", ".", "substring", "(", "0", ",", "iLastColon", ")", ";", "else", "return", "(", "(", "String", ")", "bookmark", ")", ".", "substring", "(", "iLastColon", "+", "1", ")", ";", "}", "return", "bookmark", ";", "}" ]
Get the table or object ID portion of the bookmark. @exception DBException File exception.
[ "Get", "the", "table", "or", "object", "ID", "portion", "of", "the", "bookmark", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/shared/MultiTable.java#L190-L205
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/DoradusServer.java
DoradusServer.initConfig
private void initConfig(String[] args) { """ Initialize the ServerParams module, which loads the doradus.yaml file. """ try { ServerParams.load(args); if (Utils.isEmpty(ServerParams.instance().getModuleParamString("DoradusServer", "super_user"))) { m_logger.warn("'DoradusServer.super_user' parameter is not defined. " + "Privileged commands will be available without authentication."); } } catch (ConfigurationException e) { throw new RuntimeException("Failed to initialize server configuration", e); } }
java
private void initConfig(String[] args) { try { ServerParams.load(args); if (Utils.isEmpty(ServerParams.instance().getModuleParamString("DoradusServer", "super_user"))) { m_logger.warn("'DoradusServer.super_user' parameter is not defined. " + "Privileged commands will be available without authentication."); } } catch (ConfigurationException e) { throw new RuntimeException("Failed to initialize server configuration", e); } }
[ "private", "void", "initConfig", "(", "String", "[", "]", "args", ")", "{", "try", "{", "ServerParams", ".", "load", "(", "args", ")", ";", "if", "(", "Utils", ".", "isEmpty", "(", "ServerParams", ".", "instance", "(", ")", ".", "getModuleParamString", "(", "\"DoradusServer\"", ",", "\"super_user\"", ")", ")", ")", "{", "m_logger", ".", "warn", "(", "\"'DoradusServer.super_user' parameter is not defined. \"", "+", "\"Privileged commands will be available without authentication.\"", ")", ";", "}", "}", "catch", "(", "ConfigurationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to initialize server configuration\"", ",", "e", ")", ";", "}", "}" ]
Initialize the ServerParams module, which loads the doradus.yaml file.
[ "Initialize", "the", "ServerParams", "module", "which", "loads", "the", "doradus", ".", "yaml", "file", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/DoradusServer.java#L350-L360
grpc/grpc-java
core/src/main/java/io/grpc/internal/GzipInflatingBuffer.java
GzipInflatingBuffer.inflateBytes
int inflateBytes(byte[] b, int offset, int length) throws DataFormatException, ZipException { """ Attempts to inflate {@code length} bytes of data into {@code b}. <p>Any gzipped bytes consumed by this method will be added to the counter returned by {@link #getAndResetBytesConsumed()}. This method may consume gzipped bytes without writing any data to {@code b}, and may also write data to {@code b} without consuming additional gzipped bytes (if the inflater on an earlier call consumed the bytes necessary to produce output). @param b the destination array to receive the bytes. @param offset the starting offset in the destination array. @param length the number of bytes to be copied. @throws IndexOutOfBoundsException if {@code b} is too small to hold the requested bytes. """ checkState(!closed, "GzipInflatingBuffer is closed"); int bytesRead = 0; int missingBytes; boolean madeProgress = true; while (madeProgress && (missingBytes = length - bytesRead) > 0) { switch (state) { case HEADER: madeProgress = processHeader(); break; case HEADER_EXTRA_LEN: madeProgress = processHeaderExtraLen(); break; case HEADER_EXTRA: madeProgress = processHeaderExtra(); break; case HEADER_NAME: madeProgress = processHeaderName(); break; case HEADER_COMMENT: madeProgress = processHeaderComment(); break; case HEADER_CRC: madeProgress = processHeaderCrc(); break; case INITIALIZE_INFLATER: madeProgress = initializeInflater(); break; case INFLATING: bytesRead += inflate(b, offset + bytesRead, missingBytes); if (state == State.TRAILER) { // Eagerly process trailer, if available, to validate CRC. madeProgress = processTrailer(); } else { // Continue in INFLATING until we have the required bytes or we transition to // INFLATER_NEEDS_INPUT madeProgress = true; } break; case INFLATER_NEEDS_INPUT: madeProgress = fill(); break; case TRAILER: madeProgress = processTrailer(); break; default: throw new AssertionError("Invalid state: " + state); } } // If we finished a gzip block, check if we have enough bytes to read another header isStalled = !madeProgress || (state == State.HEADER && gzipMetadataReader.readableBytes() < GZIP_HEADER_MIN_SIZE); return bytesRead; }
java
int inflateBytes(byte[] b, int offset, int length) throws DataFormatException, ZipException { checkState(!closed, "GzipInflatingBuffer is closed"); int bytesRead = 0; int missingBytes; boolean madeProgress = true; while (madeProgress && (missingBytes = length - bytesRead) > 0) { switch (state) { case HEADER: madeProgress = processHeader(); break; case HEADER_EXTRA_LEN: madeProgress = processHeaderExtraLen(); break; case HEADER_EXTRA: madeProgress = processHeaderExtra(); break; case HEADER_NAME: madeProgress = processHeaderName(); break; case HEADER_COMMENT: madeProgress = processHeaderComment(); break; case HEADER_CRC: madeProgress = processHeaderCrc(); break; case INITIALIZE_INFLATER: madeProgress = initializeInflater(); break; case INFLATING: bytesRead += inflate(b, offset + bytesRead, missingBytes); if (state == State.TRAILER) { // Eagerly process trailer, if available, to validate CRC. madeProgress = processTrailer(); } else { // Continue in INFLATING until we have the required bytes or we transition to // INFLATER_NEEDS_INPUT madeProgress = true; } break; case INFLATER_NEEDS_INPUT: madeProgress = fill(); break; case TRAILER: madeProgress = processTrailer(); break; default: throw new AssertionError("Invalid state: " + state); } } // If we finished a gzip block, check if we have enough bytes to read another header isStalled = !madeProgress || (state == State.HEADER && gzipMetadataReader.readableBytes() < GZIP_HEADER_MIN_SIZE); return bytesRead; }
[ "int", "inflateBytes", "(", "byte", "[", "]", "b", ",", "int", "offset", ",", "int", "length", ")", "throws", "DataFormatException", ",", "ZipException", "{", "checkState", "(", "!", "closed", ",", "\"GzipInflatingBuffer is closed\"", ")", ";", "int", "bytesRead", "=", "0", ";", "int", "missingBytes", ";", "boolean", "madeProgress", "=", "true", ";", "while", "(", "madeProgress", "&&", "(", "missingBytes", "=", "length", "-", "bytesRead", ")", ">", "0", ")", "{", "switch", "(", "state", ")", "{", "case", "HEADER", ":", "madeProgress", "=", "processHeader", "(", ")", ";", "break", ";", "case", "HEADER_EXTRA_LEN", ":", "madeProgress", "=", "processHeaderExtraLen", "(", ")", ";", "break", ";", "case", "HEADER_EXTRA", ":", "madeProgress", "=", "processHeaderExtra", "(", ")", ";", "break", ";", "case", "HEADER_NAME", ":", "madeProgress", "=", "processHeaderName", "(", ")", ";", "break", ";", "case", "HEADER_COMMENT", ":", "madeProgress", "=", "processHeaderComment", "(", ")", ";", "break", ";", "case", "HEADER_CRC", ":", "madeProgress", "=", "processHeaderCrc", "(", ")", ";", "break", ";", "case", "INITIALIZE_INFLATER", ":", "madeProgress", "=", "initializeInflater", "(", ")", ";", "break", ";", "case", "INFLATING", ":", "bytesRead", "+=", "inflate", "(", "b", ",", "offset", "+", "bytesRead", ",", "missingBytes", ")", ";", "if", "(", "state", "==", "State", ".", "TRAILER", ")", "{", "// Eagerly process trailer, if available, to validate CRC.", "madeProgress", "=", "processTrailer", "(", ")", ";", "}", "else", "{", "// Continue in INFLATING until we have the required bytes or we transition to", "// INFLATER_NEEDS_INPUT", "madeProgress", "=", "true", ";", "}", "break", ";", "case", "INFLATER_NEEDS_INPUT", ":", "madeProgress", "=", "fill", "(", ")", ";", "break", ";", "case", "TRAILER", ":", "madeProgress", "=", "processTrailer", "(", ")", ";", "break", ";", "default", ":", "throw", "new", "AssertionError", "(", "\"Invalid state: \"", "+", "state", ")", ";", "}", "}", "// If we finished a gzip block, check if we have enough bytes to read another header", "isStalled", "=", "!", "madeProgress", "||", "(", "state", "==", "State", ".", "HEADER", "&&", "gzipMetadataReader", ".", "readableBytes", "(", ")", "<", "GZIP_HEADER_MIN_SIZE", ")", ";", "return", "bytesRead", ";", "}" ]
Attempts to inflate {@code length} bytes of data into {@code b}. <p>Any gzipped bytes consumed by this method will be added to the counter returned by {@link #getAndResetBytesConsumed()}. This method may consume gzipped bytes without writing any data to {@code b}, and may also write data to {@code b} without consuming additional gzipped bytes (if the inflater on an earlier call consumed the bytes necessary to produce output). @param b the destination array to receive the bytes. @param offset the starting offset in the destination array. @param length the number of bytes to be copied. @throws IndexOutOfBoundsException if {@code b} is too small to hold the requested bytes.
[ "Attempts", "to", "inflate", "{", "@code", "length", "}", "bytes", "of", "data", "into", "{", "@code", "b", "}", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/GzipInflatingBuffer.java#L260-L316
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.minus
public static Number minus(Character left, Number right) { """ Subtract a Number from a Character. The ordinal value of the Character is used in the subtraction (the ordinal value is the unicode value which for simple character sets is the ASCII value). @param left a Character @param right a Number @return the Number corresponding to the subtraction of right from left @since 1.0 """ return NumberNumberMinus.minus(Integer.valueOf(left), right); }
java
public static Number minus(Character left, Number right) { return NumberNumberMinus.minus(Integer.valueOf(left), right); }
[ "public", "static", "Number", "minus", "(", "Character", "left", ",", "Number", "right", ")", "{", "return", "NumberNumberMinus", ".", "minus", "(", "Integer", ".", "valueOf", "(", "left", ")", ",", "right", ")", ";", "}" ]
Subtract a Number from a Character. The ordinal value of the Character is used in the subtraction (the ordinal value is the unicode value which for simple character sets is the ASCII value). @param left a Character @param right a Number @return the Number corresponding to the subtraction of right from left @since 1.0
[ "Subtract", "a", "Number", "from", "a", "Character", ".", "The", "ordinal", "value", "of", "the", "Character", "is", "used", "in", "the", "subtraction", "(", "the", "ordinal", "value", "is", "the", "unicode", "value", "which", "for", "simple", "character", "sets", "is", "the", "ASCII", "value", ")", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L15112-L15114
cuba-platform/yarg
core/modules/core/src/com/haulmont/yarg/util/db/QueryRunner.java
QueryRunner.prepareStatement
protected PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException { """ Factory method that creates and initializes a <code>PreparedStatement</code> object for the given SQL. <code>QueryRunner</code> methods always call this method to prepare statements for them. Subclasses can override this method to provide special PreparedStatement configuration if needed. This implementation simply calls <code>conn.prepareStatement(sql)</code>. @param conn The <code>Connection</code> used to create the <code>PreparedStatement</code> @param sql The SQL statement to prepare. @return An initialized <code>PreparedStatement</code>. @throws java.sql.SQLException if a database access error occurs """ return conn.prepareStatement(sql); }
java
protected PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException { return conn.prepareStatement(sql); }
[ "protected", "PreparedStatement", "prepareStatement", "(", "Connection", "conn", ",", "String", "sql", ")", "throws", "SQLException", "{", "return", "conn", ".", "prepareStatement", "(", "sql", ")", ";", "}" ]
Factory method that creates and initializes a <code>PreparedStatement</code> object for the given SQL. <code>QueryRunner</code> methods always call this method to prepare statements for them. Subclasses can override this method to provide special PreparedStatement configuration if needed. This implementation simply calls <code>conn.prepareStatement(sql)</code>. @param conn The <code>Connection</code> used to create the <code>PreparedStatement</code> @param sql The SQL statement to prepare. @return An initialized <code>PreparedStatement</code>. @throws java.sql.SQLException if a database access error occurs
[ "Factory", "method", "that", "creates", "and", "initializes", "a", "<code", ">", "PreparedStatement<", "/", "code", ">", "object", "for", "the", "given", "SQL", ".", "<code", ">", "QueryRunner<", "/", "code", ">", "methods", "always", "call", "this", "method", "to", "prepare", "statements", "for", "them", ".", "Subclasses", "can", "override", "this", "method", "to", "provide", "special", "PreparedStatement", "configuration", "if", "needed", ".", "This", "implementation", "simply", "calls", "<code", ">", "conn", ".", "prepareStatement", "(", "sql", ")", "<", "/", "code", ">", "." ]
train
https://github.com/cuba-platform/yarg/blob/d157286cbe29448f3e1f445e8c5dd88808351da0/core/modules/core/src/com/haulmont/yarg/util/db/QueryRunner.java#L228-L232
realtime-framework/RealtimeStorage-Android
library/src/main/java/co/realtime/storage/TableRef.java
TableRef.greaterEqual
public TableRef greaterEqual(String attributeName, ItemAttribute value) { """ Applies a filter to the table. When fetched, it will return the items greater or equal to filter property value. <pre> StorageRef storage = new StorageRef("your_app_key", "your_token"); TableRef tableRef = tableRef = storage.table("your_table"); // Retrieve all items that have their "itemProperty" value greater or equal to 10 tableRef.greaterEqual("itemProperty",new ItemAttribute(10)).getItems(new OnItemSnapshot() { &#064;Override public void run(ItemSnapshot itemSnapshot) { if (itemSnapshot != null) { Log.d("TableRef", "Item retrieved: " + itemSnapshot.val()); } } }, new OnError() { &#064;Override public void run(Integer code, String errorMessage) { Log.e("TableRef", "Error retrieving items: " + errorMessage); } }); </pre> @param attributeName The name of the property to filter. @param value The value of the property to filter. @return Current table reference """ filters.add(new Filter(StorageFilter.GREATEREQUAL, attributeName, value, null)); return this; }
java
public TableRef greaterEqual(String attributeName, ItemAttribute value){ filters.add(new Filter(StorageFilter.GREATEREQUAL, attributeName, value, null)); return this; }
[ "public", "TableRef", "greaterEqual", "(", "String", "attributeName", ",", "ItemAttribute", "value", ")", "{", "filters", ".", "add", "(", "new", "Filter", "(", "StorageFilter", ".", "GREATEREQUAL", ",", "attributeName", ",", "value", ",", "null", ")", ")", ";", "return", "this", ";", "}" ]
Applies a filter to the table. When fetched, it will return the items greater or equal to filter property value. <pre> StorageRef storage = new StorageRef("your_app_key", "your_token"); TableRef tableRef = tableRef = storage.table("your_table"); // Retrieve all items that have their "itemProperty" value greater or equal to 10 tableRef.greaterEqual("itemProperty",new ItemAttribute(10)).getItems(new OnItemSnapshot() { &#064;Override public void run(ItemSnapshot itemSnapshot) { if (itemSnapshot != null) { Log.d("TableRef", "Item retrieved: " + itemSnapshot.val()); } } }, new OnError() { &#064;Override public void run(Integer code, String errorMessage) { Log.e("TableRef", "Error retrieving items: " + errorMessage); } }); </pre> @param attributeName The name of the property to filter. @param value The value of the property to filter. @return Current table reference
[ "Applies", "a", "filter", "to", "the", "table", ".", "When", "fetched", "it", "will", "return", "the", "items", "greater", "or", "equal", "to", "filter", "property", "value", "." ]
train
https://github.com/realtime-framework/RealtimeStorage-Android/blob/05816a6b7a6dcc83f9e7400ac3048494dadca302/library/src/main/java/co/realtime/storage/TableRef.java#L658-L661
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Calendar.java
Calendar.floorDivide
protected static final int floorDivide(int numerator, int denominator, int[] remainder) { """ Divide two integers, returning the floor of the quotient, and the modulus remainder. <p> Unlike the built-in division, this is mathematically well-behaved. E.g., <code>-1/4</code> =&gt; 0 and <code>-1%4</code> =&gt; -1, but <code>floorDivide(-1,4)</code> =&gt; -1 with <code>remainder[0]</code> =&gt; 3. @param numerator the numerator @param denominator a divisor which must be &gt; 0 @param remainder an array of at least one element in which the value <code>numerator mod denominator</code> is returned. Unlike <code>numerator % denominator</code>, this will always be non-negative. @return the floor of the quotient. """ if (numerator >= 0) { remainder[0] = numerator % denominator; return numerator / denominator; } int quotient = ((numerator + 1) / denominator) - 1; remainder[0] = numerator - (quotient * denominator); return quotient; }
java
protected static final int floorDivide(int numerator, int denominator, int[] remainder) { if (numerator >= 0) { remainder[0] = numerator % denominator; return numerator / denominator; } int quotient = ((numerator + 1) / denominator) - 1; remainder[0] = numerator - (quotient * denominator); return quotient; }
[ "protected", "static", "final", "int", "floorDivide", "(", "int", "numerator", ",", "int", "denominator", ",", "int", "[", "]", "remainder", ")", "{", "if", "(", "numerator", ">=", "0", ")", "{", "remainder", "[", "0", "]", "=", "numerator", "%", "denominator", ";", "return", "numerator", "/", "denominator", ";", "}", "int", "quotient", "=", "(", "(", "numerator", "+", "1", ")", "/", "denominator", ")", "-", "1", ";", "remainder", "[", "0", "]", "=", "numerator", "-", "(", "quotient", "*", "denominator", ")", ";", "return", "quotient", ";", "}" ]
Divide two integers, returning the floor of the quotient, and the modulus remainder. <p> Unlike the built-in division, this is mathematically well-behaved. E.g., <code>-1/4</code> =&gt; 0 and <code>-1%4</code> =&gt; -1, but <code>floorDivide(-1,4)</code> =&gt; -1 with <code>remainder[0]</code> =&gt; 3. @param numerator the numerator @param denominator a divisor which must be &gt; 0 @param remainder an array of at least one element in which the value <code>numerator mod denominator</code> is returned. Unlike <code>numerator % denominator</code>, this will always be non-negative. @return the floor of the quotient.
[ "Divide", "two", "integers", "returning", "the", "floor", "of", "the", "quotient", "and", "the", "modulus", "remainder", ".", "<p", ">", "Unlike", "the", "built", "-", "in", "division", "this", "is", "mathematically", "well", "-", "behaved", ".", "E", ".", "g", ".", "<code", ">", "-", "1", "/", "4<", "/", "code", ">", "=", "&gt", ";", "0", "and", "<code", ">", "-", "1%4<", "/", "code", ">", "=", "&gt", ";", "-", "1", "but", "<code", ">", "floorDivide", "(", "-", "1", "4", ")", "<", "/", "code", ">", "=", "&gt", ";", "-", "1", "with", "<code", ">", "remainder", "[", "0", "]", "<", "/", "code", ">", "=", "&gt", ";", "3", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/Calendar.java#L6079-L6087
webmetrics/browsermob-proxy
src/main/java/org/java_bandwidthlimiter/StreamManager.java
StreamManager.setMaxBitsPerSecondThreshold
public void setMaxBitsPerSecondThreshold(long maxBitsPerSecond) { """ This function sets the max bits per second threshold {@link #setDownstreamKbps} and {@link #setDownstreamKbps(long)} won't be allowed to set a bandwidth higher than what specified here. @param maxBitsPerSecond The max bits per seconds you want this instance of StreamManager to respect. """ //setting the maximimum threshold of bits per second that //we can send EVER in upstream/downstream //the user can later decrease this value but not increment it this.maxBytesPerSecond = maxBitsPerSecond/8; //make sure the streams parameters honor the new max limit setMaxBps(this.downStream, this.downStream.maxBps); setMaxBps(this.upStream, this.upStream.maxBps); }
java
public void setMaxBitsPerSecondThreshold(long maxBitsPerSecond) { //setting the maximimum threshold of bits per second that //we can send EVER in upstream/downstream //the user can later decrease this value but not increment it this.maxBytesPerSecond = maxBitsPerSecond/8; //make sure the streams parameters honor the new max limit setMaxBps(this.downStream, this.downStream.maxBps); setMaxBps(this.upStream, this.upStream.maxBps); }
[ "public", "void", "setMaxBitsPerSecondThreshold", "(", "long", "maxBitsPerSecond", ")", "{", "//setting the maximimum threshold of bits per second that", "//we can send EVER in upstream/downstream", "//the user can later decrease this value but not increment it", "this", ".", "maxBytesPerSecond", "=", "maxBitsPerSecond", "/", "8", ";", "//make sure the streams parameters honor the new max limit", "setMaxBps", "(", "this", ".", "downStream", ",", "this", ".", "downStream", ".", "maxBps", ")", ";", "setMaxBps", "(", "this", ".", "upStream", ",", "this", ".", "upStream", ".", "maxBps", ")", ";", "}" ]
This function sets the max bits per second threshold {@link #setDownstreamKbps} and {@link #setDownstreamKbps(long)} won't be allowed to set a bandwidth higher than what specified here. @param maxBitsPerSecond The max bits per seconds you want this instance of StreamManager to respect.
[ "This", "function", "sets", "the", "max", "bits", "per", "second", "threshold", "{" ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/java_bandwidthlimiter/StreamManager.java#L205-L213
katjahahn/PortEx
src/main/java/com/github/katjahahn/parser/msdos/MSDOSHeader.java
MSDOSHeader.newInstance
public static MSDOSHeader newInstance(byte[] headerbytes, long peSigOffset) throws IOException { """ Creates and returns an instance of the MSDOSHeader with the given bytes and the file offset of the PE signature. @param headerbytes the bytes that make up the MSDOSHeader @param peSigOffset file offset to the PE signature @return MSDOSHeader instance @throws IOException if header can not be read. """ MSDOSHeader header = new MSDOSHeader(headerbytes, peSigOffset); header.read(); return header; }
java
public static MSDOSHeader newInstance(byte[] headerbytes, long peSigOffset) throws IOException { MSDOSHeader header = new MSDOSHeader(headerbytes, peSigOffset); header.read(); return header; }
[ "public", "static", "MSDOSHeader", "newInstance", "(", "byte", "[", "]", "headerbytes", ",", "long", "peSigOffset", ")", "throws", "IOException", "{", "MSDOSHeader", "header", "=", "new", "MSDOSHeader", "(", "headerbytes", ",", "peSigOffset", ")", ";", "header", ".", "read", "(", ")", ";", "return", "header", ";", "}" ]
Creates and returns an instance of the MSDOSHeader with the given bytes and the file offset of the PE signature. @param headerbytes the bytes that make up the MSDOSHeader @param peSigOffset file offset to the PE signature @return MSDOSHeader instance @throws IOException if header can not be read.
[ "Creates", "and", "returns", "an", "instance", "of", "the", "MSDOSHeader", "with", "the", "given", "bytes", "and", "the", "file", "offset", "of", "the", "PE", "signature", "." ]
train
https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/parser/msdos/MSDOSHeader.java#L205-L210
kiegroup/jbpm
jbpm-bpmn2-emfextmodel/src/main/java/org/omg/spec/bpmn/non/normative/color/util/ColorSwitch.java
ColorSwitch.doSwitch
protected T doSwitch(int classifierID, EObject theEObject) { """ Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. <!-- begin-user-doc --> <!-- end-user-doc --> @return the first non-null result returned by a <code>caseXXX</code> call. @generated """ switch (classifierID) { case ColorPackage.DOCUMENT_ROOT: { DocumentRoot documentRoot = (DocumentRoot)theEObject; T result = caseDocumentRoot(documentRoot); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } }
java
protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case ColorPackage.DOCUMENT_ROOT: { DocumentRoot documentRoot = (DocumentRoot)theEObject; T result = caseDocumentRoot(documentRoot); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } }
[ "protected", "T", "doSwitch", "(", "int", "classifierID", ",", "EObject", "theEObject", ")", "{", "switch", "(", "classifierID", ")", "{", "case", "ColorPackage", ".", "DOCUMENT_ROOT", ":", "{", "DocumentRoot", "documentRoot", "=", "(", "DocumentRoot", ")", "theEObject", ";", "T", "result", "=", "caseDocumentRoot", "(", "documentRoot", ")", ";", "if", "(", "result", "==", "null", ")", "result", "=", "defaultCase", "(", "theEObject", ")", ";", "return", "result", ";", "}", "default", ":", "return", "defaultCase", "(", "theEObject", ")", ";", "}", "}" ]
Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. <!-- begin-user-doc --> <!-- end-user-doc --> @return the first non-null result returned by a <code>caseXXX</code> call. @generated
[ "Calls", "<code", ">", "caseXXX<", "/", "code", ">", "for", "each", "class", "of", "the", "model", "until", "one", "returns", "a", "non", "null", "result", ";", "it", "yields", "that", "result", ".", "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "<!", "--", "end", "-", "user", "-", "doc", "--", ">" ]
train
https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-bpmn2-emfextmodel/src/main/java/org/omg/spec/bpmn/non/normative/color/util/ColorSwitch.java#L100-L110
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java
ConditionalCheck.notEmpty
@ArgumentsChecked @Throws( { """ Ensures that a passed collection as a parameter of the calling method is not empty. <p> We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument the name of the parameter to enhance the exception message. @param condition condition must be {@code true}^ so that the check will be performed @param collection a collection which should not be empty @throws IllegalNullArgumentException if the given argument {@code collection} is {@code null} @throws IllegalEmptyArgumentException if the given argument {@code collection} is empty """ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> void notEmpty(final boolean condition, @Nonnull final T collection) { if (condition) { Check.notEmpty(collection); } }
java
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T extends Collection<?>> void notEmpty(final boolean condition, @Nonnull final T collection) { if (condition) { Check.notEmpty(collection); } }
[ "@", "ArgumentsChecked", "@", "Throws", "(", "{", "IllegalNullArgumentException", ".", "class", ",", "IllegalEmptyArgumentException", ".", "class", "}", ")", "public", "static", "<", "T", "extends", "Collection", "<", "?", ">", ">", "void", "notEmpty", "(", "final", "boolean", "condition", ",", "@", "Nonnull", "final", "T", "collection", ")", "{", "if", "(", "condition", ")", "{", "Check", ".", "notEmpty", "(", "collection", ")", ";", "}", "}" ]
Ensures that a passed collection as a parameter of the calling method is not empty. <p> We recommend to use the overloaded method {@link Check#notEmpty(Collection, String)} and pass as second argument the name of the parameter to enhance the exception message. @param condition condition must be {@code true}^ so that the check will be performed @param collection a collection which should not be empty @throws IllegalNullArgumentException if the given argument {@code collection} is {@code null} @throws IllegalEmptyArgumentException if the given argument {@code collection} is empty
[ "Ensures", "that", "a", "passed", "collection", "as", "a", "parameter", "of", "the", "calling", "method", "is", "not", "empty", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java#L1233-L1239
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java
JobsInner.getRunbookContent
public InputStream getRunbookContent(String resourceGroupName, String automationAccountName, String jobId) { """ Retrieve the runbook content of the job identified by job id. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param jobId The job id. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the InputStream object if successful. """ return getRunbookContentWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).toBlocking().single().body(); }
java
public InputStream getRunbookContent(String resourceGroupName, String automationAccountName, String jobId) { return getRunbookContentWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).toBlocking().single().body(); }
[ "public", "InputStream", "getRunbookContent", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "jobId", ")", "{", "return", "getRunbookContentWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "jobId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Retrieve the runbook content of the job identified by job id. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param jobId The job id. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the InputStream object if successful.
[ "Retrieve", "the", "runbook", "content", "of", "the", "job", "identified", "by", "job", "id", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/JobsInner.java#L210-L212
motown-io/motown
ocpp/v15-soap/src/main/java/io/motown/ocpp/v15/soap/chargepoint/IdentifyingTokenConverterService.java
IdentifyingTokenConverterService.convertIdentifyingToken
public AuthorisationData convertIdentifyingToken(IdentifyingToken token) { """ Converts a {@code IdentifyingToken} to a {@code AuthorisationData} object. If the authentication status is not null or DELETED then the IdTagInfo will be set based on the authentication status. @param token identifying token. @return authorisation data object. """ AuthorisationData authData = new AuthorisationData(); authData.setIdTag(token.getToken()); //The OCPP spec describes that the IdTagInfo should not be present in case the charging station has to remove the entry from the list IdentifyingToken.AuthenticationStatus status = token.getAuthenticationStatus(); if (status != null && !IdentifyingToken.AuthenticationStatus.DELETED.equals(status)) { IdTagInfo info = new IdTagInfo(); switch (token.getAuthenticationStatus()) { case ACCEPTED: info.setStatus(AuthorizationStatus.ACCEPTED); break; case BLOCKED: info.setStatus(AuthorizationStatus.BLOCKED); break; case EXPIRED: info.setStatus(AuthorizationStatus.EXPIRED); break; case INVALID: info.setStatus(AuthorizationStatus.INVALID); break; case CONCURRENT_TX: info.setStatus(AuthorizationStatus.CONCURRENT_TX); break; default: throw new AssertionError(String.format("Unknown authentication status [%s] in given identifying token [%s].", token.getAuthenticationStatus(), token.getToken())); } authData.setIdTagInfo(info); } return authData; }
java
public AuthorisationData convertIdentifyingToken(IdentifyingToken token) { AuthorisationData authData = new AuthorisationData(); authData.setIdTag(token.getToken()); //The OCPP spec describes that the IdTagInfo should not be present in case the charging station has to remove the entry from the list IdentifyingToken.AuthenticationStatus status = token.getAuthenticationStatus(); if (status != null && !IdentifyingToken.AuthenticationStatus.DELETED.equals(status)) { IdTagInfo info = new IdTagInfo(); switch (token.getAuthenticationStatus()) { case ACCEPTED: info.setStatus(AuthorizationStatus.ACCEPTED); break; case BLOCKED: info.setStatus(AuthorizationStatus.BLOCKED); break; case EXPIRED: info.setStatus(AuthorizationStatus.EXPIRED); break; case INVALID: info.setStatus(AuthorizationStatus.INVALID); break; case CONCURRENT_TX: info.setStatus(AuthorizationStatus.CONCURRENT_TX); break; default: throw new AssertionError(String.format("Unknown authentication status [%s] in given identifying token [%s].", token.getAuthenticationStatus(), token.getToken())); } authData.setIdTagInfo(info); } return authData; }
[ "public", "AuthorisationData", "convertIdentifyingToken", "(", "IdentifyingToken", "token", ")", "{", "AuthorisationData", "authData", "=", "new", "AuthorisationData", "(", ")", ";", "authData", ".", "setIdTag", "(", "token", ".", "getToken", "(", ")", ")", ";", "//The OCPP spec describes that the IdTagInfo should not be present in case the charging station has to remove the entry from the list", "IdentifyingToken", ".", "AuthenticationStatus", "status", "=", "token", ".", "getAuthenticationStatus", "(", ")", ";", "if", "(", "status", "!=", "null", "&&", "!", "IdentifyingToken", ".", "AuthenticationStatus", ".", "DELETED", ".", "equals", "(", "status", ")", ")", "{", "IdTagInfo", "info", "=", "new", "IdTagInfo", "(", ")", ";", "switch", "(", "token", ".", "getAuthenticationStatus", "(", ")", ")", "{", "case", "ACCEPTED", ":", "info", ".", "setStatus", "(", "AuthorizationStatus", ".", "ACCEPTED", ")", ";", "break", ";", "case", "BLOCKED", ":", "info", ".", "setStatus", "(", "AuthorizationStatus", ".", "BLOCKED", ")", ";", "break", ";", "case", "EXPIRED", ":", "info", ".", "setStatus", "(", "AuthorizationStatus", ".", "EXPIRED", ")", ";", "break", ";", "case", "INVALID", ":", "info", ".", "setStatus", "(", "AuthorizationStatus", ".", "INVALID", ")", ";", "break", ";", "case", "CONCURRENT_TX", ":", "info", ".", "setStatus", "(", "AuthorizationStatus", ".", "CONCURRENT_TX", ")", ";", "break", ";", "default", ":", "throw", "new", "AssertionError", "(", "String", ".", "format", "(", "\"Unknown authentication status [%s] in given identifying token [%s].\"", ",", "token", ".", "getAuthenticationStatus", "(", ")", ",", "token", ".", "getToken", "(", ")", ")", ")", ";", "}", "authData", ".", "setIdTagInfo", "(", "info", ")", ";", "}", "return", "authData", ";", "}" ]
Converts a {@code IdentifyingToken} to a {@code AuthorisationData} object. If the authentication status is not null or DELETED then the IdTagInfo will be set based on the authentication status. @param token identifying token. @return authorisation data object.
[ "Converts", "a", "{", "@code", "IdentifyingToken", "}", "to", "a", "{", "@code", "AuthorisationData", "}", "object", ".", "If", "the", "authentication", "status", "is", "not", "null", "or", "DELETED", "then", "the", "IdTagInfo", "will", "be", "set", "based", "on", "the", "authentication", "status", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/v15-soap/src/main/java/io/motown/ocpp/v15/soap/chargepoint/IdentifyingTokenConverterService.java#L51-L82
BlueBrain/bluima
modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/parser/ParserEventStream.java
ParserEventStream.firstChild
private boolean firstChild(Parse child, Parse parent) { """ Returns true if the specified child is the first child of the specified parent. @param child The child parse. @param parent The parent parse. @return true if the specified child is the first child of the specified parent; false otherwise. """ return ParserME.collapsePunctuation(parent.getChildren(),punctSet)[0] == child; }
java
private boolean firstChild(Parse child, Parse parent) { return ParserME.collapsePunctuation(parent.getChildren(),punctSet)[0] == child; }
[ "private", "boolean", "firstChild", "(", "Parse", "child", ",", "Parse", "parent", ")", "{", "return", "ParserME", ".", "collapsePunctuation", "(", "parent", ".", "getChildren", "(", ")", ",", "punctSet", ")", "[", "0", "]", "==", "child", ";", "}" ]
Returns true if the specified child is the first child of the specified parent. @param child The child parse. @param parent The parent parse. @return true if the specified child is the first child of the specified parent; false otherwise.
[ "Returns", "true", "if", "the", "specified", "child", "is", "the", "first", "child", "of", "the", "specified", "parent", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/tools/parser/ParserEventStream.java#L137-L139
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/synthetic/SyntheticStorableReferenceAccess.java
SyntheticStorableReferenceAccess.copyToMasterPrimaryKey
public void copyToMasterPrimaryKey(Storable reference, S master) throws FetchException { """ Sets all the primary key properties of the given master, using the applicable properties of the given reference. @param reference source of property values @param master master whose primary key properties will be set """ try { mCopyToMasterPkMethod.invoke(reference, master); } catch (Exception e) { ThrowUnchecked.fireFirstDeclaredCause(e, FetchException.class); } }
java
public void copyToMasterPrimaryKey(Storable reference, S master) throws FetchException { try { mCopyToMasterPkMethod.invoke(reference, master); } catch (Exception e) { ThrowUnchecked.fireFirstDeclaredCause(e, FetchException.class); } }
[ "public", "void", "copyToMasterPrimaryKey", "(", "Storable", "reference", ",", "S", "master", ")", "throws", "FetchException", "{", "try", "{", "mCopyToMasterPkMethod", ".", "invoke", "(", "reference", ",", "master", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "ThrowUnchecked", ".", "fireFirstDeclaredCause", "(", "e", ",", "FetchException", ".", "class", ")", ";", "}", "}" ]
Sets all the primary key properties of the given master, using the applicable properties of the given reference. @param reference source of property values @param master master whose primary key properties will be set
[ "Sets", "all", "the", "primary", "key", "properties", "of", "the", "given", "master", "using", "the", "applicable", "properties", "of", "the", "given", "reference", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/synthetic/SyntheticStorableReferenceAccess.java#L113-L119
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.orthoSymmetric
public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { """ Apply a symmetric orthographic projection transformation for a right-handed coordinate system using the given NDC z range to this matrix and store the result in <code>dest</code>. <p> This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, boolean, Matrix4f) ortho()} with <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, then the new matrix will be <code>M * O</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the orthographic projection transformation will be applied first! <p> In order to set the matrix to a symmetric orthographic projection without post-multiplying it, use {@link #setOrthoSymmetric(float, float, float, float, boolean) setOrthoSymmetric()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #setOrthoSymmetric(float, float, float, float, boolean) @param width the distance between the right and left frustum edges @param height the distance between the top and bottom frustum edges @param zNear near clipping plane distance @param zFar far clipping plane distance @param dest will hold the result @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return dest """ if ((properties & PROPERTY_IDENTITY) != 0) return dest.setOrthoSymmetric(width, height, zNear, zFar, zZeroToOne); return orthoSymmetricGeneric(width, height, zNear, zFar, zZeroToOne, dest); }
java
public Matrix4f orthoSymmetric(float width, float height, float zNear, float zFar, boolean zZeroToOne, Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.setOrthoSymmetric(width, height, zNear, zFar, zZeroToOne); return orthoSymmetricGeneric(width, height, zNear, zFar, zZeroToOne, dest); }
[ "public", "Matrix4f", "orthoSymmetric", "(", "float", "width", ",", "float", "height", ",", "float", "zNear", ",", "float", "zFar", ",", "boolean", "zZeroToOne", ",", "Matrix4f", "dest", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "!=", "0", ")", "return", "dest", ".", "setOrthoSymmetric", "(", "width", ",", "height", ",", "zNear", ",", "zFar", ",", "zZeroToOne", ")", ";", "return", "orthoSymmetricGeneric", "(", "width", ",", "height", ",", "zNear", ",", "zFar", ",", "zZeroToOne", ",", "dest", ")", ";", "}" ]
Apply a symmetric orthographic projection transformation for a right-handed coordinate system using the given NDC z range to this matrix and store the result in <code>dest</code>. <p> This method is equivalent to calling {@link #ortho(float, float, float, float, float, float, boolean, Matrix4f) ortho()} with <code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix, then the new matrix will be <code>M * O</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the orthographic projection transformation will be applied first! <p> In order to set the matrix to a symmetric orthographic projection without post-multiplying it, use {@link #setOrthoSymmetric(float, float, float, float, boolean) setOrthoSymmetric()}. <p> Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a> @see #setOrthoSymmetric(float, float, float, float, boolean) @param width the distance between the right and left frustum edges @param height the distance between the top and bottom frustum edges @param zNear near clipping plane distance @param zFar far clipping plane distance @param dest will hold the result @param zZeroToOne whether to use Vulkan's and Direct3D's NDC z range of <code>[0..+1]</code> when <code>true</code> or whether to use OpenGL's NDC z range of <code>[-1..+1]</code> when <code>false</code> @return dest
[ "Apply", "a", "symmetric", "orthographic", "projection", "transformation", "for", "a", "right", "-", "handed", "coordinate", "system", "using", "the", "given", "NDC", "z", "range", "to", "this", "matrix", "and", "store", "the", "result", "in", "<code", ">", "dest<", "/", "code", ">", ".", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", "{", "@link", "#ortho", "(", "float", "float", "float", "float", "float", "float", "boolean", "Matrix4f", ")", "ortho", "()", "}", "with", "<code", ">", "left", "=", "-", "width", "/", "2<", "/", "code", ">", "<code", ">", "right", "=", "+", "width", "/", "2<", "/", "code", ">", "<code", ">", "bottom", "=", "-", "height", "/", "2<", "/", "code", ">", "and", "<code", ">", "top", "=", "+", "height", "/", "2<", "/", "code", ">", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "O<", "/", "code", ">", "the", "orthographic", "projection", "matrix", "then", "the", "new", "matrix", "will", "be", "<code", ">", "M", "*", "O<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "M", "*", "O", "*", "v<", "/", "code", ">", "the", "orthographic", "projection", "transformation", "will", "be", "applied", "first!", "<p", ">", "In", "order", "to", "set", "the", "matrix", "to", "a", "symmetric", "orthographic", "projection", "without", "post", "-", "multiplying", "it", "use", "{", "@link", "#setOrthoSymmetric", "(", "float", "float", "float", "float", "boolean", ")", "setOrthoSymmetric", "()", "}", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "www", ".", "songho", ".", "ca", "/", "opengl", "/", "gl_projectionmatrix", ".", "html#ortho", ">", "http", ":", "//", "www", ".", "songho", ".", "ca<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L7334-L7338
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer/src/com/ibm/ws/ejbcontainer/osgi/internal/NameSpaceBinderImpl.java
NameSpaceBinderImpl.bindJavaGlobal
@Override public void bindJavaGlobal(String name, EJBBinding bindingObject) { """ Adds the EJB reference for later lookup in the java:global name space. @param name The lookup name. @param bindingObject The binding information. """ String bindingName = buildJavaGlobalName(name); ejbJavaColonHelper.addGlobalBinding(bindingName, bindingObject); }
java
@Override public void bindJavaGlobal(String name, EJBBinding bindingObject) { String bindingName = buildJavaGlobalName(name); ejbJavaColonHelper.addGlobalBinding(bindingName, bindingObject); }
[ "@", "Override", "public", "void", "bindJavaGlobal", "(", "String", "name", ",", "EJBBinding", "bindingObject", ")", "{", "String", "bindingName", "=", "buildJavaGlobalName", "(", "name", ")", ";", "ejbJavaColonHelper", ".", "addGlobalBinding", "(", "bindingName", ",", "bindingObject", ")", ";", "}" ]
Adds the EJB reference for later lookup in the java:global name space. @param name The lookup name. @param bindingObject The binding information.
[ "Adds", "the", "EJB", "reference", "for", "later", "lookup", "in", "the", "java", ":", "global", "name", "space", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer/src/com/ibm/ws/ejbcontainer/osgi/internal/NameSpaceBinderImpl.java#L84-L88
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/effect/SeaGlassInternalShadowEffect.java
SeaGlassInternalShadowEffect.fillInternalShadowRounded
private void fillInternalShadowRounded(Graphics2D g, Shape s) { """ Fill a rounded shadow. @param g the Graphics context to paint with. @param s the shape to fill. This is only used for its bounds. """ g.setPaint(getRoundedShadowGradient(s)); g.fill(s); }
java
private void fillInternalShadowRounded(Graphics2D g, Shape s) { g.setPaint(getRoundedShadowGradient(s)); g.fill(s); }
[ "private", "void", "fillInternalShadowRounded", "(", "Graphics2D", "g", ",", "Shape", "s", ")", "{", "g", ".", "setPaint", "(", "getRoundedShadowGradient", "(", "s", ")", ")", ";", "g", ".", "fill", "(", "s", ")", ";", "}" ]
Fill a rounded shadow. @param g the Graphics context to paint with. @param s the shape to fill. This is only used for its bounds.
[ "Fill", "a", "rounded", "shadow", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/effect/SeaGlassInternalShadowEffect.java#L110-L113
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java
BikeCommonFlagEncoder.applyMaxSpeed
@Override protected double applyMaxSpeed(ReaderWay way, double speed) { """ Apply maxspeed: In contrast to the implementation of the AbstractFlagEncoder, we assume that we can reach the maxspeed for bicycles in case that the road type speed is higher and not just only 90%. @param way needed to retrieve tags @param speed speed guessed e.g. from the road type or other tags @return The assumed average speed. """ double maxSpeed = getMaxSpeed(way); if (maxSpeed >= 0) { // We strictly obey speed limits, see #600 if (speed > maxSpeed) return maxSpeed; } if (speed > maxPossibleSpeed) return maxPossibleSpeed; return speed; }
java
@Override protected double applyMaxSpeed(ReaderWay way, double speed) { double maxSpeed = getMaxSpeed(way); if (maxSpeed >= 0) { // We strictly obey speed limits, see #600 if (speed > maxSpeed) return maxSpeed; } if (speed > maxPossibleSpeed) return maxPossibleSpeed; return speed; }
[ "@", "Override", "protected", "double", "applyMaxSpeed", "(", "ReaderWay", "way", ",", "double", "speed", ")", "{", "double", "maxSpeed", "=", "getMaxSpeed", "(", "way", ")", ";", "if", "(", "maxSpeed", ">=", "0", ")", "{", "// We strictly obey speed limits, see #600", "if", "(", "speed", ">", "maxSpeed", ")", "return", "maxSpeed", ";", "}", "if", "(", "speed", ">", "maxPossibleSpeed", ")", "return", "maxPossibleSpeed", ";", "return", "speed", ";", "}" ]
Apply maxspeed: In contrast to the implementation of the AbstractFlagEncoder, we assume that we can reach the maxspeed for bicycles in case that the road type speed is higher and not just only 90%. @param way needed to retrieve tags @param speed speed guessed e.g. from the road type or other tags @return The assumed average speed.
[ "Apply", "maxspeed", ":", "In", "contrast", "to", "the", "implementation", "of", "the", "AbstractFlagEncoder", "we", "assume", "that", "we", "can", "reach", "the", "maxspeed", "for", "bicycles", "in", "case", "that", "the", "road", "type", "speed", "is", "higher", "and", "not", "just", "only", "90%", "." ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/BikeCommonFlagEncoder.java#L328-L339
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.rotateAround
public Matrix4f rotateAround(Quaternionfc quat, float ox, float oy, float oz) { """ Apply the rotation transformation of the given {@link Quaternionfc} to this matrix while using <code>(ox, oy, oz)</code> as the rotation origin. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, then the new matrix will be <code>M * Q</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, the quaternion rotation will be applied first! <p> This method is equivalent to calling: <code>translate(ox, oy, oz).rotate(quat).translate(-ox, -oy, -oz)</code> <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> @param quat the {@link Quaternionfc} @param ox the x coordinate of the rotation origin @param oy the y coordinate of the rotation origin @param oz the z coordinate of the rotation origin @return a matrix holding the result """ return rotateAround(quat, ox, oy, oz, thisOrNew()); }
java
public Matrix4f rotateAround(Quaternionfc quat, float ox, float oy, float oz) { return rotateAround(quat, ox, oy, oz, thisOrNew()); }
[ "public", "Matrix4f", "rotateAround", "(", "Quaternionfc", "quat", ",", "float", "ox", ",", "float", "oy", ",", "float", "oz", ")", "{", "return", "rotateAround", "(", "quat", ",", "ox", ",", "oy", ",", "oz", ",", "thisOrNew", "(", ")", ")", ";", "}" ]
Apply the rotation transformation of the given {@link Quaternionfc} to this matrix while using <code>(ox, oy, oz)</code> as the rotation origin. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>Q</code> the rotation matrix obtained from the given quaternion, then the new matrix will be <code>M * Q</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * Q * v</code>, the quaternion rotation will be applied first! <p> This method is equivalent to calling: <code>translate(ox, oy, oz).rotate(quat).translate(-ox, -oy, -oz)</code> <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a> @param quat the {@link Quaternionfc} @param ox the x coordinate of the rotation origin @param oy the y coordinate of the rotation origin @param oz the z coordinate of the rotation origin @return a matrix holding the result
[ "Apply", "the", "rotation", "transformation", "of", "the", "given", "{", "@link", "Quaternionfc", "}", "to", "this", "matrix", "while", "using", "<code", ">", "(", "ox", "oy", "oz", ")", "<", "/", "code", ">", "as", "the", "rotation", "origin", ".", "<p", ">", "When", "used", "with", "a", "right", "-", "handed", "coordinate", "system", "the", "produced", "rotation", "will", "rotate", "a", "vector", "counter", "-", "clockwise", "around", "the", "rotation", "axis", "when", "viewing", "along", "the", "negative", "axis", "direction", "towards", "the", "origin", ".", "When", "used", "with", "a", "left", "-", "handed", "coordinate", "system", "the", "rotation", "is", "clockwise", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is", "<code", ">", "this<", "/", "code", ">", "matrix", "and", "<code", ">", "Q<", "/", "code", ">", "the", "rotation", "matrix", "obtained", "from", "the", "given", "quaternion", "then", "the", "new", "matrix", "will", "be", "<code", ">", "M", "*", "Q<", "/", "code", ">", ".", "So", "when", "transforming", "a", "vector", "<code", ">", "v<", "/", "code", ">", "with", "the", "new", "matrix", "by", "using", "<code", ">", "M", "*", "Q", "*", "v<", "/", "code", ">", "the", "quaternion", "rotation", "will", "be", "applied", "first!", "<p", ">", "This", "method", "is", "equivalent", "to", "calling", ":", "<code", ">", "translate", "(", "ox", "oy", "oz", ")", ".", "rotate", "(", "quat", ")", ".", "translate", "(", "-", "ox", "-", "oy", "-", "oz", ")", "<", "/", "code", ">", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Rotation_matrix#Quaternion", ">", "http", ":", "//", "en", ".", "wikipedia", ".", "org<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L11223-L11225
aol/cyclops
cyclops-futurestream/src/main/java/cyclops/stream/StreamSource.java
StreamSource.ofMultiple
public static <T> MultipleStreamSource<T> ofMultiple(final QueueFactory<?> q) { """ Construct a StreamSource that supports multiple readers of the same data backed by a Queue created from the supplied QueueFactory @see QueueFactories for Factory creation options and various backpressure strategies <pre> {@code MultipleStreamSource<Integer> multi = StreamSource .ofMultiple(QueueFactories.boundedQueue(100)); FutureStream<Integer> pushable = multi.futureStream(new LazyReact()); ReactiveSeq<Integer> seq = multi.reactiveSeq(); multi.getInput().offer(100); multi.getInput().close(); pushable.collect(CyclopsCollectors.toList()); //[100] seq.collect(CyclopsCollectors.toList()); //[100] } </pre> @param q QueueFactory used to create the Adapter to back the pushable StreamSource @return a builder that will use Topics to allow multiple Streams from the same data """ Objects.requireNonNull(q); return new MultipleStreamSource<T>( StreamSource.of(q) .createQueue()); }
java
public static <T> MultipleStreamSource<T> ofMultiple(final QueueFactory<?> q) { Objects.requireNonNull(q); return new MultipleStreamSource<T>( StreamSource.of(q) .createQueue()); }
[ "public", "static", "<", "T", ">", "MultipleStreamSource", "<", "T", ">", "ofMultiple", "(", "final", "QueueFactory", "<", "?", ">", "q", ")", "{", "Objects", ".", "requireNonNull", "(", "q", ")", ";", "return", "new", "MultipleStreamSource", "<", "T", ">", "(", "StreamSource", ".", "of", "(", "q", ")", ".", "createQueue", "(", ")", ")", ";", "}" ]
Construct a StreamSource that supports multiple readers of the same data backed by a Queue created from the supplied QueueFactory @see QueueFactories for Factory creation options and various backpressure strategies <pre> {@code MultipleStreamSource<Integer> multi = StreamSource .ofMultiple(QueueFactories.boundedQueue(100)); FutureStream<Integer> pushable = multi.futureStream(new LazyReact()); ReactiveSeq<Integer> seq = multi.reactiveSeq(); multi.getInput().offer(100); multi.getInput().close(); pushable.collect(CyclopsCollectors.toList()); //[100] seq.collect(CyclopsCollectors.toList()); //[100] } </pre> @param q QueueFactory used to create the Adapter to back the pushable StreamSource @return a builder that will use Topics to allow multiple Streams from the same data
[ "Construct", "a", "StreamSource", "that", "supports", "multiple", "readers", "of", "the", "same", "data", "backed", "by", "a", "Queue", "created", "from", "the", "supplied", "QueueFactory" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops-futurestream/src/main/java/cyclops/stream/StreamSource.java#L281-L286
agmip/agmip-common-functions
src/main/java/org/agmip/functions/PTSaxton2006.java
PTSaxton2006.calcMoisture1500Kpa
public static String calcMoisture1500Kpa(String slsnd, String slcly, String omPct) { """ Equation 1 for calculating 1500 kPa moisture, %v @param slsnd Sand weight percentage by layer ([0,100]%) @param slcly Clay weight percentage by layer ([0,100]%) @param omPct Organic matter weight percentage by layer ([0,100]%), (= SLOC * 1.72) """ if ((slsnd = checkPctVal(slsnd)) == null || (slcly = checkPctVal(slcly)) == null || (omPct = checkPctVal(omPct)) == null) { LOG.error("Invalid input parameters for calculating 1500 kPa moisture, %v"); return null; } String ret = sum(product("-0.02736", slsnd), product("0.55518", slcly), product("0.684", omPct), product("0.0057", slsnd, omPct), product("-0.01482", slcly, omPct), product("0.0007752", slsnd, slcly), "1.534"); LOG.debug("Calculate result for 1500 kPa moisture, %v is {}", ret); return ret; }
java
public static String calcMoisture1500Kpa(String slsnd, String slcly, String omPct) { if ((slsnd = checkPctVal(slsnd)) == null || (slcly = checkPctVal(slcly)) == null || (omPct = checkPctVal(omPct)) == null) { LOG.error("Invalid input parameters for calculating 1500 kPa moisture, %v"); return null; } String ret = sum(product("-0.02736", slsnd), product("0.55518", slcly), product("0.684", omPct), product("0.0057", slsnd, omPct), product("-0.01482", slcly, omPct), product("0.0007752", slsnd, slcly), "1.534"); LOG.debug("Calculate result for 1500 kPa moisture, %v is {}", ret); return ret; }
[ "public", "static", "String", "calcMoisture1500Kpa", "(", "String", "slsnd", ",", "String", "slcly", ",", "String", "omPct", ")", "{", "if", "(", "(", "slsnd", "=", "checkPctVal", "(", "slsnd", ")", ")", "==", "null", "||", "(", "slcly", "=", "checkPctVal", "(", "slcly", ")", ")", "==", "null", "||", "(", "omPct", "=", "checkPctVal", "(", "omPct", ")", ")", "==", "null", ")", "{", "LOG", ".", "error", "(", "\"Invalid input parameters for calculating 1500 kPa moisture, %v\"", ")", ";", "return", "null", ";", "}", "String", "ret", "=", "sum", "(", "product", "(", "\"-0.02736\"", ",", "slsnd", ")", ",", "product", "(", "\"0.55518\"", ",", "slcly", ")", ",", "product", "(", "\"0.684\"", ",", "omPct", ")", ",", "product", "(", "\"0.0057\"", ",", "slsnd", ",", "omPct", ")", ",", "product", "(", "\"-0.01482\"", ",", "slcly", ",", "omPct", ")", ",", "product", "(", "\"0.0007752\"", ",", "slsnd", ",", "slcly", ")", ",", "\"1.534\"", ")", ";", "LOG", ".", "debug", "(", "\"Calculate result for 1500 kPa moisture, %v is {}\"", ",", "ret", ")", ";", "return", "ret", ";", "}" ]
Equation 1 for calculating 1500 kPa moisture, %v @param slsnd Sand weight percentage by layer ([0,100]%) @param slcly Clay weight percentage by layer ([0,100]%) @param omPct Organic matter weight percentage by layer ([0,100]%), (= SLOC * 1.72)
[ "Equation", "1", "for", "calculating", "1500", "kPa", "moisture", "%v" ]
train
https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/functions/PTSaxton2006.java#L121-L134
jbundle/jbundle
base/screen/model/src/main/java/org/jbundle/base/screen/model/ScreenField.java
ScreenField.getSFieldValue
public String getSFieldValue(boolean bDisplayFormat, boolean bRawData) { """ Retrieve (in HTML format) from this field. (Only for XML/HTML fields). @param bDisplayFormat Display (with html codes) or Input format? @param bRawData If true return the Raw data (not through the converters)? @return The HTML string. """ Convert converter = this.getConverter(); if (converter == null) return Constant.BLANK; if (bRawData) { converter = converter.getField(); if (converter == null) return Constant.BLANK; } return converter.getString(); }
java
public String getSFieldValue(boolean bDisplayFormat, boolean bRawData) { Convert converter = this.getConverter(); if (converter == null) return Constant.BLANK; if (bRawData) { converter = converter.getField(); if (converter == null) return Constant.BLANK; } return converter.getString(); }
[ "public", "String", "getSFieldValue", "(", "boolean", "bDisplayFormat", ",", "boolean", "bRawData", ")", "{", "Convert", "converter", "=", "this", ".", "getConverter", "(", ")", ";", "if", "(", "converter", "==", "null", ")", "return", "Constant", ".", "BLANK", ";", "if", "(", "bRawData", ")", "{", "converter", "=", "converter", ".", "getField", "(", ")", ";", "if", "(", "converter", "==", "null", ")", "return", "Constant", ".", "BLANK", ";", "}", "return", "converter", ".", "getString", "(", ")", ";", "}" ]
Retrieve (in HTML format) from this field. (Only for XML/HTML fields). @param bDisplayFormat Display (with html codes) or Input format? @param bRawData If true return the Raw data (not through the converters)? @return The HTML string.
[ "Retrieve", "(", "in", "HTML", "format", ")", "from", "this", "field", ".", "(", "Only", "for", "XML", "/", "HTML", "fields", ")", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/ScreenField.java#L569-L581
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/NNStorage.java
NNStorage.findFinalizedEditsFile
File findFinalizedEditsFile(long startTxId, long endTxId) throws IOException { """ Return the first readable finalized edits file for the given txid. """ File ret = findFile(NameNodeDirType.EDITS, getFinalizedEditsFileName(startTxId, endTxId)); if (ret == null) { throw new IOException( "No edits file for txid " + startTxId + "-" + endTxId + " exists!"); } return ret; }
java
File findFinalizedEditsFile(long startTxId, long endTxId) throws IOException { File ret = findFile(NameNodeDirType.EDITS, getFinalizedEditsFileName(startTxId, endTxId)); if (ret == null) { throw new IOException( "No edits file for txid " + startTxId + "-" + endTxId + " exists!"); } return ret; }
[ "File", "findFinalizedEditsFile", "(", "long", "startTxId", ",", "long", "endTxId", ")", "throws", "IOException", "{", "File", "ret", "=", "findFile", "(", "NameNodeDirType", ".", "EDITS", ",", "getFinalizedEditsFileName", "(", "startTxId", ",", "endTxId", ")", ")", ";", "if", "(", "ret", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"No edits file for txid \"", "+", "startTxId", "+", "\"-\"", "+", "endTxId", "+", "\" exists!\"", ")", ";", "}", "return", "ret", ";", "}" ]
Return the first readable finalized edits file for the given txid.
[ "Return", "the", "first", "readable", "finalized", "edits", "file", "for", "the", "given", "txid", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/NNStorage.java#L762-L771
MariaDB/mariadb-connector-j
src/main/java/org/mariadb/jdbc/BasePrepareStatement.java
BasePrepareStatement.setObject
public void setObject(final int parameterIndex, final Object obj, final int targetSqlType) throws SQLException { """ Sets the value of the designated parameter with the given object. This method is like the method <code>setObject</code> above, except that it assumes a scale of zero. @param parameterIndex the first parameter is 1, the second is 2, ... @param obj the object containing the input parameter value @param targetSqlType the SQL type (as defined in java.sql.Types) to be sent to the database @throws SQLException if parameterIndex does not correspond to a parameter marker in the SQL statement; if a database access error occurs or this method is called on a closed <code>PreparedStatement</code>s @see Types """ setInternalObject(parameterIndex, obj, targetSqlType, Long.MAX_VALUE); }
java
public void setObject(final int parameterIndex, final Object obj, final int targetSqlType) throws SQLException { setInternalObject(parameterIndex, obj, targetSqlType, Long.MAX_VALUE); }
[ "public", "void", "setObject", "(", "final", "int", "parameterIndex", ",", "final", "Object", "obj", ",", "final", "int", "targetSqlType", ")", "throws", "SQLException", "{", "setInternalObject", "(", "parameterIndex", ",", "obj", ",", "targetSqlType", ",", "Long", ".", "MAX_VALUE", ")", ";", "}" ]
Sets the value of the designated parameter with the given object. This method is like the method <code>setObject</code> above, except that it assumes a scale of zero. @param parameterIndex the first parameter is 1, the second is 2, ... @param obj the object containing the input parameter value @param targetSqlType the SQL type (as defined in java.sql.Types) to be sent to the database @throws SQLException if parameterIndex does not correspond to a parameter marker in the SQL statement; if a database access error occurs or this method is called on a closed <code>PreparedStatement</code>s @see Types
[ "Sets", "the", "value", "of", "the", "designated", "parameter", "with", "the", "given", "object", ".", "This", "method", "is", "like", "the", "method", "<code", ">", "setObject<", "/", "code", ">", "above", "except", "that", "it", "assumes", "a", "scale", "of", "zero", "." ]
train
https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/BasePrepareStatement.java#L963-L966
before/quality-check
modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java
ConditionalCheck.stateIsTrue
@Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean condition, final boolean expression, @Nonnull final String description) { """ Ensures that a given state is {@code true}. @param condition condition must be {@code true}^ so that the check will be performed @param expression an expression that must be {@code true} to indicate a valid state @param description will be used in the error message to describe why the arguments caused an invalid state @throws IllegalStateOfArgumentException if the given arguments caused an invalid state """ if (condition) { Check.stateIsTrue(expression, description); } }
java
@Throws(IllegalStateOfArgumentException.class) public static void stateIsTrue(final boolean condition, final boolean expression, @Nonnull final String description) { if (condition) { Check.stateIsTrue(expression, description); } }
[ "@", "Throws", "(", "IllegalStateOfArgumentException", ".", "class", ")", "public", "static", "void", "stateIsTrue", "(", "final", "boolean", "condition", ",", "final", "boolean", "expression", ",", "@", "Nonnull", "final", "String", "description", ")", "{", "if", "(", "condition", ")", "{", "Check", ".", "stateIsTrue", "(", "expression", ",", "description", ")", ";", "}", "}" ]
Ensures that a given state is {@code true}. @param condition condition must be {@code true}^ so that the check will be performed @param expression an expression that must be {@code true} to indicate a valid state @param description will be used in the error message to describe why the arguments caused an invalid state @throws IllegalStateOfArgumentException if the given arguments caused an invalid state
[ "Ensures", "that", "a", "given", "state", "is", "{", "@code", "true", "}", "." ]
train
https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/ConditionalCheck.java#L2184-L2189
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.beginGetVMSecurityRules
public SecurityGroupViewResultInner beginGetVMSecurityRules(String resourceGroupName, String networkWatcherName, String targetResourceId) { """ Gets the configured and effective security group rules on the specified VM. @param resourceGroupName The name of the resource group. @param networkWatcherName The name of the network watcher. @param targetResourceId ID of the target VM. @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 SecurityGroupViewResultInner object if successful. """ return beginGetVMSecurityRulesWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().single().body(); }
java
public SecurityGroupViewResultInner beginGetVMSecurityRules(String resourceGroupName, String networkWatcherName, String targetResourceId) { return beginGetVMSecurityRulesWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().single().body(); }
[ "public", "SecurityGroupViewResultInner", "beginGetVMSecurityRules", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "targetResourceId", ")", "{", "return", "beginGetVMSecurityRulesWithServiceResponseAsync", "(", "resourceGroupName", ",", "networkWatcherName", ",", "targetResourceId", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Gets the configured and effective security group rules on the specified VM. @param resourceGroupName The name of the resource group. @param networkWatcherName The name of the network watcher. @param targetResourceId ID of the target VM. @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 SecurityGroupViewResultInner object if successful.
[ "Gets", "the", "configured", "and", "effective", "security", "group", "rules", "on", "the", "specified", "VM", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L1370-L1372
box/box-java-sdk
src/main/java/com/box/sdk/BoxCollaboration.java
BoxCollaboration.getAllFileCollaborations
public static BoxResourceIterable<Info> getAllFileCollaborations(final BoxAPIConnection api, String fileID, int pageSize, String... fields) { """ Used to retrieve all collaborations associated with the item. @param api BoxAPIConnection from the associated file. @param fileID FileID of the associated file @param pageSize page size for server pages of the Iterable @param fields the optional fields to retrieve. @return An iterable of BoxCollaboration.Info instances associated with the item. """ QueryStringBuilder builder = new QueryStringBuilder(); if (fields.length > 0) { builder.appendParam("fields", fields); } return new BoxResourceIterable<BoxCollaboration.Info>( api, GET_ALL_FILE_COLLABORATIONS_URL.buildWithQuery(api.getBaseURL(), builder.toString(), fileID), pageSize) { @Override protected BoxCollaboration.Info factory(JsonObject jsonObject) { String id = jsonObject.get("id").asString(); return new BoxCollaboration(api, id).new Info(jsonObject); } }; }
java
public static BoxResourceIterable<Info> getAllFileCollaborations(final BoxAPIConnection api, String fileID, int pageSize, String... fields) { QueryStringBuilder builder = new QueryStringBuilder(); if (fields.length > 0) { builder.appendParam("fields", fields); } return new BoxResourceIterable<BoxCollaboration.Info>( api, GET_ALL_FILE_COLLABORATIONS_URL.buildWithQuery(api.getBaseURL(), builder.toString(), fileID), pageSize) { @Override protected BoxCollaboration.Info factory(JsonObject jsonObject) { String id = jsonObject.get("id").asString(); return new BoxCollaboration(api, id).new Info(jsonObject); } }; }
[ "public", "static", "BoxResourceIterable", "<", "Info", ">", "getAllFileCollaborations", "(", "final", "BoxAPIConnection", "api", ",", "String", "fileID", ",", "int", "pageSize", ",", "String", "...", "fields", ")", "{", "QueryStringBuilder", "builder", "=", "new", "QueryStringBuilder", "(", ")", ";", "if", "(", "fields", ".", "length", ">", "0", ")", "{", "builder", ".", "appendParam", "(", "\"fields\"", ",", "fields", ")", ";", "}", "return", "new", "BoxResourceIterable", "<", "BoxCollaboration", ".", "Info", ">", "(", "api", ",", "GET_ALL_FILE_COLLABORATIONS_URL", ".", "buildWithQuery", "(", "api", ".", "getBaseURL", "(", ")", ",", "builder", ".", "toString", "(", ")", ",", "fileID", ")", ",", "pageSize", ")", "{", "@", "Override", "protected", "BoxCollaboration", ".", "Info", "factory", "(", "JsonObject", "jsonObject", ")", "{", "String", "id", "=", "jsonObject", ".", "get", "(", "\"id\"", ")", ".", "asString", "(", ")", ";", "return", "new", "BoxCollaboration", "(", "api", ",", "id", ")", ".", "new", "Info", "(", "jsonObject", ")", ";", "}", "}", ";", "}" ]
Used to retrieve all collaborations associated with the item. @param api BoxAPIConnection from the associated file. @param fileID FileID of the associated file @param pageSize page size for server pages of the Iterable @param fields the optional fields to retrieve. @return An iterable of BoxCollaboration.Info instances associated with the item.
[ "Used", "to", "retrieve", "all", "collaborations", "associated", "with", "the", "item", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxCollaboration.java#L579-L595
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java
MercatorProjection.getPixelRelative
public static Point getPixelRelative(LatLong latLong, long mapSize, Point origin) { """ Calculates the absolute pixel position for a map size and tile size relative to origin @param latLong the geographic position. @param mapSize precomputed size of map. @return the relative pixel position to the origin values (e.g. for a tile) """ return getPixelRelative(latLong, mapSize, origin.x, origin.y); }
java
public static Point getPixelRelative(LatLong latLong, long mapSize, Point origin) { return getPixelRelative(latLong, mapSize, origin.x, origin.y); }
[ "public", "static", "Point", "getPixelRelative", "(", "LatLong", "latLong", ",", "long", "mapSize", ",", "Point", "origin", ")", "{", "return", "getPixelRelative", "(", "latLong", ",", "mapSize", ",", "origin", ".", "x", ",", "origin", ".", "y", ")", ";", "}" ]
Calculates the absolute pixel position for a map size and tile size relative to origin @param latLong the geographic position. @param mapSize precomputed size of map. @return the relative pixel position to the origin values (e.g. for a tile)
[ "Calculates", "the", "absolute", "pixel", "position", "for", "a", "map", "size", "and", "tile", "size", "relative", "to", "origin" ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/util/MercatorProjection.java#L164-L166
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/optionalusertools/PickerUtilities.java
PickerUtilities.localDateTimeToString
public static String localDateTimeToString(LocalDateTime value, String emptyTimeString) { """ localDateTimeToString, This will return the supplied LocalDateTime as a string. If the value is null, this will return the value of emptyTimeString. Time values will be output in the same format as LocalDateTime.toString(). Javadocs from LocalDateTime.toString(): Outputs this date-time as a {@code String}, such as {@code 2007-12-03T10:15:30}. <p> The output will be one of the following ISO-8601 formats: <ul> <li>{@code uuuu-MM-dd'T'HH:mm}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSS}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSS}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS}</li> </ul> The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero. """ return (value == null) ? emptyTimeString : value.toString(); }
java
public static String localDateTimeToString(LocalDateTime value, String emptyTimeString) { return (value == null) ? emptyTimeString : value.toString(); }
[ "public", "static", "String", "localDateTimeToString", "(", "LocalDateTime", "value", ",", "String", "emptyTimeString", ")", "{", "return", "(", "value", "==", "null", ")", "?", "emptyTimeString", ":", "value", ".", "toString", "(", ")", ";", "}" ]
localDateTimeToString, This will return the supplied LocalDateTime as a string. If the value is null, this will return the value of emptyTimeString. Time values will be output in the same format as LocalDateTime.toString(). Javadocs from LocalDateTime.toString(): Outputs this date-time as a {@code String}, such as {@code 2007-12-03T10:15:30}. <p> The output will be one of the following ISO-8601 formats: <ul> <li>{@code uuuu-MM-dd'T'HH:mm}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSS}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSS}</li> <li>{@code uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS}</li> </ul> The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.
[ "localDateTimeToString", "This", "will", "return", "the", "supplied", "LocalDateTime", "as", "a", "string", ".", "If", "the", "value", "is", "null", "this", "will", "return", "the", "value", "of", "emptyTimeString", ".", "Time", "values", "will", "be", "output", "in", "the", "same", "format", "as", "LocalDateTime", ".", "toString", "()", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/optionalusertools/PickerUtilities.java#L146-L148
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/CommonSteps.java
CommonSteps.clickOnAndSwitchWindow
@Conditioned @Quand("Je clique sur '(.*)-(.*)' et passe sur '(.*)' de type fenêtre[\\.|\\?]") @When("I click on '(.*)-(.*)' and switch to '(.*)' window[\\.|\\?]") public void clickOnAndSwitchWindow(String page, String toClick, String windowKey, List<GherkinStepCondition> conditions) throws FailureException, TechnicalException { """ Click on html element and switch window when the scenario contain more one windows (one more application for example), if all 'expected' parameters equals 'actual' parameters in conditions. @param page The concerned page of toClick @param toClick html element @param windowKey the key of window (popup, ...) Example: 'demo.Popup1DemoPage'. @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws FailureException if the scenario encounters a functional error @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. """ final String wKey = Page.getInstance(page).getApplication() + Page.getInstance(windowKey).getPageKey(); final String handleToSwitch = Context.getWindows().get(wKey); if (handleToSwitch != null) { Context.getDriver().switchTo().window(handleToSwitch); // As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()). Context.getDriver().manage().window().setSize(new Dimension(1920, 1080)); Context.setMainWindow(windowKey); } else { try { final Set<String> initialWindows = getDriver().getWindowHandles(); clickOn(Page.getInstance(page).getPageElementByKey('-' + toClick)); final String newWindowHandle = Context.waitUntil(WindowManager.newWindowOpens(initialWindows)); Context.addWindow(wKey, newWindowHandle); getDriver().switchTo().window(newWindowHandle); // As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()). Context.getDriver().manage().window().setSize(new Dimension(1920, 1080)); Context.setMainWindow(newWindowHandle); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW), windowKey), true, Page.getInstance(page).getCallBack()); } if (!Page.getInstance(windowKey).checkPage()) { new Result.Failure<>(windowKey, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW), windowKey), true, Page.getInstance(page).getCallBack()); } } }
java
@Conditioned @Quand("Je clique sur '(.*)-(.*)' et passe sur '(.*)' de type fenêtre[\\.|\\?]") @When("I click on '(.*)-(.*)' and switch to '(.*)' window[\\.|\\?]") public void clickOnAndSwitchWindow(String page, String toClick, String windowKey, List<GherkinStepCondition> conditions) throws FailureException, TechnicalException { final String wKey = Page.getInstance(page).getApplication() + Page.getInstance(windowKey).getPageKey(); final String handleToSwitch = Context.getWindows().get(wKey); if (handleToSwitch != null) { Context.getDriver().switchTo().window(handleToSwitch); // As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()). Context.getDriver().manage().window().setSize(new Dimension(1920, 1080)); Context.setMainWindow(windowKey); } else { try { final Set<String> initialWindows = getDriver().getWindowHandles(); clickOn(Page.getInstance(page).getPageElementByKey('-' + toClick)); final String newWindowHandle = Context.waitUntil(WindowManager.newWindowOpens(initialWindows)); Context.addWindow(wKey, newWindowHandle); getDriver().switchTo().window(newWindowHandle); // As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()). Context.getDriver().manage().window().setSize(new Dimension(1920, 1080)); Context.setMainWindow(newWindowHandle); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW), windowKey), true, Page.getInstance(page).getCallBack()); } if (!Page.getInstance(windowKey).checkPage()) { new Result.Failure<>(windowKey, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW), windowKey), true, Page.getInstance(page).getCallBack()); } } }
[ "@", "Conditioned", "@", "Quand", "(", "\"Je clique sur '(.*)-(.*)' et passe sur '(.*)' de type fenêtre[\\\\.|\\\\?]\")", "\r", "@", "When", "(", "\"I click on '(.*)-(.*)' and switch to '(.*)' window[\\\\.|\\\\?]\"", ")", "public", "void", "clickOnAndSwitchWindow", "(", "String", "page", ",", "String", "toClick", ",", "String", "windowKey", ",", "List", "<", "GherkinStepCondition", ">", "conditions", ")", "throws", "FailureException", ",", "TechnicalException", "{", "final", "String", "wKey", "=", "Page", ".", "getInstance", "(", "page", ")", ".", "getApplication", "(", ")", "+", "Page", ".", "getInstance", "(", "windowKey", ")", ".", "getPageKey", "(", ")", ";", "final", "String", "handleToSwitch", "=", "Context", ".", "getWindows", "(", ")", ".", "get", "(", "wKey", ")", ";", "if", "(", "handleToSwitch", "!=", "null", ")", "{", "Context", ".", "getDriver", "(", ")", ".", "switchTo", "(", ")", ".", "window", "(", "handleToSwitch", ")", ";", "// As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()).\r", "Context", ".", "getDriver", "(", ")", ".", "manage", "(", ")", ".", "window", "(", ")", ".", "setSize", "(", "new", "Dimension", "(", "1920", ",", "1080", ")", ")", ";", "Context", ".", "setMainWindow", "(", "windowKey", ")", ";", "}", "else", "{", "try", "{", "final", "Set", "<", "String", ">", "initialWindows", "=", "getDriver", "(", ")", ".", "getWindowHandles", "(", ")", ";", "clickOn", "(", "Page", ".", "getInstance", "(", "page", ")", ".", "getPageElementByKey", "(", "'", "'", "+", "toClick", ")", ")", ";", "final", "String", "newWindowHandle", "=", "Context", ".", "waitUntil", "(", "WindowManager", ".", "newWindowOpens", "(", "initialWindows", ")", ")", ";", "Context", ".", "addWindow", "(", "wKey", ",", "newWindowHandle", ")", ";", "getDriver", "(", ")", ".", "switchTo", "(", ")", ".", "window", "(", "newWindowHandle", ")", ";", "// As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()).\r", "Context", ".", "getDriver", "(", ")", ".", "manage", "(", ")", ".", "window", "(", ")", ".", "setSize", "(", "new", "Dimension", "(", "1920", ",", "1080", ")", ")", ";", "Context", ".", "setMainWindow", "(", "newWindowHandle", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "new", "Result", ".", "Failure", "<>", "(", "e", ".", "getMessage", "(", ")", ",", "Messages", ".", "format", "(", "Messages", ".", "getMessage", "(", "Messages", ".", "FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW", ")", ",", "windowKey", ")", ",", "true", ",", "Page", ".", "getInstance", "(", "page", ")", ".", "getCallBack", "(", ")", ")", ";", "}", "if", "(", "!", "Page", ".", "getInstance", "(", "windowKey", ")", ".", "checkPage", "(", ")", ")", "{", "new", "Result", ".", "Failure", "<>", "(", "windowKey", ",", "Messages", ".", "format", "(", "Messages", ".", "getMessage", "(", "Messages", ".", "FAIL_MESSAGE_UNABLE_TO_SWITCH_WINDOW", ")", ",", "windowKey", ")", ",", "true", ",", "Page", ".", "getInstance", "(", "page", ")", ".", "getCallBack", "(", ")", ")", ";", "}", "}", "}" ]
Click on html element and switch window when the scenario contain more one windows (one more application for example), if all 'expected' parameters equals 'actual' parameters in conditions. @param page The concerned page of toClick @param toClick html element @param windowKey the key of window (popup, ...) Example: 'demo.Popup1DemoPage'. @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws FailureException if the scenario encounters a functional error @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
[ "Click", "on", "html", "element", "and", "switch", "window", "when", "the", "scenario", "contain", "more", "one", "windows", "(", "one", "more", "application", "for", "example", ")", "if", "all", "expected", "parameters", "equals", "actual", "parameters", "in", "conditions", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/CommonSteps.java#L454-L483
mgormley/optimize
src/main/java/edu/jhu/hlt/optimize/function/AbstractSumBatchFunction.java
AbstractSumBatchFunction.getGradient
public void getGradient(int[] batch, double[] gradient) { """ Gets the gradient at the current point, computed on the given batch of examples. @param batch A set of indices indicating the examples over which the gradient should be computed. @param gradient The output gradient, a vector of partial derivatives. """ for (int i=0; i<batch.length; i++) { addGradient(i, gradient); } }
java
public void getGradient(int[] batch, double[] gradient) { for (int i=0; i<batch.length; i++) { addGradient(i, gradient); } }
[ "public", "void", "getGradient", "(", "int", "[", "]", "batch", ",", "double", "[", "]", "gradient", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "batch", ".", "length", ";", "i", "++", ")", "{", "addGradient", "(", "i", ",", "gradient", ")", ";", "}", "}" ]
Gets the gradient at the current point, computed on the given batch of examples. @param batch A set of indices indicating the examples over which the gradient should be computed. @param gradient The output gradient, a vector of partial derivatives.
[ "Gets", "the", "gradient", "at", "the", "current", "point", "computed", "on", "the", "given", "batch", "of", "examples", "." ]
train
https://github.com/mgormley/optimize/blob/3d1b93260b99febb8a5ecd9e8543c223e151a8d3/src/main/java/edu/jhu/hlt/optimize/function/AbstractSumBatchFunction.java#L33-L37
EMCECS/nfs-client-java
src/main/java/com/emc/ecs/nfsclient/nfs/NfsResponseBase.java
NfsResponseBase.unmarshallingFileHandle
protected void unmarshallingFileHandle(Xdr xdr, boolean force) { """ Unmarshall the object if it is there, or skip the existence check if <code>force</code> is <code>true</code>. Convenience method for use in subclasses. @param xdr @param force """ if (force || xdr.getBoolean()) { _fileHandle = xdr.getByteArray(); } }
java
protected void unmarshallingFileHandle(Xdr xdr, boolean force) { if (force || xdr.getBoolean()) { _fileHandle = xdr.getByteArray(); } }
[ "protected", "void", "unmarshallingFileHandle", "(", "Xdr", "xdr", ",", "boolean", "force", ")", "{", "if", "(", "force", "||", "xdr", ".", "getBoolean", "(", ")", ")", "{", "_fileHandle", "=", "xdr", ".", "getByteArray", "(", ")", ";", "}", "}" ]
Unmarshall the object if it is there, or skip the existence check if <code>force</code> is <code>true</code>. Convenience method for use in subclasses. @param xdr @param force
[ "Unmarshall", "the", "object", "if", "it", "is", "there", "or", "skip", "the", "existence", "check", "if", "<code", ">", "force<", "/", "code", ">", "is", "<code", ">", "true<", "/", "code", ">", ".", "Convenience", "method", "for", "use", "in", "subclasses", "." ]
train
https://github.com/EMCECS/nfs-client-java/blob/7ba25bad5052b95cd286052745327729288b2843/src/main/java/com/emc/ecs/nfsclient/nfs/NfsResponseBase.java#L163-L167
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/StaticMessageSource.java
StaticMessageSource.addMessage
public @Nonnull StaticMessageSource addMessage(@Nonnull Locale locale, @Nonnull String code, @Nonnull String message) { """ Adds a message to the default locale. @param locale The locale @param code The code @param message The the message @return This message source """ ArgumentUtils.requireNonNull("locale", locale); if (StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(message)) { messageMap.put(new MessageKey(locale, code), message); } return this; }
java
public @Nonnull StaticMessageSource addMessage(@Nonnull Locale locale, @Nonnull String code, @Nonnull String message) { ArgumentUtils.requireNonNull("locale", locale); if (StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(message)) { messageMap.put(new MessageKey(locale, code), message); } return this; }
[ "public", "@", "Nonnull", "StaticMessageSource", "addMessage", "(", "@", "Nonnull", "Locale", "locale", ",", "@", "Nonnull", "String", "code", ",", "@", "Nonnull", "String", "message", ")", "{", "ArgumentUtils", ".", "requireNonNull", "(", "\"locale\"", ",", "locale", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "code", ")", "&&", "StringUtils", ".", "isNotEmpty", "(", "message", ")", ")", "{", "messageMap", ".", "put", "(", "new", "MessageKey", "(", "locale", ",", "code", ")", ",", "message", ")", ";", "}", "return", "this", ";", "}" ]
Adds a message to the default locale. @param locale The locale @param code The code @param message The the message @return This message source
[ "Adds", "a", "message", "to", "the", "default", "locale", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/StaticMessageSource.java#L58-L64
Netflix/Nicobar
nicobar-core/src/main/java/com/netflix/nicobar/core/module/GraphUtils.java
GraphUtils.addAllVertices
public static <V> void addAllVertices(DirectedGraph<V, DefaultEdge> graph, Set<V> vertices) { """ Add all of the vertices to the graph without any edges. If the the graph already contains any one of the vertices, that vertex is not added. @param graph graph to be mutated @param vertices vertices to add """ // add all of the new vertices to prep for linking for (V vertex : vertices) { graph.addVertex(vertex); } }
java
public static <V> void addAllVertices(DirectedGraph<V, DefaultEdge> graph, Set<V> vertices) { // add all of the new vertices to prep for linking for (V vertex : vertices) { graph.addVertex(vertex); } }
[ "public", "static", "<", "V", ">", "void", "addAllVertices", "(", "DirectedGraph", "<", "V", ",", "DefaultEdge", ">", "graph", ",", "Set", "<", "V", ">", "vertices", ")", "{", "// add all of the new vertices to prep for linking", "for", "(", "V", "vertex", ":", "vertices", ")", "{", "graph", ".", "addVertex", "(", "vertex", ")", ";", "}", "}" ]
Add all of the vertices to the graph without any edges. If the the graph already contains any one of the vertices, that vertex is not added. @param graph graph to be mutated @param vertices vertices to add
[ "Add", "all", "of", "the", "vertices", "to", "the", "graph", "without", "any", "edges", ".", "If", "the", "the", "graph", "already", "contains", "any", "one", "of", "the", "vertices", "that", "vertex", "is", "not", "added", "." ]
train
https://github.com/Netflix/Nicobar/blob/507173dcae4a86a955afc3df222a855862fab8d7/nicobar-core/src/main/java/com/netflix/nicobar/core/module/GraphUtils.java#L79-L84
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.ensureRequiredZnodesExist
void ensureRequiredZnodesExist(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { """ Make sure the required znodes are present on the quorum. @param zookeeper ZooKeeper connection to use. @param znode Base-path for our znodes. """ mkdirp(zookeeper, znode); createIfNotThere(zookeeper, QUEUE_NODE); createIfNotThere(zookeeper, POOL_NODE); }
java
void ensureRequiredZnodesExist(ZooKeeper zookeeper, String znode) throws KeeperException, InterruptedException { mkdirp(zookeeper, znode); createIfNotThere(zookeeper, QUEUE_NODE); createIfNotThere(zookeeper, POOL_NODE); }
[ "void", "ensureRequiredZnodesExist", "(", "ZooKeeper", "zookeeper", ",", "String", "znode", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "mkdirp", "(", "zookeeper", ",", "znode", ")", ";", "createIfNotThere", "(", "zookeeper", ",", "QUEUE_NODE", ")", ";", "createIfNotThere", "(", "zookeeper", ",", "POOL_NODE", ")", ";", "}" ]
Make sure the required znodes are present on the quorum. @param zookeeper ZooKeeper connection to use. @param znode Base-path for our znodes.
[ "Make", "sure", "the", "required", "znodes", "are", "present", "on", "the", "quorum", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L93-L97
gallandarakhneorg/afc
core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/astar/AStar.java
AStar.estimate
@Pure protected double estimate(PT p1, PT p2) { """ Evaluate the distance between two points in the graph. <p>By default, this function uses the heuristic passed as parameter of the constructor. @param p1 the first point. @param p2 the second point. @return the evaluated distance between {@code p1} and {@code p2}. """ assert p1 != null && p2 != null; if (this.heuristic == null) { throw new IllegalStateException(Locale.getString("E1")); //$NON-NLS-1$ } return this.heuristic.evaluate(p1, p2); }
java
@Pure protected double estimate(PT p1, PT p2) { assert p1 != null && p2 != null; if (this.heuristic == null) { throw new IllegalStateException(Locale.getString("E1")); //$NON-NLS-1$ } return this.heuristic.evaluate(p1, p2); }
[ "@", "Pure", "protected", "double", "estimate", "(", "PT", "p1", ",", "PT", "p2", ")", "{", "assert", "p1", "!=", "null", "&&", "p2", "!=", "null", ";", "if", "(", "this", ".", "heuristic", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "Locale", ".", "getString", "(", "\"E1\"", ")", ")", ";", "//$NON-NLS-1$", "}", "return", "this", ".", "heuristic", ".", "evaluate", "(", "p1", ",", "p2", ")", ";", "}" ]
Evaluate the distance between two points in the graph. <p>By default, this function uses the heuristic passed as parameter of the constructor. @param p1 the first point. @param p2 the second point. @return the evaluated distance between {@code p1} and {@code p2}.
[ "Evaluate", "the", "distance", "between", "two", "points", "in", "the", "graph", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgraph/src/main/java/org/arakhne/afc/math/graph/astar/AStar.java#L301-L308
Talend/tesb-rt-se
request-callback/src/main/java/org/talend/esb/mep/requestcallback/feature/RequestCallbackFeature.java
RequestCallbackFeature.applyWsdlExtensions
public static void applyWsdlExtensions(Bus bus) { """ Adds JAXB WSDL extensions to allow work with custom WSDL elements such as \"partner-link\" @param bus CXF bus """ ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry(); try { JAXBExtensionHelper.addExtensions(registry, javax.wsdl.Definition.class, org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class); JAXBExtensionHelper.addExtensions(registry, javax.wsdl.Binding.class, org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class); } catch (JAXBException e) { throw new RuntimeException("Failed to add WSDL JAXB extensions", e); } }
java
public static void applyWsdlExtensions(Bus bus) { ExtensionRegistry registry = bus.getExtension(WSDLManager.class).getExtensionRegistry(); try { JAXBExtensionHelper.addExtensions(registry, javax.wsdl.Definition.class, org.talend.esb.mep.requestcallback.impl.wsdl.PLType.class); JAXBExtensionHelper.addExtensions(registry, javax.wsdl.Binding.class, org.talend.esb.mep.requestcallback.impl.wsdl.CallbackExtension.class); } catch (JAXBException e) { throw new RuntimeException("Failed to add WSDL JAXB extensions", e); } }
[ "public", "static", "void", "applyWsdlExtensions", "(", "Bus", "bus", ")", "{", "ExtensionRegistry", "registry", "=", "bus", ".", "getExtension", "(", "WSDLManager", ".", "class", ")", ".", "getExtensionRegistry", "(", ")", ";", "try", "{", "JAXBExtensionHelper", ".", "addExtensions", "(", "registry", ",", "javax", ".", "wsdl", ".", "Definition", ".", "class", ",", "org", ".", "talend", ".", "esb", ".", "mep", ".", "requestcallback", ".", "impl", ".", "wsdl", ".", "PLType", ".", "class", ")", ";", "JAXBExtensionHelper", ".", "addExtensions", "(", "registry", ",", "javax", ".", "wsdl", ".", "Binding", ".", "class", ",", "org", ".", "talend", ".", "esb", ".", "mep", ".", "requestcallback", ".", "impl", ".", "wsdl", ".", "CallbackExtension", ".", "class", ")", ";", "}", "catch", "(", "JAXBException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to add WSDL JAXB extensions\"", ",", "e", ")", ";", "}", "}" ]
Adds JAXB WSDL extensions to allow work with custom WSDL elements such as \"partner-link\" @param bus CXF bus
[ "Adds", "JAXB", "WSDL", "extensions", "to", "allow", "work", "with", "custom", "WSDL", "elements", "such", "as", "\\", "partner", "-", "link", "\\" ]
train
https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/request-callback/src/main/java/org/talend/esb/mep/requestcallback/feature/RequestCallbackFeature.java#L84-L101
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_10_01/implementation/RegistriesInner.java
RegistriesInner.updatePoliciesAsync
public Observable<RegistryPoliciesInner> updatePoliciesAsync(String resourceGroupName, String registryName, RegistryPoliciesInner registryPoliciesUpdateParameters) { """ Updates the policies for the specified container registry. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param registryPoliciesUpdateParameters The parameters for updating policies of a container registry. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return updatePoliciesWithServiceResponseAsync(resourceGroupName, registryName, registryPoliciesUpdateParameters).map(new Func1<ServiceResponse<RegistryPoliciesInner>, RegistryPoliciesInner>() { @Override public RegistryPoliciesInner call(ServiceResponse<RegistryPoliciesInner> response) { return response.body(); } }); }
java
public Observable<RegistryPoliciesInner> updatePoliciesAsync(String resourceGroupName, String registryName, RegistryPoliciesInner registryPoliciesUpdateParameters) { return updatePoliciesWithServiceResponseAsync(resourceGroupName, registryName, registryPoliciesUpdateParameters).map(new Func1<ServiceResponse<RegistryPoliciesInner>, RegistryPoliciesInner>() { @Override public RegistryPoliciesInner call(ServiceResponse<RegistryPoliciesInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "RegistryPoliciesInner", ">", "updatePoliciesAsync", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "RegistryPoliciesInner", "registryPoliciesUpdateParameters", ")", "{", "return", "updatePoliciesWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ",", "registryPoliciesUpdateParameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "RegistryPoliciesInner", ">", ",", "RegistryPoliciesInner", ">", "(", ")", "{", "@", "Override", "public", "RegistryPoliciesInner", "call", "(", "ServiceResponse", "<", "RegistryPoliciesInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Updates the policies for the specified container registry. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param registryPoliciesUpdateParameters The parameters for updating policies of a container registry. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Updates", "the", "policies", "for", "the", "specified", "container", "registry", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_10_01/implementation/RegistriesInner.java#L1605-L1612
bazaarvoice/emodb
sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlDataReaderDAO.java
CqlDataReaderDAO.deltaQueryAsync
private Iterator<Iterable<Row>> deltaQueryAsync(DeltaPlacement placement, Statement statement, boolean singleRow, String errorContext, Object... errorContextArgs) { """ Asynchronously executes the provided statement. Although the iterator is returned immediately the actual results may still be loading in the background. The statement must query the delta table as returned from {@link com.bazaarvoice.emodb.sor.db.astyanax.DeltaPlacement#getDeltaTableDDL()} """ return doDeltaQuery(placement, statement, singleRow, true, errorContext, errorContextArgs); }
java
private Iterator<Iterable<Row>> deltaQueryAsync(DeltaPlacement placement, Statement statement, boolean singleRow, String errorContext, Object... errorContextArgs) { return doDeltaQuery(placement, statement, singleRow, true, errorContext, errorContextArgs); }
[ "private", "Iterator", "<", "Iterable", "<", "Row", ">", ">", "deltaQueryAsync", "(", "DeltaPlacement", "placement", ",", "Statement", "statement", ",", "boolean", "singleRow", ",", "String", "errorContext", ",", "Object", "...", "errorContextArgs", ")", "{", "return", "doDeltaQuery", "(", "placement", ",", "statement", ",", "singleRow", ",", "true", ",", "errorContext", ",", "errorContextArgs", ")", ";", "}" ]
Asynchronously executes the provided statement. Although the iterator is returned immediately the actual results may still be loading in the background. The statement must query the delta table as returned from {@link com.bazaarvoice.emodb.sor.db.astyanax.DeltaPlacement#getDeltaTableDDL()}
[ "Asynchronously", "executes", "the", "provided", "statement", ".", "Although", "the", "iterator", "is", "returned", "immediately", "the", "actual", "results", "may", "still", "be", "loading", "in", "the", "background", ".", "The", "statement", "must", "query", "the", "delta", "table", "as", "returned", "from", "{" ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlDataReaderDAO.java#L243-L246
finmath/finmath-lib
src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java
ForwardCurveInterpolation.createForwardCurveFromForwards
public static ForwardCurveInterpolation createForwardCurveFromForwards(String name, double[] times, double[] givenForwards, AnalyticModel model, String discountCurveName, double paymentOffset) { """ Create a forward curve from given times and given forwards with respect to an associated discount curve and payment offset. @param name The name of this curve. @param times A vector of given time points. @param givenForwards A vector of given forwards (corresponding to the given time points). @param model An analytic model providing a context. The discount curve (if needed) is obtained from this model. @param discountCurveName Name of the discount curve associated with this index (associated with it's funding or collateralization). @param paymentOffset Time between fixing and payment. @return A new ForwardCurve object. """ RandomVariable[] givenForwardsAsRandomVariables = DoubleStream.of(givenForwards).mapToObj(new DoubleFunction<RandomVariableFromDoubleArray>() { @Override public RandomVariableFromDoubleArray apply(double x) { return new RandomVariableFromDoubleArray(x); } }).toArray(RandomVariable[]::new); return createForwardCurveFromForwards(name, times, givenForwardsAsRandomVariables, model, discountCurveName, paymentOffset); }
java
public static ForwardCurveInterpolation createForwardCurveFromForwards(String name, double[] times, double[] givenForwards, AnalyticModel model, String discountCurveName, double paymentOffset) { RandomVariable[] givenForwardsAsRandomVariables = DoubleStream.of(givenForwards).mapToObj(new DoubleFunction<RandomVariableFromDoubleArray>() { @Override public RandomVariableFromDoubleArray apply(double x) { return new RandomVariableFromDoubleArray(x); } }).toArray(RandomVariable[]::new); return createForwardCurveFromForwards(name, times, givenForwardsAsRandomVariables, model, discountCurveName, paymentOffset); }
[ "public", "static", "ForwardCurveInterpolation", "createForwardCurveFromForwards", "(", "String", "name", ",", "double", "[", "]", "times", ",", "double", "[", "]", "givenForwards", ",", "AnalyticModel", "model", ",", "String", "discountCurveName", ",", "double", "paymentOffset", ")", "{", "RandomVariable", "[", "]", "givenForwardsAsRandomVariables", "=", "DoubleStream", ".", "of", "(", "givenForwards", ")", ".", "mapToObj", "(", "new", "DoubleFunction", "<", "RandomVariableFromDoubleArray", ">", "(", ")", "{", "@", "Override", "public", "RandomVariableFromDoubleArray", "apply", "(", "double", "x", ")", "{", "return", "new", "RandomVariableFromDoubleArray", "(", "x", ")", ";", "}", "}", ")", ".", "toArray", "(", "RandomVariable", "[", "]", "::", "new", ")", ";", "return", "createForwardCurveFromForwards", "(", "name", ",", "times", ",", "givenForwardsAsRandomVariables", ",", "model", ",", "discountCurveName", ",", "paymentOffset", ")", ";", "}" ]
Create a forward curve from given times and given forwards with respect to an associated discount curve and payment offset. @param name The name of this curve. @param times A vector of given time points. @param givenForwards A vector of given forwards (corresponding to the given time points). @param model An analytic model providing a context. The discount curve (if needed) is obtained from this model. @param discountCurveName Name of the discount curve associated with this index (associated with it's funding or collateralization). @param paymentOffset Time between fixing and payment. @return A new ForwardCurve object.
[ "Create", "a", "forward", "curve", "from", "given", "times", "and", "given", "forwards", "with", "respect", "to", "an", "associated", "discount", "curve", "and", "payment", "offset", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/ForwardCurveInterpolation.java#L317-L323
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java
MapUtils.getBoundingBox
public static BoundingBox getBoundingBox(GoogleMap map) { """ Get the WGS84 bounding box of the current map view screen. The max longitude will be larger than the min resulting in values larger than 180.0. @param map google map @return current bounding box """ LatLngBounds visibleBounds = map.getProjection() .getVisibleRegion().latLngBounds; LatLng southwest = visibleBounds.southwest; LatLng northeast = visibleBounds.northeast; double minLatitude = southwest.latitude; double maxLatitude = northeast.latitude; double minLongitude = southwest.longitude; double maxLongitude = northeast.longitude; if (maxLongitude < minLongitude) { maxLongitude += (2 * ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH); } BoundingBox boundingBox = new BoundingBox(minLongitude, minLatitude, maxLongitude, maxLatitude); return boundingBox; }
java
public static BoundingBox getBoundingBox(GoogleMap map) { LatLngBounds visibleBounds = map.getProjection() .getVisibleRegion().latLngBounds; LatLng southwest = visibleBounds.southwest; LatLng northeast = visibleBounds.northeast; double minLatitude = southwest.latitude; double maxLatitude = northeast.latitude; double minLongitude = southwest.longitude; double maxLongitude = northeast.longitude; if (maxLongitude < minLongitude) { maxLongitude += (2 * ProjectionConstants.WGS84_HALF_WORLD_LON_WIDTH); } BoundingBox boundingBox = new BoundingBox(minLongitude, minLatitude, maxLongitude, maxLatitude); return boundingBox; }
[ "public", "static", "BoundingBox", "getBoundingBox", "(", "GoogleMap", "map", ")", "{", "LatLngBounds", "visibleBounds", "=", "map", ".", "getProjection", "(", ")", ".", "getVisibleRegion", "(", ")", ".", "latLngBounds", ";", "LatLng", "southwest", "=", "visibleBounds", ".", "southwest", ";", "LatLng", "northeast", "=", "visibleBounds", ".", "northeast", ";", "double", "minLatitude", "=", "southwest", ".", "latitude", ";", "double", "maxLatitude", "=", "northeast", ".", "latitude", ";", "double", "minLongitude", "=", "southwest", ".", "longitude", ";", "double", "maxLongitude", "=", "northeast", ".", "longitude", ";", "if", "(", "maxLongitude", "<", "minLongitude", ")", "{", "maxLongitude", "+=", "(", "2", "*", "ProjectionConstants", ".", "WGS84_HALF_WORLD_LON_WIDTH", ")", ";", "}", "BoundingBox", "boundingBox", "=", "new", "BoundingBox", "(", "minLongitude", ",", "minLatitude", ",", "maxLongitude", ",", "maxLatitude", ")", ";", "return", "boundingBox", ";", "}" ]
Get the WGS84 bounding box of the current map view screen. The max longitude will be larger than the min resulting in values larger than 180.0. @param map google map @return current bounding box
[ "Get", "the", "WGS84", "bounding", "box", "of", "the", "current", "map", "view", "screen", ".", "The", "max", "longitude", "will", "be", "larger", "than", "the", "min", "resulting", "in", "values", "larger", "than", "180", ".", "0", "." ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/MapUtils.java#L81-L100
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java
ImageIOUtil.writeImage
public static boolean writeImage(BufferedImage image, String filename, int dpi) throws IOException { """ Writes a buffered image to a file using the given image format. See {@link #writeImage(BufferedImage image, String formatName, OutputStream output, int dpi, float quality)} for more details. @param image the image to be written @param filename used to construct the filename for the individual image. Its suffix will be used as the image format. @param dpi the resolution in dpi (dots per inch) to be used in metadata @return true if the image file was produced, false if there was an error. @throws IOException if an I/O error occurs """ return writeImage(image, filename, dpi, 1.0f); }
java
public static boolean writeImage(BufferedImage image, String filename, int dpi) throws IOException { return writeImage(image, filename, dpi, 1.0f); }
[ "public", "static", "boolean", "writeImage", "(", "BufferedImage", "image", ",", "String", "filename", ",", "int", "dpi", ")", "throws", "IOException", "{", "return", "writeImage", "(", "image", ",", "filename", ",", "dpi", ",", "1.0f", ")", ";", "}" ]
Writes a buffered image to a file using the given image format. See {@link #writeImage(BufferedImage image, String formatName, OutputStream output, int dpi, float quality)} for more details. @param image the image to be written @param filename used to construct the filename for the individual image. Its suffix will be used as the image format. @param dpi the resolution in dpi (dots per inch) to be used in metadata @return true if the image file was produced, false if there was an error. @throws IOException if an I/O error occurs
[ "Writes", "a", "buffered", "image", "to", "a", "file", "using", "the", "given", "image", "format", ".", "See", "{", "@link", "#writeImage", "(", "BufferedImage", "image", "String", "formatName", "OutputStream", "output", "int", "dpi", "float", "quality", ")", "}", "for", "more", "details", "." ]
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java#L62-L66
Samsung/GearVRf
GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java
ExternalScriptable.get
public synchronized Object get(int index, Scriptable start) { """ Returns the value of the indexed property or NOT_FOUND. @param index the numeric index for the property @param start the object in which the lookup began @return the value of the property (may be null), or NOT_FOUND """ Integer key = new Integer(index); if (indexedProps.containsKey(index)) { return indexedProps.get(key); } else { return NOT_FOUND; } }
java
public synchronized Object get(int index, Scriptable start) { Integer key = new Integer(index); if (indexedProps.containsKey(index)) { return indexedProps.get(key); } else { return NOT_FOUND; } }
[ "public", "synchronized", "Object", "get", "(", "int", "index", ",", "Scriptable", "start", ")", "{", "Integer", "key", "=", "new", "Integer", "(", "index", ")", ";", "if", "(", "indexedProps", ".", "containsKey", "(", "index", ")", ")", "{", "return", "indexedProps", ".", "get", "(", "key", ")", ";", "}", "else", "{", "return", "NOT_FOUND", ";", "}", "}" ]
Returns the value of the indexed property or NOT_FOUND. @param index the numeric index for the property @param start the object in which the lookup began @return the value of the property (may be null), or NOT_FOUND
[ "Returns", "the", "value", "of", "the", "indexed", "property", "or", "NOT_FOUND", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java#L128-L135
alkacon/opencms-core
src/org/opencms/xml/content/CmsXmlContent.java
CmsXmlContent.removeValue
public void removeValue(String name, Locale locale, int index) { """ Removes an existing XML content value of the given element name and locale at the given index position from this XML content document.<p> @param name the name of the XML content value element @param locale the locale where to remove the value @param index the index where to remove the value (relative to all other values of this type) """ // first get the value from the selected locale and index I_CmsXmlContentValue value = getValue(name, locale, index); if (!value.isChoiceOption()) { // check for the min / max occurs constrains List<I_CmsXmlContentValue> values = getValues(name, locale); if (values.size() <= value.getMinOccurs()) { // must not allow removing an element if min occurs would be violated throw new CmsRuntimeException( Messages.get().container( Messages.ERR_XMLCONTENT_ELEM_MINOCCURS_2, name, new Integer(value.getMinOccurs()))); } } // detach the value node from the XML document value.getElement().detach(); // re-initialize this XML content initDocument(m_document, m_encoding, m_contentDefinition); }
java
public void removeValue(String name, Locale locale, int index) { // first get the value from the selected locale and index I_CmsXmlContentValue value = getValue(name, locale, index); if (!value.isChoiceOption()) { // check for the min / max occurs constrains List<I_CmsXmlContentValue> values = getValues(name, locale); if (values.size() <= value.getMinOccurs()) { // must not allow removing an element if min occurs would be violated throw new CmsRuntimeException( Messages.get().container( Messages.ERR_XMLCONTENT_ELEM_MINOCCURS_2, name, new Integer(value.getMinOccurs()))); } } // detach the value node from the XML document value.getElement().detach(); // re-initialize this XML content initDocument(m_document, m_encoding, m_contentDefinition); }
[ "public", "void", "removeValue", "(", "String", "name", ",", "Locale", "locale", ",", "int", "index", ")", "{", "// first get the value from the selected locale and index", "I_CmsXmlContentValue", "value", "=", "getValue", "(", "name", ",", "locale", ",", "index", ")", ";", "if", "(", "!", "value", ".", "isChoiceOption", "(", ")", ")", "{", "// check for the min / max occurs constrains", "List", "<", "I_CmsXmlContentValue", ">", "values", "=", "getValues", "(", "name", ",", "locale", ")", ";", "if", "(", "values", ".", "size", "(", ")", "<=", "value", ".", "getMinOccurs", "(", ")", ")", "{", "// must not allow removing an element if min occurs would be violated", "throw", "new", "CmsRuntimeException", "(", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_XMLCONTENT_ELEM_MINOCCURS_2", ",", "name", ",", "new", "Integer", "(", "value", ".", "getMinOccurs", "(", ")", ")", ")", ")", ";", "}", "}", "// detach the value node from the XML document", "value", ".", "getElement", "(", ")", ".", "detach", "(", ")", ";", "// re-initialize this XML content", "initDocument", "(", "m_document", ",", "m_encoding", ",", "m_contentDefinition", ")", ";", "}" ]
Removes an existing XML content value of the given element name and locale at the given index position from this XML content document.<p> @param name the name of the XML content value element @param locale the locale where to remove the value @param index the index where to remove the value (relative to all other values of this type)
[ "Removes", "an", "existing", "XML", "content", "value", "of", "the", "given", "element", "name", "and", "locale", "at", "the", "given", "index", "position", "from", "this", "XML", "content", "document", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsXmlContent.java#L717-L740
ZieIony/Carbon
carbon/src/main/java/carbon/CarbonResources.java
CarbonResources.createFromResourceStream
public Drawable createFromResourceStream(TypedValue value, InputStream is, String srcName) { """ Create a drawable from an inputstream, using the given resources and value to determine density information. """ return createFromResourceStream(value, is, srcName, null); }
java
public Drawable createFromResourceStream(TypedValue value, InputStream is, String srcName) { return createFromResourceStream(value, is, srcName, null); }
[ "public", "Drawable", "createFromResourceStream", "(", "TypedValue", "value", ",", "InputStream", "is", ",", "String", "srcName", ")", "{", "return", "createFromResourceStream", "(", "value", ",", "is", ",", "srcName", ",", "null", ")", ";", "}" ]
Create a drawable from an inputstream, using the given resources and value to determine density information.
[ "Create", "a", "drawable", "from", "an", "inputstream", "using", "the", "given", "resources", "and", "value", "to", "determine", "density", "information", "." ]
train
https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/CarbonResources.java#L99-L101
buschmais/jqa-maven-plugin
src/main/java/com/buschmais/jqassistant/scm/maven/AbstractMojo.java
AbstractMojo.getStoreConfiguration
private StoreConfiguration getStoreConfiguration(MavenProject rootModule) { """ Creates the {@link StoreConfiguration}. This is a copy of the {@link #store} enriched by default values and additional command line parameters. @param rootModule The root module. @return The directory. """ StoreConfiguration.StoreConfigurationBuilder builder = StoreConfiguration.builder(); if (store.getUri() == null) { File storeDirectory = OptionHelper.selectValue(new File(rootModule.getBuild().getDirectory(), STORE_DIRECTORY), this.storeDirectory); storeDirectory.getParentFile().mkdirs(); URI uri = new File(storeDirectory, "/").toURI(); builder.uri(uri); } else { builder.uri(store.getUri()); builder.username(store.getUsername()); builder.password(store.getPassword()); builder.encryptionLevel(store.getEncryptionLevel()); } builder.properties(store.getProperties()); builder.embedded(getEmbeddedNeo4jConfiguration()); StoreConfiguration storeConfiguration = builder.build(); getLog().debug("Using store configuration " + storeConfiguration); return storeConfiguration; }
java
private StoreConfiguration getStoreConfiguration(MavenProject rootModule) { StoreConfiguration.StoreConfigurationBuilder builder = StoreConfiguration.builder(); if (store.getUri() == null) { File storeDirectory = OptionHelper.selectValue(new File(rootModule.getBuild().getDirectory(), STORE_DIRECTORY), this.storeDirectory); storeDirectory.getParentFile().mkdirs(); URI uri = new File(storeDirectory, "/").toURI(); builder.uri(uri); } else { builder.uri(store.getUri()); builder.username(store.getUsername()); builder.password(store.getPassword()); builder.encryptionLevel(store.getEncryptionLevel()); } builder.properties(store.getProperties()); builder.embedded(getEmbeddedNeo4jConfiguration()); StoreConfiguration storeConfiguration = builder.build(); getLog().debug("Using store configuration " + storeConfiguration); return storeConfiguration; }
[ "private", "StoreConfiguration", "getStoreConfiguration", "(", "MavenProject", "rootModule", ")", "{", "StoreConfiguration", ".", "StoreConfigurationBuilder", "builder", "=", "StoreConfiguration", ".", "builder", "(", ")", ";", "if", "(", "store", ".", "getUri", "(", ")", "==", "null", ")", "{", "File", "storeDirectory", "=", "OptionHelper", ".", "selectValue", "(", "new", "File", "(", "rootModule", ".", "getBuild", "(", ")", ".", "getDirectory", "(", ")", ",", "STORE_DIRECTORY", ")", ",", "this", ".", "storeDirectory", ")", ";", "storeDirectory", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ";", "URI", "uri", "=", "new", "File", "(", "storeDirectory", ",", "\"/\"", ")", ".", "toURI", "(", ")", ";", "builder", ".", "uri", "(", "uri", ")", ";", "}", "else", "{", "builder", ".", "uri", "(", "store", ".", "getUri", "(", ")", ")", ";", "builder", ".", "username", "(", "store", ".", "getUsername", "(", ")", ")", ";", "builder", ".", "password", "(", "store", ".", "getPassword", "(", ")", ")", ";", "builder", ".", "encryptionLevel", "(", "store", ".", "getEncryptionLevel", "(", ")", ")", ";", "}", "builder", ".", "properties", "(", "store", ".", "getProperties", "(", ")", ")", ";", "builder", ".", "embedded", "(", "getEmbeddedNeo4jConfiguration", "(", ")", ")", ";", "StoreConfiguration", "storeConfiguration", "=", "builder", ".", "build", "(", ")", ";", "getLog", "(", ")", ".", "debug", "(", "\"Using store configuration \"", "+", "storeConfiguration", ")", ";", "return", "storeConfiguration", ";", "}" ]
Creates the {@link StoreConfiguration}. This is a copy of the {@link #store} enriched by default values and additional command line parameters. @param rootModule The root module. @return The directory.
[ "Creates", "the", "{", "@link", "StoreConfiguration", "}", ".", "This", "is", "a", "copy", "of", "the", "{", "@link", "#store", "}", "enriched", "by", "default", "values", "and", "additional", "command", "line", "parameters", "." ]
train
https://github.com/buschmais/jqa-maven-plugin/blob/5c21a8058fc1b013333081907fbf00d3525e11c3/src/main/java/com/buschmais/jqassistant/scm/maven/AbstractMojo.java#L449-L467
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/graph/rebond/RebondTool.java
RebondTool.bondAtom
private void bondAtom(IAtomContainer container, IAtom atom) { """ Rebonds one atom by looking up nearby atom using the binary space partition tree. """ double myCovalentRadius = atom.getCovalentRadius(); double searchRadius = myCovalentRadius + maxCovalentRadius + bondTolerance; Point tupleAtom = new Point(atom.getPoint3d().x, atom.getPoint3d().y, atom.getPoint3d().z); for (Bspt.EnumerateSphere e = bspt.enumHemiSphere(tupleAtom, searchRadius); e.hasMoreElements();) { IAtom atomNear = ((TupleAtom) e.nextElement()).getAtom(); if (!atomNear.equals(atom) && container.getBond(atom, atomNear) == null) { boolean bonded = isBonded(myCovalentRadius, atomNear.getCovalentRadius(), e.foundDistance2()); if (bonded) { IBond bond = atom.getBuilder().newInstance(IBond.class, atom, atomNear, IBond.Order.SINGLE); container.addBond(bond); } } } }
java
private void bondAtom(IAtomContainer container, IAtom atom) { double myCovalentRadius = atom.getCovalentRadius(); double searchRadius = myCovalentRadius + maxCovalentRadius + bondTolerance; Point tupleAtom = new Point(atom.getPoint3d().x, atom.getPoint3d().y, atom.getPoint3d().z); for (Bspt.EnumerateSphere e = bspt.enumHemiSphere(tupleAtom, searchRadius); e.hasMoreElements();) { IAtom atomNear = ((TupleAtom) e.nextElement()).getAtom(); if (!atomNear.equals(atom) && container.getBond(atom, atomNear) == null) { boolean bonded = isBonded(myCovalentRadius, atomNear.getCovalentRadius(), e.foundDistance2()); if (bonded) { IBond bond = atom.getBuilder().newInstance(IBond.class, atom, atomNear, IBond.Order.SINGLE); container.addBond(bond); } } } }
[ "private", "void", "bondAtom", "(", "IAtomContainer", "container", ",", "IAtom", "atom", ")", "{", "double", "myCovalentRadius", "=", "atom", ".", "getCovalentRadius", "(", ")", ";", "double", "searchRadius", "=", "myCovalentRadius", "+", "maxCovalentRadius", "+", "bondTolerance", ";", "Point", "tupleAtom", "=", "new", "Point", "(", "atom", ".", "getPoint3d", "(", ")", ".", "x", ",", "atom", ".", "getPoint3d", "(", ")", ".", "y", ",", "atom", ".", "getPoint3d", "(", ")", ".", "z", ")", ";", "for", "(", "Bspt", ".", "EnumerateSphere", "e", "=", "bspt", ".", "enumHemiSphere", "(", "tupleAtom", ",", "searchRadius", ")", ";", "e", ".", "hasMoreElements", "(", ")", ";", ")", "{", "IAtom", "atomNear", "=", "(", "(", "TupleAtom", ")", "e", ".", "nextElement", "(", ")", ")", ".", "getAtom", "(", ")", ";", "if", "(", "!", "atomNear", ".", "equals", "(", "atom", ")", "&&", "container", ".", "getBond", "(", "atom", ",", "atomNear", ")", "==", "null", ")", "{", "boolean", "bonded", "=", "isBonded", "(", "myCovalentRadius", ",", "atomNear", ".", "getCovalentRadius", "(", ")", ",", "e", ".", "foundDistance2", "(", ")", ")", ";", "if", "(", "bonded", ")", "{", "IBond", "bond", "=", "atom", ".", "getBuilder", "(", ")", ".", "newInstance", "(", "IBond", ".", "class", ",", "atom", ",", "atomNear", ",", "IBond", ".", "Order", ".", "SINGLE", ")", ";", "container", ".", "addBond", "(", "bond", ")", ";", "}", "}", "}", "}" ]
Rebonds one atom by looking up nearby atom using the binary space partition tree.
[ "Rebonds", "one", "atom", "by", "looking", "up", "nearby", "atom", "using", "the", "binary", "space", "partition", "tree", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/graph/rebond/RebondTool.java#L96-L110
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java
DependencyBundlingAnalyzer.ecoSystemIs
private boolean ecoSystemIs(String ecoSystem, Dependency dependency, Dependency nextDependency) { """ Determine if the dependency ecosystem is equal in the given dependencies. @param ecoSystem the ecosystem to validate against @param dependency a dependency to compare @param nextDependency a dependency to compare @return true if the ecosystem is equal in both dependencies; otherwise false """ return ecoSystem.equals(dependency.getEcosystem()) && ecoSystem.equals(nextDependency.getEcosystem()); }
java
private boolean ecoSystemIs(String ecoSystem, Dependency dependency, Dependency nextDependency) { return ecoSystem.equals(dependency.getEcosystem()) && ecoSystem.equals(nextDependency.getEcosystem()); }
[ "private", "boolean", "ecoSystemIs", "(", "String", "ecoSystem", ",", "Dependency", "dependency", ",", "Dependency", "nextDependency", ")", "{", "return", "ecoSystem", ".", "equals", "(", "dependency", ".", "getEcosystem", "(", ")", ")", "&&", "ecoSystem", ".", "equals", "(", "nextDependency", ".", "getEcosystem", "(", ")", ")", ";", "}" ]
Determine if the dependency ecosystem is equal in the given dependencies. @param ecoSystem the ecosystem to validate against @param dependency a dependency to compare @param nextDependency a dependency to compare @return true if the ecosystem is equal in both dependencies; otherwise false
[ "Determine", "if", "the", "dependency", "ecosystem", "is", "equal", "in", "the", "given", "dependencies", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java#L485-L487
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/user/UserClient.java
UserClient.getUserList
public UserListResult getUserList(int start, int count) throws APIConnectionException, APIRequestException { """ Get user list @param start The start index of the list @param count The number that how many you want to get from list @return User info list @throws APIConnectionException connect exception @throws APIRequestException request exception """ if (start < 0 || count <= 0 || count > 500) { throw new IllegalArgumentException("negative index or count must more than 0 and less than 501"); } ResponseWrapper response = _httpClient.sendGet(_baseUrl + userPath + "?start=" + start + "&count=" + count); return UserListResult.fromResponse(response, UserListResult.class); }
java
public UserListResult getUserList(int start, int count) throws APIConnectionException, APIRequestException { if (start < 0 || count <= 0 || count > 500) { throw new IllegalArgumentException("negative index or count must more than 0 and less than 501"); } ResponseWrapper response = _httpClient.sendGet(_baseUrl + userPath + "?start=" + start + "&count=" + count); return UserListResult.fromResponse(response, UserListResult.class); }
[ "public", "UserListResult", "getUserList", "(", "int", "start", ",", "int", "count", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "if", "(", "start", "<", "0", "||", "count", "<=", "0", "||", "count", ">", "500", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"negative index or count must more than 0 and less than 501\"", ")", ";", "}", "ResponseWrapper", "response", "=", "_httpClient", ".", "sendGet", "(", "_baseUrl", "+", "userPath", "+", "\"?start=\"", "+", "start", "+", "\"&count=\"", "+", "count", ")", ";", "return", "UserListResult", ".", "fromResponse", "(", "response", ",", "UserListResult", ".", "class", ")", ";", "}" ]
Get user list @param start The start index of the list @param count The number that how many you want to get from list @return User info list @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Get", "user", "list" ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/user/UserClient.java#L210-L219
brunocvcunha/inutils4j
src/main/java/org/brunocvcunha/inutils4j/MyStringUtils.java
MyStringUtils.replaceHtmlEntities
public static String replaceHtmlEntities(String content, Map<String, Character> map) { """ Replace HTML entities @param content Content @param map Map @return Replaced content """ for (Entry<String, Character> entry : escapeStrings.entrySet()) { if (content.indexOf(entry.getKey()) != -1) { content = content.replace(entry.getKey(), String.valueOf(entry.getValue())); } } return content; }
java
public static String replaceHtmlEntities(String content, Map<String, Character> map) { for (Entry<String, Character> entry : escapeStrings.entrySet()) { if (content.indexOf(entry.getKey()) != -1) { content = content.replace(entry.getKey(), String.valueOf(entry.getValue())); } } return content; }
[ "public", "static", "String", "replaceHtmlEntities", "(", "String", "content", ",", "Map", "<", "String", ",", "Character", ">", "map", ")", "{", "for", "(", "Entry", "<", "String", ",", "Character", ">", "entry", ":", "escapeStrings", ".", "entrySet", "(", ")", ")", "{", "if", "(", "content", ".", "indexOf", "(", "entry", ".", "getKey", "(", ")", ")", "!=", "-", "1", ")", "{", "content", "=", "content", ".", "replace", "(", "entry", ".", "getKey", "(", ")", ",", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ")", ";", "}", "}", "return", "content", ";", "}" ]
Replace HTML entities @param content Content @param map Map @return Replaced content
[ "Replace", "HTML", "entities" ]
train
https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/MyStringUtils.java#L2096-L2107
VoltDB/voltdb
src/frontend/org/voltdb/ClientInterface.java
ClientInterface.callExecuteTaskAsync
public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException { """ Asynchronous version, call @ExecuteTask to generate a MP transaction. @param cb maximum timeout in milliseconds @param params actual parameter(s) for sub task to run @return @throws IOException @throws InterruptedException """ final String procedureName = "@ExecuteTask"; Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName); Procedure proc = procedureConfig.asCatalogProcedure(); StoredProcedureInvocation spi = new StoredProcedureInvocation(); spi.setProcName(procedureName); spi.setParams(params); spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb)); if (spi.getSerializedParams() == null) { spi = MiscUtils.roundTripForCL(spi); } synchronized (m_executeTaskAdpater) { m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi, proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(), new int[] { 0 } /* Can provide anything for multi-part */, spi.getSerializedSize(), System.nanoTime()); } }
java
public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException { final String procedureName = "@ExecuteTask"; Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName); Procedure proc = procedureConfig.asCatalogProcedure(); StoredProcedureInvocation spi = new StoredProcedureInvocation(); spi.setProcName(procedureName); spi.setParams(params); spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb)); if (spi.getSerializedParams() == null) { spi = MiscUtils.roundTripForCL(spi); } synchronized (m_executeTaskAdpater) { m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi, proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(), new int[] { 0 } /* Can provide anything for multi-part */, spi.getSerializedSize(), System.nanoTime()); } }
[ "public", "void", "callExecuteTaskAsync", "(", "SimpleClientResponseAdapter", ".", "Callback", "cb", ",", "byte", "[", "]", "params", ")", "throws", "IOException", "{", "final", "String", "procedureName", "=", "\"@ExecuteTask\"", ";", "Config", "procedureConfig", "=", "SystemProcedureCatalog", ".", "listing", ".", "get", "(", "procedureName", ")", ";", "Procedure", "proc", "=", "procedureConfig", ".", "asCatalogProcedure", "(", ")", ";", "StoredProcedureInvocation", "spi", "=", "new", "StoredProcedureInvocation", "(", ")", ";", "spi", ".", "setProcName", "(", "procedureName", ")", ";", "spi", ".", "setParams", "(", "params", ")", ";", "spi", ".", "setClientHandle", "(", "m_executeTaskAdpater", ".", "registerCallback", "(", "cb", ")", ")", ";", "if", "(", "spi", ".", "getSerializedParams", "(", ")", "==", "null", ")", "{", "spi", "=", "MiscUtils", ".", "roundTripForCL", "(", "spi", ")", ";", "}", "synchronized", "(", "m_executeTaskAdpater", ")", "{", "m_dispatcher", ".", "createTransaction", "(", "m_executeTaskAdpater", ".", "connectionId", "(", ")", ",", "spi", ",", "proc", ".", "getReadonly", "(", ")", ",", "proc", ".", "getSinglepartition", "(", ")", ",", "proc", ".", "getEverysite", "(", ")", ",", "new", "int", "[", "]", "{", "0", "}", "/* Can provide anything for multi-part */", ",", "spi", ".", "getSerializedSize", "(", ")", ",", "System", ".", "nanoTime", "(", ")", ")", ";", "}", "}" ]
Asynchronous version, call @ExecuteTask to generate a MP transaction. @param cb maximum timeout in milliseconds @param params actual parameter(s) for sub task to run @return @throws IOException @throws InterruptedException
[ "Asynchronous", "version", "call", "@ExecuteTask", "to", "generate", "a", "MP", "transaction", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ClientInterface.java#L2091-L2108
Stratio/bdt
src/main/java/com/stratio/qa/specs/KafkaSpec.java
KafkaSpec.connectKafka
@Given("^I connect to kafka at '(.+)' using path '(.+)'$") public void connectKafka(String zkHost, String zkPath) throws UnknownHostException { """ Connect to Kafka. @param zkHost ZK host @param zkPath ZK port @throws UnknownHostException exception """ String zkPort = zkHost.split(":")[1]; zkHost = zkHost.split(":")[0]; commonspec.getKafkaUtils().setZkHost(zkHost, zkPort, zkPath); commonspec.getKafkaUtils().connect(); }
java
@Given("^I connect to kafka at '(.+)' using path '(.+)'$") public void connectKafka(String zkHost, String zkPath) throws UnknownHostException { String zkPort = zkHost.split(":")[1]; zkHost = zkHost.split(":")[0]; commonspec.getKafkaUtils().setZkHost(zkHost, zkPort, zkPath); commonspec.getKafkaUtils().connect(); }
[ "@", "Given", "(", "\"^I connect to kafka at '(.+)' using path '(.+)'$\"", ")", "public", "void", "connectKafka", "(", "String", "zkHost", ",", "String", "zkPath", ")", "throws", "UnknownHostException", "{", "String", "zkPort", "=", "zkHost", ".", "split", "(", "\":\"", ")", "[", "1", "]", ";", "zkHost", "=", "zkHost", ".", "split", "(", "\":\"", ")", "[", "0", "]", ";", "commonspec", ".", "getKafkaUtils", "(", ")", ".", "setZkHost", "(", "zkHost", ",", "zkPort", ",", "zkPath", ")", ";", "commonspec", ".", "getKafkaUtils", "(", ")", ".", "connect", "(", ")", ";", "}" ]
Connect to Kafka. @param zkHost ZK host @param zkPath ZK port @throws UnknownHostException exception
[ "Connect", "to", "Kafka", "." ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/KafkaSpec.java#L49-L55
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getLocalizedMessages
public Future<LocalizedMessages> getLocalizedMessages(String version, String locale) { """ <p> Retrieve localized strings for the english locale </p> This method does not count towards your rate limit @param version The data dragon version of the data @param locale The locale to lookup. @return A list of localized message @see <a href="https://developer.riotgames.com/api/methods#!/931/3226">The official api documentation</a> """ return new DummyFuture<>(handler.getLocalizedMessages(version, locale)); }
java
public Future<LocalizedMessages> getLocalizedMessages(String version, String locale) { return new DummyFuture<>(handler.getLocalizedMessages(version, locale)); }
[ "public", "Future", "<", "LocalizedMessages", ">", "getLocalizedMessages", "(", "String", "version", ",", "String", "locale", ")", "{", "return", "new", "DummyFuture", "<>", "(", "handler", ".", "getLocalizedMessages", "(", "version", ",", "locale", ")", ")", ";", "}" ]
<p> Retrieve localized strings for the english locale </p> This method does not count towards your rate limit @param version The data dragon version of the data @param locale The locale to lookup. @return A list of localized message @see <a href="https://developer.riotgames.com/api/methods#!/931/3226">The official api documentation</a>
[ "<p", ">", "Retrieve", "localized", "strings", "for", "the", "english", "locale", "<", "/", "p", ">", "This", "method", "does", "not", "count", "towards", "your", "rate", "limit" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L910-L912
podio/podio-java
src/main/java/com/podio/space/SpaceAPI.java
SpaceAPI.updateSpaceMembership
public void updateSpaceMembership(int spaceId, int userId, Role role) { """ Updates a space membership with another role @param spaceId The id of the space @param userId The id of the user @param role The new role for the membership """ getResourceFactory() .getApiResource("/space/" + spaceId + "/member/" + userId) .entity(new SpaceMemberUpdate(role), MediaType.APPLICATION_JSON_TYPE).put(); }
java
public void updateSpaceMembership(int spaceId, int userId, Role role) { getResourceFactory() .getApiResource("/space/" + spaceId + "/member/" + userId) .entity(new SpaceMemberUpdate(role), MediaType.APPLICATION_JSON_TYPE).put(); }
[ "public", "void", "updateSpaceMembership", "(", "int", "spaceId", ",", "int", "userId", ",", "Role", "role", ")", "{", "getResourceFactory", "(", ")", ".", "getApiResource", "(", "\"/space/\"", "+", "spaceId", "+", "\"/member/\"", "+", "userId", ")", ".", "entity", "(", "new", "SpaceMemberUpdate", "(", "role", ")", ",", "MediaType", ".", "APPLICATION_JSON_TYPE", ")", ".", "put", "(", ")", ";", "}" ]
Updates a space membership with another role @param spaceId The id of the space @param userId The id of the user @param role The new role for the membership
[ "Updates", "a", "space", "membership", "with", "another", "role" ]
train
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/space/SpaceAPI.java#L110-L115
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/decomposition/qr/QrUpdate_DDRM.java
QrUpdate_DDRM.setQR
private void setQR(DMatrixRMaj Q , DMatrixRMaj R , int growRows ) { """ Provides the results of a QR decomposition. These will be modified by adding or removing rows from the original 'A' matrix. @param Q The Q matrix which is to be modified. Is modified later and reference saved. @param R The R matrix which is to be modified. Is modified later and reference saved. """ if( Q.numRows != Q.numCols ) { throw new IllegalArgumentException("Q should be square."); } this.Q = Q; this.R = R; m = Q.numRows; n = R.numCols; if( m+growRows > maxRows || n > maxCols ) { if( autoGrow ) { declareInternalData(m+growRows,n); } else { throw new IllegalArgumentException("Autogrow has been set to false and the maximum number of rows" + " or columns has been exceeded."); } } }
java
private void setQR(DMatrixRMaj Q , DMatrixRMaj R , int growRows ) { if( Q.numRows != Q.numCols ) { throw new IllegalArgumentException("Q should be square."); } this.Q = Q; this.R = R; m = Q.numRows; n = R.numCols; if( m+growRows > maxRows || n > maxCols ) { if( autoGrow ) { declareInternalData(m+growRows,n); } else { throw new IllegalArgumentException("Autogrow has been set to false and the maximum number of rows" + " or columns has been exceeded."); } } }
[ "private", "void", "setQR", "(", "DMatrixRMaj", "Q", ",", "DMatrixRMaj", "R", ",", "int", "growRows", ")", "{", "if", "(", "Q", ".", "numRows", "!=", "Q", ".", "numCols", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Q should be square.\"", ")", ";", "}", "this", ".", "Q", "=", "Q", ";", "this", ".", "R", "=", "R", ";", "m", "=", "Q", ".", "numRows", ";", "n", "=", "R", ".", "numCols", ";", "if", "(", "m", "+", "growRows", ">", "maxRows", "||", "n", ">", "maxCols", ")", "{", "if", "(", "autoGrow", ")", "{", "declareInternalData", "(", "m", "+", "growRows", ",", "n", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Autogrow has been set to false and the maximum number of rows\"", "+", "\" or columns has been exceeded.\"", ")", ";", "}", "}", "}" ]
Provides the results of a QR decomposition. These will be modified by adding or removing rows from the original 'A' matrix. @param Q The Q matrix which is to be modified. Is modified later and reference saved. @param R The R matrix which is to be modified. Is modified later and reference saved.
[ "Provides", "the", "results", "of", "a", "QR", "decomposition", ".", "These", "will", "be", "modified", "by", "adding", "or", "removing", "rows", "from", "the", "original", "A", "matrix", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/decomposition/qr/QrUpdate_DDRM.java#L215-L234
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/DrizzlePreparedStatement.java
DrizzlePreparedStatement.setTime
public void setTime(final int parameterIndex, final Time time, final Calendar cal) throws SQLException { """ Sets the designated parameter to the given <code>java.sql.Time</code> value, using the given <code>Calendar</code> object. The driver uses the <code>Calendar</code> object to construct an SQL <code>TIME</code> value, which the driver then sends to the database. With a <code>Calendar</code> object, the driver can calculate the time taking into account a custom timezone. If no <code>Calendar</code> object is specified, the driver uses the default timezone, which is that of the virtual machine running the application. @param parameterIndex the first parameter is 1, the second is 2, ... @param time the parameter value @param cal the <code>Calendar</code> object the driver will use to construct the time @throws java.sql.SQLException if parameterIndex does not correspond to a parameter marker in the SQL statement; if a database access error occurs or this method is called on a closed <code>PreparedStatement</code> @since 1.2 """ // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // sdf.setCalendar(cal); if(time == null) { setNull(parameterIndex, Types.TIME); return; } setParameter(parameterIndex, new TimeParameter(time.getTime())); }
java
public void setTime(final int parameterIndex, final Time time, final Calendar cal) throws SQLException { // SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // sdf.setCalendar(cal); if(time == null) { setNull(parameterIndex, Types.TIME); return; } setParameter(parameterIndex, new TimeParameter(time.getTime())); }
[ "public", "void", "setTime", "(", "final", "int", "parameterIndex", ",", "final", "Time", "time", ",", "final", "Calendar", "cal", ")", "throws", "SQLException", "{", "// SimpleDateFormat sdf = new SimpleDateFormat(\"HH:mm:ss\");", "// sdf.setCalendar(cal);", "if", "(", "time", "==", "null", ")", "{", "setNull", "(", "parameterIndex", ",", "Types", ".", "TIME", ")", ";", "return", ";", "}", "setParameter", "(", "parameterIndex", ",", "new", "TimeParameter", "(", "time", ".", "getTime", "(", ")", ")", ")", ";", "}" ]
Sets the designated parameter to the given <code>java.sql.Time</code> value, using the given <code>Calendar</code> object. The driver uses the <code>Calendar</code> object to construct an SQL <code>TIME</code> value, which the driver then sends to the database. With a <code>Calendar</code> object, the driver can calculate the time taking into account a custom timezone. If no <code>Calendar</code> object is specified, the driver uses the default timezone, which is that of the virtual machine running the application. @param parameterIndex the first parameter is 1, the second is 2, ... @param time the parameter value @param cal the <code>Calendar</code> object the driver will use to construct the time @throws java.sql.SQLException if parameterIndex does not correspond to a parameter marker in the SQL statement; if a database access error occurs or this method is called on a closed <code>PreparedStatement</code> @since 1.2
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "<code", ">", "java", ".", "sql", ".", "Time<", "/", "code", ">", "value", "using", "the", "given", "<code", ">", "Calendar<", "/", "code", ">", "object", ".", "The", "driver", "uses", "the", "<code", ">", "Calendar<", "/", "code", ">", "object", "to", "construct", "an", "SQL", "<code", ">", "TIME<", "/", "code", ">", "value", "which", "the", "driver", "then", "sends", "to", "the", "database", ".", "With", "a", "<code", ">", "Calendar<", "/", "code", ">", "object", "the", "driver", "can", "calculate", "the", "time", "taking", "into", "account", "a", "custom", "timezone", ".", "If", "no", "<code", ">", "Calendar<", "/", "code", ">", "object", "is", "specified", "the", "driver", "uses", "the", "default", "timezone", "which", "is", "that", "of", "the", "virtual", "machine", "running", "the", "application", "." ]
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzlePreparedStatement.java#L375-L385
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/Jinx.java
Jinx.uploadOrReplace
protected <T> T uploadOrReplace(Map<String, String> params, byte[] photoData, Class<T> tClass, OAuthRequest request) throws JinxException { """ Handle Flickr upload and replace API calls. <br> The action taken will depend on the OAuth request object that is passed in. The upload and replace methods delegate to this method. This method does the work to ensure that the OAuth signature is generated correctly according to Flickr's requirements for uploads. @param params request parameters. @param photoData the data to send to Flickr. @param tClass the class that will be returned. @param <T> type of the class returned. @param request the OAuthRequest object to use. @return an instance of the specified class containing data from Flickr. @throws JinxException if there are any errors. """ String boundary = JinxUtils.generateBoundary(); request.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary); for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); if (!key.equals("photo") && !key.equals("filename") && !key.equals("filemimetype")) { request.addQuerystringParameter(key, String.valueOf(entry.getValue())); } } this.oAuthService.signRequest(this.accessToken, request); // add all parameters to payload params.putAll(request.getOauthParameters()); request.addPayload(buildMultipartBody(params, photoData, boundary)); org.scribe.model.Response flickrResponse = request.send(); if (flickrResponse == null || flickrResponse.getBody() == null) { throw new JinxException("Null return from call to Flickr."); } if (verboseLogging) { JinxLogger.getLogger().log("RESPONSE is " + flickrResponse.getBody()); } // upload returns XML, so convert to json String json = JinxUtils.xml2json(flickrResponse.getBody()); T fromJson = gson.fromJson(json, tClass); if (this.flickrErrorThrowsException && ((Response) fromJson).getCode() != 0) { Response r = (Response) fromJson; throw new JinxException("Flickr returned non-zero status.", null, r); } return fromJson; }
java
protected <T> T uploadOrReplace(Map<String, String> params, byte[] photoData, Class<T> tClass, OAuthRequest request) throws JinxException { String boundary = JinxUtils.generateBoundary(); request.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary); for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); if (!key.equals("photo") && !key.equals("filename") && !key.equals("filemimetype")) { request.addQuerystringParameter(key, String.valueOf(entry.getValue())); } } this.oAuthService.signRequest(this.accessToken, request); // add all parameters to payload params.putAll(request.getOauthParameters()); request.addPayload(buildMultipartBody(params, photoData, boundary)); org.scribe.model.Response flickrResponse = request.send(); if (flickrResponse == null || flickrResponse.getBody() == null) { throw new JinxException("Null return from call to Flickr."); } if (verboseLogging) { JinxLogger.getLogger().log("RESPONSE is " + flickrResponse.getBody()); } // upload returns XML, so convert to json String json = JinxUtils.xml2json(flickrResponse.getBody()); T fromJson = gson.fromJson(json, tClass); if (this.flickrErrorThrowsException && ((Response) fromJson).getCode() != 0) { Response r = (Response) fromJson; throw new JinxException("Flickr returned non-zero status.", null, r); } return fromJson; }
[ "protected", "<", "T", ">", "T", "uploadOrReplace", "(", "Map", "<", "String", ",", "String", ">", "params", ",", "byte", "[", "]", "photoData", ",", "Class", "<", "T", ">", "tClass", ",", "OAuthRequest", "request", ")", "throws", "JinxException", "{", "String", "boundary", "=", "JinxUtils", ".", "generateBoundary", "(", ")", ";", "request", ".", "addHeader", "(", "\"Content-Type\"", ",", "\"multipart/form-data; boundary=\"", "+", "boundary", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "params", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "!", "key", ".", "equals", "(", "\"photo\"", ")", "&&", "!", "key", ".", "equals", "(", "\"filename\"", ")", "&&", "!", "key", ".", "equals", "(", "\"filemimetype\"", ")", ")", "{", "request", ".", "addQuerystringParameter", "(", "key", ",", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ")", ";", "}", "}", "this", ".", "oAuthService", ".", "signRequest", "(", "this", ".", "accessToken", ",", "request", ")", ";", "// add all parameters to payload", "params", ".", "putAll", "(", "request", ".", "getOauthParameters", "(", ")", ")", ";", "request", ".", "addPayload", "(", "buildMultipartBody", "(", "params", ",", "photoData", ",", "boundary", ")", ")", ";", "org", ".", "scribe", ".", "model", ".", "Response", "flickrResponse", "=", "request", ".", "send", "(", ")", ";", "if", "(", "flickrResponse", "==", "null", "||", "flickrResponse", ".", "getBody", "(", ")", "==", "null", ")", "{", "throw", "new", "JinxException", "(", "\"Null return from call to Flickr.\"", ")", ";", "}", "if", "(", "verboseLogging", ")", "{", "JinxLogger", ".", "getLogger", "(", ")", ".", "log", "(", "\"RESPONSE is \"", "+", "flickrResponse", ".", "getBody", "(", ")", ")", ";", "}", "// upload returns XML, so convert to json", "String", "json", "=", "JinxUtils", ".", "xml2json", "(", "flickrResponse", ".", "getBody", "(", ")", ")", ";", "T", "fromJson", "=", "gson", ".", "fromJson", "(", "json", ",", "tClass", ")", ";", "if", "(", "this", ".", "flickrErrorThrowsException", "&&", "(", "(", "Response", ")", "fromJson", ")", ".", "getCode", "(", ")", "!=", "0", ")", "{", "Response", "r", "=", "(", "Response", ")", "fromJson", ";", "throw", "new", "JinxException", "(", "\"Flickr returned non-zero status.\"", ",", "null", ",", "r", ")", ";", "}", "return", "fromJson", ";", "}" ]
Handle Flickr upload and replace API calls. <br> The action taken will depend on the OAuth request object that is passed in. The upload and replace methods delegate to this method. This method does the work to ensure that the OAuth signature is generated correctly according to Flickr's requirements for uploads. @param params request parameters. @param photoData the data to send to Flickr. @param tClass the class that will be returned. @param <T> type of the class returned. @param request the OAuthRequest object to use. @return an instance of the specified class containing data from Flickr. @throws JinxException if there are any errors.
[ "Handle", "Flickr", "upload", "and", "replace", "API", "calls", ".", "<br", ">", "The", "action", "taken", "will", "depend", "on", "the", "OAuth", "request", "object", "that", "is", "passed", "in", ".", "The", "upload", "and", "replace", "methods", "delegate", "to", "this", "method", ".", "This", "method", "does", "the", "work", "to", "ensure", "that", "the", "OAuth", "signature", "is", "generated", "correctly", "according", "to", "Flickr", "s", "requirements", "for", "uploads", "." ]
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/Jinx.java#L637-L672
andi12/msbuild-maven-plugin
msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/AbstractMSBuildPluginMojo.java
AbstractMSBuildPluginMojo.findConfiguredToolPath
private File findConfiguredToolPath( String toolName, File pomValue, String prop, String envvar ) { """ Find a configuration for the specified tool path. The following precedence is observed: System property, POM value, Project property, Environment variable @param toolName the name of the tool being sought, used for logging @param pomValue the value found in the POM @param prop the property name @param envvar the environment variable name @return the value determined or null if not found """ String systemPropertyValue = System.getProperty( prop ); if ( systemPropertyValue != null && !systemPropertyValue.isEmpty() ) { getLog().debug( toolName + " found in " + prop + " system property" ); return new File( systemPropertyValue ); } // No system property, we'll use the pom configured value if provided File result = pomValue; if ( result == null ) { // Try project property ... String projectPropertyValue = mavenProject.getProperties().getProperty( prop ); if ( projectPropertyValue != null && !projectPropertyValue.isEmpty() ) { getLog().debug( toolName + " found in " + prop + " property" ); result = new File( projectPropertyValue ); } else { // Try environment variable ... String envValue = System.getenv( envvar ); if ( envValue != null && !envValue.isEmpty() ) { getLog().debug( toolName + " found in environment variable " + envvar ); result = new File( envValue ); } } } return result; }
java
private File findConfiguredToolPath( String toolName, File pomValue, String prop, String envvar ) { String systemPropertyValue = System.getProperty( prop ); if ( systemPropertyValue != null && !systemPropertyValue.isEmpty() ) { getLog().debug( toolName + " found in " + prop + " system property" ); return new File( systemPropertyValue ); } // No system property, we'll use the pom configured value if provided File result = pomValue; if ( result == null ) { // Try project property ... String projectPropertyValue = mavenProject.getProperties().getProperty( prop ); if ( projectPropertyValue != null && !projectPropertyValue.isEmpty() ) { getLog().debug( toolName + " found in " + prop + " property" ); result = new File( projectPropertyValue ); } else { // Try environment variable ... String envValue = System.getenv( envvar ); if ( envValue != null && !envValue.isEmpty() ) { getLog().debug( toolName + " found in environment variable " + envvar ); result = new File( envValue ); } } } return result; }
[ "private", "File", "findConfiguredToolPath", "(", "String", "toolName", ",", "File", "pomValue", ",", "String", "prop", ",", "String", "envvar", ")", "{", "String", "systemPropertyValue", "=", "System", ".", "getProperty", "(", "prop", ")", ";", "if", "(", "systemPropertyValue", "!=", "null", "&&", "!", "systemPropertyValue", ".", "isEmpty", "(", ")", ")", "{", "getLog", "(", ")", ".", "debug", "(", "toolName", "+", "\" found in \"", "+", "prop", "+", "\" system property\"", ")", ";", "return", "new", "File", "(", "systemPropertyValue", ")", ";", "}", "// No system property, we'll use the pom configured value if provided", "File", "result", "=", "pomValue", ";", "if", "(", "result", "==", "null", ")", "{", "// Try project property ...", "String", "projectPropertyValue", "=", "mavenProject", ".", "getProperties", "(", ")", ".", "getProperty", "(", "prop", ")", ";", "if", "(", "projectPropertyValue", "!=", "null", "&&", "!", "projectPropertyValue", ".", "isEmpty", "(", ")", ")", "{", "getLog", "(", ")", ".", "debug", "(", "toolName", "+", "\" found in \"", "+", "prop", "+", "\" property\"", ")", ";", "result", "=", "new", "File", "(", "projectPropertyValue", ")", ";", "}", "else", "{", "// Try environment variable ...", "String", "envValue", "=", "System", ".", "getenv", "(", "envvar", ")", ";", "if", "(", "envValue", "!=", "null", "&&", "!", "envValue", ".", "isEmpty", "(", ")", ")", "{", "getLog", "(", ")", ".", "debug", "(", "toolName", "+", "\" found in environment variable \"", "+", "envvar", ")", ";", "result", "=", "new", "File", "(", "envValue", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Find a configuration for the specified tool path. The following precedence is observed: System property, POM value, Project property, Environment variable @param toolName the name of the tool being sought, used for logging @param pomValue the value found in the POM @param prop the property name @param envvar the environment variable name @return the value determined or null if not found
[ "Find", "a", "configuration", "for", "the", "specified", "tool", "path", ".", "The", "following", "precedence", "is", "observed", ":", "System", "property", "POM", "value", "Project", "property", "Environment", "variable" ]
train
https://github.com/andi12/msbuild-maven-plugin/blob/224159c15efba20d482f8c630f7947339b1a1b86/msbuild-maven-plugin/src/main/java/uk/org/raje/maven/plugin/msbuild/AbstractMSBuildPluginMojo.java#L112-L146
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/parser/PdfContentStreamProcessor.java
PdfContentStreamProcessor.displayPdfString
public void displayPdfString(PdfString string, float tj) { """ Displays text. @param string the text to display @param tj the text adjustment """ String unicode = decode(string); // this is width in unscaled units - we have to normalize by the Tm scaling float width = getStringWidth(unicode, tj); Matrix nextTextMatrix = new Matrix(width, 0).multiply(textMatrix); displayText(unicode, nextTextMatrix); textMatrix = nextTextMatrix; }
java
public void displayPdfString(PdfString string, float tj) { String unicode = decode(string); // this is width in unscaled units - we have to normalize by the Tm scaling float width = getStringWidth(unicode, tj); Matrix nextTextMatrix = new Matrix(width, 0).multiply(textMatrix); displayText(unicode, nextTextMatrix); textMatrix = nextTextMatrix; }
[ "public", "void", "displayPdfString", "(", "PdfString", "string", ",", "float", "tj", ")", "{", "String", "unicode", "=", "decode", "(", "string", ")", ";", "// this is width in unscaled units - we have to normalize by the Tm scaling\r", "float", "width", "=", "getStringWidth", "(", "unicode", ",", "tj", ")", ";", "Matrix", "nextTextMatrix", "=", "new", "Matrix", "(", "width", ",", "0", ")", ".", "multiply", "(", "textMatrix", ")", ";", "displayText", "(", "unicode", ",", "nextTextMatrix", ")", ";", "textMatrix", "=", "nextTextMatrix", ";", "}" ]
Displays text. @param string the text to display @param tj the text adjustment
[ "Displays", "text", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/parser/PdfContentStreamProcessor.java#L244-L251
sawano/java-commons
src/main/java/se/sawano/java/commons/lang/validate/Validate.java
Validate.inclusiveBetween
public static long inclusiveBetween(long start, long end, long value, String message) { """ Validate that the specified primitive value falls between the two inclusive values specified; otherwise, throws an exception with the specified message. <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre> @param start the inclusive start value @param end the inclusive end value @param value the value to validate @param message the exception message if invalid, not null @return the value @throws IllegalArgumentValidationException if the value falls outside the boundaries """ return INSTANCE.inclusiveBetween(start, end, value, message); }
java
public static long inclusiveBetween(long start, long end, long value, String message) { return INSTANCE.inclusiveBetween(start, end, value, message); }
[ "public", "static", "long", "inclusiveBetween", "(", "long", "start", ",", "long", "end", ",", "long", "value", ",", "String", "message", ")", "{", "return", "INSTANCE", ".", "inclusiveBetween", "(", "start", ",", "end", ",", "value", ",", "message", ")", ";", "}" ]
Validate that the specified primitive value falls between the two inclusive values specified; otherwise, throws an exception with the specified message. <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre> @param start the inclusive start value @param end the inclusive end value @param value the value to validate @param message the exception message if invalid, not null @return the value @throws IllegalArgumentValidationException if the value falls outside the boundaries
[ "Validate", "that", "the", "specified", "primitive", "value", "falls", "between", "the", "two", "inclusive", "values", "specified", ";", "otherwise", "throws", "an", "exception", "with", "the", "specified", "message", ".", "<pre", ">", "Validate", ".", "inclusiveBetween", "(", "0", "2", "1", "Not", "in", "range", ")", ";", "<", "/", "pre", ">" ]
train
https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L1501-L1503
jcuda/jcudnn
JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java
JCudnn.cudnnDeriveBNTensorDescriptor
public static int cudnnDeriveBNTensorDescriptor( cudnnTensorDescriptor derivedBnDesc, cudnnTensorDescriptor xDesc, int mode) { """ <pre> Derives a tensor descriptor from layer data descriptor for BatchNormalization scale, invVariance, bnBias, bnScale tensors. Use this tensor desc for bnScaleBiasMeanVarDesc and bnScaleBiasDiffDesc in Batch Normalization forward and backward functions. </pre> """ return checkResult(cudnnDeriveBNTensorDescriptorNative(derivedBnDesc, xDesc, mode)); }
java
public static int cudnnDeriveBNTensorDescriptor( cudnnTensorDescriptor derivedBnDesc, cudnnTensorDescriptor xDesc, int mode) { return checkResult(cudnnDeriveBNTensorDescriptorNative(derivedBnDesc, xDesc, mode)); }
[ "public", "static", "int", "cudnnDeriveBNTensorDescriptor", "(", "cudnnTensorDescriptor", "derivedBnDesc", ",", "cudnnTensorDescriptor", "xDesc", ",", "int", "mode", ")", "{", "return", "checkResult", "(", "cudnnDeriveBNTensorDescriptorNative", "(", "derivedBnDesc", ",", "xDesc", ",", "mode", ")", ")", ";", "}" ]
<pre> Derives a tensor descriptor from layer data descriptor for BatchNormalization scale, invVariance, bnBias, bnScale tensors. Use this tensor desc for bnScaleBiasMeanVarDesc and bnScaleBiasDiffDesc in Batch Normalization forward and backward functions. </pre>
[ "<pre", ">", "Derives", "a", "tensor", "descriptor", "from", "layer", "data", "descriptor", "for", "BatchNormalization", "scale", "invVariance", "bnBias", "bnScale", "tensors", ".", "Use", "this", "tensor", "desc", "for", "bnScaleBiasMeanVarDesc", "and", "bnScaleBiasDiffDesc", "in", "Batch", "Normalization", "forward", "and", "backward", "functions", ".", "<", "/", "pre", ">" ]
train
https://github.com/jcuda/jcudnn/blob/ce71f2fc02817cecace51a80e6db5f0c7f10cffc/JCudnnJava/src/main/java/jcuda/jcudnn/JCudnn.java#L2187-L2193
sd4324530/fastweixin
src/main/java/com/github/sd4324530/fastweixin/api/QrcodeAPI.java
QrcodeAPI.createQrcode
public QrcodeResponse createQrcode(QrcodeType actionName, String sceneId, String sceneStr, Integer expireSeconds) { """ 创建二维码 @param actionName 二维码类型,QR_SCENE为临时,QR_LIMIT_SCENE为永久 @param sceneId 场景值ID,临时二维码时为32位非0整型,永久二维码时最大值为100000(目前参数只支持1--100000) @param sceneStr 场景值ID(字符串形式的ID),字符串类型,长度限制为1到64,仅永久二维码支持此字段 @param expireSeconds 该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为30秒 @return 二维码对象 """ BeanUtil.requireNonNull(actionName, "actionName is null"); BeanUtil.requireNonNull(sceneId, "actionInfo is null"); LOG.debug("创建二维码信息....."); QrcodeResponse response = null; String url = BASE_API_URL + "cgi-bin/qrcode/create?access_token=#"; Map<String, Object> param = new HashMap<String, Object>(); param.put("action_name", actionName); Map<String, Object> actionInfo = new HashMap<String, Object>(); Map<String, Object> scene = new HashMap<String, Object>(); if (StrUtil.isNotBlank(sceneId)) scene.put("scene_id", sceneId); if (StrUtil.isNotBlank(sceneStr)) scene.put("scene_str", sceneStr); actionInfo.put("scene", scene); param.put("action_info", actionInfo); if (BeanUtil.nonNull(expireSeconds) && 0 != expireSeconds) { param.put("expire_seconds", expireSeconds); } BaseResponse r = executePost(url, JSONUtil.toJson(param)); String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); response = JSONUtil.toBean(resultJson, QrcodeResponse.class); return response; }
java
public QrcodeResponse createQrcode(QrcodeType actionName, String sceneId, String sceneStr, Integer expireSeconds) { BeanUtil.requireNonNull(actionName, "actionName is null"); BeanUtil.requireNonNull(sceneId, "actionInfo is null"); LOG.debug("创建二维码信息....."); QrcodeResponse response = null; String url = BASE_API_URL + "cgi-bin/qrcode/create?access_token=#"; Map<String, Object> param = new HashMap<String, Object>(); param.put("action_name", actionName); Map<String, Object> actionInfo = new HashMap<String, Object>(); Map<String, Object> scene = new HashMap<String, Object>(); if (StrUtil.isNotBlank(sceneId)) scene.put("scene_id", sceneId); if (StrUtil.isNotBlank(sceneStr)) scene.put("scene_str", sceneStr); actionInfo.put("scene", scene); param.put("action_info", actionInfo); if (BeanUtil.nonNull(expireSeconds) && 0 != expireSeconds) { param.put("expire_seconds", expireSeconds); } BaseResponse r = executePost(url, JSONUtil.toJson(param)); String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); response = JSONUtil.toBean(resultJson, QrcodeResponse.class); return response; }
[ "public", "QrcodeResponse", "createQrcode", "(", "QrcodeType", "actionName", ",", "String", "sceneId", ",", "String", "sceneStr", ",", "Integer", "expireSeconds", ")", "{", "BeanUtil", ".", "requireNonNull", "(", "actionName", ",", "\"actionName is null\"", ")", ";", "BeanUtil", ".", "requireNonNull", "(", "sceneId", ",", "\"actionInfo is null\"", ")", ";", "LOG", ".", "debug", "(", "\"创建二维码信息.....\");", "", "", "QrcodeResponse", "response", "=", "null", ";", "String", "url", "=", "BASE_API_URL", "+", "\"cgi-bin/qrcode/create?access_token=#\"", ";", "Map", "<", "String", ",", "Object", ">", "param", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "param", ".", "put", "(", "\"action_name\"", ",", "actionName", ")", ";", "Map", "<", "String", ",", "Object", ">", "actionInfo", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "scene", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "if", "(", "StrUtil", ".", "isNotBlank", "(", "sceneId", ")", ")", "scene", ".", "put", "(", "\"scene_id\"", ",", "sceneId", ")", ";", "if", "(", "StrUtil", ".", "isNotBlank", "(", "sceneStr", ")", ")", "scene", ".", "put", "(", "\"scene_str\"", ",", "sceneStr", ")", ";", "actionInfo", ".", "put", "(", "\"scene\"", ",", "scene", ")", ";", "param", ".", "put", "(", "\"action_info\"", ",", "actionInfo", ")", ";", "if", "(", "BeanUtil", ".", "nonNull", "(", "expireSeconds", ")", "&&", "0", "!=", "expireSeconds", ")", "{", "param", ".", "put", "(", "\"expire_seconds\"", ",", "expireSeconds", ")", ";", "}", "BaseResponse", "r", "=", "executePost", "(", "url", ",", "JSONUtil", ".", "toJson", "(", "param", ")", ")", ";", "String", "resultJson", "=", "isSuccess", "(", "r", ".", "getErrcode", "(", ")", ")", "?", "r", ".", "getErrmsg", "(", ")", ":", "r", ".", "toJsonString", "(", ")", ";", "response", "=", "JSONUtil", ".", "toBean", "(", "resultJson", ",", "QrcodeResponse", ".", "class", ")", ";", "return", "response", ";", "}" ]
创建二维码 @param actionName 二维码类型,QR_SCENE为临时,QR_LIMIT_SCENE为永久 @param sceneId 场景值ID,临时二维码时为32位非0整型,永久二维码时最大值为100000(目前参数只支持1--100000) @param sceneStr 场景值ID(字符串形式的ID),字符串类型,长度限制为1到64,仅永久二维码支持此字段 @param expireSeconds 该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为30秒 @return 二维码对象
[ "创建二维码" ]
train
https://github.com/sd4324530/fastweixin/blob/6bc0a7abfa23aad0dbad4c3123a47a7fb53f3447/src/main/java/com/github/sd4324530/fastweixin/api/QrcodeAPI.java#L51-L77
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/FreesoundClient.java
FreesoundClient.refreshAccessToken
public Response<AccessTokenDetails> refreshAccessToken(final String refreshToken) throws FreesoundClientException { """ Retrieve a new OAuth2 access token using a refresh token. @param refreshToken The refresh token to present @return Details of the access token returned @throws FreesoundClientException Any exception thrown during call """ final RefreshOAuth2AccessTokenRequest tokenRequest = new RefreshOAuth2AccessTokenRequest(clientId, clientSecret, refreshToken); return executeQuery(tokenRequest); }
java
public Response<AccessTokenDetails> refreshAccessToken(final String refreshToken) throws FreesoundClientException { final RefreshOAuth2AccessTokenRequest tokenRequest = new RefreshOAuth2AccessTokenRequest(clientId, clientSecret, refreshToken); return executeQuery(tokenRequest); }
[ "public", "Response", "<", "AccessTokenDetails", ">", "refreshAccessToken", "(", "final", "String", "refreshToken", ")", "throws", "FreesoundClientException", "{", "final", "RefreshOAuth2AccessTokenRequest", "tokenRequest", "=", "new", "RefreshOAuth2AccessTokenRequest", "(", "clientId", ",", "clientSecret", ",", "refreshToken", ")", ";", "return", "executeQuery", "(", "tokenRequest", ")", ";", "}" ]
Retrieve a new OAuth2 access token using a refresh token. @param refreshToken The refresh token to present @return Details of the access token returned @throws FreesoundClientException Any exception thrown during call
[ "Retrieve", "a", "new", "OAuth2", "access", "token", "using", "a", "refresh", "token", "." ]
train
https://github.com/Sonoport/freesound-java/blob/ab029e25de068c6f8cc028bc7f916938fd97c036/src/main/java/com/sonoport/freesound/FreesoundClient.java#L263-L268
pryzach/midao
midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/CallableUtils.java
CallableUtils.getStoredProcedureFullName
public static String getStoredProcedureFullName(String decodedSql) { """ Returns full function name. Example: call schema.package.name - "schema.package.name" would be returned @param decodedSql SQL String which would be processed @return full procedure name """ String spName = null; Pattern regexPattern = null; Matcher regexMatcher = null; regexPattern = Pattern.compile(REGEX_PROCEDURE_FULL_NAME, Pattern.CASE_INSENSITIVE); regexMatcher = regexPattern.matcher(decodedSql); if (regexMatcher.find() == true) { spName = regexMatcher.group(); spName = spName.trim(); } else { throw new IllegalArgumentException(String.format(ERROR_FULL_PROCEDURE_NAME_NOT_FOUND, decodedSql)); } return spName; }
java
public static String getStoredProcedureFullName(String decodedSql) { String spName = null; Pattern regexPattern = null; Matcher regexMatcher = null; regexPattern = Pattern.compile(REGEX_PROCEDURE_FULL_NAME, Pattern.CASE_INSENSITIVE); regexMatcher = regexPattern.matcher(decodedSql); if (regexMatcher.find() == true) { spName = regexMatcher.group(); spName = spName.trim(); } else { throw new IllegalArgumentException(String.format(ERROR_FULL_PROCEDURE_NAME_NOT_FOUND, decodedSql)); } return spName; }
[ "public", "static", "String", "getStoredProcedureFullName", "(", "String", "decodedSql", ")", "{", "String", "spName", "=", "null", ";", "Pattern", "regexPattern", "=", "null", ";", "Matcher", "regexMatcher", "=", "null", ";", "regexPattern", "=", "Pattern", ".", "compile", "(", "REGEX_PROCEDURE_FULL_NAME", ",", "Pattern", ".", "CASE_INSENSITIVE", ")", ";", "regexMatcher", "=", "regexPattern", ".", "matcher", "(", "decodedSql", ")", ";", "if", "(", "regexMatcher", ".", "find", "(", ")", "==", "true", ")", "{", "spName", "=", "regexMatcher", ".", "group", "(", ")", ";", "spName", "=", "spName", ".", "trim", "(", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "ERROR_FULL_PROCEDURE_NAME_NOT_FOUND", ",", "decodedSql", ")", ")", ";", "}", "return", "spName", ";", "}" ]
Returns full function name. Example: call schema.package.name - "schema.package.name" would be returned @param decodedSql SQL String which would be processed @return full procedure name
[ "Returns", "full", "function", "name", ".", "Example", ":", "call", "schema", ".", "package", ".", "name", "-", "schema", ".", "package", ".", "name", "would", "be", "returned" ]
train
https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/CallableUtils.java#L85-L103
ModeShape/modeshape
sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/StandardDdlParser.java
StandardDdlParser.parseAlterStatement
protected AstNode parseAlterStatement( DdlTokenStream tokens, AstNode parentNode ) throws ParsingException { """ Parses DDL ALTER statement based on SQL 92 specifications. @param tokens the {@link DdlTokenStream} representing the tokenized DDL content; may not be null @param parentNode the parent {@link AstNode} node; may not be null @return the parsed ALTER {@link AstNode} @throws ParsingException """ assert tokens != null; assert parentNode != null; if (tokens.matches(ALTER, TABLE)) { return parseAlterTableStatement(tokens, parentNode); } else if (tokens.matches("ALTER", "DOMAIN")) { markStartOfStatement(tokens); tokens.consume("ALTER", "DOMAIN"); String domainName = parseName(tokens); AstNode alterNode = nodeFactory().node(domainName, parentNode, TYPE_ALTER_DOMAIN_STATEMENT); parseUntilTerminator(tokens); markEndOfStatement(tokens, alterNode); return alterNode; } return null; }
java
protected AstNode parseAlterStatement( DdlTokenStream tokens, AstNode parentNode ) throws ParsingException { assert tokens != null; assert parentNode != null; if (tokens.matches(ALTER, TABLE)) { return parseAlterTableStatement(tokens, parentNode); } else if (tokens.matches("ALTER", "DOMAIN")) { markStartOfStatement(tokens); tokens.consume("ALTER", "DOMAIN"); String domainName = parseName(tokens); AstNode alterNode = nodeFactory().node(domainName, parentNode, TYPE_ALTER_DOMAIN_STATEMENT); parseUntilTerminator(tokens); markEndOfStatement(tokens, alterNode); return alterNode; } return null; }
[ "protected", "AstNode", "parseAlterStatement", "(", "DdlTokenStream", "tokens", ",", "AstNode", "parentNode", ")", "throws", "ParsingException", "{", "assert", "tokens", "!=", "null", ";", "assert", "parentNode", "!=", "null", ";", "if", "(", "tokens", ".", "matches", "(", "ALTER", ",", "TABLE", ")", ")", "{", "return", "parseAlterTableStatement", "(", "tokens", ",", "parentNode", ")", ";", "}", "else", "if", "(", "tokens", ".", "matches", "(", "\"ALTER\"", ",", "\"DOMAIN\"", ")", ")", "{", "markStartOfStatement", "(", "tokens", ")", ";", "tokens", ".", "consume", "(", "\"ALTER\"", ",", "\"DOMAIN\"", ")", ";", "String", "domainName", "=", "parseName", "(", "tokens", ")", ";", "AstNode", "alterNode", "=", "nodeFactory", "(", ")", ".", "node", "(", "domainName", ",", "parentNode", ",", "TYPE_ALTER_DOMAIN_STATEMENT", ")", ";", "parseUntilTerminator", "(", "tokens", ")", ";", "markEndOfStatement", "(", "tokens", ",", "alterNode", ")", ";", "return", "alterNode", ";", "}", "return", "null", ";", "}" ]
Parses DDL ALTER statement based on SQL 92 specifications. @param tokens the {@link DdlTokenStream} representing the tokenized DDL content; may not be null @param parentNode the parent {@link AstNode} node; may not be null @return the parsed ALTER {@link AstNode} @throws ParsingException
[ "Parses", "DDL", "ALTER", "statement", "based", "on", "SQL", "92", "specifications", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/sequencers/modeshape-sequencer-ddl/src/main/java/org/modeshape/sequencer/ddl/StandardDdlParser.java#L605-L622
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/Objects2.java
Objects2.checkNotEmpty
public static <T> T checkNotEmpty(T reference, Object errorMessage) { """ Performs emptiness and nullness check. @see #checkNotEmpty(Object, String, Object...) """ checkNotNull(reference, "Expected not null object, got '%s'", reference); checkNotEmpty(reference, String.valueOf(errorMessage), Arrays2.EMPTY_ARRAY); return reference; }
java
public static <T> T checkNotEmpty(T reference, Object errorMessage) { checkNotNull(reference, "Expected not null object, got '%s'", reference); checkNotEmpty(reference, String.valueOf(errorMessage), Arrays2.EMPTY_ARRAY); return reference; }
[ "public", "static", "<", "T", ">", "T", "checkNotEmpty", "(", "T", "reference", ",", "Object", "errorMessage", ")", "{", "checkNotNull", "(", "reference", ",", "\"Expected not null object, got '%s'\"", ",", "reference", ")", ";", "checkNotEmpty", "(", "reference", ",", "String", ".", "valueOf", "(", "errorMessage", ")", ",", "Arrays2", ".", "EMPTY_ARRAY", ")", ";", "return", "reference", ";", "}" ]
Performs emptiness and nullness check. @see #checkNotEmpty(Object, String, Object...)
[ "Performs", "emptiness", "and", "nullness", "check", "." ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/Objects2.java#L604-L608
mangstadt/biweekly
src/main/java/biweekly/component/VAlarm.java
VAlarm.setRepeat
public void setRepeat(int count, Duration pauseDuration) { """ Sets the repetition information for the alarm. @param count the repeat count (e.g. "2" to repeat it two more times after it was initially triggered, for a total of three times) @param pauseDuration the length of the pause between repeats @see <a href="http://tools.ietf.org/html/rfc5545#page-133">RFC 5545 p.133</a> @see <a href="http://tools.ietf.org/html/rfc2445#page-126">RFC 2445 p.126-7</a> """ Repeat repeat = new Repeat(count); DurationProperty duration = new DurationProperty(pauseDuration); setRepeat(repeat); setDuration(duration); }
java
public void setRepeat(int count, Duration pauseDuration) { Repeat repeat = new Repeat(count); DurationProperty duration = new DurationProperty(pauseDuration); setRepeat(repeat); setDuration(duration); }
[ "public", "void", "setRepeat", "(", "int", "count", ",", "Duration", "pauseDuration", ")", "{", "Repeat", "repeat", "=", "new", "Repeat", "(", "count", ")", ";", "DurationProperty", "duration", "=", "new", "DurationProperty", "(", "pauseDuration", ")", ";", "setRepeat", "(", "repeat", ")", ";", "setDuration", "(", "duration", ")", ";", "}" ]
Sets the repetition information for the alarm. @param count the repeat count (e.g. "2" to repeat it two more times after it was initially triggered, for a total of three times) @param pauseDuration the length of the pause between repeats @see <a href="http://tools.ietf.org/html/rfc5545#page-133">RFC 5545 p.133</a> @see <a href="http://tools.ietf.org/html/rfc2445#page-126">RFC 2445 p.126-7</a>
[ "Sets", "the", "repetition", "information", "for", "the", "alarm", "." ]
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/component/VAlarm.java#L487-L492
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/linkbuilder/StandardLinkBuilder.java
StandardLinkBuilder.processLink
protected String processLink(final IExpressionContext context, final String link) { """ <p> Process an already-built URL just before returning it. </p> <p> By default, this method will apply the {@code HttpServletResponse.encodeURL(url)} mechanism, as standard when using the Java Servlet API. Note however that this will only be applied if {@code context} is an implementation of {@code IWebContext} (i.e. the Servlet API will only be applied in web environments). </p> <p> This method can be overridden by any subclasses that want to change this behaviour (e.g. in order to avoid using the Servlet API). </p> @param context the execution context. @param link the already-built URL. @return the processed URL, ready to be used. """ if (!(context instanceof IWebContext)) { return link; } final HttpServletResponse response = ((IWebContext)context).getResponse(); return (response != null? response.encodeURL(link) : link); }
java
protected String processLink(final IExpressionContext context, final String link) { if (!(context instanceof IWebContext)) { return link; } final HttpServletResponse response = ((IWebContext)context).getResponse(); return (response != null? response.encodeURL(link) : link); }
[ "protected", "String", "processLink", "(", "final", "IExpressionContext", "context", ",", "final", "String", "link", ")", "{", "if", "(", "!", "(", "context", "instanceof", "IWebContext", ")", ")", "{", "return", "link", ";", "}", "final", "HttpServletResponse", "response", "=", "(", "(", "IWebContext", ")", "context", ")", ".", "getResponse", "(", ")", ";", "return", "(", "response", "!=", "null", "?", "response", ".", "encodeURL", "(", "link", ")", ":", "link", ")", ";", "}" ]
<p> Process an already-built URL just before returning it. </p> <p> By default, this method will apply the {@code HttpServletResponse.encodeURL(url)} mechanism, as standard when using the Java Servlet API. Note however that this will only be applied if {@code context} is an implementation of {@code IWebContext} (i.e. the Servlet API will only be applied in web environments). </p> <p> This method can be overridden by any subclasses that want to change this behaviour (e.g. in order to avoid using the Servlet API). </p> @param context the execution context. @param link the already-built URL. @return the processed URL, ready to be used.
[ "<p", ">", "Process", "an", "already", "-", "built", "URL", "just", "before", "returning", "it", ".", "<", "/", "p", ">", "<p", ">", "By", "default", "this", "method", "will", "apply", "the", "{", "@code", "HttpServletResponse", ".", "encodeURL", "(", "url", ")", "}", "mechanism", "as", "standard", "when", "using", "the", "Java", "Servlet", "API", ".", "Note", "however", "that", "this", "will", "only", "be", "applied", "if", "{", "@code", "context", "}", "is", "an", "implementation", "of", "{", "@code", "IWebContext", "}", "(", "i", ".", "e", ".", "the", "Servlet", "API", "will", "only", "be", "applied", "in", "web", "environments", ")", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "can", "be", "overridden", "by", "any", "subclasses", "that", "want", "to", "change", "this", "behaviour", "(", "e", ".", "g", ".", "in", "order", "to", "avoid", "using", "the", "Servlet", "API", ")", ".", "<", "/", "p", ">" ]
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/linkbuilder/StandardLinkBuilder.java#L521-L530
ltsopensource/light-task-scheduler
lts-core/src/main/java/com/github/ltsopensource/core/commons/utils/GenericsUtils.java
GenericsUtils.getSuperClassGenericType
public static Class getSuperClassGenericType(Class clazz, int index) { """ 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> @param clazz clazz 需要反射的类,该类必须继承范型父类 @param index 泛型参数所在索引,从0开始. @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code> """ Type genType = clazz.getGenericSuperclass();//得到泛型父类 //如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class if (!(genType instanceof ParameterizedType)) { return Object.class; } //返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型 Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { throw new IllegalArgumentException("index "+ (index<0 ? " must > 0 " : " over total arguments")); } if (!(params[index] instanceof Class)) { return Object.class; } return (Class) params[index]; }
java
public static Class getSuperClassGenericType(Class clazz, int index) { Type genType = clazz.getGenericSuperclass();//得到泛型父类 //如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class if (!(genType instanceof ParameterizedType)) { return Object.class; } //返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型 Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { throw new IllegalArgumentException("index "+ (index<0 ? " must > 0 " : " over total arguments")); } if (!(params[index] instanceof Class)) { return Object.class; } return (Class) params[index]; }
[ "public", "static", "Class", "getSuperClassGenericType", "(", "Class", "clazz", ",", "int", "index", ")", "{", "Type", "genType", "=", "clazz", ".", "getGenericSuperclass", "(", ")", ";", "//得到泛型父类 ", "//如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class", "if", "(", "!", "(", "genType", "instanceof", "ParameterizedType", ")", ")", "{", "return", "Object", ".", "class", ";", "}", "//返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型 ", "Type", "[", "]", "params", "=", "(", "(", "ParameterizedType", ")", "genType", ")", ".", "getActualTypeArguments", "(", ")", ";", "if", "(", "index", ">=", "params", ".", "length", "||", "index", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"index \"", "+", "(", "index", "<", "0", "?", "\" must > 0 \"", ":", "\" over total arguments\"", ")", ")", ";", "}", "if", "(", "!", "(", "params", "[", "index", "]", "instanceof", "Class", ")", ")", "{", "return", "Object", ".", "class", ";", "}", "return", "(", "Class", ")", "params", "[", "index", "]", ";", "}" ]
通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> @param clazz clazz 需要反射的类,该类必须继承范型父类 @param index 泛型参数所在索引,从0开始. @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
[ "通过反射", "获得指定类的父类的泛型参数的实际类型", ".", "如BuyerServiceBean", "extends", "DaoSupport<Buyer", ">" ]
train
https://github.com/ltsopensource/light-task-scheduler/blob/64d3aa000ff5022be5e94f511b58f405e5f4c8eb/lts-core/src/main/java/com/github/ltsopensource/core/commons/utils/GenericsUtils.java#L22-L38
redkale/redkale
src/org/redkale/util/ByteArray.java
ByteArray.toDecodeString
public String toDecodeString(final int offset, int len, final Charset charset) { """ 将指定的起始位置和长度按指定字符集并转义后转成字符串 @param offset 起始位置 @param len 长度 @param charset 字符集 @return 字符串 """ int start = offset; final int end = offset + len; boolean flag = false; //是否需要转义 byte[] bs = content; for (int i = offset; i < end; i++) { if (content[i] == '+' || content[i] == '%') { flag = true; break; } } if (flag) { int index = 0; bs = new byte[len]; for (int i = offset; i < end; i++) { switch (content[i]) { case '+': bs[index] = ' '; break; case '%': bs[index] = (byte) ((hexBit(content[++i]) * 16 + hexBit(content[++i]))); break; default: bs[index] = content[i]; break; } index++; } start = 0; len = index; } if (charset == null) return new String(Utility.decodeUTF8(bs, start, len)); return new String(bs, start, len, charset); }
java
public String toDecodeString(final int offset, int len, final Charset charset) { int start = offset; final int end = offset + len; boolean flag = false; //是否需要转义 byte[] bs = content; for (int i = offset; i < end; i++) { if (content[i] == '+' || content[i] == '%') { flag = true; break; } } if (flag) { int index = 0; bs = new byte[len]; for (int i = offset; i < end; i++) { switch (content[i]) { case '+': bs[index] = ' '; break; case '%': bs[index] = (byte) ((hexBit(content[++i]) * 16 + hexBit(content[++i]))); break; default: bs[index] = content[i]; break; } index++; } start = 0; len = index; } if (charset == null) return new String(Utility.decodeUTF8(bs, start, len)); return new String(bs, start, len, charset); }
[ "public", "String", "toDecodeString", "(", "final", "int", "offset", ",", "int", "len", ",", "final", "Charset", "charset", ")", "{", "int", "start", "=", "offset", ";", "final", "int", "end", "=", "offset", "+", "len", ";", "boolean", "flag", "=", "false", ";", "//是否需要转义\r", "byte", "[", "]", "bs", "=", "content", ";", "for", "(", "int", "i", "=", "offset", ";", "i", "<", "end", ";", "i", "++", ")", "{", "if", "(", "content", "[", "i", "]", "==", "'", "'", "||", "content", "[", "i", "]", "==", "'", "'", ")", "{", "flag", "=", "true", ";", "break", ";", "}", "}", "if", "(", "flag", ")", "{", "int", "index", "=", "0", ";", "bs", "=", "new", "byte", "[", "len", "]", ";", "for", "(", "int", "i", "=", "offset", ";", "i", "<", "end", ";", "i", "++", ")", "{", "switch", "(", "content", "[", "i", "]", ")", "{", "case", "'", "'", ":", "bs", "[", "index", "]", "=", "'", "'", ";", "break", ";", "case", "'", "'", ":", "bs", "[", "index", "]", "=", "(", "byte", ")", "(", "(", "hexBit", "(", "content", "[", "++", "i", "]", ")", "*", "16", "+", "hexBit", "(", "content", "[", "++", "i", "]", ")", ")", ")", ";", "break", ";", "default", ":", "bs", "[", "index", "]", "=", "content", "[", "i", "]", ";", "break", ";", "}", "index", "++", ";", "}", "start", "=", "0", ";", "len", "=", "index", ";", "}", "if", "(", "charset", "==", "null", ")", "return", "new", "String", "(", "Utility", ".", "decodeUTF8", "(", "bs", ",", "start", ",", "len", ")", ")", ";", "return", "new", "String", "(", "bs", ",", "start", ",", "len", ",", "charset", ")", ";", "}" ]
将指定的起始位置和长度按指定字符集并转义后转成字符串 @param offset 起始位置 @param len 长度 @param charset 字符集 @return 字符串
[ "将指定的起始位置和长度按指定字符集并转义后转成字符串" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/util/ByteArray.java#L339-L372
nakamura5akihito/six-util
src/main/java/jp/go/aist/six/util/core/xml/spring327/AbstractMarshaller.java
AbstractMarshaller.marshalSaxResult
protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException { """ Template method for handling {@code SAXResult}s. <p>This implementation delegates to {@code marshalSaxHandlers}. @param graph the root of the object graph to marshal @param saxResult the {@code SAXResult} @throws XmlMappingException if the given object cannot be marshalled to the result @see #marshalSaxHandlers(Object, org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler) """ ContentHandler contentHandler = saxResult.getHandler(); Assert.notNull(contentHandler, "ContentHandler not set on SAXResult"); LexicalHandler lexicalHandler = saxResult.getLexicalHandler(); marshalSaxHandlers(graph, contentHandler, lexicalHandler); }
java
protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException { ContentHandler contentHandler = saxResult.getHandler(); Assert.notNull(contentHandler, "ContentHandler not set on SAXResult"); LexicalHandler lexicalHandler = saxResult.getLexicalHandler(); marshalSaxHandlers(graph, contentHandler, lexicalHandler); }
[ "protected", "void", "marshalSaxResult", "(", "Object", "graph", ",", "SAXResult", "saxResult", ")", "throws", "XmlMappingException", "{", "ContentHandler", "contentHandler", "=", "saxResult", ".", "getHandler", "(", ")", ";", "Assert", ".", "notNull", "(", "contentHandler", ",", "\"ContentHandler not set on SAXResult\"", ")", ";", "LexicalHandler", "lexicalHandler", "=", "saxResult", ".", "getLexicalHandler", "(", ")", ";", "marshalSaxHandlers", "(", "graph", ",", "contentHandler", ",", "lexicalHandler", ")", ";", "}" ]
Template method for handling {@code SAXResult}s. <p>This implementation delegates to {@code marshalSaxHandlers}. @param graph the root of the object graph to marshal @param saxResult the {@code SAXResult} @throws XmlMappingException if the given object cannot be marshalled to the result @see #marshalSaxHandlers(Object, org.xml.sax.ContentHandler, org.xml.sax.ext.LexicalHandler)
[ "Template", "method", "for", "handling", "{" ]
train
https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/core/xml/spring327/AbstractMarshaller.java#L247-L252
mfornos/humanize
humanize-icu/src/main/java/humanize/ICUHumanize.java
ICUHumanize.dateFormatInstance
public static DateFormat dateFormatInstance(final String pattern, final Locale locale) { """ <p> Same as {@link #dateFormatInstance(String) dateFormatInstance} for the specified locale. </p> @param pattern Format pattern that follows the conventions of {@link com.ibm.icu.text.DateFormat DateFormat} @param locale Target locale @return a DateFormat instance for the current thread """ return withinLocale(new Callable<DateFormat>() { public DateFormat call() throws Exception { return dateFormatInstance(pattern); } }, locale); }
java
public static DateFormat dateFormatInstance(final String pattern, final Locale locale) { return withinLocale(new Callable<DateFormat>() { public DateFormat call() throws Exception { return dateFormatInstance(pattern); } }, locale); }
[ "public", "static", "DateFormat", "dateFormatInstance", "(", "final", "String", "pattern", ",", "final", "Locale", "locale", ")", "{", "return", "withinLocale", "(", "new", "Callable", "<", "DateFormat", ">", "(", ")", "{", "public", "DateFormat", "call", "(", ")", "throws", "Exception", "{", "return", "dateFormatInstance", "(", "pattern", ")", ";", "}", "}", ",", "locale", ")", ";", "}" ]
<p> Same as {@link #dateFormatInstance(String) dateFormatInstance} for the specified locale. </p> @param pattern Format pattern that follows the conventions of {@link com.ibm.icu.text.DateFormat DateFormat} @param locale Target locale @return a DateFormat instance for the current thread
[ "<p", ">", "Same", "as", "{", "@link", "#dateFormatInstance", "(", "String", ")", "dateFormatInstance", "}", "for", "the", "specified", "locale", ".", "<", "/", "p", ">" ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-icu/src/main/java/humanize/ICUHumanize.java#L278-L287
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java
MapIterate.getIfAbsentDefault
public static <K, V> V getIfAbsentDefault(Map<K, V> map, K key, V defaultValue) { """ Get and return the value in the Map at the specified key, or if there is no value at the key, return the {@code defaultValue}. """ V result = map.get(key); if (MapIterate.isAbsent(result, map, key)) { result = defaultValue; } return result; }
java
public static <K, V> V getIfAbsentDefault(Map<K, V> map, K key, V defaultValue) { V result = map.get(key); if (MapIterate.isAbsent(result, map, key)) { result = defaultValue; } return result; }
[ "public", "static", "<", "K", ",", "V", ">", "V", "getIfAbsentDefault", "(", "Map", "<", "K", ",", "V", ">", "map", ",", "K", "key", ",", "V", "defaultValue", ")", "{", "V", "result", "=", "map", ".", "get", "(", "key", ")", ";", "if", "(", "MapIterate", ".", "isAbsent", "(", "result", ",", "map", ",", "key", ")", ")", "{", "result", "=", "defaultValue", ";", "}", "return", "result", ";", "}" ]
Get and return the value in the Map at the specified key, or if there is no value at the key, return the {@code defaultValue}.
[ "Get", "and", "return", "the", "value", "in", "the", "Map", "at", "the", "specified", "key", "or", "if", "there", "is", "no", "value", "at", "the", "key", "return", "the", "{" ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/MapIterate.java#L216-L224
EdwardRaff/JSAT
JSAT/src/jsat/distributions/kernels/BaseL2Kernel.java
BaseL2Kernel.getSqrdNorm
protected double getSqrdNorm(int i, int j, List<? extends Vec> vecs, List<Double> cache) { """ Returns the squared L<sup>2</sup> norm between two points from the cache values. @param i the first index in the vector list @param j the second index in the vector list @param vecs the list of vectors that make the collection @param cache the cache of values for each vector in the collection @return the squared norm ||x<sub>i</sub>-x<sub>j</sub>||<sup>2</sup> """ if(cache == null) return Math.pow(vecs.get(i).pNormDist(2.0, vecs.get(j)), 2); return cache.get(i)+cache.get(j)-2*vecs.get(i).dot(vecs.get(j)); }
java
protected double getSqrdNorm(int i, int j, List<? extends Vec> vecs, List<Double> cache) { if(cache == null) return Math.pow(vecs.get(i).pNormDist(2.0, vecs.get(j)), 2); return cache.get(i)+cache.get(j)-2*vecs.get(i).dot(vecs.get(j)); }
[ "protected", "double", "getSqrdNorm", "(", "int", "i", ",", "int", "j", ",", "List", "<", "?", "extends", "Vec", ">", "vecs", ",", "List", "<", "Double", ">", "cache", ")", "{", "if", "(", "cache", "==", "null", ")", "return", "Math", ".", "pow", "(", "vecs", ".", "get", "(", "i", ")", ".", "pNormDist", "(", "2.0", ",", "vecs", ".", "get", "(", "j", ")", ")", ",", "2", ")", ";", "return", "cache", ".", "get", "(", "i", ")", "+", "cache", ".", "get", "(", "j", ")", "-", "2", "*", "vecs", ".", "get", "(", "i", ")", ".", "dot", "(", "vecs", ".", "get", "(", "j", ")", ")", ";", "}" ]
Returns the squared L<sup>2</sup> norm between two points from the cache values. @param i the first index in the vector list @param j the second index in the vector list @param vecs the list of vectors that make the collection @param cache the cache of values for each vector in the collection @return the squared norm ||x<sub>i</sub>-x<sub>j</sub>||<sup>2</sup>
[ "Returns", "the", "squared", "L<sup", ">", "2<", "/", "sup", ">", "norm", "between", "two", "points", "from", "the", "cache", "values", "." ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/BaseL2Kernel.java#L45-L50
edwardcapriolo/gossip
src/main/java/com/google/code/gossip/manager/impl/SendMembersActiveGossipThread.java
SendMembersActiveGossipThread.sendMembershipList
protected void sendMembershipList(LocalGossipMember me, List<LocalGossipMember> memberList) { """ Performs the sending of the membership list, after we have incremented our own heartbeat. """ GossipService.LOGGER.debug("Send sendMembershipList() is called."); me.setHeartbeat(System.currentTimeMillis()); LocalGossipMember member = selectPartner(memberList); if (member == null) { return; } try (DatagramSocket socket = new DatagramSocket()) { socket.setSoTimeout(gossipManager.getSettings().getGossipInterval()); InetAddress dest = InetAddress.getByName(member.getHost()); ActiveGossipMessage message = new ActiveGossipMessage(); message.getMembers().add(convert(me)); for (LocalGossipMember other : memberList) { message.getMembers().add(convert(other)); } byte[] json_bytes = om.writeValueAsString(message).getBytes(); int packet_length = json_bytes.length; if (packet_length < GossipManager.MAX_PACKET_SIZE) { byte[] buf = createBuffer(packet_length, json_bytes); DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, dest, member.getPort()); socket.send(datagramPacket); } else { GossipService.LOGGER.error("The length of the to be send message is too large (" + packet_length + " > " + GossipManager.MAX_PACKET_SIZE + ")."); } } catch (IOException e1) { GossipService.LOGGER.warn(e1); } }
java
protected void sendMembershipList(LocalGossipMember me, List<LocalGossipMember> memberList) { GossipService.LOGGER.debug("Send sendMembershipList() is called."); me.setHeartbeat(System.currentTimeMillis()); LocalGossipMember member = selectPartner(memberList); if (member == null) { return; } try (DatagramSocket socket = new DatagramSocket()) { socket.setSoTimeout(gossipManager.getSettings().getGossipInterval()); InetAddress dest = InetAddress.getByName(member.getHost()); ActiveGossipMessage message = new ActiveGossipMessage(); message.getMembers().add(convert(me)); for (LocalGossipMember other : memberList) { message.getMembers().add(convert(other)); } byte[] json_bytes = om.writeValueAsString(message).getBytes(); int packet_length = json_bytes.length; if (packet_length < GossipManager.MAX_PACKET_SIZE) { byte[] buf = createBuffer(packet_length, json_bytes); DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, dest, member.getPort()); socket.send(datagramPacket); } else { GossipService.LOGGER.error("The length of the to be send message is too large (" + packet_length + " > " + GossipManager.MAX_PACKET_SIZE + ")."); } } catch (IOException e1) { GossipService.LOGGER.warn(e1); } }
[ "protected", "void", "sendMembershipList", "(", "LocalGossipMember", "me", ",", "List", "<", "LocalGossipMember", ">", "memberList", ")", "{", "GossipService", ".", "LOGGER", ".", "debug", "(", "\"Send sendMembershipList() is called.\"", ")", ";", "me", ".", "setHeartbeat", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "LocalGossipMember", "member", "=", "selectPartner", "(", "memberList", ")", ";", "if", "(", "member", "==", "null", ")", "{", "return", ";", "}", "try", "(", "DatagramSocket", "socket", "=", "new", "DatagramSocket", "(", ")", ")", "{", "socket", ".", "setSoTimeout", "(", "gossipManager", ".", "getSettings", "(", ")", ".", "getGossipInterval", "(", ")", ")", ";", "InetAddress", "dest", "=", "InetAddress", ".", "getByName", "(", "member", ".", "getHost", "(", ")", ")", ";", "ActiveGossipMessage", "message", "=", "new", "ActiveGossipMessage", "(", ")", ";", "message", ".", "getMembers", "(", ")", ".", "add", "(", "convert", "(", "me", ")", ")", ";", "for", "(", "LocalGossipMember", "other", ":", "memberList", ")", "{", "message", ".", "getMembers", "(", ")", ".", "add", "(", "convert", "(", "other", ")", ")", ";", "}", "byte", "[", "]", "json_bytes", "=", "om", ".", "writeValueAsString", "(", "message", ")", ".", "getBytes", "(", ")", ";", "int", "packet_length", "=", "json_bytes", ".", "length", ";", "if", "(", "packet_length", "<", "GossipManager", ".", "MAX_PACKET_SIZE", ")", "{", "byte", "[", "]", "buf", "=", "createBuffer", "(", "packet_length", ",", "json_bytes", ")", ";", "DatagramPacket", "datagramPacket", "=", "new", "DatagramPacket", "(", "buf", ",", "buf", ".", "length", ",", "dest", ",", "member", ".", "getPort", "(", ")", ")", ";", "socket", ".", "send", "(", "datagramPacket", ")", ";", "}", "else", "{", "GossipService", ".", "LOGGER", ".", "error", "(", "\"The length of the to be send message is too large (\"", "+", "packet_length", "+", "\" > \"", "+", "GossipManager", ".", "MAX_PACKET_SIZE", "+", "\").\"", ")", ";", "}", "}", "catch", "(", "IOException", "e1", ")", "{", "GossipService", ".", "LOGGER", ".", "warn", "(", "e1", ")", ";", "}", "}" ]
Performs the sending of the membership list, after we have incremented our own heartbeat.
[ "Performs", "the", "sending", "of", "the", "membership", "list", "after", "we", "have", "incremented", "our", "own", "heartbeat", "." ]
train
https://github.com/edwardcapriolo/gossip/blob/ac87301458c7ba4eb7d952046894ebf42ffb0518/src/main/java/com/google/code/gossip/manager/impl/SendMembersActiveGossipThread.java#L57-L85
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuStreamCreateWithPriority
public static int cuStreamCreateWithPriority(CUstream phStream, int flags, int priority) { """ Create a stream with the given priority Creates a stream with the specified priority and returns a handle in phStream. This API alters the scheduler priority of work in the stream. Work in a higher priority stream may preempt work already executing in a low priority stream. priority follows a convention where lower numbers represent higher priorities. '0' represents default priority. The range of meaningful numerical priorities can be queried using ::cuCtxGetStreamPriorityRange. If the specified priority is outside the numerical range returned by ::cuCtxGetStreamPriorityRange, it will automatically be clamped to the lowest or the highest number in the range. @param phStream Returned newly created stream @param flags Flags for stream creation. See ::cuStreamCreate for a list of valid flags @param priority Stream priority. Lower numbers represent higher priorities. See ::cuCtxGetStreamPriorityRange for more information about meaningful stream priorities that can be passed. Note: Stream priorities are supported only on GPUs with compute capability 3.5 or higher. Note: In the current implementation, only compute kernels launched in priority streams are affected by the stream's priority. Stream priorities have no effect on host-to-device and device-to-host memory operations. @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY @see JCudaDriver#cuStreamDestroy @see JCudaDriver#cuStreamCreate @see JCudaDriver#cuStreamGetPriority @see JCudaDriver#cuCtxGetStreamPriorityRange @see JCudaDriver#cuStreamGetFlags @see JCudaDriver#cuStreamWaitEvent @see JCudaDriver#cuStreamQuery @see JCudaDriver#cuStreamSynchronize @see JCudaDriver#cuStreamAddCallback @see JCudaDriver#cudaStreamCreateWithPriority """ return checkResult(cuStreamCreateWithPriorityNative(phStream, flags, priority)); }
java
public static int cuStreamCreateWithPriority(CUstream phStream, int flags, int priority) { return checkResult(cuStreamCreateWithPriorityNative(phStream, flags, priority)); }
[ "public", "static", "int", "cuStreamCreateWithPriority", "(", "CUstream", "phStream", ",", "int", "flags", ",", "int", "priority", ")", "{", "return", "checkResult", "(", "cuStreamCreateWithPriorityNative", "(", "phStream", ",", "flags", ",", "priority", ")", ")", ";", "}" ]
Create a stream with the given priority Creates a stream with the specified priority and returns a handle in phStream. This API alters the scheduler priority of work in the stream. Work in a higher priority stream may preempt work already executing in a low priority stream. priority follows a convention where lower numbers represent higher priorities. '0' represents default priority. The range of meaningful numerical priorities can be queried using ::cuCtxGetStreamPriorityRange. If the specified priority is outside the numerical range returned by ::cuCtxGetStreamPriorityRange, it will automatically be clamped to the lowest or the highest number in the range. @param phStream Returned newly created stream @param flags Flags for stream creation. See ::cuStreamCreate for a list of valid flags @param priority Stream priority. Lower numbers represent higher priorities. See ::cuCtxGetStreamPriorityRange for more information about meaningful stream priorities that can be passed. Note: Stream priorities are supported only on GPUs with compute capability 3.5 or higher. Note: In the current implementation, only compute kernels launched in priority streams are affected by the stream's priority. Stream priorities have no effect on host-to-device and device-to-host memory operations. @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_OUT_OF_MEMORY @see JCudaDriver#cuStreamDestroy @see JCudaDriver#cuStreamCreate @see JCudaDriver#cuStreamGetPriority @see JCudaDriver#cuCtxGetStreamPriorityRange @see JCudaDriver#cuStreamGetFlags @see JCudaDriver#cuStreamWaitEvent @see JCudaDriver#cuStreamQuery @see JCudaDriver#cuStreamSynchronize @see JCudaDriver#cuStreamAddCallback @see JCudaDriver#cudaStreamCreateWithPriority
[ "Create", "a", "stream", "with", "the", "given", "priority" ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L14441-L14444
cryptomator/cryptofs
src/main/java/org/cryptomator/cryptofs/CryptoFileSystemUri.java
CryptoFileSystemUri.create
public static URI create(Path pathToVault, String... pathComponentsInsideVault) { """ Constructs a CryptoFileSystem URI by using the given absolute path to a vault and constructing a path inside the vault from components. @param pathToVault path to the vault @param pathComponentsInsideVault path components to node inside the vault """ try { return new URI(URI_SCHEME, pathToVault.toUri().toString(), "/" + String.join("/", pathComponentsInsideVault), null, null); } catch (URISyntaxException e) { throw new IllegalArgumentException("Can not create URI from given input", e); } }
java
public static URI create(Path pathToVault, String... pathComponentsInsideVault) { try { return new URI(URI_SCHEME, pathToVault.toUri().toString(), "/" + String.join("/", pathComponentsInsideVault), null, null); } catch (URISyntaxException e) { throw new IllegalArgumentException("Can not create URI from given input", e); } }
[ "public", "static", "URI", "create", "(", "Path", "pathToVault", ",", "String", "...", "pathComponentsInsideVault", ")", "{", "try", "{", "return", "new", "URI", "(", "URI_SCHEME", ",", "pathToVault", ".", "toUri", "(", ")", ".", "toString", "(", ")", ",", "\"/\"", "+", "String", ".", "join", "(", "\"/\"", ",", "pathComponentsInsideVault", ")", ",", "null", ",", "null", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Can not create URI from given input\"", ",", "e", ")", ";", "}", "}" ]
Constructs a CryptoFileSystem URI by using the given absolute path to a vault and constructing a path inside the vault from components. @param pathToVault path to the vault @param pathComponentsInsideVault path components to node inside the vault
[ "Constructs", "a", "CryptoFileSystem", "URI", "by", "using", "the", "given", "absolute", "path", "to", "a", "vault", "and", "constructing", "a", "path", "inside", "the", "vault", "from", "components", "." ]
train
https://github.com/cryptomator/cryptofs/blob/67fc1a4950dd1c150cd2e2c75bcabbeb7c9ac82e/src/main/java/org/cryptomator/cryptofs/CryptoFileSystemUri.java#L73-L79
casmi/casmi
src/main/java/casmi/graphics/element/Lines.java
Lines.vertex
public void vertex(double x, double y, double z) { """ Adds the point to Lines. @param x The x-coordinate of a new added point. @param y The y-coordinate of a new added point. @param z The z-coordinate of a new added point. """ MODE = LINES_3D; this.x.add(x); this.y.add(y); this.z.add(z); colors.add(this.strokeColor); calcG(); }
java
public void vertex(double x, double y, double z) { MODE = LINES_3D; this.x.add(x); this.y.add(y); this.z.add(z); colors.add(this.strokeColor); calcG(); }
[ "public", "void", "vertex", "(", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "MODE", "=", "LINES_3D", ";", "this", ".", "x", ".", "add", "(", "x", ")", ";", "this", ".", "y", ".", "add", "(", "y", ")", ";", "this", ".", "z", ".", "add", "(", "z", ")", ";", "colors", ".", "add", "(", "this", ".", "strokeColor", ")", ";", "calcG", "(", ")", ";", "}" ]
Adds the point to Lines. @param x The x-coordinate of a new added point. @param y The y-coordinate of a new added point. @param z The z-coordinate of a new added point.
[ "Adds", "the", "point", "to", "Lines", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Lines.java#L93-L100
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/GeneralSubtrees.java
GeneralSubtrees.createWidestSubtree
private GeneralSubtree createWidestSubtree(GeneralNameInterface name) { """ create a subtree containing an instance of the input name type that widens all other names of that type. @params name GeneralNameInterface name @returns GeneralSubtree containing widest name of that type @throws RuntimeException on error (should not occur) """ try { GeneralName newName; switch (name.getType()) { case GeneralNameInterface.NAME_ANY: // Create new OtherName with same OID as baseName, but // empty value ObjectIdentifier otherOID = ((OtherName)name).getOID(); newName = new GeneralName(new OtherName(otherOID, null)); break; case GeneralNameInterface.NAME_RFC822: newName = new GeneralName(new RFC822Name("")); break; case GeneralNameInterface.NAME_DNS: newName = new GeneralName(new DNSName("")); break; case GeneralNameInterface.NAME_X400: newName = new GeneralName(new X400Address((byte[])null)); break; case GeneralNameInterface.NAME_DIRECTORY: newName = new GeneralName(new X500Name("")); break; case GeneralNameInterface.NAME_EDI: newName = new GeneralName(new EDIPartyName("")); break; case GeneralNameInterface.NAME_URI: newName = new GeneralName(new URIName("")); break; case GeneralNameInterface.NAME_IP: newName = new GeneralName(new IPAddressName((byte[])null)); break; case GeneralNameInterface.NAME_OID: newName = new GeneralName (new OIDName(new ObjectIdentifier((int[])null))); break; default: throw new IOException ("Unsupported GeneralNameInterface type: " + name.getType()); } return new GeneralSubtree(newName, 0, -1); } catch (IOException e) { throw new RuntimeException("Unexpected error: " + e, e); } }
java
private GeneralSubtree createWidestSubtree(GeneralNameInterface name) { try { GeneralName newName; switch (name.getType()) { case GeneralNameInterface.NAME_ANY: // Create new OtherName with same OID as baseName, but // empty value ObjectIdentifier otherOID = ((OtherName)name).getOID(); newName = new GeneralName(new OtherName(otherOID, null)); break; case GeneralNameInterface.NAME_RFC822: newName = new GeneralName(new RFC822Name("")); break; case GeneralNameInterface.NAME_DNS: newName = new GeneralName(new DNSName("")); break; case GeneralNameInterface.NAME_X400: newName = new GeneralName(new X400Address((byte[])null)); break; case GeneralNameInterface.NAME_DIRECTORY: newName = new GeneralName(new X500Name("")); break; case GeneralNameInterface.NAME_EDI: newName = new GeneralName(new EDIPartyName("")); break; case GeneralNameInterface.NAME_URI: newName = new GeneralName(new URIName("")); break; case GeneralNameInterface.NAME_IP: newName = new GeneralName(new IPAddressName((byte[])null)); break; case GeneralNameInterface.NAME_OID: newName = new GeneralName (new OIDName(new ObjectIdentifier((int[])null))); break; default: throw new IOException ("Unsupported GeneralNameInterface type: " + name.getType()); } return new GeneralSubtree(newName, 0, -1); } catch (IOException e) { throw new RuntimeException("Unexpected error: " + e, e); } }
[ "private", "GeneralSubtree", "createWidestSubtree", "(", "GeneralNameInterface", "name", ")", "{", "try", "{", "GeneralName", "newName", ";", "switch", "(", "name", ".", "getType", "(", ")", ")", "{", "case", "GeneralNameInterface", ".", "NAME_ANY", ":", "// Create new OtherName with same OID as baseName, but", "// empty value", "ObjectIdentifier", "otherOID", "=", "(", "(", "OtherName", ")", "name", ")", ".", "getOID", "(", ")", ";", "newName", "=", "new", "GeneralName", "(", "new", "OtherName", "(", "otherOID", ",", "null", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_RFC822", ":", "newName", "=", "new", "GeneralName", "(", "new", "RFC822Name", "(", "\"\"", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_DNS", ":", "newName", "=", "new", "GeneralName", "(", "new", "DNSName", "(", "\"\"", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_X400", ":", "newName", "=", "new", "GeneralName", "(", "new", "X400Address", "(", "(", "byte", "[", "]", ")", "null", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_DIRECTORY", ":", "newName", "=", "new", "GeneralName", "(", "new", "X500Name", "(", "\"\"", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_EDI", ":", "newName", "=", "new", "GeneralName", "(", "new", "EDIPartyName", "(", "\"\"", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_URI", ":", "newName", "=", "new", "GeneralName", "(", "new", "URIName", "(", "\"\"", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_IP", ":", "newName", "=", "new", "GeneralName", "(", "new", "IPAddressName", "(", "(", "byte", "[", "]", ")", "null", ")", ")", ";", "break", ";", "case", "GeneralNameInterface", ".", "NAME_OID", ":", "newName", "=", "new", "GeneralName", "(", "new", "OIDName", "(", "new", "ObjectIdentifier", "(", "(", "int", "[", "]", ")", "null", ")", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "IOException", "(", "\"Unsupported GeneralNameInterface type: \"", "+", "name", ".", "getType", "(", ")", ")", ";", "}", "return", "new", "GeneralSubtree", "(", "newName", ",", "0", ",", "-", "1", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unexpected error: \"", "+", "e", ",", "e", ")", ";", "}", "}" ]
create a subtree containing an instance of the input name type that widens all other names of that type. @params name GeneralNameInterface name @returns GeneralSubtree containing widest name of that type @throws RuntimeException on error (should not occur)
[ "create", "a", "subtree", "containing", "an", "instance", "of", "the", "input", "name", "type", "that", "widens", "all", "other", "names", "of", "that", "type", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/GeneralSubtrees.java#L243-L286
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/utils/disruptor/RingBuffer.java
RingBuffer.publishEvents
public <A, B, C> void publishEvents(EventTranslatorThreeArg<E, A, B, C> translator, int batchStartsAt, int batchSize, A[] arg0, B[] arg1, C[] arg2) { """ Allows three user supplied arguments per event. @param translator The user specified translation for the event @param batchStartsAt The first element of the array which is within the batch. @param batchSize The number of elements in the batch. @param arg0 An array of user supplied arguments, one element per event. @param arg1 An array of user supplied arguments, one element per event. @param arg2 An array of user supplied arguments, one element per event. @see #publishEvents(EventTranslator[]) """ checkBounds(arg0, arg1, arg2, batchStartsAt, batchSize); final long finalSequence = sequencer.next(batchSize); translateAndPublishBatch(translator, arg0, arg1, arg2, batchStartsAt, batchSize, finalSequence); }
java
public <A, B, C> void publishEvents(EventTranslatorThreeArg<E, A, B, C> translator, int batchStartsAt, int batchSize, A[] arg0, B[] arg1, C[] arg2) { checkBounds(arg0, arg1, arg2, batchStartsAt, batchSize); final long finalSequence = sequencer.next(batchSize); translateAndPublishBatch(translator, arg0, arg1, arg2, batchStartsAt, batchSize, finalSequence); }
[ "public", "<", "A", ",", "B", ",", "C", ">", "void", "publishEvents", "(", "EventTranslatorThreeArg", "<", "E", ",", "A", ",", "B", ",", "C", ">", "translator", ",", "int", "batchStartsAt", ",", "int", "batchSize", ",", "A", "[", "]", "arg0", ",", "B", "[", "]", "arg1", ",", "C", "[", "]", "arg2", ")", "{", "checkBounds", "(", "arg0", ",", "arg1", ",", "arg2", ",", "batchStartsAt", ",", "batchSize", ")", ";", "final", "long", "finalSequence", "=", "sequencer", ".", "next", "(", "batchSize", ")", ";", "translateAndPublishBatch", "(", "translator", ",", "arg0", ",", "arg1", ",", "arg2", ",", "batchStartsAt", ",", "batchSize", ",", "finalSequence", ")", ";", "}" ]
Allows three user supplied arguments per event. @param translator The user specified translation for the event @param batchStartsAt The first element of the array which is within the batch. @param batchSize The number of elements in the batch. @param arg0 An array of user supplied arguments, one element per event. @param arg1 An array of user supplied arguments, one element per event. @param arg2 An array of user supplied arguments, one element per event. @see #publishEvents(EventTranslator[])
[ "Allows", "three", "user", "supplied", "arguments", "per", "event", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/utils/disruptor/RingBuffer.java#L710-L714
headius/invokebinder
src/main/java/com/headius/invokebinder/Signature.java
Signature.dropArg
public Signature dropArg(String name) { """ Drops the first argument with the given name. @param name the name of the argument to drop @return a new signature """ String[] newArgNames = new String[argNames.length - 1]; MethodType newType = methodType; for (int i = 0, j = 0; i < argNames.length; i++) { if (argNames[i].equals(name)) { newType = newType.dropParameterTypes(j, j + 1); continue; } newArgNames[j++] = argNames[i]; } if (newType == null) { // arg name not found; should we error? return this; } return new Signature(newType, newArgNames); }
java
public Signature dropArg(String name) { String[] newArgNames = new String[argNames.length - 1]; MethodType newType = methodType; for (int i = 0, j = 0; i < argNames.length; i++) { if (argNames[i].equals(name)) { newType = newType.dropParameterTypes(j, j + 1); continue; } newArgNames[j++] = argNames[i]; } if (newType == null) { // arg name not found; should we error? return this; } return new Signature(newType, newArgNames); }
[ "public", "Signature", "dropArg", "(", "String", "name", ")", "{", "String", "[", "]", "newArgNames", "=", "new", "String", "[", "argNames", ".", "length", "-", "1", "]", ";", "MethodType", "newType", "=", "methodType", ";", "for", "(", "int", "i", "=", "0", ",", "j", "=", "0", ";", "i", "<", "argNames", ".", "length", ";", "i", "++", ")", "{", "if", "(", "argNames", "[", "i", "]", ".", "equals", "(", "name", ")", ")", "{", "newType", "=", "newType", ".", "dropParameterTypes", "(", "j", ",", "j", "+", "1", ")", ";", "continue", ";", "}", "newArgNames", "[", "j", "++", "]", "=", "argNames", "[", "i", "]", ";", "}", "if", "(", "newType", "==", "null", ")", "{", "// arg name not found; should we error?", "return", "this", ";", "}", "return", "new", "Signature", "(", "newType", ",", "newArgNames", ")", ";", "}" ]
Drops the first argument with the given name. @param name the name of the argument to drop @return a new signature
[ "Drops", "the", "first", "argument", "with", "the", "given", "name", "." ]
train
https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/Signature.java#L308-L326
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/SessionApi.java
SessionApi.initializeWorkspace
public ApiSuccessResponse initializeWorkspace(String code, String redirectUri, String state, String authorization) throws ApiException { """ Get and register an auth token Retrieve the authorization token using the authorization code. Workspace then registers the token and prepares the user&#39;s environment. @param code The authorization code. You must include this parameter for the [Authorization Code Grant flow](/reference/authentication/). (optional) @param redirectUri The same redirect URI you used in the initial login step. You must include this parameter for the [Authorization Code Grant flow](/reference/authentication/). (optional) @param state The state parameter provide by the auth service on redirect that should be used to validate. This parameter must be provided if the include_state parameter is sent with the /login request. (optional) @param authorization Bearer authorization. For example, \&quot;Authorization&amp;colon; Bearer access_token\&quot;. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = initializeWorkspaceWithHttpInfo(code, redirectUri, state, authorization); return resp.getData(); }
java
public ApiSuccessResponse initializeWorkspace(String code, String redirectUri, String state, String authorization) throws ApiException { ApiResponse<ApiSuccessResponse> resp = initializeWorkspaceWithHttpInfo(code, redirectUri, state, authorization); return resp.getData(); }
[ "public", "ApiSuccessResponse", "initializeWorkspace", "(", "String", "code", ",", "String", "redirectUri", ",", "String", "state", ",", "String", "authorization", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "initializeWorkspaceWithHttpInfo", "(", "code", ",", "redirectUri", ",", "state", ",", "authorization", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Get and register an auth token Retrieve the authorization token using the authorization code. Workspace then registers the token and prepares the user&#39;s environment. @param code The authorization code. You must include this parameter for the [Authorization Code Grant flow](/reference/authentication/). (optional) @param redirectUri The same redirect URI you used in the initial login step. You must include this parameter for the [Authorization Code Grant flow](/reference/authentication/). (optional) @param state The state parameter provide by the auth service on redirect that should be used to validate. This parameter must be provided if the include_state parameter is sent with the /login request. (optional) @param authorization Bearer authorization. For example, \&quot;Authorization&amp;colon; Bearer access_token\&quot;. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "and", "register", "an", "auth", "token", "Retrieve", "the", "authorization", "token", "using", "the", "authorization", "code", ".", "Workspace", "then", "registers", "the", "token", "and", "prepares", "the", "user&#39", ";", "s", "environment", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/SessionApi.java#L1097-L1100
geomajas/geomajas-project-server
plugin/layer-geotools/geotools/src/main/java/org/geomajas/layer/shapeinmem/ShapeInMemLayer.java
ShapeInMemLayer.setUrl
@Api public void setUrl(String url) throws LayerException { """ Set the url for the shape file. @param url shape file url @throws LayerException file cannot be accessed @since 1.7.1 """ try { this.url = url; Map<String, Object> params = new HashMap<String, Object>(); params.put("url", url); DataStore store = DataStoreFactory.create(params); setDataStore(store); } catch (IOException ioe) { throw new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url); } }
java
@Api public void setUrl(String url) throws LayerException { try { this.url = url; Map<String, Object> params = new HashMap<String, Object>(); params.put("url", url); DataStore store = DataStoreFactory.create(params); setDataStore(store); } catch (IOException ioe) { throw new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url); } }
[ "@", "Api", "public", "void", "setUrl", "(", "String", "url", ")", "throws", "LayerException", "{", "try", "{", "this", ".", "url", "=", "url", ";", "Map", "<", "String", ",", "Object", ">", "params", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "params", ".", "put", "(", "\"url\"", ",", "url", ")", ";", "DataStore", "store", "=", "DataStoreFactory", ".", "create", "(", "params", ")", ";", "setDataStore", "(", "store", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "throw", "new", "LayerException", "(", "ioe", ",", "ExceptionCode", ".", "INVALID_SHAPE_FILE_URL", ",", "url", ")", ";", "}", "}" ]
Set the url for the shape file. @param url shape file url @throws LayerException file cannot be accessed @since 1.7.1
[ "Set", "the", "url", "for", "the", "shape", "file", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/layer-geotools/geotools/src/main/java/org/geomajas/layer/shapeinmem/ShapeInMemLayer.java#L133-L144
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/impl/modes/DefaultUrlMode.java
DefaultUrlMode.getRootPath
private String getRootPath(String path, int rootLevel, ResourceResolver resourceResolver) { """ Gets site root level path of a site. @param path Path of page within the site @param rootLevel Level of root page @param resourceResolver Resource resolver @return Site root path for the site. The path is not checked for validness. """ String rootPath = Path.getAbsoluteParent(path, rootLevel, resourceResolver); // strip off everything after first "." - root path may be passed with selectors/extension which is not relevant if (StringUtils.contains(rootPath, ".")) { rootPath = StringUtils.substringBefore(rootPath, "."); } return rootPath; }
java
private String getRootPath(String path, int rootLevel, ResourceResolver resourceResolver) { String rootPath = Path.getAbsoluteParent(path, rootLevel, resourceResolver); // strip off everything after first "." - root path may be passed with selectors/extension which is not relevant if (StringUtils.contains(rootPath, ".")) { rootPath = StringUtils.substringBefore(rootPath, "."); } return rootPath; }
[ "private", "String", "getRootPath", "(", "String", "path", ",", "int", "rootLevel", ",", "ResourceResolver", "resourceResolver", ")", "{", "String", "rootPath", "=", "Path", ".", "getAbsoluteParent", "(", "path", ",", "rootLevel", ",", "resourceResolver", ")", ";", "// strip off everything after first \".\" - root path may be passed with selectors/extension which is not relevant", "if", "(", "StringUtils", ".", "contains", "(", "rootPath", ",", "\".\"", ")", ")", "{", "rootPath", "=", "StringUtils", ".", "substringBefore", "(", "rootPath", ",", "\".\"", ")", ";", "}", "return", "rootPath", ";", "}" ]
Gets site root level path of a site. @param path Path of page within the site @param rootLevel Level of root page @param resourceResolver Resource resolver @return Site root path for the site. The path is not checked for validness.
[ "Gets", "site", "root", "level", "path", "of", "a", "site", "." ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/impl/modes/DefaultUrlMode.java#L107-L116
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/splitassigner/InputSplitManager.java
InputSplitManager.registerJob
public void registerJob(final ExecutionGraph executionGraph) { """ Registers a new job represented by its {@link ExecutionGraph} with the input split manager. @param executionGraph the job to be registered """ final Iterator<ExecutionGroupVertex> it = new ExecutionGroupVertexIterator(executionGraph, true, -1); while (it.hasNext()) { final ExecutionGroupVertex groupVertex = it.next(); final InputSplit[] inputSplits = groupVertex.getInputSplits(); if (inputSplits == null) { continue; } if (inputSplits.length == 0) { continue; } final AbstractInvokable invokable = groupVertex.getEnvironment().getInvokable(); if (!(invokable instanceof AbstractInputTask)) { LOG.error(groupVertex.getName() + " has " + inputSplits.length + " input splits, but is not of typt AbstractInputTask, ignoring..."); continue; } @SuppressWarnings("unchecked") final AbstractInputTask<? extends InputSplit> inputTask = (AbstractInputTask<? extends InputSplit>) invokable; final Class<? extends InputSplit> splitType = inputTask.getInputSplitType(); final InputSplitAssigner assigner = getAssignerByType(splitType, true); // Add entry to cache for fast retrieval during the job execution this.assignerCache.put(groupVertex, assigner); assigner.registerGroupVertex(groupVertex); } // Register job with the input split tracker this.inputSplitTracker.registerJob(executionGraph); }
java
public void registerJob(final ExecutionGraph executionGraph) { final Iterator<ExecutionGroupVertex> it = new ExecutionGroupVertexIterator(executionGraph, true, -1); while (it.hasNext()) { final ExecutionGroupVertex groupVertex = it.next(); final InputSplit[] inputSplits = groupVertex.getInputSplits(); if (inputSplits == null) { continue; } if (inputSplits.length == 0) { continue; } final AbstractInvokable invokable = groupVertex.getEnvironment().getInvokable(); if (!(invokable instanceof AbstractInputTask)) { LOG.error(groupVertex.getName() + " has " + inputSplits.length + " input splits, but is not of typt AbstractInputTask, ignoring..."); continue; } @SuppressWarnings("unchecked") final AbstractInputTask<? extends InputSplit> inputTask = (AbstractInputTask<? extends InputSplit>) invokable; final Class<? extends InputSplit> splitType = inputTask.getInputSplitType(); final InputSplitAssigner assigner = getAssignerByType(splitType, true); // Add entry to cache for fast retrieval during the job execution this.assignerCache.put(groupVertex, assigner); assigner.registerGroupVertex(groupVertex); } // Register job with the input split tracker this.inputSplitTracker.registerJob(executionGraph); }
[ "public", "void", "registerJob", "(", "final", "ExecutionGraph", "executionGraph", ")", "{", "final", "Iterator", "<", "ExecutionGroupVertex", ">", "it", "=", "new", "ExecutionGroupVertexIterator", "(", "executionGraph", ",", "true", ",", "-", "1", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "final", "ExecutionGroupVertex", "groupVertex", "=", "it", ".", "next", "(", ")", ";", "final", "InputSplit", "[", "]", "inputSplits", "=", "groupVertex", ".", "getInputSplits", "(", ")", ";", "if", "(", "inputSplits", "==", "null", ")", "{", "continue", ";", "}", "if", "(", "inputSplits", ".", "length", "==", "0", ")", "{", "continue", ";", "}", "final", "AbstractInvokable", "invokable", "=", "groupVertex", ".", "getEnvironment", "(", ")", ".", "getInvokable", "(", ")", ";", "if", "(", "!", "(", "invokable", "instanceof", "AbstractInputTask", ")", ")", "{", "LOG", ".", "error", "(", "groupVertex", ".", "getName", "(", ")", "+", "\" has \"", "+", "inputSplits", ".", "length", "+", "\" input splits, but is not of typt AbstractInputTask, ignoring...\"", ")", ";", "continue", ";", "}", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "final", "AbstractInputTask", "<", "?", "extends", "InputSplit", ">", "inputTask", "=", "(", "AbstractInputTask", "<", "?", "extends", "InputSplit", ">", ")", "invokable", ";", "final", "Class", "<", "?", "extends", "InputSplit", ">", "splitType", "=", "inputTask", ".", "getInputSplitType", "(", ")", ";", "final", "InputSplitAssigner", "assigner", "=", "getAssignerByType", "(", "splitType", ",", "true", ")", ";", "// Add entry to cache for fast retrieval during the job execution", "this", ".", "assignerCache", ".", "put", "(", "groupVertex", ",", "assigner", ")", ";", "assigner", ".", "registerGroupVertex", "(", "groupVertex", ")", ";", "}", "// Register job with the input split tracker", "this", ".", "inputSplitTracker", ".", "registerJob", "(", "executionGraph", ")", ";", "}" ]
Registers a new job represented by its {@link ExecutionGraph} with the input split manager. @param executionGraph the job to be registered
[ "Registers", "a", "new", "job", "represented", "by", "its", "{", "@link", "ExecutionGraph", "}", "with", "the", "input", "split", "manager", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/jobmanager/splitassigner/InputSplitManager.java#L89-L125
arakelian/more-commons
src/main/java/com/arakelian/core/utils/XmlStreamReaderUtils.java
XmlStreamReaderUtils.optionalStringAttribute
public static String optionalStringAttribute( final XMLStreamReader reader, final String localName, final String defaultValue) { """ Returns the value of an attribute as a String. If the attribute is empty, this method returns the default value provided. @param reader <code>XMLStreamReader</code> that contains attribute values. @param localName local name of attribute (the namespace is ignored). @param defaultValue default value @return value of attribute, or the default value if the attribute is empty. """ return optionalStringAttribute(reader, null, localName, defaultValue); }
java
public static String optionalStringAttribute( final XMLStreamReader reader, final String localName, final String defaultValue) { return optionalStringAttribute(reader, null, localName, defaultValue); }
[ "public", "static", "String", "optionalStringAttribute", "(", "final", "XMLStreamReader", "reader", ",", "final", "String", "localName", ",", "final", "String", "defaultValue", ")", "{", "return", "optionalStringAttribute", "(", "reader", ",", "null", ",", "localName", ",", "defaultValue", ")", ";", "}" ]
Returns the value of an attribute as a String. If the attribute is empty, this method returns the default value provided. @param reader <code>XMLStreamReader</code> that contains attribute values. @param localName local name of attribute (the namespace is ignored). @param defaultValue default value @return value of attribute, or the default value if the attribute is empty.
[ "Returns", "the", "value", "of", "an", "attribute", "as", "a", "String", ".", "If", "the", "attribute", "is", "empty", "this", "method", "returns", "the", "default", "value", "provided", "." ]
train
https://github.com/arakelian/more-commons/blob/83c607044f64a7f6c005a67866c0ef7cb68d6e29/src/main/java/com/arakelian/core/utils/XmlStreamReaderUtils.java#L932-L937
real-logic/simple-binary-encoding
sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/XmlSchemaParser.java
XmlSchemaParser.checkForValidName
public static void checkForValidName(final Node node, final String name) { """ Check name against validity for C++ and Java naming. Warning if not valid. @param node to have the name checked. @param name of the node to be checked. """ if (!ValidationUtil.isSbeCppName(name)) { handleWarning(node, "name is not valid for C++: " + name); } if (!ValidationUtil.isSbeJavaName(name)) { handleWarning(node, "name is not valid for Java: " + name); } if (!ValidationUtil.isSbeGolangName(name)) { handleWarning(node, "name is not valid for Golang: " + name); } if (!ValidationUtil.isSbeCSharpName(name)) { handleWarning(node, "name is not valid for C#: " + name); } }
java
public static void checkForValidName(final Node node, final String name) { if (!ValidationUtil.isSbeCppName(name)) { handleWarning(node, "name is not valid for C++: " + name); } if (!ValidationUtil.isSbeJavaName(name)) { handleWarning(node, "name is not valid for Java: " + name); } if (!ValidationUtil.isSbeGolangName(name)) { handleWarning(node, "name is not valid for Golang: " + name); } if (!ValidationUtil.isSbeCSharpName(name)) { handleWarning(node, "name is not valid for C#: " + name); } }
[ "public", "static", "void", "checkForValidName", "(", "final", "Node", "node", ",", "final", "String", "name", ")", "{", "if", "(", "!", "ValidationUtil", ".", "isSbeCppName", "(", "name", ")", ")", "{", "handleWarning", "(", "node", ",", "\"name is not valid for C++: \"", "+", "name", ")", ";", "}", "if", "(", "!", "ValidationUtil", ".", "isSbeJavaName", "(", "name", ")", ")", "{", "handleWarning", "(", "node", ",", "\"name is not valid for Java: \"", "+", "name", ")", ";", "}", "if", "(", "!", "ValidationUtil", ".", "isSbeGolangName", "(", "name", ")", ")", "{", "handleWarning", "(", "node", ",", "\"name is not valid for Golang: \"", "+", "name", ")", ";", "}", "if", "(", "!", "ValidationUtil", ".", "isSbeCSharpName", "(", "name", ")", ")", "{", "handleWarning", "(", "node", ",", "\"name is not valid for C#: \"", "+", "name", ")", ";", "}", "}" ]
Check name against validity for C++ and Java naming. Warning if not valid. @param node to have the name checked. @param name of the node to be checked.
[ "Check", "name", "against", "validity", "for", "C", "++", "and", "Java", "naming", ".", "Warning", "if", "not", "valid", "." ]
train
https://github.com/real-logic/simple-binary-encoding/blob/9a7be490c86d98f0e430e4189bc6c8c4fbef658b/sbe-tool/src/main/java/uk/co/real_logic/sbe/xml/XmlSchemaParser.java#L363-L384
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiffChecker.java
ApiDiffChecker.getReceiver
private ClassSymbol getReceiver(ExpressionTree tree, Symbol sym) { """ Finds the class of the expression's receiver: the declaring class of a static member access, or the type that an instance member is accessed on. """ if (sym.isStatic() || sym instanceof ClassSymbol) { return sym.enclClass(); } switch (tree.getKind()) { case MEMBER_SELECT: case METHOD_INVOCATION: Type receiver = ASTHelpers.getType(ASTHelpers.getReceiver(tree)); if (receiver == null) { return null; } return receiver.tsym.enclClass(); case IDENTIFIER: // Simple names are implicitly qualified by an enclosing instance, so if we get here // we're inside the compilation unit that declares the receiver, and the diff doesn't // contain accurate information. return null; default: return null; } }
java
private ClassSymbol getReceiver(ExpressionTree tree, Symbol sym) { if (sym.isStatic() || sym instanceof ClassSymbol) { return sym.enclClass(); } switch (tree.getKind()) { case MEMBER_SELECT: case METHOD_INVOCATION: Type receiver = ASTHelpers.getType(ASTHelpers.getReceiver(tree)); if (receiver == null) { return null; } return receiver.tsym.enclClass(); case IDENTIFIER: // Simple names are implicitly qualified by an enclosing instance, so if we get here // we're inside the compilation unit that declares the receiver, and the diff doesn't // contain accurate information. return null; default: return null; } }
[ "private", "ClassSymbol", "getReceiver", "(", "ExpressionTree", "tree", ",", "Symbol", "sym", ")", "{", "if", "(", "sym", ".", "isStatic", "(", ")", "||", "sym", "instanceof", "ClassSymbol", ")", "{", "return", "sym", ".", "enclClass", "(", ")", ";", "}", "switch", "(", "tree", ".", "getKind", "(", ")", ")", "{", "case", "MEMBER_SELECT", ":", "case", "METHOD_INVOCATION", ":", "Type", "receiver", "=", "ASTHelpers", ".", "getType", "(", "ASTHelpers", ".", "getReceiver", "(", "tree", ")", ")", ";", "if", "(", "receiver", "==", "null", ")", "{", "return", "null", ";", "}", "return", "receiver", ".", "tsym", ".", "enclClass", "(", ")", ";", "case", "IDENTIFIER", ":", "// Simple names are implicitly qualified by an enclosing instance, so if we get here", "// we're inside the compilation unit that declares the receiver, and the diff doesn't", "// contain accurate information.", "return", "null", ";", "default", ":", "return", "null", ";", "}", "}" ]
Finds the class of the expression's receiver: the declaring class of a static member access, or the type that an instance member is accessed on.
[ "Finds", "the", "class", "of", "the", "expression", "s", "receiver", ":", "the", "declaring", "class", "of", "a", "static", "member", "access", "or", "the", "type", "that", "an", "instance", "member", "is", "accessed", "on", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiffChecker.java#L128-L148
mikepenz/Android-Iconics
library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java
IconicsDrawable.backgroundContourWidthDp
@NonNull public IconicsDrawable backgroundContourWidthDp(@Dimension(unit = DP) int sizeDp) { """ Set background contour width from dp for the icon @return The current IconicsDrawable for chaining. """ return backgroundContourWidthPx(Utils.convertDpToPx(mContext, sizeDp)); }
java
@NonNull public IconicsDrawable backgroundContourWidthDp(@Dimension(unit = DP) int sizeDp) { return backgroundContourWidthPx(Utils.convertDpToPx(mContext, sizeDp)); }
[ "@", "NonNull", "public", "IconicsDrawable", "backgroundContourWidthDp", "(", "@", "Dimension", "(", "unit", "=", "DP", ")", "int", "sizeDp", ")", "{", "return", "backgroundContourWidthPx", "(", "Utils", ".", "convertDpToPx", "(", "mContext", ",", "sizeDp", ")", ")", ";", "}" ]
Set background contour width from dp for the icon @return The current IconicsDrawable for chaining.
[ "Set", "background", "contour", "width", "from", "dp", "for", "the", "icon" ]
train
https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java#L1143-L1146
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/GaussianAffinityMatrixBuilder.java
GaussianAffinityMatrixBuilder.buildDistanceMatrix
protected double[][] buildDistanceMatrix(ArrayDBIDs ids, DistanceQuery<?> dq) { """ Build a distance matrix of squared distances. @param ids DBIDs @param dq Distance query @return Distance matrix """ final int size = ids.size(); double[][] dmat = new double[size][size]; final boolean square = !dq.getDistanceFunction().isSquared(); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Computing distance matrix", (size * (size - 1)) >>> 1, LOG) : null; Duration timer = LOG.isStatistics() ? LOG.newDuration(this.getClass().getName() + ".runtime.distancematrix").begin() : null; DBIDArrayIter ix = ids.iter(), iy = ids.iter(); for(ix.seek(0); ix.valid(); ix.advance()) { double[] dmat_x = dmat[ix.getOffset()]; for(iy.seek(ix.getOffset() + 1); iy.valid(); iy.advance()) { final double dist = dq.distance(ix, iy); dmat[iy.getOffset()][ix.getOffset()] = dmat_x[iy.getOffset()] = square ? (dist * dist) : dist; } if(prog != null) { int row = ix.getOffset() + 1; prog.setProcessed(row * size - ((row * (row + 1)) >>> 1), LOG); } } LOG.ensureCompleted(prog); if(timer != null) { LOG.statistics(timer.end()); } return dmat; }
java
protected double[][] buildDistanceMatrix(ArrayDBIDs ids, DistanceQuery<?> dq) { final int size = ids.size(); double[][] dmat = new double[size][size]; final boolean square = !dq.getDistanceFunction().isSquared(); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Computing distance matrix", (size * (size - 1)) >>> 1, LOG) : null; Duration timer = LOG.isStatistics() ? LOG.newDuration(this.getClass().getName() + ".runtime.distancematrix").begin() : null; DBIDArrayIter ix = ids.iter(), iy = ids.iter(); for(ix.seek(0); ix.valid(); ix.advance()) { double[] dmat_x = dmat[ix.getOffset()]; for(iy.seek(ix.getOffset() + 1); iy.valid(); iy.advance()) { final double dist = dq.distance(ix, iy); dmat[iy.getOffset()][ix.getOffset()] = dmat_x[iy.getOffset()] = square ? (dist * dist) : dist; } if(prog != null) { int row = ix.getOffset() + 1; prog.setProcessed(row * size - ((row * (row + 1)) >>> 1), LOG); } } LOG.ensureCompleted(prog); if(timer != null) { LOG.statistics(timer.end()); } return dmat; }
[ "protected", "double", "[", "]", "[", "]", "buildDistanceMatrix", "(", "ArrayDBIDs", "ids", ",", "DistanceQuery", "<", "?", ">", "dq", ")", "{", "final", "int", "size", "=", "ids", ".", "size", "(", ")", ";", "double", "[", "]", "[", "]", "dmat", "=", "new", "double", "[", "size", "]", "[", "size", "]", ";", "final", "boolean", "square", "=", "!", "dq", ".", "getDistanceFunction", "(", ")", ".", "isSquared", "(", ")", ";", "FiniteProgress", "prog", "=", "LOG", ".", "isVerbose", "(", ")", "?", "new", "FiniteProgress", "(", "\"Computing distance matrix\"", ",", "(", "size", "*", "(", "size", "-", "1", ")", ")", ">>>", "1", ",", "LOG", ")", ":", "null", ";", "Duration", "timer", "=", "LOG", ".", "isStatistics", "(", ")", "?", "LOG", ".", "newDuration", "(", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".runtime.distancematrix\"", ")", ".", "begin", "(", ")", ":", "null", ";", "DBIDArrayIter", "ix", "=", "ids", ".", "iter", "(", ")", ",", "iy", "=", "ids", ".", "iter", "(", ")", ";", "for", "(", "ix", ".", "seek", "(", "0", ")", ";", "ix", ".", "valid", "(", ")", ";", "ix", ".", "advance", "(", ")", ")", "{", "double", "[", "]", "dmat_x", "=", "dmat", "[", "ix", ".", "getOffset", "(", ")", "]", ";", "for", "(", "iy", ".", "seek", "(", "ix", ".", "getOffset", "(", ")", "+", "1", ")", ";", "iy", ".", "valid", "(", ")", ";", "iy", ".", "advance", "(", ")", ")", "{", "final", "double", "dist", "=", "dq", ".", "distance", "(", "ix", ",", "iy", ")", ";", "dmat", "[", "iy", ".", "getOffset", "(", ")", "]", "[", "ix", ".", "getOffset", "(", ")", "]", "=", "dmat_x", "[", "iy", ".", "getOffset", "(", ")", "]", "=", "square", "?", "(", "dist", "*", "dist", ")", ":", "dist", ";", "}", "if", "(", "prog", "!=", "null", ")", "{", "int", "row", "=", "ix", ".", "getOffset", "(", ")", "+", "1", ";", "prog", ".", "setProcessed", "(", "row", "*", "size", "-", "(", "(", "row", "*", "(", "row", "+", "1", ")", ")", ">>>", "1", ")", ",", "LOG", ")", ";", "}", "}", "LOG", ".", "ensureCompleted", "(", "prog", ")", ";", "if", "(", "timer", "!=", "null", ")", "{", "LOG", ".", "statistics", "(", "timer", ".", "end", "(", ")", ")", ";", "}", "return", "dmat", ";", "}" ]
Build a distance matrix of squared distances. @param ids DBIDs @param dq Distance query @return Distance matrix
[ "Build", "a", "distance", "matrix", "of", "squared", "distances", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/projection/GaussianAffinityMatrixBuilder.java#L116-L139
Stratio/stratio-connector-commons
connector-commons/src/main/java/com/stratio/connector/commons/connection/Connection.java
Connection.addObjectToSession
public void addObjectToSession(String name, Object value) { """ Add a object into the session. @param name the object name. @param value the objecet value. """ if (session == null) { session = new HashMap<>(); } if (logger.isDebugEnabled()) { logger.debug("Add object [" + name + "] to session with value [" + value + "]"); } session.put(name, value); }
java
public void addObjectToSession(String name, Object value) { if (session == null) { session = new HashMap<>(); } if (logger.isDebugEnabled()) { logger.debug("Add object [" + name + "] to session with value [" + value + "]"); } session.put(name, value); }
[ "public", "void", "addObjectToSession", "(", "String", "name", ",", "Object", "value", ")", "{", "if", "(", "session", "==", "null", ")", "{", "session", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Add object [\"", "+", "name", "+", "\"] to session with value [\"", "+", "value", "+", "\"]\"", ")", ";", "}", "session", ".", "put", "(", "name", ",", "value", ")", ";", "}" ]
Add a object into the session. @param name the object name. @param value the objecet value.
[ "Add", "a", "object", "into", "the", "session", "." ]
train
https://github.com/Stratio/stratio-connector-commons/blob/d7cc66cb9591344a13055962e87a91f01c3707d1/connector-commons/src/main/java/com/stratio/connector/commons/connection/Connection.java#L80-L88
elki-project/elki
elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/OUTRES.java
OUTRES.outresScore
public double outresScore(final int s, long[] subspace, DBIDRef id, KernelDensityEstimator kernel, DBIDs cands) { """ Main loop of OUTRES. Run for each object @param s start dimension @param subspace Current subspace @param id Current object ID @param kernel Kernel @param cands neighbor candidates @return Score """ double score = 1.0; // Initial score is 1.0 final SubspaceEuclideanDistanceFunction df = new SubspaceEuclideanDistanceFunction(subspace); MeanVariance meanv = new MeanVariance(); ModifiableDoubleDBIDList neighcand = DBIDUtil.newDistanceDBIDList(cands.size()); ModifiableDoubleDBIDList nn = DBIDUtil.newDistanceDBIDList(cands.size()); for(int i = s; i < kernel.dim; i++) { assert !BitsUtil.get(subspace, i); BitsUtil.setI(subspace, i); df.setSelectedDimensions(subspace); final double adjustedEps = kernel.adjustedEps(kernel.dim); DoubleDBIDList neigh = initialRange(id, cands, df, adjustedEps * 2, kernel, neighcand); // Relevance test if(neigh.size() > 2) { if(relevantSubspace(subspace, neigh, kernel)) { final double density = kernel.subspaceDensity(subspace, neigh); // Compute mean and standard deviation for densities of neighbors. meanv.reset(); for(DoubleDBIDListIter neighbor = neigh.iter(); neighbor.valid(); neighbor.advance()) { subsetNeighborhoodQuery(neighcand, neighbor, df, adjustedEps, kernel, nn); meanv.put(kernel.subspaceDensity(subspace, nn)); } final double deviation = (meanv.getMean() - density) / (2. * meanv.getSampleStddev()); // High deviation: if(deviation >= 1) { score *= density / deviation; } // Recursion score *= outresScore(i + 1, subspace, id, kernel, neighcand); } } BitsUtil.clearI(subspace, i); } return score; }
java
public double outresScore(final int s, long[] subspace, DBIDRef id, KernelDensityEstimator kernel, DBIDs cands) { double score = 1.0; // Initial score is 1.0 final SubspaceEuclideanDistanceFunction df = new SubspaceEuclideanDistanceFunction(subspace); MeanVariance meanv = new MeanVariance(); ModifiableDoubleDBIDList neighcand = DBIDUtil.newDistanceDBIDList(cands.size()); ModifiableDoubleDBIDList nn = DBIDUtil.newDistanceDBIDList(cands.size()); for(int i = s; i < kernel.dim; i++) { assert !BitsUtil.get(subspace, i); BitsUtil.setI(subspace, i); df.setSelectedDimensions(subspace); final double adjustedEps = kernel.adjustedEps(kernel.dim); DoubleDBIDList neigh = initialRange(id, cands, df, adjustedEps * 2, kernel, neighcand); // Relevance test if(neigh.size() > 2) { if(relevantSubspace(subspace, neigh, kernel)) { final double density = kernel.subspaceDensity(subspace, neigh); // Compute mean and standard deviation for densities of neighbors. meanv.reset(); for(DoubleDBIDListIter neighbor = neigh.iter(); neighbor.valid(); neighbor.advance()) { subsetNeighborhoodQuery(neighcand, neighbor, df, adjustedEps, kernel, nn); meanv.put(kernel.subspaceDensity(subspace, nn)); } final double deviation = (meanv.getMean() - density) / (2. * meanv.getSampleStddev()); // High deviation: if(deviation >= 1) { score *= density / deviation; } // Recursion score *= outresScore(i + 1, subspace, id, kernel, neighcand); } } BitsUtil.clearI(subspace, i); } return score; }
[ "public", "double", "outresScore", "(", "final", "int", "s", ",", "long", "[", "]", "subspace", ",", "DBIDRef", "id", ",", "KernelDensityEstimator", "kernel", ",", "DBIDs", "cands", ")", "{", "double", "score", "=", "1.0", ";", "// Initial score is 1.0", "final", "SubspaceEuclideanDistanceFunction", "df", "=", "new", "SubspaceEuclideanDistanceFunction", "(", "subspace", ")", ";", "MeanVariance", "meanv", "=", "new", "MeanVariance", "(", ")", ";", "ModifiableDoubleDBIDList", "neighcand", "=", "DBIDUtil", ".", "newDistanceDBIDList", "(", "cands", ".", "size", "(", ")", ")", ";", "ModifiableDoubleDBIDList", "nn", "=", "DBIDUtil", ".", "newDistanceDBIDList", "(", "cands", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "s", ";", "i", "<", "kernel", ".", "dim", ";", "i", "++", ")", "{", "assert", "!", "BitsUtil", ".", "get", "(", "subspace", ",", "i", ")", ";", "BitsUtil", ".", "setI", "(", "subspace", ",", "i", ")", ";", "df", ".", "setSelectedDimensions", "(", "subspace", ")", ";", "final", "double", "adjustedEps", "=", "kernel", ".", "adjustedEps", "(", "kernel", ".", "dim", ")", ";", "DoubleDBIDList", "neigh", "=", "initialRange", "(", "id", ",", "cands", ",", "df", ",", "adjustedEps", "*", "2", ",", "kernel", ",", "neighcand", ")", ";", "// Relevance test", "if", "(", "neigh", ".", "size", "(", ")", ">", "2", ")", "{", "if", "(", "relevantSubspace", "(", "subspace", ",", "neigh", ",", "kernel", ")", ")", "{", "final", "double", "density", "=", "kernel", ".", "subspaceDensity", "(", "subspace", ",", "neigh", ")", ";", "// Compute mean and standard deviation for densities of neighbors.", "meanv", ".", "reset", "(", ")", ";", "for", "(", "DoubleDBIDListIter", "neighbor", "=", "neigh", ".", "iter", "(", ")", ";", "neighbor", ".", "valid", "(", ")", ";", "neighbor", ".", "advance", "(", ")", ")", "{", "subsetNeighborhoodQuery", "(", "neighcand", ",", "neighbor", ",", "df", ",", "adjustedEps", ",", "kernel", ",", "nn", ")", ";", "meanv", ".", "put", "(", "kernel", ".", "subspaceDensity", "(", "subspace", ",", "nn", ")", ")", ";", "}", "final", "double", "deviation", "=", "(", "meanv", ".", "getMean", "(", ")", "-", "density", ")", "/", "(", "2.", "*", "meanv", ".", "getSampleStddev", "(", ")", ")", ";", "// High deviation:", "if", "(", "deviation", ">=", "1", ")", "{", "score", "*=", "density", "/", "deviation", ";", "}", "// Recursion", "score", "*=", "outresScore", "(", "i", "+", "1", ",", "subspace", ",", "id", ",", "kernel", ",", "neighcand", ")", ";", "}", "}", "BitsUtil", ".", "clearI", "(", "subspace", ",", "i", ")", ";", "}", "return", "score", ";", "}" ]
Main loop of OUTRES. Run for each object @param s start dimension @param subspace Current subspace @param id Current object ID @param kernel Kernel @param cands neighbor candidates @return Score
[ "Main", "loop", "of", "OUTRES", ".", "Run", "for", "each", "object" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/OUTRES.java#L151-L186
opencb/biodata
biodata-tools/src/main/java/org/opencb/biodata/tools/variant/stats/VariantAggregatedExacStatsCalculator.java
VariantAggregatedExacStatsCalculator.addHomozygousGenotype
private void addHomozygousGenotype(Variant variant, int numAllele, String[] alternateAlleles, VariantStats stats, String[] homCounts) { """ Adds the homozygous genotypes to a variant stats. Those are (in this order): 1/1, 2/2, 3/3... @param variant @param numAllele @param alternateAlleles @param stats @param homCounts parsed string """ if (homCounts.length == alternateAlleles.length) { for (int i = 0; i < homCounts.length; i++) { Integer alleles[] = new Integer[2]; getHomozygousGenotype(i + 1, alleles); String gt = VariantVcfFactory.mapToMultiallelicIndex(alleles[0], numAllele) + "/" + VariantVcfFactory.mapToMultiallelicIndex(alleles[1], numAllele); Genotype genotype = new Genotype(gt, variant.getReference(), alternateAlleles[numAllele]); stats.addGenotype(genotype, Integer.parseInt(homCounts[i])); } } }
java
private void addHomozygousGenotype(Variant variant, int numAllele, String[] alternateAlleles, VariantStats stats, String[] homCounts) { if (homCounts.length == alternateAlleles.length) { for (int i = 0; i < homCounts.length; i++) { Integer alleles[] = new Integer[2]; getHomozygousGenotype(i + 1, alleles); String gt = VariantVcfFactory.mapToMultiallelicIndex(alleles[0], numAllele) + "/" + VariantVcfFactory.mapToMultiallelicIndex(alleles[1], numAllele); Genotype genotype = new Genotype(gt, variant.getReference(), alternateAlleles[numAllele]); stats.addGenotype(genotype, Integer.parseInt(homCounts[i])); } } }
[ "private", "void", "addHomozygousGenotype", "(", "Variant", "variant", ",", "int", "numAllele", ",", "String", "[", "]", "alternateAlleles", ",", "VariantStats", "stats", ",", "String", "[", "]", "homCounts", ")", "{", "if", "(", "homCounts", ".", "length", "==", "alternateAlleles", ".", "length", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "homCounts", ".", "length", ";", "i", "++", ")", "{", "Integer", "alleles", "[", "]", "=", "new", "Integer", "[", "2", "]", ";", "getHomozygousGenotype", "(", "i", "+", "1", ",", "alleles", ")", ";", "String", "gt", "=", "VariantVcfFactory", ".", "mapToMultiallelicIndex", "(", "alleles", "[", "0", "]", ",", "numAllele", ")", "+", "\"/\"", "+", "VariantVcfFactory", ".", "mapToMultiallelicIndex", "(", "alleles", "[", "1", "]", ",", "numAllele", ")", ";", "Genotype", "genotype", "=", "new", "Genotype", "(", "gt", ",", "variant", ".", "getReference", "(", ")", ",", "alternateAlleles", "[", "numAllele", "]", ")", ";", "stats", ".", "addGenotype", "(", "genotype", ",", "Integer", ".", "parseInt", "(", "homCounts", "[", "i", "]", ")", ")", ";", "}", "}", "}" ]
Adds the homozygous genotypes to a variant stats. Those are (in this order): 1/1, 2/2, 3/3... @param variant @param numAllele @param alternateAlleles @param stats @param homCounts parsed string
[ "Adds", "the", "homozygous", "genotypes", "to", "a", "variant", "stats", ".", "Those", "are", "(", "in", "this", "order", ")", ":", "1", "/", "1", "2", "/", "2", "3", "/", "3", "..." ]
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/variant/stats/VariantAggregatedExacStatsCalculator.java#L236-L246
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
CpeMemoryIndex.open
public synchronized void open(CveDB cve, Settings settings) throws IndexException { """ Creates and loads data into an in memory index. @param cve the data source to retrieve the cpe data @param settings a reference to the dependency-check settings @throws IndexException thrown if there is an error creating the index """ if (INSTANCE.usageCount.addAndGet(1) == 1) { try { final File temp = settings.getTempDirectory(); index = new MMapDirectory(temp.toPath()); buildIndex(cve); indexReader = DirectoryReader.open(index); } catch (IOException ex) { throw new IndexException(ex); } indexSearcher = new IndexSearcher(indexReader); searchingAnalyzer = createSearchingAnalyzer(); queryParser = new QueryParser(Fields.DOCUMENT_KEY, searchingAnalyzer); } }
java
public synchronized void open(CveDB cve, Settings settings) throws IndexException { if (INSTANCE.usageCount.addAndGet(1) == 1) { try { final File temp = settings.getTempDirectory(); index = new MMapDirectory(temp.toPath()); buildIndex(cve); indexReader = DirectoryReader.open(index); } catch (IOException ex) { throw new IndexException(ex); } indexSearcher = new IndexSearcher(indexReader); searchingAnalyzer = createSearchingAnalyzer(); queryParser = new QueryParser(Fields.DOCUMENT_KEY, searchingAnalyzer); } }
[ "public", "synchronized", "void", "open", "(", "CveDB", "cve", ",", "Settings", "settings", ")", "throws", "IndexException", "{", "if", "(", "INSTANCE", ".", "usageCount", ".", "addAndGet", "(", "1", ")", "==", "1", ")", "{", "try", "{", "final", "File", "temp", "=", "settings", ".", "getTempDirectory", "(", ")", ";", "index", "=", "new", "MMapDirectory", "(", "temp", ".", "toPath", "(", ")", ")", ";", "buildIndex", "(", "cve", ")", ";", "indexReader", "=", "DirectoryReader", ".", "open", "(", "index", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "IndexException", "(", "ex", ")", ";", "}", "indexSearcher", "=", "new", "IndexSearcher", "(", "indexReader", ")", ";", "searchingAnalyzer", "=", "createSearchingAnalyzer", "(", ")", ";", "queryParser", "=", "new", "QueryParser", "(", "Fields", ".", "DOCUMENT_KEY", ",", "searchingAnalyzer", ")", ";", "}", "}" ]
Creates and loads data into an in memory index. @param cve the data source to retrieve the cpe data @param settings a reference to the dependency-check settings @throws IndexException thrown if there is an error creating the index
[ "Creates", "and", "loads", "data", "into", "an", "in", "memory", "index", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L134-L149
UrielCh/ovh-java-sdk
ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java
ApiOvhEmailexchange.organizationName_service_exchangeService_externalContact_POST
public OvhTask organizationName_service_exchangeService_externalContact_POST(String organizationName, String exchangeService, String displayName, String externalEmailAddress, String firstName, Boolean hiddenFromGAL, String initials, String lastName, String organization2010) throws IOException { """ create new external contact REST: POST /email/exchange/{organizationName}/service/{exchangeService}/externalContact @param displayName [required] Contact display name @param lastName [required] Contact last name @param organization2010 [required] Indicates to which organization this newly created external contact will belongs (Exchange 2010 only) @param initials [required] Contact initials @param hiddenFromGAL [required] Hide the contact in Global Address List @param firstName [required] Contact first name @param externalEmailAddress [required] Contact email address @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service """ String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/externalContact"; StringBuilder sb = path(qPath, organizationName, exchangeService); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "displayName", displayName); addBody(o, "externalEmailAddress", externalEmailAddress); addBody(o, "firstName", firstName); addBody(o, "hiddenFromGAL", hiddenFromGAL); addBody(o, "initials", initials); addBody(o, "lastName", lastName); addBody(o, "organization2010", organization2010); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
java
public OvhTask organizationName_service_exchangeService_externalContact_POST(String organizationName, String exchangeService, String displayName, String externalEmailAddress, String firstName, Boolean hiddenFromGAL, String initials, String lastName, String organization2010) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/externalContact"; StringBuilder sb = path(qPath, organizationName, exchangeService); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "displayName", displayName); addBody(o, "externalEmailAddress", externalEmailAddress); addBody(o, "firstName", firstName); addBody(o, "hiddenFromGAL", hiddenFromGAL); addBody(o, "initials", initials); addBody(o, "lastName", lastName); addBody(o, "organization2010", organization2010); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhTask.class); }
[ "public", "OvhTask", "organizationName_service_exchangeService_externalContact_POST", "(", "String", "organizationName", ",", "String", "exchangeService", ",", "String", "displayName", ",", "String", "externalEmailAddress", ",", "String", "firstName", ",", "Boolean", "hiddenFromGAL", ",", "String", "initials", ",", "String", "lastName", ",", "String", "organization2010", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/exchange/{organizationName}/service/{exchangeService}/externalContact\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "organizationName", ",", "exchangeService", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"displayName\"", ",", "displayName", ")", ";", "addBody", "(", "o", ",", "\"externalEmailAddress\"", ",", "externalEmailAddress", ")", ";", "addBody", "(", "o", ",", "\"firstName\"", ",", "firstName", ")", ";", "addBody", "(", "o", ",", "\"hiddenFromGAL\"", ",", "hiddenFromGAL", ")", ";", "addBody", "(", "o", ",", "\"initials\"", ",", "initials", ")", ";", "addBody", "(", "o", ",", "\"lastName\"", ",", "lastName", ")", ";", "addBody", "(", "o", ",", "\"organization2010\"", ",", "organization2010", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhTask", ".", "class", ")", ";", "}" ]
create new external contact REST: POST /email/exchange/{organizationName}/service/{exchangeService}/externalContact @param displayName [required] Contact display name @param lastName [required] Contact last name @param organization2010 [required] Indicates to which organization this newly created external contact will belongs (Exchange 2010 only) @param initials [required] Contact initials @param hiddenFromGAL [required] Hide the contact in Global Address List @param firstName [required] Contact first name @param externalEmailAddress [required] Contact email address @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service
[ "create", "new", "external", "contact" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L987-L1000